试图理解编写Python/C++混合的链接过程

ely*_*ely 7 c++ python

我想开始学习更多关于使用SWIG和其他方法来连接Python和C++的知识.首先,我想编译另一篇文章中提到的这个简单程序:

#include <Python.h> 

 int main() 
 { 
      Py_Initialize(); 
      PyRun_SimpleString ("import sys; sys.path.insert(0, '/home/ely/Desktop/Python/C-Python/')");

      PyObject* pModule = NULL; 
      PyObject* pFunc   = NULL; 

      pModule = PyImport_ImportModule("hello");
      if(pModule == NULL){
           printf("Error importing module.");
           exit(-1);
      }


      pFunc   = PyObject_GetAttrString(pModule, "Hello"); 
      PyEval_CallObject(pFunc, NULL); 
      Py_Finalize(); 
      return 0; 
 }
Run Code Online (Sandbox Code Playgroud)

文件"hello.py"只包含内容:

 def Hello():
     print "Hello world!"
Run Code Online (Sandbox Code Playgroud)

注意:我已经安装了python2.7-dev和python-dev以及libboost-python-dev.但是当我去编译代码时,我得到错误,我认为是由于错误地链接到Python库.

 ely@AMDESK:~/Desktop/Python/C-Python$ gcc -I/usr/include/python2.7 test.cpp    /tmp/ccVnzwDp.o: In function `main':
 test.cpp:(.text+0x9): undefined reference to `Py_Initialize'
 test.cpp:(.text+0x23): undefined reference to `PyImport_ImportModule'
 test.cpp:(.text+0x58): undefined reference to `PyObject_GetAttrString'
 test.cpp:(.text+0x72): undefined reference to `PyEval_CallObjectWithKeywords'
 test.cpp:(.text+0x77): undefined reference to `Py_Finalize'
 /tmp/ccVnzwDp.o:(.eh_frame+0x12): undefined reference to `__gxx_personality_v0'
 collect2: ld returned 1 exit status
Run Code Online (Sandbox Code Playgroud)

我在网上搜索这个例子,我发现以下语法,导致代码编译成目标文件,但后来我无法实际执行该文件.

 ely@AMDESK:~/Desktop/Python/C-Python$ gcc -c -g -I/usr/include/python2.7 test.cpp 
 ely@AMDESK:~/Desktop/Python/C-Python$ ./test.o
 bash: ./test.o: Permission denied
 ely@AMDESK:~/Desktop/Python/C-Python$ chmod ug=rx ./test.o
 ely@AMDESK:~/Desktop/Python/C-Python$ ./test.o
 bash: ./test.o: cannot execute binary file
 ely@AMDESK:~/Desktop/Python/C-Python$ sudo chmod ug=rx ./test.o
 ely@AMDESK:~/Desktop/Python/C-Python$ ./test.o
 bash: ./test.o: cannot execute binary file
Run Code Online (Sandbox Code Playgroud)

如果我使用g++而不是,仍然可以看到与上面相同的行为gcc.

帮助理解我在链接中的错误会很棒,甚至更好的任何解释都可以帮助我理解我需要做的链接背后的"逻辑",这样我就会更好地记住我忘记了什么可能的事情下一次.谢谢!

BЈо*_*вић 9

你看到的是链接器错误.要解决这些问题,您需要链接python2.7库.

尝试下一行:

gcc -I/usr/include/python2.7 test.c -lpython2.7
Run Code Online (Sandbox Code Playgroud)

它应该工作.

  • @EMS,用`g ++`而不是`gcc`编译。 (2认同)