Search code examples
pythonc++boostcompiler-errorsembedding

g++ -shared argument seems to be causing a segmentation fault


I am just getting started learning cpp, coming from a background in python and java. A few days ago I decided to try and mess around with python embedding in cpp using boost. I got the library installed, and I tried for a long time to get it working. However, no matter what I did, I kept running into a segmentation fault. At first I just assumed that I was doing something wrong with including the library, but eventually, I discovered that I still got the segfault even after removing all of the code related to boost from my program. I even converted the program into a simple hello world and still got the segfault! Here is what my program looks like now:

//#include <boost/python.hpp>
//#include <Python.h>
//using namespace boost::python;

#include <iostream>
using namespace std;

int main() {

  //Py_Initialize();
  cout << "Test";
}

I compiled the code using these two commands:

gcc -c boost.cpp -o boost.o -fPIC
g++ boost.o -o boost -shared

and this is the output of running the compiled program:

Segmentation fault

Upon further messing around, I discovered that if I removed the -shared argument:

g++ boost.o -o boost

The program would run as expected. This would be fine, except that in order to include the boost library the compiler needs this argument. If I attempt to uncomment the #include <boost/python.hpp> line in my code and recompile without the -shared argument, I get this error:

boost.o: In function `boost::python::api::object::object()':
boost.cpp: (.text._ZN5boost6python3api6objectC2Ev[_ZN5boost6python3api6objectC5Ev]+0x14): undefined reference to `_Py_NoneStruct'
collect2: error: ld returned 1 exit status

I have no idea what is going on. I am doing this on ubuntu, and I installed boost by using this command:

sudo apt-get install libboost-all-dev

I am still relatively new to cpp, so if I have done something completely stupid, feel free to let me know! Thanks in advance for any help!


Solution

  • You don't need -shared to link with the boost libraries. You need to add the python libraries too to resolve the undefined reference to _Py_NoneStruct.

    Note that the order of the libraries is important:

     g++ boost.cpp -o boost -lboost_python38 -lpython3.8
    

    Here I've added the boost_mpi_python libraries too in case you need them:

    g++ boost.cpp -o boost -lboost_mpi_python38 -lboost_mpi -lboost_serialization -lboost_python38 -lpython3.8
    

    Replace 3.8 (and 38) with the actual version you have on your system.