背景
学习数据结构,写了很多C语言程序,这些C语言程序都保存在一个Git仓库中,以章节、实验内容为目录存放,形如:
之前一直是通过gcc
命令手动编译、运行,但随着程序逐渐复杂,希望简化构建过程,做到一键编译运行,同时支持断点调试。
环境
- VSCode,安装了C/C++扩展
- Linux
- GCC
解决方案
思路:设立一个build
目录专门用来编译、运行、调试单个C语言程序,即“当前C语言程序”。通过符号链接将指定的C语言程序目录设为build
目录。
- 在
~/bin
目录中创建Bash脚本set-data-structure-build-dir
,实现将当前目录设为build
目录:
给脚本添加执行权限:# 构建目录的路径 build_dir="<Git仓库>/build" # 删除现有的符号链接 rm -f $build_dir # 将当前目录做符号链接到构建目录 # 当前目录路径中包含空格,所以要用双引号包裹 ln -s "$(pwd)" $build_dir
因为chmod +x set-data-structure-build-dir
~/bin
在环境变量PATH
中,所以可以全局执行此脚本。 - 编辑
.gitignore
,让Git忽略build
目录:# 注意:因为build是符号链接,所以尾部不要加/ build
- 在
.vscode
目录中创建tasks.json
和launch.json
,让VSCode在build
目录中编译、调试运行C语言程序。
tasks.json
:{"tasks": [{"type": "cppbuild","label": "GCC编译","command": "/usr/bin/gcc","args": ["-fdiagnostics-color=always","-g",// 支持多个源文件"<Git仓库>/build/*.c","-o","<Git仓库>/build/a.out"],"options": {"cwd": "<Git仓库>/build"},"problemMatcher": ["$gcc"],"group": {"kind": "build","isDefault": true},"detail": "GCC编译"}],"version": "2.0.0" }
launch.json
:{"version": "0.2.0","configurations": [{"name": "GDB调试","type": "cppdbg","request": "launch","program": "<Git仓库>/build/a.out","args": [],"stopAtEntry": false,"cwd": "<Git仓库>/build","environment": [],"externalConsole": false,"MIMode": "gdb","setupCommands": [{"description": "Enable pretty-printing for gdb","text": "-enable-pretty-printing","ignoreFailures": true},{"description": "Set Disassembly Flavor to Intel","text": "-gdb-set disassembly-flavor intel","ignoreFailures": true}],"preLaunchTask": "GCC编译","miDebuggerPath": "/usr/bin/gdb"}] }
结果
在VSCode中,右键任何一个C语言程序的目录,在终端打开,然后执行set-data-structure-build-dir
。
按F5编译、运行。
实测发现,即使是在原始的C语言程序目录而不是build
目录中对源文件打断点,调试器也能正确在断点停住。