How to link python static library with my c ++ program

I am implementing a C ++ program that uses python / C ++ extensions. At the moment, I am explicitly binding my program to the python static library that I compiled. I am wondering if there is a way to associate my program with the installed python system (I mean the default python installation that comes with Linux)

+6
python
source share
1 answer

Yes. The command line utility is called python-config :

 Usage: /usr/bin/python-config [--prefix|--exec-prefix|--includes|--libs|--cflags|--ldflags|--help] 

For snapping purposes, you must invoke it with the --ldflags . It will print a list of flags that you must pass to the linker (or g++ ) to associate with the python libraries installed on the system:

 $ python-config --ldflags -L/usr/lib/python2.6/config -lpthread -ldl -lutil -lm -lpython2.6 

It can also provide you with flags for compilation with the --cflags :

 $ python-config --cflags -I/usr/include/python2.6 -I/usr/include/python2.6 -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes 

Say you have a test program in the test.cpp file, then you can do something like this to compile and link:

 g++ $(python-config --cflags) -o test $(python-config --ldflags) ./test.cpp 

This will link your program with shared libraries. If you want to be static, you can pass the -static option to the linker. But this will be related to all static things, including the runtime. If you want to go only with static python, you have to find these libraries yourself. One option is to parse the output of python-config --ldflags and search for libraries with .a extensions. But I would prefer to stick to all dynamic or all static.

Hope this helps. Good luck

+14
source share

All Articles