如何解决VS Code调试CMake生成的MyTinyrender.exe异常?
问题原因
你的调试流程之所以会生成src目录下的单独exe,核心问题出在预启动任务配置错误:
launch.json中指定了preLaunchTask: "clang++",而tasks.json里名为clang++的任务是直接编译当前打开的单个源文件(${file}),输出到源文件同目录的${file}.exe,完全绕过了CMake的构建流程。- 这就导致每次调试前,VS Code会先编译
src/main.cpp生成单独的exe,而不是去构建你通过CMake生成的build/MyTinyrender.exe,自然调试的是这个单文件编译的程序。
正确调试的解决步骤
1. 替换tasks.json,添加CMake构建任务
删掉原来冗余的单文件编译任务,添加专门的CMake构建任务,确保调试前先执行CMake的完整构建:
{ "version": "2.0.0", "tasks": [ { "label": "CMake Build", "type": "shell", "command": "cmake", "args": [ "--build", "${workspaceFolder}/build", "--config", "Debug" ], "group": { "kind": "build", "isDefault": true }, "problemMatcher": "$gcc", "presentation": { "reveal": "always", "panel": "shared" } } ] }
这个任务会调用CMake去build目录构建带调试信息的Debug版本程序,保证生成的MyTinyrender.exe是最新且可调试的。
2. 修改launch.json,关联正确的预启动任务
将preLaunchTask的值改为上面的CMake Build,同时确认目标程序路径无误:
{ "version": "0.2.0", "configurations": [ { "name": "(gdb) Launch", "type": "cppdbg", "request": "launch", "program": "${workspaceFolder}\\build\\MyTinyrender.exe", "args": [], "stopAtEntry": false, "cwd": "${workspaceRoot}", "targetArchitecture": "x86_64", "externalConsole": true, "internalConsoleOptions": "neverOpen", "MIMode": "gdb", "miDebuggerPath": "D:\\LLVM\\bin\\gdb.exe", "preLaunchTask": "CMake Build", "setupCommands": [ { "description": "为 gdb 启用整齐打印", "text": "-enable-pretty-printing", "ignoreFailures": true } ] } ] }
3. 确保CMake生成Debug配置
如果之前CMake是用Release模式生成的,需要在build目录重新生成Debug配置:
打开终端执行以下命令:
cd build cmake .. -DCMAKE_BUILD_TYPE=Debug
额外注意
- 关闭VS Code的
C_Cpp: Auto Build设置,避免自动编译单个源文件干扰流程。 - 首次调试前可手动执行一次
CMake Build任务,确认build/MyTinyrender.exe已更新。
内容的提问来源于stack exchange,提问作者Windy Green
相关产品推荐
相关产品推荐

