之前写 C/C++ 一直在 CLion 上,但现在工作了,主要写的语言就只有 Golang 了,但其实工作中还要看一些 PHP,帮同事改改跑跑 Python 脚本啥的,所以现在统一开始使用 vscode 进行开发了,有时候心血来潮也用用 Neovim
这里分享一下 C/C++ 的运行配置,系统用的是 wsl2-Debian
软件安装
首先是安装必备的软件
1 2 3
| sudo apt install gdb gcc build-essential // 可选 sudo apt install glibc-source
|
tasks.json
接下来就是创建一个项目目录,执行 Ctrl+Shift+P
输入 Configure Default Build Task
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| { "version": "2.0.0", "tasks": [ { "type": "cppbuild", "label": "C/C++: g++ build active file", "command": "/usr/bin/g++", "args": [ "-fdiagnostics-color=always", "-g", "${file}", "-o", "${workspaceFolder}/exe/${fileBasenameNoExtension}" ], "options": { "cwd": "${fileDirname}" }, "problemMatcher": [ "$gcc" ], "group": { "kind": "build", "isDefault": true }, "detail": "compiler: /usr/bin/g++" } ] }
|
需要重点看的配置项有 command
, args
, isDefault
args
的多个项中有如下含义:
-g
用来指定编译的文件
$file
当前文件,同时编译多个只能指定类型,如:${workspaceFolder}/*.cpp
-o
指定生成的可执行文件的地址
launch.json
第二步是添加运行配置: Run->Add Configuration
生成 launch.json
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| { "version": "0.2.0", "configurations": [ { "name": "g++ - 生成和调试活动文件 ", "type": "cppdbg", "request": "launch", "program": "${workspaceFolder}/bin/${fileBasenameNoExtension}", "args": [], "stopAtEntry": false, "cwd": "${fileDirname}", "environment": [], "externalConsole": false, "MIMode": "gdb", "setupCommands": [ { "description": " 为 gdb 启用整齐打印 ", "text": "-enable-pretty-printing", "ignoreFailures": true }, { "description": " 将反汇编风格设置为 Intel", "text": "-gdb-set disassembly-flavor intel", "ignoreFailures": true } ], "preLaunchTask": "C/C++: g++ build active file", "miDebuggerPath": "/usr/bin/gdb", "sourceFileMap": { "/build/glibc-eX1tMB": "/usr/src/glibc" } } ] }
|
这里的 stopAtEntry
必须设置为 true 才能打断点, sourceFileMap
如果有报错可以进行安装设置(最开始的可选安装)
声明路径
调试会需要获取获取相关路径,因为设置过 glibc 的原因可以不进行声明,但是要忍受红红的报错,也可以关掉报错,但是最好不要掩耳盗铃
获取相关路径的方式也很简单,只需要执行 g++ -v -E -x c++ -
然后添加到配置即可
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| { "configurations": [ { "name": "Linux", "includePath": [ "${workspaceFolder}/**", "/usr/include/**", "/usr/include/c++/11/**", "/usr/include/x86_64-linux-gnu/c++/11/**", "/usr/include/c++/11/backward/**", "/usr/lib/gcc/x86_64-linux-gnu/11/include/**", "/usr/local/include/**", "/usr/include/x86_64-linux-gnu/**" ], "defines": [], "compilerPath": "/usr/bin/gcc", "cStandard": "gnu17", "cppStandard": "gnu++14", "intelliSenseMode": "linux-gcc-x64", "browse": { "limitSymbolsToIncludedHeaders": true } } ], "version": 4 }
|
END