在 gcc 中链接 Python 3.8 库时出现问题

我正在尝试编译嵌入 Python 的示例 C 应用程序(来自此处 https://docs.python.org/3.8/extending/embedding.html

#define PY_SSIZE_T_CLEAN
#include <Python.h>

int
main(int argc,char *argv[])
{
    wchar_t *program = Py_DecodeLocale(argv[0],NULL);
    if (program == NULL) {
        fprintf(stderr,"Fatal error: cannot decode argv[0]\n");
        exit(1);
    }
    Py_SetProgramName(program);  /* optional but recommended */
    Py_Initialize();
    PyRun_SimpleString("from time import time,ctime\n"
                       "print('Today is',ctime(time()))\n");
    if (Py_FinalizeEx() < 0) {
        exit(120);
    }
    PyMem_RawFree(program);
    return 0;
}

我正在使用由 python3.8-config 生成的 gcc 选项。 因此,编译和链接如下:

gcc $(python3.8-config --cflags) -c embePy.c -o embePy.o

gcc $(python3.8-config --ldflags) -o embePy.o

编译很顺利,但是链接会报错:

/usr/bin/ld: /usr/lib/gcc/x86_64-linux-gnu/9/../../../x86_64-linux-gnu/Scrt1.o: in function `_start':
(.text+0x24): undefined reference to `main'
collect2: error: ld returned 1 exit status

以防万一:

$ /usr/bin/python3-config --cflags
-I/usr/include/python3.8 -I/usr/include/python3.8  -Wno-unused-result -Wsign-compare -g -fdebug-prefix-map=/build/python3.8-CoVRmP/python3.8-3.8.10=. -specs=/usr/share/dpkg/no-pie-compile.specs -fstack-protector -Wformat -Werror=format-security  -DNDEBUG -g -fwrapv -O3 -Wall

$ /usr/bin/python3-config --ldflags
-L/usr/lib/python3.8/config-3.8-x86_64-linux-gnu -L/usr/lib  -lcrypt -lpthread -ldl  -lutil -lm -lm 

我没有手动控制 gcc 选项的经验,我所做的只是从 IDE 内部编译并自动设置标志。有人可以帮我找出问题所在吗?谢谢。

zhang00shuai 回答:在 gcc 中链接 Python 3.8 库时出现问题

我解决了问题,感谢@deamentiaemundi 和来自这里的帖子:https://stackoverflow.com/a/27672776/9256844

为避免“重定位 R_X86_64_32”,请使用 -fPIE 进行编译:

gcc $(python3.8-config --cflags) -fPIE -c embePy.c -o embePy.o

要链接 Python 库,我必须将目标文件放在 python 的标志之前并手动添加 -lpython3.8:

gcc embePy.o $(python3.8-config --ldflags) -lpython3.8 -o embePy

看起来我的 Python 版本错误地输出了重复的标志 -lm 而不是 -lpython3.8 (Python 3.8.10):

$ python3.8-config --ldflags
-L/usr/lib/python3.8/config-3.8-x86_64-linux-gnu -L/usr/lib  -lcrypt -lpthread -ldl  -lutil -lm -lm 
本文链接:https://www.f2er.com/512.html

大家都在问