Linux
環境下,使用VS Code
編譯C++
工程
1. 準備
-
安裝
VS Code
-
安裝
g++
(gcc
)編譯器
sudo apt-get install g++
或者更新
sudo apt-get update
- 安裝
gdb
調試器
sudo apt-get install build-essential gdb
2. 創建Hello World
VS Code
需要爲工程配置3個文件:
`tasks.json` :編譯器配置
`launch.json`:調試器配置
`c_cpp_properties.json` (編譯器路徑、智能提示)
- 創建
Hello World
工程
mkdir hello_world
cd hello_world
code .
- 新建
hello_world.cpp
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
vector<string> msg {"Hello", "C++", "World", "from", "VS Code", "and the C++ extension!"};
for (const string& word : msg)
{
cout << word << " ";
}
cout << endl;
}
3. 編譯hello_world.cpp
在.vscode
文件夾中,創建tasks.json
文件,選擇C/C++: g++ build active file
{
"version": "2.0.0",
"tasks": [
{
"type": "shell",
"label": "g++ build active file",
"command": "/usr/bin/g++",
"args": ["-g", "${file}", "-o", "${fileDirname}/${fileBasenameNoExtension}"],
"options": {
"cwd": "/usr/bin"
},
"problemMatcher": ["$gcc"],
"group": {
"kind": "build",
"isDefault": true
}
}
]
}
command
:指定運行程序(g++
);
args
:指定g++
的命令行參數,參數必須按照編譯器指定的順序。
本例中,g++
編譯活動文件(${file}
,若要編譯所有文件,可用${workspaceFolder}/*.cpp"
替換),並在當前目錄(${fileDirname}
)中創建與活動文件同名(無擴展名)的可執行文件(${fileBasenameNoExtension}
);
label
:任務列表中的值,可以任意命名。
isDefault
:group
對象成員,true
表示按Ctrl + Shift + B
時,該任務執行;如果設爲false
,可以從Terminal
菜單Tasks: Run Build Task
處執行。
4. 調試hello_world.cpp
在.vscode
文件夾中,創建launch.json
文件,選擇g++ build and debug active file
{
"version": "0.2.0",
"configurations": [
{
"name": "g++ build and debug active file",
"type": "cppdbg",
"request": "launch",
"program": "${fileDirname}/${fileBasenameNoExtension}",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": false,
"MIMode": "gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
],
"preLaunchTask": "g++ build active file",
"miDebuggerPath": "/usr/bin/gdb"
}
]
}
program
:指定要調試的程序,${fileDirname}
表示活動文件文件夾、${fileBasenameNoExtension}
表示不帶擴展名的活動文件名。
默認情況下,C++ extension
不會在源代碼中添加斷點,並將stopAtEntry
設爲false
。將stopAtEntry
更改爲true
,以便調試時,調試器在main
方法上停止。
5. C/C++
配置
若要修改C/C++ extension
,可創建c_cpp_properties.json
文件,該文件用於設置編譯器路徑、C++
標準(默認爲C++17
)等。調用命令面板(Ctrl+Shift+P
),選擇C/C++: Edit Configurations (UI)
,
{
"configurations": [
{
"name": "Linux",
"includePath": ["${workspaceFolder}/**"],
"defines": [],
"compilerPath": "/usr/bin/gcc",
"cStandard": "c11",
"cppStandard": "c++17",
"intelliSenseMode": "clang-x64"
}
],
"version": 4
}