Python - Py_Initialize 在编译期间未解决

2024-01-29

我已经静态编译了Python2.7,没有任何错误。 为了测试我的构建,我使用以下代码片段:

#include "Python.h"
int main()
{
   Py_Initialize();
}

我这样编译它:

$ gcc -static -I/path/to/python/header -L/path/to/my/staticpythonlib \ 
 -lpython2.7 -ldl -l_all_other_needed_lib /tmp/my_previous_snippet.c -o myouput

然而,出现了错误。海湾合作委员会声称著名undefined reference.

test.c:(.text+0x1): 对“Py_Initialize”的未定义引用

奇怪的是,我使用带有详细标志的 gcc(我不会在此处粘贴结果),编译器说,它正在使用我的 libpython,但找不到参考。所以我列出了静态 python2.7 库的符号:

$ nm /path/to/pythonlib |grep Py_Initialize
frozenmain.o           U Py_Initialize
pythonrun.o  0000009e9 T Py_Initialize
pythonrun.o  000000052 T Py_Initialize_Ex
main.o                 U Py_Initialize

我们可以看到,那Py_Initialize在 pythonrun.o 中正确引用。但是我不知道编译器如何选择正确的目标文件。

我的问题是:

  1. 我如何确定 gcc 在我的 .a lib 中使用正确的目标文件?
  2. 我的编译选项有问题吗?

感谢您的帮助。


顺序很重要!更具体地说,gcc 参数中的顺序很重要。更具体地说,如果bar对象使用函数bluh从图书馆bleh,然后顺序-lbleh bar.o是有问题的,因为它没有提供 gcc 查找该函数的理由bluh in bleh。另一方面,当您使用bar.o -lbleh那么 gcc 知道你指的是bluh当它开始处理时-lbleh它试图解决依赖性。这很快就被提到了http://gcc.gnu.org/onlinedocs/gcc/Link-Options.html http://gcc.gnu.org/onlinedocs/gcc/Link-Options.html。通常,始终在对象之后指定库。

要重现您的问题,请创建一个文件a1.c as in:

#include "Python.h"

int main()
{
    Py_Initialize();
    return 0;
}

现在编译gcc -static -I/usr/include/python2.7 -L/usr/lib/python2.7/config/ -lpython2.7 -ldl -lm -lutil -lz -pthread -o a1 a1.c。这给出了未定义的引用Py_Initialize。当然,您必须更改路径以匹配您的安装。

现在,改为编译gcc -static -I/usr/include/python2.7 -L/usr/lib/python2.7/config/ -o a1 a1.c -lpython2.7 -ldl -lm -lutil -lz -pthread它有效(忽略可能的许多警告,这是另一回事)。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python - Py_Initialize 在编译期间未解决 的相关文章

随机推荐