【发布时间】:2018-09-08 03:13:40
【问题描述】:
我从这里复制的示例:https://docs.python.org/3.5/extending/embedding.html
#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");
Py_Finalize();
PyMem_RawFree(program);
return 0;
}
如果像这样编译和链接:
gcc -fno-diagnostics-color -Wall -Wno-unused-function -fPIC -ggdb \
-I. -I/usr/include/python3.5m -c test_embed.c -o test_embed.o
gcc -fno-diagnostics-color -Wall -Wno-unused-function -fPIC -ggdb \
-I. -I/usr/include/python3.5m -shared -lpython3.5m ./test_embed.o \
-o test_embed
运行时出现段错误并将堆栈破坏到无法弄清楚发生了什么的程度。我需要任何特定的设置来编译它吗?
当我使用/usr/bin/python3.5-config --cflags 和/usr/bin/python3.5-config --ldconfig 给出的编译器选项时,该示例将无法构建,因为它在共享对象中找不到符号。
根据要求,这里是编译和链接命令以及错误输出:
$ gcc $(python3.5-config --cflags) -c test_embed.c -o test_embed.o
$ gcc $(python3.5-config --ldflags) ./test_embed.o -o test_embed
./test_embed.o: In function `main':
redacted/test_embed.c:6: undefined reference to `Py_DecodeLocale'
redacted/test_embed.c:11: undefined reference to `Py_SetProgramName'
redacted/test_embed.c:12: undefined reference to `Py_Initialize'
redacted/test_embed.c:13: undefined reference to `PyRun_SimpleStringFlags'
redacted/test_embed.c:15: undefined reference to `Py_Finalize'
redacted/test_embed.c:16: undefined reference to `PyMem_RawFree'
collect2: error: ld returned 1 exit status
$ python3.5-config --ldflags
-L/usr/lib/python3.5/config-3.5m-x86_64-linux-gnu -L/usr/lib -lpython3.5m -lpthread -ldl -lutil -lm -Xlinker -export-dynamic -Wl,-O1 -Wl,-Bsymbolic-functions
【问题讨论】:
-
这个 python3.5m 是来自一个包(如 apt 或 rpm),还是你从源代码配置和编译的?
-
@MarkPlotnick 抱歉,它是从 Ubuntu PPA 安装的。我也有从源代码编译的 Python 3.6,但这个不是我的。