[pybind11] debug C++代码

首先要有一个项目,我发布在github上了【传送门

项目的结构如下:

其中src目录下是C++代码,test.py是python测试代码。

然后直接开始演示。

1、把项目下载到本地

bash 复制代码
git clone --recursive https://github.com/immortalmin/pybind11_debug_eg.git

2、修改CMakeLists.txt(包括当前项目和pybind11),各添加两行代码

当前项目:

python 复制代码
# pybind_debug_eg/CMakeLists.txt
cmake_minimum_required(VERSION 3.4...3.18)
project(cmake_example)

# ------- 添加这两行 -------
set(CMAKE_BUILD_TYPE Debug)
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -g")

add_library(mymath STATIC src/mymath.cpp)
set_target_properties(mymath PROPERTIES POSITION_INDEPENDENT_CODE ON)

add_subdirectory(pybind11)
pybind11_add_module(cmake_example src/binder.cpp)
target_link_libraries(cmake_example PRIVATE mymath)

pybind11:

python 复制代码
# pybind11_debug_eg/pybind11/CMakeLists.txt
...
cmake_minimum_required(VERSION 3.5)

# ------- 添加这两行 -------
set(CMAKE_BUILD_TYPE Debug)
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -g")

# The `cmake_minimum_required(VERSION 3.5...3.26)` syntax does not work with
# some versions of VS that have a patched CMake 3.11. This forces us to emulate
# the behavior using the following workaround:
if(${CMAKE_VERSION} VERSION_LESS 3.26)
  cmake_policy(VERSION ${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION})
else()
  cmake_policy(VERSION 3.26)
endif()
...

3、编译项目

bash 复制代码
# 1.先切换回项目的根目录
# 2.
mkdir build; cd build
# 3.-DPYTHON_EXECUTABLE是python的路径
cmake .. -DPYTHON_EXECUTABLE=/Users/username/miniconda3/bin/python
# 4.
cd ..
python setup.py build_ext --inplace
# 然后就生成了一个.so文件

4、测试编译是否正常

bash 复制代码
# 在项目根目录执行
python test.py

# 输出结果:
# i: 1, j: 2
# 3

5、debug

bash 复制代码
# 1.运行ipython。没安装的直接运行 pip install ipython
ipython
# 2.进入ipython后,运行下面的命令,找到ipython的pid。假设为11003
In [1]: !ps aux | grep -i ipython

另外打开一个终端

bash 复制代码
# 1.运行lldb
lldb
# 2.进入lldb后
(lldb) attach --pid 11003
# 3.
(lldb) c
# 4.在想要debug的地方打上断点
(lldb) breakpoint set -f mymath.cpp -l 5

返回第一个终端

bash 复制代码
# 执行test.py
run test.py

你会发现卡住了,这时候第二个终端就会显示debug的画面

参考博客与视频:
Debugging C/C++ libraries called by Python
Using C++ in python with pybind11 and cmake

相关推荐
倒头就睡的小比特18 小时前
算法竞赛C++常用的STL
c++·算法
默_笙18 小时前
🍙 给每个请求过安检:FastAPI 是怎么把校验写进类型注解的
python
weilx123418 小时前
C++笔记-文件IO-<fcntl.h>
c++
qq_4260039618 小时前
启动playwright录制codegen生成自动化测试脚本
python·自动化
虎头金猫18 小时前
4K 视频总卡在公网带宽?用 N1 + OpenList 把网盘播放链路重新理顺
运维·服务器·网络·python·容器·beautifulsoup·pandas
长沙三为智能科技19 小时前
家政小程序开发从0到上线:五阶段交付流程与验收清单
python
伞伞悦读19 小时前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
Smileyqp沛沛20 小时前
前端?C++ ?较大差异基础罗列
c++·基础·前端转c++
只睡四小时20 小时前
Canvas 弹道联机实战:700 行 + 固定时间步长
python·websocket·html5·游戏开发·canvas
C语言小火车20 小时前
C/C++ 为什么需要编译器?
开发语言·c++