lang链接器,ld:找不到体系结构x86_64的符号

时间:2019-01-08 08:40:53

标签: python-3.x c++11 cmake

我正在尝试为项目将一些python代码嵌入C ++中。我已经能够在Windows上运行此简单教程,并且可以正常工作(5.1非常高级的嵌入https://docs.python.org/2/extending/embedding.html

但是我也想在我的Mac上实现它,并且在构建项目时遇到以下问题:

import { DomSanitizer } from '@angular/platform-browser';
// ... then 
constructor(private sanitizer: DomSanitizer) {
}
// ... then (I used it with url, but it has an html sanitizer)
this.path = this.sanitizer.bypassSecurityTrustResourceUrl(this.sanitizer.sanitize(SecurityContext.URL, 'SOME_URL'));
// ... then in HTML
<iframe [src]="path"></iframe>

我的代码是:

====================[ Build | TestCharacter | Debub ]===========================
/Applications/CLion.app/Contents/bin/cmake/mac/bin/cmake --build /Users/michaelstettler/CLionProjects/TestCharacter/cmake-build-debug --target TestCharacter -- -j 4
Scanning dependencies of target TestCharacter
[ 50%] Building CXX object CMakeFiles/TestCharacter.dir/main.cpp.o
[100%] Linking CXX executable TestCharacter
Undefined symbols for architecture x86_64:
  "_PyMem_RawFree", referenced from:
      _main in main.cpp.o
  "_PyRun_SimpleStringFlags", referenced from:
      _main in main.cpp.o
  "_Py_DecodeLocale", referenced from:
      _main in main.cpp.o
  "_Py_FinalizeEx", referenced from:
      _main in main.cpp.o
  "_Py_Initialize", referenced from:
      _main in main.cpp.o
  "_Py_SetProgramName", referenced from:
      _main in main.cpp.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make[3]: *** [TestCharacter] Error 1
make[2]: *** [CMakeFiles/TestCharacter.dir/all] Error 2
make[1]: *** [CMakeFiles/TestCharacter.dir/rule] Error 2
make: *** [TestCharacter] Error 2

我不得不修改CmakeLists.txt来查找标头,因为起初我找不到Python.h库。

#include <iostream>
#include <string>
#include <Python.h> // modified the CMake to make it findable

using namespace std;

int main(int argc, char *argv[]) {
    cout << "Hello, World!" << endl;

    wchar_t *program = Py_DecodeLocale(argv[0], NULL);
    if (program == NULL) {
        fprintf(stderr, "Fatal error: cannot decode argv[0]\n");
        exit(1);
    }
    Py_SetProgramName(program);
    Py_Initialize();
    PyRun_SimpleString("from time import time,ctime\n"
                   "print('Today is', ctime(time()))\n");
    if (Py_FinalizeEx() < 0) {
        exit(120);
    }
    PyMem_RawFree(program);
    return 0;
}

似乎我的链接器是错误的,但是我还没有弄清楚该怎么做。我也无法使用该调用工具。

如果有帮助,我正在使用Clion。

1 个答案:

答案 0 :(得分:1)

问题出在您的CMakeLists.txt中。您可以使用内置的FindPythonLibs函数来设置所需的路径和库:

find_package(PythonLibs REQUIRED)

add_executable(TestCharacter main.cpp)

target_include_directories(TestCharacter PRIVATE ${PYTHON_INCLUDE_DIRS})
target_link_libraries(TestCharacter PRIVATE ${PYTHON_LIBRARIES})

请注意,此代码段中没有任何版本要求。您可以通过以下方式配置您的构建:

cmake -D CMAKE_MODULE_PATH=/usr/local/Cellar/python/3.6.5 path/to/your/project

现在应该将正确的包含路径和链接器标志传递给编译器和链接器(您可以在命令行上进行编译,例如,使用make VERBOSE=1进行验证)。