LoginSignup
136
136

More than 5 years have passed since last update.

Mac の Visual Studio Code で C/C++/C# を実行する

Last updated at Posted at 2016-03-04

はじめに

Mac で C/C++/C# を1エディタで完結して試せる環境が欲しかったので用意した。
このやり方なら上記の3つ以外の他言語でも可能なので、暇を見つけて追加していく。

手順

インストール

Visual Studio Code

まずは Visual Studio Code をインストール。持ってる場合はもちろん省略。

Runner

Visual Studio Code にはファイルタイプや拡張子ごとにファイルを実行できる
Runner というエクステンションがあるのでインストールする。

Visual Studio Code 上で F1 を押して下記を入力してインストールする。

ext install runner

mono

C#の実行環境として mono を brew で入れておく。

brew install mono

シェルスクリプトを用意

コンパイルして実行するためのシェルスクリプトを言語ごとに用意する。

clang.sh
#!/bin/sh
clang -o out $1
./out
rm out
cpp.sh
#!/bin/sh
clang++ -o out $1
./out
rm out
csharp.sh
#!/bin/sh
mcs $1 -out:out.exe
mono out.exe
rm out.exe

Runner の設定を変更する

実行するシェルスクリプトを指定

Code > Preferences > User Settings で下記の設定を追記。
これでファイルごとに上記で作成したシェルスクリプトを設定。

"runner.languageMap": {
  "c"      : "~/sh/clang.sh",
  "cpp"    : "~/sh/cpp.sh",
  "csharp" : "~/sh/csharp.sh"
},

キーボードショートカットを指定

Code > Preferences > Keyboard Shortcuts でショートカットを変更。
Mac の場合、他の機能とバッティングして動作しなかったので、別のショートカットに変える。

[
  { "key": "cmd+shift+,",  "command": "extension.runner.start",
                              "when": "editorTextFocus" },
  { "key": "cmd+shift+.",  "command": "extension.runner.stop" }
]

テスト

Visual Studio Code で下記のようなテストファイルを作成したら、
上で設定したキーボードショートカットを実行する。
※ extension.runner.start を設定した方のショートカット
正しく動作すると OUTPUT に出力が表示される。

test.c
#include <stdio.h>

int main (int argc, char *args[])
{
    printf("Hello, World! Clang");
    return 0;
}
test.cpp
#include <stdio.h>

class Test
{
public:
  Test() {
    printf("Hello, World! C++");
  }
};

int main (int argc, char *args[])
{
  Test test;
  return 0;
}  
test.cs
using System;

public class Hello
{
  public static void Main()
  {
    System.Console.WriteLine("Hello, World! C#");
  }
}
136
136
5

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
136
136