简体   繁体   English

如何将python静态库与我的c ++程序链接起来

[英]how to link python static library with my c++ program

I am implementing a C++ program that uses python/C++ Extensions. 我正在实现一个使用python / C ++ Extensions的C ++程序。 As of now I am explicitly linking my program to python static library I compiled. 截至目前,我明确地将我的程序链接到我编译的python静态库。 I am wondering is there any way to link my program with system installed python(i mean the default python installation that comes with linux) 我想知道有没有办法将我的程序与系统安装的python链接(我的意思是linux附带的默认python安装)

Yes. 是。 There is a command line utility called python-config : 有一个名为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. 出于链接目的,您必须使用--ldflags参数调用它。 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: 它将打印您必须传递给链接器(或g++ )的标志列表,以便与系统安装的python库链接:

$ 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: 它还可以为您提供使用--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 test.cpp file, then you can do something like this in order to compile and link: 假设你在test.cpp文件中有一个测试程序,那么你可以做这样的事情来编译和链接:

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. 如果要转为静态,可以将-static选项传递给链接器。 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. 如果你想只使用静态python,你必须自己找到这些库。 One of the option is to parse python-config --ldflags output and look for libraries with .a extensions. 其中一个选项是解析python-config --ldflags输出并查找带有.a扩展名的库。 But I'd rather stick to all dynamic or all static. 但我宁愿坚持所有动态或全静态。

Hope it helps. 希望能帮助到你。 Good luck! 祝好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM