Pybind11绑定Protobuf时导入.so文件遇未定义符号错误求助
问题解决:导入pybind11扩展时出现Protobuf未定义符号错误
错误原因
你遇到的undefined symbol: _ZN6google8protobuf8internal26fixed_address_empty_stringB5cxx11E错误,说明你的Python扩展模块编译时未正确链接Google Protobuf库。虽然你配置了Protobuf的头文件路径(include_dirs),但链接阶段缺少Protobuf库文件的引用,导致运行时找不到对应的符号。
解决方案
修改setup.py,在Extension配置中添加链接Protobuf库的参数,若Protobuf库不在系统默认搜索路径,还需指定库文件目录。
修改后的setup.py代码
import os, sys from distutils.core import setup, Extension from distutils import sysconfig cpp_args = ['-std=c++11'] ext_modules = [ Extension( 'pybindx', ['class1.cpp', 'class2.cpp', 'base_class1.cpp', 'base_class2.cpp', 'pybindx.cpp'], include_dirs=['paths/to/include/header/files', 'path/to/protobuf/include'], # 若Protobuf库不在系统默认目录,添加库文件搜索路径 library_dirs=['path/to/protobuf/lib'], language='c++', extra_compile_args = cpp_args, # 添加链接Protobuf库的参数 extra_link_args=['-lprotobuf'], ), ] setup( name='pybindx', version='0.0.1', author='xxxxx', author_email='xxxxx', description='desc', ext_modules=ext_modules, )
关键修改说明
library_dirs=['path/to/protobuf/lib']:替换为你实际的Protobuf库文件所在目录(如手动编译Protobuf后的lib目录),若Protobuf是通过系统包管理器(如apt、yum)安装的,可省略此参数。extra_link_args=['-lprotobuf']:告知链接器需要链接Protobuf的动态库(libprotobuf.so)或静态库(libprotobuf.a)。
后续操作
- 删除之前的编译产物:移除
build目录和已生成的.so文件 - 重新编译:执行
python setup.py build_ext --inplace(--inplace会将.so文件生成在当前目录,方便测试) - 再次运行
test.py尝试导入模块
内容的提问来源于stack exchange,提问作者Irrepressible_sa1
相关产品推荐
相关产品推荐

