我正在做一些试验,将python嵌入到c程序中。
我使用CMake 2.8.12.2和gcc 4.8.1来构建应用程序。我的Python版本是2.7.11。在W7上运行。
这就是我在CMakeLists.txt中链接库的方式,CMakeLists.txt以前一直对我使用静态库:
的CMakeLists.txt
cmake_minimum_required(VERSION 2.7 FATAL_ERROR)
project(testpy)
include_directories("C:\\Anaconda\\include")
link_directories("C:\\Anaconda\\libs")
set(CMAKE_BUILD_TYPE Release)
set(SOURCE_FILES testpy.c)
add_executable(testpy ${SOURCE_FILES} Python.h)
set(PYLIB_DIR "C:\\Anaconda\\libs")
message(${PYLIB_DIR})
find_library(PYlib python27.lib HINTS ${PYLIB_DIR})
include_directories(${PYLIB_DIR})
message(${PYlib})
TARGET_LINK_LIBRARIES(testpy ${PYlib})
testpy.c
#include <Python.h>
int main(int argc, char *argv[])
{
Py_Initialize();
PyRun_SimpleString("from time import time,ctime\nprint('Today is',ctime(time())\n)");
Py_Finalize();
return 0;
}
制作时遇到的错误:
CMakeFiles\testpy.dir/objects.a(testpy.c.obj):testpy.c:(.text.startup+0x10): und
efined reference to `_imp__Py_Initialize'
CMakeFiles\testpy.dir/objects.a(testpy.c.obj):testpy.c:(.text.startup+0x25): und
efined reference to `_imp__PyRun_SimpleStringFlags'
c:/mingw/bin/../lib/gcc/mingw32/4.8.1/../../../../mingw32/bin/ld.exe: CMakeFiles
\testpy.dir/objects.a(testpy.c.obj): bad reloc address 0x25 in section `.text.st
artup'
c:/mingw/bin/../lib/gcc/mingw32/4.8.1/../../../../mingw32/bin/ld.exe: final link
failed: Invalid operation
collect2.exe: error: ld returned 1 exit status
CMakeFiles\testpy.dir\build.make:90: recipe for target 'testpy.exe' failed
mingw32-make[2]: *** [testpy.exe] Error 1
CMakeFiles\Makefile2:62: recipe for target 'CMakeFiles/testpy.dir/all' failed
mingw32-make[1]: *** [CMakeFiles/testpy.dir/all] Error 2
Makefile:74: recipe for target 'all' failed
mingw32-make: *** [all] Error 2
我很害羞是一个链接问题,但我仍然没有看到它的位置,以及如何解决它。看到并尝试了很多在这里和其他论坛中提出的解决方案,但没有成功。
在\ include和\ libs文件夹中分别可以找到python.h和python27.lib。
提前感谢您的反馈。