Boost python linking

2019-03-25 06:55发布

问题:

I'm adding boost.python for my Game. I write wrappers for my classes to use them in scripts. The problem is linking that library to my app. I'm using cmake build system.

Now I have a simple app with 1 file and makefile for it:

PYTHON = /usr/include/python2.7

BOOST_INC = /usr/include
BOOST_LIB = /usr/lib

TARGET = main

$(TARGET).so: $(TARGET).o
    g++ -shared -Wl,--export-dynamic \
    $(TARGET).o -L$(BOOST_LIB) -lboost_python \
    -L/usr/lib/python2.7/config -lpython2.7 \
    -o $(TARGET).so

$(TARGET).o: $(TARGET).cpp
    g++ -I$(PYTHON) -I$(BOOST_INC) -c -fPIC $(TARGET).cpp

And this works. It builds a 'so' file for me which I can import from python.

Now the question: how to get this for cmake?

I wrote in main CMakeList.txt:

...
find_package(Boost COMPONENTS filesystem system date_time python REQUIRED)
message("Include dirs of boost: " ${Boost_INCLUDE_DIRS} )
message("Libs of boost: " ${Boost_LIBRARIES} )

include_directories(
    ${Boost_INCLUDE_DIRS}
        ...
)

target_link_libraries(Themisto
    ${Boost_LIBRARIES}
    ...
)
...

message calls show:

Include dirs of boost: /usr/include
Libs of boost: /usr/lib/libboost_filesystem-mt.a/usr/lib/libboost_system-mt.a/usr/lib/libboost_date_time-mt.a/usr/lib/libboost_python-mt.a

Ok, so I've added simple .cpp-file for my project with include of <boost/python.hpp>. I get an error at compiling:

/usr/include/boost/python/detail/wrap_python.hpp:50:23: fatal error: pyconfig.h: No such file or directory

So it doesn't take all need include directories.

And second question:

How to organize 2-step building of script-cpp files? In makefile I showed there are TARGET.o and TARGET.so, how to process that 2 commands in cmake?

As I understand, the best way is to create subproject and do something there.

Thanks.

回答1:

You are missing your include directory and libs for python in your CMakeList.txt. Use the PythonFindLibs macro or the same find_package strategy you used for Boost

find_package(Boost COMPONENTS filesystem system date_time python REQUIRED)
message("Include dirs of boost: " ${Boost_INCLUDE_DIRS} )
message("Libs of boost: " ${Boost_LIBRARIES} )

find_package(PythonLibs REQUIRED)
message("Include dirs of Python: " ${PYTHON_INCLUDE_DIRS} )
message("Libs of Python: " ${PYTHON_LIBRARIES} )

include_directories(
    ${Boost_INCLUDE_DIRS}
    ${PYTHON_INCLUDE_DIRS}  # <-------
        ...
)

target_link_libraries(Themisto
    ${Boost_LIBRARIES}
    ${PYTHON_LIBRARIES} # <------
    ...
)
...