I\'m new on Visual Studio Code and Docker. Now I want to use Visual Studio Code to edit my C++ code and Docker to compile/debug.
I don\'t know how to write the launch.js
I set up a minimal working example on GitHub: https://github.com/fschwaiger/docker-cpp-vscode
The idea is as follows, assuming you have the ms-vscode.cpptools
extension:
gcc
and gdb
installed (can be the same)gdb
from within the containergcc
and gdb
gcc
is available directly from Docker Hub: docker pull gcc
. I did not find gdb
there, so there is a Dockerfile to build it:
FROM gcc:latest
RUN apt-get update && apt-get install -y gdb
RUN echo "set auto-load safe-path /" >> /root/.gdbinit
It builds on gcc:latest
and installs gdb
, so you can use the same image to compile and debug. It also sets option set auto-load safe-path /
in /root/.gdbinit
to suppress a warning when running gdb
in the container. Safety should not be a concern for local development.
Build the image using docker build -t gdb .
in the working directory, or in Visual Studio Code run the preconfigured task build docker gdb
from F1 → Run Task.
In the project, run docker run --rm -it -v ${pwd}:/work --workdir /work gcc make debug
from a PowerShell window in the working directory. Using Visual Studio Code, this can be done by the preconfigured task make debug
from F1 → Run Task.
You want to configure Visual Studio Code to run /usr/bin/gdb
from within the container. You can use the pipeTransport
option in launch.json
for that and make it run:
docker run --rm --interactive --volume ${workspaceFolder}:/work --workdir /work --privileged gdb sh -c /usr/bin/gdb
Explanation:
--privileged
: allow binary debugging--volume ${workspaceFolder}:/work --workdir /work
: mount the project folder into the container--rm
: remove the container after exit--interactive
: VSCode will issue interactive commands to the gdb shellsh -c
: defines a shell entrypoint within GDB is runThe overall launch.json
looks like follows. Notice that program
and cwd
are the paths within the container. sourceFileMap
allows the debugger to match the breakpoints with the source files. The rest is the default template stuff from the C++ extension.
{
"version": "0.2.0",
"configurations": [
{
"name": "(gdb) Docker",
"type": "cppdbg",
"request": "launch",
"program": "build/apps/program",
"args": [],
"stopAtEntry": true,
"cwd": "/work",
"environment": [],
"externalConsole": true,
"preLaunchTask": "make debug",
"targetArchitecture": "x64",
"sourceFileMap": { "/work": "${workspaceFolder}" },
"pipeTransport": {
"debuggerPath": "/usr/bin/gdb",
"pipeProgram": "docker.exe",
"pipeArgs": ["run","--rm","--interactive","--volume","${workspaceFolder}:/work","--workdir","/work","--privileged","gdb","sh","-c"],
"pipeCwd": ""
},
"MIMode": "gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
]
}
]
}
With this setup, all you need to do is press play in the debug workspace.