Pass Command-Line Arguments When Debugging with CMake In Visual C++


I have a “Hello World” C application created as a Visual C++ CMake project. I debug this project in WSL (Windows Subsystem for Linux) Ubuntu Linux. The project runs fine, but now I need to pass command-line parameters. How can I achieve this?

I found a solution online suggesting to add launchConfigurations to CMakePresets.json:

"launchConfigurations": [
    {
        "name": "Run with arguments",
        "type": "default",
        "args": ["arg1", "arg2", "arg3"], // Arguments for the executable
        "cwd": "${sourceDir}/out/build/${presetName}" // Optional: Set working directory
    }
]

However, this does not work. How can I correctly pass command-line arguments to my executable?

Content of CMakeList.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()

part of 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
        }
      ]
    }
  }
},

Leave a Reply

Your email address will not be published. Required fields are marked *