Python - Py_Initialize 在编译期间未解析

标签 python gcc static-libraries unresolved-external

我已经静态编译了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

但是,发生了错误。 gcc 声明了著名的 undefined reference

test.c:(.text+0x1): Undefined reference to '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

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

我的问题是:

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

感谢您的帮助。

最佳答案

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

要重现您的问题,请创建文件 a1.c,如下所示:

#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 的 undefined reference 。当然,您必须更改路径以匹配您的安装。

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

关于Python - Py_Initialize 在编译期间未解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13782618/

相关文章:

c++ - 如何提高 Visual C++ 编译时间?

linux - 我如何告诉 cmake 我希望我的项目静态链接库?

c - 在 Windows 10 cmd 提示符下将 crypt() 库添加到 C 程序

Python 选择器库 - 如何在同一个套接字上发送两种方式?

python - 在python中同步2个线程

python - while i 和 j/while j 和 i 在 python 中的区别

c - Linux 上 CLion 中的数学库链接错误

python - wxPython:如何正确选择CListCtrl项?

c - Cygwin 的 GCC 与 Windows 上的 MSVC 编译器之间是否存在任何性能问题?

ios - 在静态库中使用 ALAssetsLibrary 时无法枚举组/结果