我正在尝试编译嵌入 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 内部编译并自动设置标志。有人可以帮我找出问题所在吗?谢谢。