静态链接不适用于节点模块

kir*_*ran 6 linker shared-libraries static-linking node-modules aws-lambda

我正在为AWS lambda开发一个本机节点模块.该节点模块需要json-c

根据AWS lambda准则,节点模块不应具有动态依赖性.所以尝试链接静态版本的json-c库.但我得到编译时错误.

由于节点模块只是一个共享库,我编写了一个示例C应用程序(主要重命名)来模拟节点模块编译,结果如下:

g++      -shared -pthread -rdynamic -m64  -Wl,-soname=addon.node -o addon.node testjson.cpp  -I /usr/include/json-c/  -L  /lib/x86_64-linux-gnu/  -l:libjson-c.a
testjson.cpp: In function ‘int test()’:
testjson.cpp:6:14: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]
  char *str = "{ \"msg-type\": [ \"0xdeadbeef\", \"irc log\" ], \
              ^
/usr/bin/ld: /tmp/ccihB9d8.o: relocation R_X86_64_32S against `.rodata' can not be used when making a shared object; recompile with -fPIC
/tmp/ccihB9d8.o: error adding symbols: Bad value
collect2: error: ld returned 1 exit status
Run Code Online (Sandbox Code Playgroud)

当我尝试使用"--whole-archive"时:

g++ -shared -o libshared.so -Wl,--whole-archive -fPIC -l:/usr/lib/x86_64-linux-gnu/libjson-c.a  -Wl,--no-whole-archive testjson.cpp -I /usr/include/json-c/
testjson.cpp: In function ‘int test()’:
testjson.cpp:6:14: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]
  char *str = "{ \"msg-type\": [ \"0xdeadbeef\", \"irc log\" ], \
              ^
/usr/bin/ld: /usr/lib/x86_64-linux-gnu/libjson-c.a(json_c_version.o): relocation R_X86_64_32 against `.rodata.str1.1' can not be used when making a shared object; recompile with -fPIC
/usr/lib/x86_64-linux-gnu/libjson-c.a(json_c_version.o): error adding symbols: Bad value
collect2: error: ld returned 1 exit status
Run Code Online (Sandbox Code Playgroud)

我做错了什么?是不是可以将库静态链接到共享对象?

Abd*_*naf 3

首先,您需要手动构建 json-c 作为静态库。

创建 Json-c 静态库

像这样配置 Binding.gyp 文件后(它适用于使用 node-gyp 工具将源代码构建到 npm 库)。

{
  "targets": [
     {
      "target_name": "testName",
      "sources": ["yourCode.c"],
      "libraries": ["/var/task/lib/libjson-c.a"]
     }
  ]
}
Run Code Online (Sandbox Code Playgroud)

它对我有用。