简体   繁体   中英

Linking a shared library with node-addon-api

I'm building a Node.js wrapper for a C shared library using node-gyp<\/code> and node-addon-api<\/code> . It works! But as the library was built from Golang code, I have different builds for different architectures -- the module can't compile the C library from the Go source itself.

I want the library in a subdirectory so that I can provide copies built for different architectures using conditionals.

node-mylib/
┣ build/
┃ ┣ Release/
┃ ┃ ┣ .deps/
┃ ┃ ┃ ┗ Release/
┃ ┃ ┃   ┣ obj.target/
┃ ┃ ┃   ┗ mylib.node.d
┃ ┃ ┣ obj.target/
┃ ┃ ┃ ┗ mylib/
┃ ┃ ┃   ┗ mylib.o
┃ ┃ ┗ mylib.node
┃ ┣ Makefile
┃ ┣ binding.Makefile
┃ ┣ config.gypi
┃ ┣ mylib.target.mk
┃ ┗ gyp-mac-tool
┣ binding.gyp
┣ mylib.cc
┣ index.js
┣ libmylib.h
┣ libmylib.so
┣ package-lock.json
┗ package.json

The only way I could get this working was to use install_name_tool<\/code> in a node-gyp postbuild<\/code> :

{
  "targets": [
    {
      "conditions": [
        ['OS=="mac"', {
            'cflags+': ['-fvisibility=hidden'],
            'xcode_settings': {
              'GCC_SYMBOLS_PRIVATE_EXTERN': 'YES', # -fvisibility=hidden
            }
        }]
      ],
      "defines": [ 'NAPI_DISABLE_CPP_EXCEPTIONS' ],
      "include_dirs": ["<(module_root_dir)/macos-arm64", "<!(node -p \"require('node-addon-api').include_dir\")"],
      "target_name": "mylib",
      "sources": [ "macos-arm64/mylib.cc" ],
      "libraries": ['<(module_root_dir)/macos-arm64/libmylib.so'],
      "postbuilds": [
        {
          "postbuild_name": 'Change libmylib load path',
          "action": ['install_name_tool', '-change',  'libmylib.so', '@loader_path/../../macos-arm64/libmylib.so', '<(PRODUCT_DIR)/mylib.node'],
        },
      ],
    }
  ]
}

See my answer to this question: Program compiles, but cannot run because of missing library that exists

Everything I said applies to macOS too. You have 3 ways to make your library known to the runtime linker:

  • install it in one of the standard locations
  • specify an environment variable before running it
  • embed a custom location the executable when linking it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM