【问题标题】:Embed python code in C++ (Windows + minGW + Python 2.7.2 + Eclipse)在 C++ 中嵌入 python 代码(Windows + minGW + Python 2.7.2 + Eclipse)
【发布时间】:2011-11-04 03:22:27
【问题描述】:

我正在尝试将 python 代码嵌入C++ (Windows 7 + minGW + Python 2.7.2 + Eclipse Indigo with CDT and PyDev)。

所以,这是简单的代码:

#include <Python.h> //Python.h
#include <iostream> //iostream
using namespace std;
int main(int argc, char *argv[])
{
    Py_Initialize();
    PyRun_SimpleString("from time import time,ctime\n"
    "print('Today is', ctime(time()))\n");
    Py_Finalize();
    return 0;
}

我不明白我做错了什么。 我包含了 C:\Python27\include 和 C:\Python27\libs 的目录,但我无法构建我的项目。

1) 当我尝试构建我的项目时,我收到了这个错误:

**** Internal Builder is used for build               **** g++
-IC:\Python27\include -IC:\Python27\libs -O0 -g3 -Wall -c
-fmessage-length=0 -o main.o ..\main.cpp g++ -o testpy2.exe main.o
main.o: In function `main':
C:\Users\const\workspace\testpy2\Debug/../main.cpp:7: undefined
reference to `_imp__Py_Initialize'
C:\Users\const\workspace\testpy2\Debug/../main.cpp:9: undefined
reference to `_imp__PyRun_SimpleStringFlags'
C:\Users\const\workspace\testpy2\Debug/../main.cpp:10: undefined
reference to `_imp__Py_Finalize' 
collect2: ld returned 1 exit status
Build error occurred, build is stopped Time consumed: 1507  ms.

2) 如果我将 Eclipse 中的当前工具链从“minGW”更改为“CrossGCC”.. 我收到此错误:

**** Build of configuration Release for project testpy ****

make all  Building file: ../main.cpp Invoking: Cross G++ Compiler g++
-I"C:\Python27\include" -I"C:\Python27\libs" -O3 -Wall -c
-fmessage-length=0 -MMD -MP -MF"main.d" -MT"main.d" -o "main.o"
"../main.cpp" Finished building: ../main.cpp   Building target:
testpy.exe Invoking: Cross G++ Linker g++  -o "testpy.exe"  ./main.o  
-l"C:/Python27/libs/libpython27.a" -l"C:/Python27/libs/python27.lib"
c:/mingw/bin/../lib/gcc/mingw32/4.5.2/../../../../mingw32/bin/ld.exe:
cannot find -lC:/Python27/libs/libpython27.a
c:/mingw/bin/../lib/gcc/mingw32/4.5.2/../../../../mingw32/bin/ld.exe:
cannot find -lC:/Python27/libs/python27.lib collect2: ld returned 1
exit status make: *** [testpy.exe] Error 1

**** Build Finished ****

谁能告诉我我的代码或设置有什么问题?

谢谢

【问题讨论】:

    标签: c++ python eclipse embed mingw


    【解决方案1】:

    这是一个链接器错误,而不是编译器错误。您需要链接到python。如您所见,有了“CrossGCC”工具链,您就快到了:

    -lC:/Python27/libs/libpython27.a
    

    您需要将其更改为

    -LC:/Python27/libs -lpython
    

    【讨论】:

    • 谢谢!它可以工作,但有一些小的变化......而不是 -lpython 我添加了 -lpython27。现在我得到了:调用:Cross G++ Linker g++ -LC:/Python27/libs -lpython27 -L"C:\Python27\libs" -L"C:\Python27\include" -o "testpy.exe" ./main. o -lpython27
    猜你喜欢
    • 1970-01-01
    • 2021-06-14
    • 1970-01-01
    • 1970-01-01
    • 2016-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-20
    相关资源
    最近更新 更多