Question

I try to embed Python in my C++ application, but the linker keeps saying this error:

[ILINK32 Error] Error: Unresolved external '_PyModule_Create2TraceRefs' referenced from E:\CPP PROJECTS\ANDERLICHT\WIN32\DEBUG\ANDERLICHT.OBJ

I'm using Embarcadero C++ Builder XE2, so I converted the python33.lib with coff2omf.exe.

This is my code in main.cpp:

#include "anderlicht.c"
#pragma comment(lib, "python33_omf.lib")

// In main():
PyImport_AppendInittab("anderlicht",PyInit_anderlicht);
Py_SetProgramName(programName.w_str());
Py_Initialize();

In anderlicht.c the Python.h is included. What do I have to do to fix this error?

Was it helpful?

Solution 2

The problem is most likely that you're using different compiler flags in building your code than were used in building the Python DLL. In particular, PyModule_Create2TraceRefs is only defined if you have -DPy_TRACE_REFS (which usually passed in via EXTRA_CFLAGS in the make command on Unix; I have no idea how you do it with Embarcadero C++ Builder on Windows). Usually, this isn't defined—in particular, if you're using a DLL from a pre-build Python binary, it won't have it defined.

So, if you want to have custom flags in building your code, you need to rebuild Python itself with the same flags. Otherwise, you need to get the flags that were used to build Python, and use the same ones when building your code.

On Unix, this is trivial: Just call python3.3-config --cflags and python3.3-config --ldflags to get the flags to pass to your compile and link steps. On Windows, it's less trivial. The Building C and C++ Extensions on Windows chapter in the docs explains how to do it when you're using the same toolchain used to build Python itself (usually MSVC), and if you're using mingw with its MSVC-compat features there's documentation elsewhere on how to do that… but if you're using a different toolchain, you will need to figure some of it out yourself.

OTHER TIPS

I had the same problem, but I found a solution that doesn't need rebuild.

If you are developing a new application, you are in debug mode: the compiler defines _DEBUG. In the file "pyconfig.h" (near line 336 for python 3.6.3) you can find:

#ifdef _DEBUG
#define Py_DEBUG
#endif

=> Remove this code.

If you leave that code,you are in Py_Debug mode, so in object.h triggers this:

#if defined(Py_DEBUG) && !defined(Py_TRACE_REFS)
#define Py_TRACE_REFS
#endif

That in modsupport.h defines this alias:

#ifdef Py_TRACE_REFS
 /* When we are tracing reference counts, rename module creation functions so
    modules compiled with incompatible settings will generate a
    link-time error. */
 #define PyModule_Create2 PyModule_Create2TraceRefs
 #define PyModule_FromDefAndSpec2 PyModule_FromDefAndSpec2TraceRefs
#endif

So your compiler needs a custom version of Python.

Now enjoy your standard embedded python.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top