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

后端 未结 1 1094
陌清茗
陌清茗 2021-02-08 04:45

I am implementing a C++ program that uses python/C++ Extensions. As of now I am explicitly linking my program to python static library I compiled. I am wondering is there any wa

1条回答
  •  隐瞒了意图╮
    2021-02-08 05:44

    Yes. There is a command line utility called python-config:

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

    For linkage purposes, you have to invoke it with --ldflags parameter. It will print a list of flags you have to pass to the linker (or g++) in order to link with system installed python libraries:

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

    It also can give you flags to compilation with --cflags parameter:

    $ 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 test.cpp file, then you can do something like this in order to compile and link:

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

    That will link your program with shared libraries. If you want to go static, you can pass -static option to the linker. But that will link with all static stuff, including a runtime. If you want to go just with static python, you have to find those libraries yourself. One of the option is to parse python-config --ldflags output and look for libraries with .a extensions. But I'd rather stick to all dynamic or all static.

    Hope it helps. Good luck!

    0 讨论(0)
提交回复
热议问题