我问了另一个问题,这个问题太复杂了,无法直接回答,所以我把它归结为这个基本问题......
当我使用标准的 cython distutils 构建我的 aModule.so
时,它似乎没有链接到 libpython
:
$ otool -L aModule.so
aModule.so:
/usr/local/lib/libboost_thread-mt.dylib (compatibility version 0.0.0, current version 0.0.0)
/usr/local/opt/thrift/lib/libthrift-0.9.0.dylib (compatibility version 0.0.0, current version 0.0.0)
/usr/lib/libstdc++.6.dylib (compatibility version 7.0.0, current version 7.9.0)
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 125.2.11)
但是当我使用 cmake 设置进行构建时,它会不断生成链接器命令,将 libpython
链接到 .so 中:
$ otool -L aModule.so
aModule.so:
/System/Library/Frameworks/Python.framework/Versions/2.7/Python (compatibility version 2.7.0, current version 2.7.1)
/usr/local/opt/thrift/lib/libthrift-0.9.0.dylib (compatibility version 0.0.0, current version 0.0.0)
/usr/local/lib/libboost_thread-mt.dylib (compatibility version 0.0.0, current version 0.0.0)
/usr/lib/libstdc++.6.dylib (compatibility version 7.0.0, current version 52.0.0)
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 159.1.0)
distutils 生成的模块似乎适用于我的任何 python2.7 安装(系统,或我项目的 virtualenv)。而当我尝试使用链接的系统 python 以外的任何东西导入它时,cmake 因版本不匹配而崩溃。
为什么 distutils 模块在没有链接的情况下也能正常工作?如果是这样的话,为什么我需要让 cmake 构建链接 libpython,如果是这样的话我该如何防止它与我的任何 python2.7 解释器一起工作而不会崩溃?
目前,我可以将 cmake 指向正确的 python:CXX=g++ cmake -DPYTHON_LIBRARY=/path/to/another/Python
最佳答案
我意识到问题的根源与 cython-cmake-example
有关以及它的 UseCython.cmake
cython_add_module()
函数会显式地将库链接到 libpython。
由于我不知道这是否是一个完全可移植的解决方案,我最终为自己的使用所做的是向该函数添加一个标志来表示 DYNAMIC_LOOKUP
:
function( cython_add_module _name _dynamic_lookup )
set( pyx_module_sources "" )
set( other_module_sources "" )
foreach( _file ${ARGN} )
if( ${_file} MATCHES ".*\\.py[x]?$" )
list( APPEND pyx_module_sources ${_file} )
else()
list( APPEND other_module_sources ${_file} )
endif()
endforeach()
compile_pyx( ${_name} generated_file ${pyx_module_sources} )
include_directories( ${PYTHON_INCLUDE_DIRS} )
python_add_module( ${_name} ${generated_file} ${other_module_sources} )
### Added here ##
if( ${_dynamic_lookup} )
message( STATUS "Not linking target ${_name} against libpython" )
set_target_properties( ${_name} PROPERTIES LINK_FLAGS "-undefined dynamic_lookup")
else()
target_link_libraries( ${_name} ${PYTHON_LIBRARIES} )
endif()
endfunction()
现在我可以调用 cython_add_module
,它不会链接到 libpython。
关于python - cython-distutils 与 cmake : linking against libpython?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15584144/