Python - Py_Initialize unresolved during compilation

﹥>﹥吖頭↗ 提交于 2019-12-04 05:17:40

The order matters! More specifically, the order in the arguments for gcc matters. More specifically, if a bar object uses a function bluh from library bleh, then the order -lbleh bar.o is problematic because it provides no reason to gcc look for the function bluh in bleh. On the other hand, when you use bar.o -lbleh then gcc knows you are referring to bluh and when it gets to handle -lbleh it tries to resolve the dependence. This is quickly mentioned at http://gcc.gnu.org/onlinedocs/gcc/Link-Options.html. As a rule, always specifies libraries after your objects.

To reproduce your problem, create a file a1.c as in:

#include "Python.h"

int main()
{
    Py_Initialize();
    return 0;
}

Now compile with gcc -static -I/usr/include/python2.7 -L/usr/lib/python2.7/config/ -lpython2.7 -ldl -lm -lutil -lz -pthread -o a1 a1.c. This gives the undefined reference to Py_Initialize. Of course you have to change the paths to match your installation.

Now, instead, compile with gcc -static -I/usr/include/python2.7 -L/usr/lib/python2.7/config/ -o a1 a1.c -lpython2.7 -ldl -lm -lutil -lz -pthread and it works (ignoring the possible many warnings, which is a different matter).

I am using python 2.7 and set the path of python installation directory in the environment variable. I also use boost 1.5.0

follow the steps to Compile the below code

#include <python2.7/Python.h>
int main()
{
Py_Initialize();

PyRun_SimpleString("print \"Hello, world!\"");

Py_Finalize();
return 0;
}

Run the command:-

g++ hello.cc -lpython2.7
./a.out
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!