平台:Ubuntu
使用VSCODE 编写C/C++ 代码,需要至少配置好以下三个文件:
c_cpp_properties.json, launch.json, tasks.json
c_cpp_properties.json 用来配置头文件路径,编译器路径,以及使用的C/C++ 标准等。当VSCODE没有生成该文件时,可以使用"Ctrl + Shift + P" 调出命令搜索,输入"C/C++:Edit", 然后点击第一个选项即可打开该json配置文件。
{
"configurations": [
{
"name": "Linux",
"includePath": [
"${workspaceFolder}/**",
"/usr/local/include/**"
],
"defines": [],
"compilerPath": "/usr/bin/gcc",
"cStandard": "gnu17",
"cppStandard": "c++17",
"intelliSenseMode": "linux-gcc-x64"
}
],
"version": 4
}
tasks.json 用来配置Terminal 编译命令,当使用了第三方库时,需要在"args" 字段中指定链接库参数,如"-luv" 表示链接libuv.a 静态库,否则会报"undefined reference to xxx" 的错误,即找不到函数实现。
{
"tasks": [
{
"type": "cppbuild",
"label": "demo",
"command": "/usr/bin/gcc",
"args": [
"-g",
"${file}",
"-o",
"${fileDirname}/${fileBasenameNoExtension}",
"-luv"
],
"options": {
"cwd": "${fileDirname}"
},
"problemMatcher": [
"$gcc"
],
"group": "build",
"detail": "Task generated by Debugger."
}
],
"version": "2.0.0"
}
launch.json 用来配置debug 运行时的一些参数,特别注意的是"preLaunchTask" 字段要与tasks.json 中的"label" 字段相对应,表示匹配tasks.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": "my_debug",
"type": "cppdbg",
"request": "launch",
"program": "${fileDirname}/${fileBasenameNoExtension}",
"args": [],
"stopAtEntry": false,
"cwd": "${fileDirname}",
"environment": [],
"externalConsole": false,
"MIMode": "gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
],
"preLaunchTask": "demo",
"miDebuggerPath": "/usr/bin/gdb"
}
]
}
其中"name" 字段是自定义的,设置debug配置的名字。
"args" 字段是运行时传递给main函数的参数。
当使用Windows平台时,需要自行安装C/C++编译器,相关文件的配置相似,一般只需要关注头文件包含,库文件链接和编译器路径。