python - 在 C 中嵌入 Python,链接失败, undefined reference `Py_Initialize'

标签 python c python-c-extension

我正在尝试编译文档中的示例 https://docs.python.org/2.7/extending/embedding.html我的代码看起来和 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;
}

我使用以下命令对其进行编译,这对我来说效果很好,并为我提供了所需的目标文件:

gcc -c $(python2.7-config --cflags) embedpy.c

为了链接它,我使用了以下命令,但最终出现以下错误:

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

我无法找出我做错了什么或我忘记让示例正常工作的地方。

PS:python2.7-config 命令在我的 Xubuntu 机器上给出了以下输出:

>>> 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 

最佳答案

链接时库必须在目标文件之后,所以:

gcc  embedpy.o $(/usr/bin/python2.7-config --ldflags)

关于python - 在 C 中嵌入 Python,链接失败, undefined reference `Py_Initialize',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27672572/

相关文章:

objective-c - 如何在 LAPACK 中找到完整形式的 sgesv

c - C语言中的迭代函数有什么作用?

c++ - Codeblocks 中的图形程序

python - 如何为不同操作系统/Python 版本编译 Python C/C++ 扩展?

python - 使用python更改CSV文件中列的值

python - 用 Python 打包数据

比较字符串和 strftime 值时,运算符中的 Python 无法按预期工作

python - 如何获得发送者开始和结束的索引?

python - 如何从 C 扩展引发 Python 异常

Python:返回多个值的 C++ 扩展