Linking Python into my C++ code on windows - linke

2019-08-15 07:36发布

问题:

I have an error trying to link python into my C++ code.

This is the error line I am getting:

C:\Python27\libs/libpython27.a(dmmes00855.o):(.idata$7+0x0): undefined reference to `_head_C__build27_cpython_PCBuild_libpython27_a'

collect2.exe: error: ld returned 1 exit status

For background, here is minimal case:

#include <Python.h>

int main()
{
    Py_Initialize();
}

I am using scons to build:

import os
env = Environment(ENV = os.environ)
env.Append(CPPPATH = "C:/Python27/include/")
env.Append(LIBPATH = "C:/Python27/libs/")
env.Append(LIBS = "python27")
env.Program("test", "test.cpp")

It generates the following commands:

g++ -o test.o -c -IC:\Python27\include test.cpp
g++ -o test.exe test.o -LC:\Python27\libs -lpython27

Compiler is the mingw that I have as part of my Qt download.

回答1:

No problems with g++ commands. Apparently, this is a bug.

A bugfix release 2.7.10 is currently available. First of all Upgrade to 2.7.10

Then you need to create libpython27.a with

gendef.exe python27.dll

and

dlltool.exe --dllname python27.dll --def python27.def --output-lib libpython27.a

and place it in C:\Python27\libs

Now compiling with MinGW will work fine.