在Visual C++的CMake项目中调试WSL程序时传递命令行参数
为WSL Ubuntu中Visual C++ CMake项目传递命令行参数
问题背景
我创建了一个基于Visual C++的CMake项目(C语言"Hello World"程序),在WSL Ubuntu系统中调试运行正常,但需要传递命令行参数时,网上找到的在CMakePresets.json中添加launchConfigurations的方案无效,求正确实现方式。
我的CMakeLists.txt内容:
cmake_minimum_required (VERSION 3.8) # Enable Hot Reload for MSVC compilers if supported. if (POLICY CMP0141) cmake_policy(SET CMP0141 NEW) set(CMAKE_MSVC_DEBUG_INFORMATION_FORMAT "$<IF:$<AND:$<C_COMPILER_ID:MSVC>,$<CXX_COMPILER_ID:MSVC>>,$<$<CONFIG:Debug,RelWithDebInfo>:EditAndContinue>,$<$<CONFIG:Debug,RelWithDebInfo>:ProgramDatabase>>") endif() project ("pThread4") add_executable (t1 "t1.c") target_link_libraries(t1 PRIVATE pthread) if (CMAKE_VERSION VERSION_GREATER 3.12) set_property(TARGET pThread4 PROPERTY CXX_STANDARD 20) endif()
CMakePresets.json相关片段:
{ "name": "linux-debug", "displayName": "Linux Debug", "generator": "Ninja", "binaryDir": "${sourceDir}/out/build/${presetName}", "installDir": "${sourceDir}/out/install/${presetName}", "cacheVariables": { "CMAKE_BUILD_TYPE": "Debug" }, "condition": { "type": "equals", "lhs": "${hostSystemName}", "rhs": "Linux" }, "vendor": { "microsoft.com/VisualStudioRemoteSettings/CMake/1.0": { "sourceDir": "$env{HOME}/.vs/$ms{projectDirName}", "launchConfigurations": [ { "name": "Run with arguments", "type": "default", "args": [ "arg1", "arg2", "arg3" ], // Arguments for the executable "cwd": "${sourceDir}/out/build/${presetName}" // Optional: Set working directory } ] } } },
问题原因
之前的launchConfigurations配置缺少目标可执行文件的指定,且针对WSL远程调试场景,配置类型和结构不符合要求,导致调试器无法正确关联到你的t1可执行文件。
正确解决方案
方案1:修正CMakePresets.json的launch配置
调整launchConfigurations结构,明确指定调试目标和适配WSL的调试器类型:
{ "name": "linux-debug", "displayName": "Linux Debug", "generator": "Ninja", "binaryDir": "${sourceDir}/out/build/${presetName}", "installDir": "${sourceDir}/out/install/${presetName}", "cacheVariables": { "CMAKE_BUILD_TYPE": "Debug" }, "condition": { "type": "equals", "lhs": "${hostSystemName}", "rhs": "Linux" }, "vendor": { "microsoft.com/VisualStudioRemoteSettings/CMake/1.0": { "sourceDir": "$env{HOME}/.vs/$ms{projectDirName}", "launchConfigurations": [ { "name": "t1 with args", "type": "cppvsdbg", // 适配WSL远程调试的类型 "target": "${binaryDir}/t1", // 指定编译生成的可执行文件路径 "args": ["arg1", "arg2", "arg3"], "cwd": "${binaryDir}" } ] } } }
type设为cppvsdbg:这是Visual Studio针对Linux/WSL远程调试的标准调试器类型,替代原有的default可确保识别。target必须明确指向t1可执行文件,让调试器知道要启动的程序。
方案2:在Visual Studio调试界面直接设置
如果使用Visual Studio开发:
- 点击顶部工具栏的调试目标选择框(默认显示
t1或项目名),选择**"管理调试配置"**。 - 在弹出的"调试启动设置"窗口中,找到你的Linux调试预设,点击**"编辑"**。
- 在配置编辑界面的"命令参数"输入框中,填入需要的参数(如
arg1 arg2 arg3),保存即可。 - 启动调试时,参数会自动传递给程序。
方案3:WSL终端手动运行传参
若无需通过Visual Studio调试,直接在WSL终端操作:
- 进入编译生成的可执行文件目录:
cd /path/to/your/project/out/build/linux-debug - 运行程序时直接追加参数:
./t1 arg1 arg2 arg3
额外注意事项
你的CMakeLists.txt最后一行存在错误:可执行目标是t1而非pThread4,且项目为C语言,应使用C_STANDARD而非CXX_STANDARD,修正如下:
if (CMAKE_VERSION VERSION_GREATER 3.12) set_property(TARGET t1 PROPERTY C_STANDARD 11) endif()
内容的提问来源于stack exchange,提问作者vico
相关产品推荐
相关产品推荐

