使用嵌入式Python / C函数编译文件.c

时间:2012-10-18 12:48:27

标签: python c gcc python-c-api python-c-extension

我正在开始研究Python / C API,我制作了第一个测试某些函数的代码,我写道:

file:test.c

#include "Python.h"

int main() {
    PyObject* none = Py_BuildValue("");
}

我用命令编译:

gcc -I/usr/include/python2.7 test.c

我对'Py_BuildValue'

的错误未定义引用

我跑完后:

gcc -I/usr/include/python2.7 --shared -fPIC hashmem.c

这个编译没有错误,但是当我运行已编译的文件时,我有一个

Segmentation fault (core dumped)

如何设置gcc参数?

我是ubuntu 12.04,python 2.7.3,gcc 4.6.3,我安装了python-dev。

感谢。

1 个答案:

答案 0 :(得分:1)

在评论中@Pablo提供了解决方案

gcc -I/usr/include/python2.7 test.c -lpython2.7

我忘了将python库与“-l”参数链接起来。

  

-llibrary   -l库   链接时搜索名为library的库。 (第二种替代方法,将库作为​​单独的参数仅适用于POSIX),不推荐使用。)在编写此选项的命令中,它会有所不同;链接器按照指定的顺序搜索和处理库和目标文件。因此,在文件foo.o之后但在bar.o之前foo.o -lz bar.o' searches library z'。如果bar.o引用z', those functions may not be loaded.The linker searches a standard list of directories for the library, which is actually a file named liblibrary.a. The linker then uses this file as if it had been specified precisely by name.The directories searched include several standard system directories plus any that you specify with -L.Normally the files found this way are library files—archive files whose members are object files. The linker handles an archive file by scanning through it for members which define symbols that have so far been referenced but not defined. But if the file that is found is an ordinary object file, it is linked in the usual fashion. The only difference between using an -l option and specifying a file name is that - l surrounds library with lib'和`.a'中的函数并搜索多个目录。

Parameter description source