此答案假定您没有尝试对多个容器执行任何操作...我假设您只想使用单个容器来构建一些 C++ 代码,并且您的所有代码都在一个名为C:\vsc_docker_cc_gdb。我还假设您在 Visual Studio Code 中安装了 Microsoft 的 C++ 和 Docker 扩展。
让我们从一个名为 hello.cc 的简单 C++ 文件开始:
#include <iostream>
int main(int argc, char **argv) {
std::cout << "Hello from Docker" << std::endl;
}
让我们也添加一个 Makefile:
CXXFLAGS = -O3 -ggdb -m64
LDFLAGS = -m64
all: hello.exe
.PRECIOUS: hello.exe hello.o
.PHONY: all clean
%.o: %.cc
$(CXX) -c $< -o $@ $(CXXFLAGS)
%.exe: %.o
$(CXX) $^ -o $@ $(LDFLAGS)
clean:
rm -f hello.o hello.exe
这是一个通过添加 GDB 和 gdbserver 扩展 gcc:latest 的 Dockerfile(注意:我不确定是否需要 gdbserver):
FROM gcc:latest
LABEL Name=vsc_docker_cc_gdb Version=0.0.2
RUN apt-get -y update
RUN apt-get -y install gdb gdbserver
WORKDIR /root
这里是 .vscode/tasks.json:
{
"version": "2.0.0",
"tasks": [
{
"label": "build (in container)",
"type": "shell",
"command": "docker run --privileged -v c:/vsc_docker_cc_gdb/:/root vsc_docker_cc_gdb make",
"group": {
"kind": "build",
"isDefault": true
},
"problemMatcher": {
"owner": "cpp",
"fileLocation": [
"relative",
"${workspaceFolder}"
],
"pattern": {
"regexp": "^(.*):(\\d+):(\\d+):\\s+(warning|error):\\s+(.*)$",
"file": 1,
"line": 2,
"column": 3,
"severity": 4,
"message": 5
}
}
},
{
"label": "clean (in container)",
"type": "shell",
"command": "docker run --privileged -v c:/vsc_docker_cc_gdb/:/root vsc_docker_cc_gdb make clean",
"group": "build",
"problemMatcher": []
},
{
"label": "remove containers",
"type": "shell",
"command": "docker ps -a -q | % { docker rm $_ }",
"problemMatcher": []
},
{
"label": "run the code",
"type": "shell",
"command": "docker run --privileged -v c:/vsc_docker_cc_gdb/:/root vsc_docker_cc_gdb ./hello.exe",
"group": "build",
"problemMatcher": []
},
{
"label": "prepare to debug",
"type": "shell",
"command": "docker run --privileged -v c:/vsc_docker_cc_gdb/:/root --name debug_vsc -it vsc_docker_cc_gdb ",
"group": "build",
"problemMatcher": []
}
]
}
最后,.vscode/launch.json:
{
"version": "0.2.0",
"configurations": [{
"name": "(gdb) Pipe Launch",
"type": "cppdbg",
"request": "launch",
"program": "/root/hello.exe",
"cwd": "/root",
"args": [],
"stopAtEntry": true,
"environment": [],
"externalConsole": true,
"pipeTransport": {
"debuggerPath": "/usr/bin/gdb",
"pipeProgram": "docker.exe",
"pipeArgs": ["exec", "-i", "debug_vsc", "sh", "-c"],
"pipeCwd": "${workspaceRoot}"
},
"MIMode": "gdb",
"setupCommands": [{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}]
}, ]
}
这里有两件重要的事情。首先是您会注意到launch.json 的部分引用容器中的路径(/root/),而其他部分引用Windows 主机上的路径(workspaceRoot)。这很重要。
第二个是你需要有一个容器运行,然后你可以启动一个调试进程进入它。这是从零开始到启动该特殊容器并在其中启动调试器的方法。
- 来自 PowerShell:
docker pull gcc
- 来自 Visual Studio 代码:F1,Docker:构建映像(选择 vsc_docker_cc_gdb:latest)
- 从 Visual Studio 代码:Ctrl + Shift + B 构建代码
- 来自 Visual Studio 代码:F1,任务:运行任务(选择“删除容器”)
- 来自 Visual Studio 代码:F1,任务:运行任务(选择“准备调试”)
- 从 Visual Studio 代码:F5 启动调试器
从那里,Visual Studio Code Debug Console 应该可以工作了,您应该能够设置断点、观察变量和输入调试命令。