I have a main.cpp
like so:
#include <boost/python.hpp>
const char* greeting()
{
return "Hello world?";
}
BOOST_PYTHON_MODULE(test)
{
using namespace boost::python;
def("greeting", greeting);
}
And a CMakeLists.txt
file:
project(test)
cmake_minimum_required(VERSION 2.8)
# get boost
set(Boost_USE_STATIC_LIBS ON)
set(Boost_USE_MULTITHREADED ON)
find_package(Boost COMPONENTS
system
thread
python
REQUIRED)
include_directories(${Boost_INCLUDE_DIRS})
link_directories(${Boost_LIBRARY_DIRS})
# get python
find_package(PythonLibs REQUIRED)
include_directories(${PYTHON_INCLUDE_DIRS})
link_directories(${PYTHON_LIBRARIES})
add_library(test SHARED
main.cpp
)
I can run cmake
and make
just fine. It outputs a nice little libtest.so
file for me. To test it out, I have a Python script like so:
import libtest
print(libtest.greeting())
Running this in the same directory as libtest.so
gives the following error:
Traceback (most recent call last):
File "test.py", line 1, in <module>
import libtest
ImportError: /home/travis/projects/boost-python-test/build/libtest.so: undefined symbol: _ZNK5boost6python7objects21py_function_impl_base9max_arityEv
Yikes! The problem is pretty clear with make VERBOSE=1
...the line creating my libtest.so
looks like this:
/usr/bin/c++ -fPIC -shared -Wl,-soname,libtest.so -o libtest.so CMakeFiles/test.dir/main.cpp.o -L/usr/lib/libpython2.7.so
I'm having a mental block as to why I do not see an -L/usr/lib/libboost_python-mt-py27.a
on that line. It clearly worked for find_package(PythonLibs ...)
. I'm falling short due to some CMake newbishness.
The solution to this is quite simple. One has to explicitly link the libraries with target_link_libraries
after the add_library
statement.
target_link_libraries(test
${Boost_LIBRARIES}
${PYTHON_LIBRARIES}
)
I'm still not sure why it worked for Python without that. Magic?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With