7

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.

1 Answer 1

10

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?

Sign up to request clarification or add additional context in comments.

1 Comment

thanks for posting the answer after you found it yourself, which solved my problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.