- Visual Studioを使うのが楽でしょうが、今回はVisual Studio Code(以下VSC)で設定してみました
前提
- cppが対象
- g++が入っていて、g++ hoge.cpp && ./a.out が動くとする
- VSCにエクステンション”C/C++ for Visual Studio Code”が入っている
準備
- 作業位置で、例えばexperiment.cppを作り、簡単なコードを書く
#include <stdio.h>
int main() {
int a = 8;
int b = 10;
int c = a * b;
printf("%d\n", c);
return 0;
}
- おもむろにF5を押す
- 「launch.jsonがないので作りますか?」と聞かれるので編集する
- ちなみに位置は
- /Users/kt/Documents/VisualStudioCode/.vscode
- など
- launch.json
{
// 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": "cppdbg",
"request": "launch",
"program": "${fileDirname}/a.out",
"args": [],
"stopAtEntry": false,
"cwd": "${fileDirname}",
"environment": [],
"externalConsole": true,
"MIMode": "lldb",
"preLaunchTask": "build before debug"
}
]
}
- このように書き換えた
- ポイントは、現在編集しているファイル位置のa.outを実行したいので${fileDirname}を使う
- 後で書くが、デバッグ前にコンパイルしたいので"preLaunchTask": "build before debug"を書く
コンパイル用にTaskを作る
- Terminal > Compile Tasksからtasks.jsonを作る
- ちなみに位置は
- /Users/kt/Documents/VisualStudioCode/.vscode
- など
- tasks.jsonを以下のように書き換えた
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"label": "build before debug",
"type": "shell",
"command": "g++",
"args": ["-g", "${fileDirname}/*.cpp", "-o", "${fileDirname}/a.out"],
"group": {
"kind": "build",
"isDefault": true
}
}
]
}
- ポイントは、g++でコンパイルするcppと、出力のa.outを、編集しているファイル位置に作る
- argsに*.cppと書いてあることから分かるように、編集しているファイルの位置にcppは1つのみと仮定している
- エントリーポイントとなるcppがmain.cppだとすると、*.cppをmain.cppと書き換えてもいい
- labelはTaskから呼ぶときに使える
- g++に-gオプションを付けている。これがないとブレークポイントで止まったりするデバッグができない
- 以上で設定完了
デバッグ
- たとえばexperiment.cppを書き換える
- VSC上でブレークポイントも設定する
- F5を押す
- launch.jsonが読まれる
- preLaunchTaskとしてコンパイルが走る
- その後、デバッガがLaunchされる
- ブレークポイントで止まる
参考
code.visualstudio.com