1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

C++ 環境構築メモ g++ (Mac)

Last updated at Posted at 2021-04-09

はじめに

大学の研究で普段,Windows PCでC++を扱うのですが,最近Macに買い換えて環境構築を行ったので,その時のことを軽くメモしました.

手順

基本は参考の記事に従って環境構築を行いました.

C++のコンパイラにはClangとgccがあるようですが,今回はgccを選びました.

1. VSCodeの拡張機能をインストール

以下のものをインストール.

  • C/C++: コード整形,タグジャンプ,自動補完,InteiliSence機能
  • Visual Studio IntelliCode: 上と同じ.
  • code-runner: VSCode上でショートカット操作でshell scriptを実行

2. gccをインストール

terminalでbrewコマンドによりgccをインストール.


$ brew install gcc

3. path設定

インストール後,以下2つのコンパイラが同居している状態.

  • /usr/bin/g++ (clang)
  • /usr/local/bin/g++-10 (gcc)

-10の部分はversionによって異なるので注意(2021/4/9時点).

現状だと,g++コマンドを実行すると,以下のようにclangのコンパイラが呼び出される.


$ which g++
/usr/bin/g++

そのため,ln -sコマンドによりシンボリックを作成して,g++コマンドでgccのコンパイラが呼び出されるようにする.


$ ln -s /usr/local/bin/g++-10 /usr/local/bin/g++

再度,g++コマンドの呼び出し元を確認して以下のようになればok. 変化がない場合は,terminalを再起動してみる.


$ which g++
/usr/local/bin/g++

4. コンパイル

code-runnerを用いてc++ファイルのコンパイルを行います.

4.1. code-runnerの設定

code-runnerをterminal上で実行できるようにするため,左側のExtensionタブを選択し,install済のCode Runnerを探す.
Code Runnerの歯車のマークをクリックし,Extension Settingsを選択.
右画面に設定画面が出てくるので
Code-Runner: Run In Terminalのチェックボックスを入れる

4.2. 動作確認

テストのため,以下のコードを作成.


# include <iostream>
using namespace std;

int main(){

    string name;
    cin >> name;
    cout << "Hello, " + name << endl;

}

control + option + n キーを入力すると,コンパイルされる.nameをterminal上で入力して,"Hello, "が出力されればok.

余談

なお,code-runnerは格言語(拡張子)に対して行う処理が規定されている.code-runnerの設定画面からCode-runner: Executor Mapを見ると,以下のようなcppに対応する処理が記載されている.


{
    "code-runner.runInTerminal": true,
    "code-runner.executorMap": {
        "javascript": "node",
        "java": "cd $dir && javac $fileName && java $fileNameWithoutExt",
        "c": "cd $dir && gcc $fileName -o $fileNameWithoutExt && $dir$fileNameWithoutExt",
        "cpp": "cd $dir && g++ $fileName -o $fileNameWithoutExt && $dir$fileNameWithoutExt",
        ~省略~
    }
}

上記より,内部では以下の処理が実行される.


cd $dir && g++ $fileName -o $fileNameWithoutExt && $dir$fileNameWithoutExt"

このコマンドでは以下の3つの処理を実行.

  1. ソースコードのあるディレクトリに移動
  2. test.cppをコンパイルし、実行ファイルtestを生成する
  3. 実行ファイルtestを実行する

補足

  • 参考した記事では,#include を使えるようにするためには,上記以外にもやることがあるみたいだったのですが,今回の手順でも特にエラーは起きませんでした.

参考

1
2
0

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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?