本記事では、Visual StudioのMSVC(Microsoft Visual C++)を利用して、C++ファイルのデバッグ実行を行う方法を解説します。
競技プログラミング等でvscodeのデバッグツールを使いたい方におすすめです。
全体の流れ
- Visual Studio 2022 のインストール
- tasks.json/launch.json の作成
- デバッグ実行
1. Visual Studio 2022 のインストール
まずは、以下のリンクから、Visual Studio 2022 をダウンロードします。
Visual Studio 2022
ダウンロードしたら、VisualStudioSetup.exeファイルからインストーラーを起動します。
Visual Studio Community 2022 をインストールします。
C++によるデスクトップ開発にチェックをいれて、インストールします。
2. tasks.json,launch.json の作成
vscodeを起動し、プロジェクトフォルダを作成します。
ルートディレクトリに、.vscodeフォルダを作成し、.vscode下に、launch.jsonとtasks.jsonを作成します。
作成したlaunch.json,tasks.jsonに以下をペーストしてください。
(tasks.jsonの"VsDevCmd.bat"は、必要に応じてパスを書き換えてください)
launch.json
{
"version": "0.2.0",
"configurations": [
{
"name": "Debug current file",
"type": "cppvsdbg", // dbgのタイプ指定
"request": "launch",
"program": "${fileDirname}\\out\\${fileBasenameNoExtension}.exe", // 実行ファイル指定
"stopAtEntry": false, // エントリーポイントで停止しない
"cwd": "${fileDirname}",
"console": "integratedTerminal", // 統合ターミナルを使用
"preLaunchTask": "Build current file with cl.exe", // タスク指定
"justMyCode": true // 自分のコードのみをデバッグ対象に
}
]
}
tasks.json
{
"version": "2.0.0",
"tasks": [
{
"label": "Build current file with cl.exe",
"type": "shell",
"command": "cl.exe",
"args": [
"/Zi",
"/EHsc",
"/utf-8",
"/Fe:${fileDirname}\\out\\${fileBasenameNoExtension}.exe",
"/Fo:${fileDirname}\\out\\",
"/Fd:${fileDirname}\\out\\",
"${file}"
],
"options": {
"shell": {
"executable": "C:\\Program Files\\Microsoft Visual Studio\\2022\\Community\\Common7\\Tools\\VsDevCmd.bat",
"args": ["&&"]
}
},
"group": {
"kind": "build",
"isDefault": true
},
"problemMatcher": ["$msCompile"],
"dependsOn": ["Create out directory"]
},
{
"label": "Create out directory",
"type": "shell",
"command": "if not exist \"${fileDirname}\\out\" mkdir \"${fileDirname}\\out\"",
"options": {
"shell": {
"executable": "C:\\Windows\\System32\\cmd.exe",
"args": ["/C"] // コマンドを一度実行し、cmd.exeプロセスを終了
}
}
}
]
}
3. デバッグ実行
例として、ルートディレクトリにtest.cppファイルを作成して、デバッグを実行してみます。
test.cpp
#include<iostream>
using namespace std;
test.cpp
int main(){
string s;
cin >> s;
cout << s << endl;
}
-
ブレークポイントを設定したい行の左端をクリックします。設置すると行番号の左に赤い丸が表示されます。
(以下の例では、7行目に設置しています。)
-
Run and Debug(ctrl+shift+D)を開き、StartDebugging(F5)を押します。
(参照ファイル上でF5を押すだけでも実行できます)
実行すると、以下のように /outディレクトリが作られ、exeファイルなどが保存されます。
その後、自動的に.exeファイルが実行され、デバッグを行える状態になります。
まとめ
以上の手順で、Visual StudioのMSVCを使ったC++プログラムのデバッグが可能になります。