- 参考链接
准备工作
- 安装好Vscode
- 安装好python, python extend, c++, c++ extend插件
- 安装
python C++ Debugger插件 - 安装好gdb, pybind-dev
- 以下代码均适用于ubuntu,理论上windows也可以用,但是需要自行配置一下。
bash
sudo apt install gdb pybind11-dev正式开始
- 在
.vscode目录下新建一个launch.json文件,里面的内容,python环境(programe)和gdb路径(miDebuggerPath)改成你的。
json
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Python C++ Debugger",
"type": "pythoncpp",
"request": "launch",
"pythonLaunchName": "Python: Current File",
"cppAttachName": "(gdb) Attach"
},
{
"name": "(gdb) Attach",
"type": "cppdbg",
"request": "attach",
"program": "/home/tlntin/anaconda3/envs/paddle/bin/python3",
"processId": "",
"MIMode": "gdb",
"miDebuggerPath": "/usr/bin/gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
]
},
{
"name": "Python: Current File",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal"
}
]
}- 对与pybind调用的cpp文件,一般会有makefile储存对应的生成脚本,注意脚本里面是否有-g参数,如果没有,给它加一个。以下面的案例为例:
- 修改前
bash
CXXFLAGS += -O3 -Wall -shared -std=c++11 -fPIC -fdiagnostics-color
CPPFLAGS += $(shell python3 -m pybind11 --includes)
LIBNAME = helpers
LIBEXT = $(shell python3-config --extension-suffix)
default: $(LIBNAME)$(LIBEXT)
%$(LIBEXT): %.cpp
$(CXX) $(CXXFLAGS) $(CPPFLAGS) $< -o $@- 修改后
bash
CXXFLAGS += -g -O3 -Wall -shared -std=c++11 -fPIC -fdiagnostics-color
CPPFLAGS += $(shell python3 -m pybind11 --includes)
LIBNAME = helpers
LIBEXT = $(shell python3-config --extension-suffix)
default: $(LIBNAME)$(LIBEXT)
%$(LIBEXT): %.cpp
$(CXX) $(CXXFLAGS) $(CPPFLAGS) $< -o $@- 在cpp文件中,设置断点,然后,在cpp所在的makefile文件夹,重新执行make,再生成一次so文件(可以先把原so文件删除。)。
- 回到python文件,按F5,开始调试,观察是否跳到cpp文件中,如果是,则说明方案成功。