VSCodeを使ったC++の環境構築【macOS】

VSCodeを使ったC++の環境構築【macOS

更新日:2022/12/21 M1 Macの場合は下記を参照

【競プロ】AtCoderを始めるためのC++の基本 | そまちょブログ

Visual studio codeで競プロ環境構築[mac OS] - Qiita


更新日:2020/03/13 VSCodeの更新が盛んなので,時間がたつと記事がアテにならなくなるとのこと.


1. 下準備

2. コンパイルから実行まで

2.1. サンプルコードの作成

$ mkdir sample && cd sample
$ touch main.cpp
#include <iostream>

using namespace std;

int main(){
    int year = 1986, month = 5, date = 5;

    cout << "hello world: " << endl
         << "birthday is " << year << month << date << endl;
    return 0;
}

2.2. コンパイラPathの設定

gccをinstallすると,Mac上に2つのコンパイラ(clang, gcc)が同居する状態になる.それぞれのPathは,

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

競技プラグラミングでは<stdc++.h>というライブラリを使うのが便利で,それはgccにのみ入っているということ. そこで,ここではgccコンパイラを使うように設定を行っていきます.

まずはg++コマンドで/usr/local/bin/g++-9が呼ばれるようにシンボリックリンクを貼ります.

$ ln -s /usr/local/bin/g++-9 /usr/local/bin/g++
$ which g++  >>  /usr/local/bin/g++(/usr/bin/g++から変わりました)

ちなみに優先順位が,/usr/local/bin/g++ > /usr/bin/g++となるのは環境変数$PATHの設定によるものです.

$ echo $PATH
/usr/local/bin:/usr/local/sbin:/usr/bin

2.3. Code Runnerの設定

VSCode上からC++コンパイルを行うためにCode Runnerの設定を行います.
Extension --> Code Runner --> 設定(歯車マーク) --> Extension Setting --> Code-runner:Executor Map --> Edit in settings.json
でsettings.jsonを開きます.

{
    "code-runner.runInTerminal": true,
    "workbench.sideBar.location": "left",
    "editor.suggestSelection": "first",
    "vsintellicode.modify.editor.suggestSelection": "automaticallyOverrodeDefaultValue",
    "runner.languageMap": {
        "cpp": "/Users/ユーザー名/vsc_run/cpp.sh"
    }
}

重要なのは"runner.languageMap"の部分で,使用言語毎に走らせるshell scriptのPathを設定します.
vsc_run/cpp.shはまだ存在しないので,これから作成します.

2.3. Shell scriptの作成

cpp.shを作ります.

$ mkdir ~/vsc_run
$ emacs cpp.sh

cpp.shの一例

#!/bin/sh
file = $1
objfile = `echo $f | sed 's/\.[^\.]*$//'`

g++ -g -o $objfile $file
./$objfile

main.cppをコンパイルしてmainという実行ファイルを作成する,という内容です.
VSCodeのCode Runnerによってこのshell scriptが呼ばれ,コンパイルおよび実行がされます.

2.4. 動作確認

それではVSCodeから実行します.デフォルトではcontrol + option + nで実行されます.(押しにくい) VSCode画面下部のターミナルに,

hello world: 
birthday is 198655

と表示されれば成功です.歳がバレますね.

2.5. stdc++.hを使えるようにする

競プロで便利だと言われるstdc++.hをincludeできるように設定していきます.
先ほどのサンプルでincludeした含め,必要なライブラリのincludeがこれ1つで出来るようになります.

まず,stdc++.hの在処を見つけましょう.

$ cd /usr/local/
$ find . -name "stdc++.h"
./Cellar/gcc/9.2.0_1/include/c++/9.2.0/x86_64-apple-darwin18/bits/stdc++.h

このファイルをコンパイラが認識できる/usr/local/下に配置します.

$ mkdir /usr/local/include/bits
$ cp ./Cellar/gcc/9.2.0/include/c++/9.2.0/x86_64-apple-darwin18/bits/stdc++.h /usr/local/include/bits/

ここまで作業すれば,#include <bits/stdc++.h>でコンパイルが通るようになります.

