将Python嵌入C语言后,链接失败,并带有未定义的对`Py_Initialize'的引用 [英] Embedding Python in C, linking fails with undefined reference to `Py_Initialize'
问题描述
我正在尝试从docs https://docs.python编译该示例. org/2.7/extending/embedding.html ,而我的代码与5.1下的代码完全相同:
I am trying to compile the example from the docs https://docs.python.org/2.7/extending/embedding.html and my code looks exactly like the one under 5.1:
#include <Python.h>
int
main(int argc, char *argv[])
{
Py_SetProgramName(argv[0]);
Py_Initialize();
PyRun_SimpleString("from time import time, ctime\n"
"print 'Today is', ctime(time())\n");
Py_Finalize();
return 0;
}
我使用以下命令对其进行编译,该命令对我而言效果很好,并为我提供了所需的目标文件:
I use the following command to compile it which works fine for me and gives me the desired object file:
gcc -c $(python2.7-config --cflags) embedpy.c
要链接它,我使用以下命令,最终出现以下错误:
To link it I use the following command which ends up in the following error:
gcc $(/usr/bin/python2.7-config --ldflags) embedpy.o
embedpy.o: In function `main':
/home/miguellissimo/embedpy.c:6: undefined reference to `Py_SetProgramName'
/home/miguellissimo/embedpy.c:7: undefined reference to `Py_Initialize'
/home/miguellissimo/embedpy.c:8: undefined reference to `PyRun_SimpleStringFlags'
/home/miguellissimo/embedpy.c:11: undefined reference to `Py_Finalize'
collect2: error: ld returned 1 exit status
我无法找出我做错了什么,或者忘记了如何使示例正常工作.
I can't find out what I am doing wrong or what I forget to get the example working.
PS:python2.7-config命令在我的Xubuntu机器上提供以下输出:
PS: The python2.7-config command gives the following output on my Xubuntu machine:
>>> python2.7-config --cflags
-I/usr/include/python2.7 -I/usr/include/x86_64-linux-gnu/python2.7 -fno-stri
ct-aliasing -D_FORTIFY_SOURCE=2 -g -fstack-protector --param=ssp-buffer-size=
4 -Wformat -Werror=format-security -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-pr
ototypes
>>> python2.7-config --ldflags
-L/usr/lib/python2.7/config-x86_64-linux-gnu -L/usr/lib -lpthread -ldl -luti
l -lm -lpython2.7 -Xlinker -export-dynamic -Wl,-O1 -Wl,-Bsymbolic-functions
推荐答案
链接时,库必须位于目标文件之后,
Libraries have to come after the object files when you are linking, so do:
gcc embedpy.o $(/usr/bin/python2.7-config --ldflags)
这篇关于将Python嵌入C语言后,链接失败,并带有未定义的对`Py_Initialize'的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!