2

I am trying to build a hello world C++ Python extension using boost-python.

I got the following source code from https://www.mantidproject.org/Boost_Python_Introduction:

 // test.cpp
 #include <iostream>
 #include <boost/python.hpp>


 void sayHello()
 {
   std::cout << "Hello, Python!\n";
 }

 BOOST_PYTHON_MODULE(test)  // Name here must match the name of the final shared library, i.e. mantid.dll or mantid.so
 {
    boost::python::def("sayHello", &sayHello);
 }

However, when I try to compile using the following command:

g++ -fPIC -I/usr/include/python3.6m test.cpp -c
g++ -shared test.o -o test.so -I/usr/include/python3.6m -I/lib64/libboost_python3

This command compiles successfully the code and creates a library file test.so.

However, when I try to import the module in python3, I get the following error:

ImportError: /home/yt/C++/test.so: undefined symbol: _ZNK5boost6python7objects21py_function_impl_base9max_arityEv

The link Import Error on boost python hello program seems to suggest the command I used above would solve the problem by adding -I/usr/include/python3.6m and -I/lib64/libboost_python3, but it does not.

What am I doing wrong?

Thanks!

OS: Fedora 29 x86_64

PintoDoido
  • 1,011
  • 16
  • 35
  • 1
    I think your linker flags should be `-l` (lower-case L) not `-I` (upper-case I). Includes don't make sense on a link line, and the error you're getting is a result of missing linker symbols. – metal Apr 01 '19 at 13:20
  • Thanks. However, doing **g++ -L/lib64 -shared test.o -o test.so -l python3.6 -l libboost_python3** results in the errors: **/usr/bin/ld: cannot find -lpython3.6 /usr/bin/ld: cannot find -llibboost_python3** – PintoDoido Apr 01 '19 at 13:43
  • 1
    `-L` is for library paths, `-l` is for libraries themselves, and you typically omit the `lib` prefix and `.so` suffix. That would mean your flags should be something like `-lpython3.6 -lboost_python3`. – metal Apr 01 '19 at 13:50
  • 1
    Check your /lib64 directory for boost_python3 library existance. In my case library name is libboost_python.so. But I built it from the source code and didn't install it to the system folders. – Dmitry Apr 01 '19 at 13:53

1 Answers1

1

Thanks guys!

The problem was the linker command. The correct one is:

g++ -fPIC -I/usr/include/python3.6m test.cpp -c

g++ -L /lib64 -shared test.o -o test.so -lpython3.6m -lboost_python3

Now it works on Fedora 29

PintoDoido
  • 1,011
  • 16
  • 35