无法在Mac上使用CMake链接到.so文件

时间:2019-01-02 08:48:45

标签: macos cmake shared-libraries ld

我正在使用Swig开发PHP 7扩展,并试图链接到libphp7.so。从我的CMakeLists.txt文件中:

find_library(php7_lib php7 PATHS "/usr/local/Cellar/php/7.3.0/lib/httpd/modules" NO_DEFAULT_PATH)
target_link_libraries(navdb_php7_client_api ${php7_lib} dl)

但是我得到一个错误:

[100%] Linking CXX shared module .../lib/libnavdb_php7_client_api.so 
...
ld: can't link with bundle (MH_BUNDLE) only dylibs (MH_DYLIB) file '/usr/local/Cellar/php/7.3.0/lib/httpd/modules/libphp7.so' for architecture x86_64

我要链接的文件:

$ file /usr/local/Cellar/php/7.3.0/lib/httpd/modules/libphp7.so
/usr/local/Cellar/php/7.3.0/lib/httpd/modules/libphp7.so: Mach-O 64-bit bundle x86_64

关于如何解决此问题的任何想法?

2 个答案:

答案 0 :(得分:0)

尽管Apple建议为捆绑软件提供扩展名.bundle,但出于跨平台熟悉的考虑,许多开发人员都为捆绑软件提供了.so扩展名。在Linux上,共享模块(在MacOS上为捆绑包)和共享库(在MacOS上为dylib)之间没有区别。

了解,如ld所述,您不能链接到MacOS上的MH_BUNDLE。要么它是要链接的dylib,要么需要使用dyld API加载.so

This link给出了如何在MacOS上动态加载捆绑软件的示例:

#include <stdio.h>
#import <mach-o/dyld.h>

int main( )
{
  int the_answer;
  int rc;                // Success or failure result value
  NSObjectFileImage img; // Represents the bundle's object file
  NSModule handle;       // Handle to the loaded bundle
  NSSymbol sym;          // Represents a symbol in the bundle

  int (*get_answer) (void);  // Function pointer for get_answer

  /* Get an object file for the bundle. */
  rc = NSCreateObjectFileImageFromFile("libanswer.bundle", &img);
  if (rc != NSObjectFileImageSuccess) {
    fprintf(stderr, "Could not load libanswer.bundle.\n");
    exit(-1);
  }

  /* Get a handle for the bundle. */
  handle = NSLinkModule(img, "libanswer.bundle", FALSE);

  /* Look up the get_answer function. */
  sym = NSLookupSymbolInModule(handle, "_get_answer");
  if (sym == NULL)
  {
    fprintf(stderr, "Could not find symbol: _get_answer.\n");
    exit(-2);
  }

  /* Get the address of the function. */
  get_answer = NSAddressOfSymbol(sym);

  /* Invoke the function and display the answer. */
  the_answer = get_answer( );
  printf("The answer is... %d\n", the_answer);

  fprintf(stderr, "%d??!!\n", the_answer);
  return 0;
}

答案 1 :(得分:0)

我从此链接中找到了如何/做什么: Clang and undefined symbols when building a library

libphp7.so不需要在编译时链接到,运行时工作正常。可以通过设置CXX_FLAG启用此功能(有关详细信息,请参见链接)。