'Visual Studio Code - Launching GDB in specific directory

I just have a quick question:

EDIT: This is run under Ubuntu 20.04 WSL2 using Visual Studio Code.

So I am debugging a kernel for gdb and the symbol files require that GDB is launched in the project directory, but the problem is GDB keep launching in the location of the program:

-exec pwd
Working directory /home/user/project-directory/obj/kern

I need GDB to stay in the project-directory:/home/user/project-directory

In the VSCode launch.json file, I made a workaround by adding a custom launch setup as shown below:

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Debug Kernel",
            "type": "cppdbg",
            "request": "launch",
            "program": "${workspaceRoot}/obj/kern/kernel",
            "args": [],
            "stopAtEntry": false,
            "cwd": "${workspaceFolder}",
            "environment": [],
            "externalConsole": false,
            "MIMode": "gdb",
            "printCalls": true, 
            "showDevDebugOutput": true, 
            "setupCommands": [
                {
                    "description": "Change back to the workspace folder",
                    "text": "cd ${workspaceRoot}",
                    "ignoreFailures": true
                },
                {
                    "description": "Enable pretty-printing for gdb",
                    "text": "-enable-pretty-printing",
                    "ignoreFailures": true
                }
            ],
            // "preLaunchTask": "Launch Qemu (no graphic)",
            "miDebuggerPath": "/usr/bin/gdb",
            "miDebuggerArgs": "",
            "targetArchitecture": "x86_64",
            "customLaunchSetupCommands": [
                {
                    "text": "target remote localhost:1234",
                    "description": "Connect to QEMU remote debugger"
                },
                {
                    "text": "symbol-file obj/kern/kernel",
                    "description": "Get kernel symbols"
                },
                // {
                //     "text": "set architecture i8086",
                //     "description": "Sets the current architecture"
                // }
            ],
            "avoidWindowsConsoleRedirection": true
        }
    ]
}

The ${workspaceFolder} and ${workspaceRoot} are located in the project's directory, but without the setup to change back into the workspace folder, it won't work. Any tips would be appreciated!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source