How configure launch.json in VSCode to debug an unit ctest(cmake) from the new testing explorer view? – Cmake

by
Ali Hasan
c++ cmake ctest launch visual-studio-code

Quick Fix: Add "args": [ "\({cmake.testArgs}" ] to launch.json to debug specific tests, and prefer "\)" over "$" as the program to allow different launch targets.

The Solutions:

Solution 1: Accessing Unit Tests from the Testing Explorer View

To launch unit tests from the Testing Explorer view in Visual Studio Code, modify the launch.json file to use the cmake.testProgram variable as the launch target. This allows you to map the selected test to a single launch configuration. Additionally, include "args": [ "${cmake.testArgs}" ] to specify specific test arguments.

Updated launch.json:

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "(ctest) Launch",
            "type": "lldb",
            "request": "launch",
            "program": "${cmake.testProgram}",
            "args": [ "${cmake.testArgs}" ],
            "initCommands": ["breakpoint set -n main -N entry"],
            "exitCommands": ["breakpoint delete entry"],
            "cwd": "${workspaceRoot}"
        }
    ]
}

GDB

{
    "name": "(ctest) Launch",
    "type": "cppdbg",
    "cwd": "${workspaceRoot}",
    "request": "launch",
    "program": "${cmake.testProgram}",
    "args": [ "${cmake.testArgs}" ],
    // other options...
}

MSVC

{
    "name": "(ctest) Launch",
    "type": "cppvsdbg",
    "request": "launch",
    "program": "${cmake.testProgram}",
    "args": [ "${cmake.testArgs}" ],
    // other options...
}

Solution 2: Configure launch.json with cmake.launchTargetPath

In your launch.json file, define a debug configuration with the following value in the "program" attribute:

"program": "${command:cmake.launchTargetPath}"

This value will be dynamically resolved by the CMake Tools extension to the path of the executable associated with the test item clicked in the Testing Explorer view.

By using this dynamic value, you can have a single launch configuration that handles debugging for all your unit tests, eliminating the need to maintain separate configurations for each test.

Video Explanation:

The following video, titled "Introduction to Google Test and CMake - YouTube", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

I decided to throw in CMake as well and show how to start a new ... My Visual Studio Code Setup for Web Development. ForrestKnight•1M views · 26: ...