2.6. C/C++ Intellisenseの設定

コンパイルは通るものの,未だ#include <bits/stdc++.h>に赤破線が出たり,コードの補完が効かない状態にあるそうです.
これを正常に動作させるために,Intellisense機能に/usr/local/include/をpathとして登録し,stdc++.hが認識できるようにします.

Command+Shift+Pでコマンドパレットを開き,"C/Cpp: Edit configurations"を選択する.
jsonファイルのなかの"includePath"の部分に,/usr/local/include/**を追加してpathを登録します.
"compilerPath"も2.2.で設定した/usr/local/bin/g++になっているか確認しましょう.

"configurations": [
    {
        "name": "Mac",
        "includePath": [
            "${workspaceFolder}/**",
            "/usr/local/include/**"
        ],
        "defines": [],
        "macFrameworkPath": [
            "/Library/Developer/CommandLineTools/SDKs/MacOSX10.14.sdk/System/Library/Frameworks"
        ],
        "compilerPath": "/usr/local/bin/g++",
        "cStandard": "c11",
        "cppStandard": "c++17",
        "intelliSenseMode": "gcc-x64"
    }
],
"version": 4

}

3. デバッグ

デバッグできる環境作成のためにtasks.json,およびlaunch.jsonの設定を行います.

3.1. tasks.jsonの設定

Command+Shift+Pでコマンドパレットを開き,taskと入力し,選択肢から"Tasks: Configure Default Build Task"を選択します. いくつか選択肢が出てくるので,今回使用するコンパイラに合わせて"C/Cpp: g++ build active file"を選択します.(少々うろ覚え)
以下にtasks.jsonの例を示します.環境変数fileDirname, fileBasenameNoExtensionを使ってあげると,いちいちファイル毎に引数を設定する必要がなくなり楽です.

{
    // See https://go.microsoft.com/fwlink/?LinkId=733558 
    // for the documentation about the tasks.json format
    "version": "2.0.0",
    "tasks": [
        {
            "type": "shell",
            "label": "g++ build active file",
            "command": "/usr/local/bin/g++",
            "args": [
                "-g",
                "${file}",
                "-o",
                "${fileDirname}/${fileBasenameNoExtension}"
            ],
            "options": {
                "cwd": "/usr/local/bin"
            },
            "problemMatcher": [
                "$gcc"
            ],
            "group": {
                "kind": "build",
                "isDefault": true
            }
        }
    ]
}

3.2. launch.jsonの設定

次にデバッグ設定のlaunch.jsonを作成します. Command+Shift+Pでコマンドパレットを開き,debugと入力し,選択肢から"Debug: Open launch.json"を選択します. 環境の選択は"C++(GDB/LLDB)"を選択.(うろ覚え)
LLDBをデバッガとして使うため,"type"を"lldb"に設定します. "externalConsole"をtrueに設定することで,競技プログラミングで出てくるような外部入力用コンソールが立ち上がるようになります.

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "(lldb) Launch",
            "type": "lldb",  // cppdbgから変更
            "request": "launch",
            "program": "${fileDirname}/${fileBasenameNoExtension}",
            "args": [],
            "stopAtEntry": false,
            "cwd": "${workspaceFolder}",
            "environment": [],
            "externalConsole": true,
            "MIMode": "lldb"
        }
    ]
}

3.3. デバッグしてみる

確認したい箇所にブレークポイントを貼り,画面左の方にある虫さんマークを選択します.
debugの情報表示画面が出てきたら,F5でdebugを開始しましょう.

しかしここでハマりました. 冒頭で書いたCtrl+option+nでbuildすると何か違うモードに入ってしまうようで,ブレークポイントを設定しても止まってくれませんでした. Shift+command+bで再buildしてあげると正常にdebugを行う事ができました.
そう考えると今回の件ではCodeRunnerを使うメリットはあまりなかったということになりますね.

まとめ

めでたくbuild & debug環境をmacVSCode上で構築する事が出来ました.
これで競技プログラミング含め,Cppの勉強が捗ると思います.

Reference