Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boost.Python and CMake Link and Load Errors

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.

like image 740
Travis Gockel Avatar asked May 01 '11 20:05

Travis Gockel


1 Answers

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?

like image 161
Travis Gockel Avatar answered Nov 15 '22 21:11

Travis Gockel