gpt4 book ai didi

c++ - Node native 模块 - 链接静态库

转载 作者:行者123 更新时间:2023-11-30 05:04:03 29 4
gpt4 key购买 nike

我正在构建一个依赖于另一个库 (libboost-regex) 的 NodeJS native 模块。

如果我使用下面的 binding.gyp 文件动态链接库,一切正常:

{
"targets": [
{
"libraries": [
"/usr/lib/x86_64-linux-gnu/libboost_regex.so",
"-ludev"
],
"target_name": "utils",
"sources": [ "src/native/utils.cpp" ]
}
]
}

但是这种方式只适用于我的机器。在另一台 Linux 机器上,它说找不到这个模块 libboost_regex.so。在某些 Linux 发行版上,这个版本(目前为 1.58)甚至不可用。

是否可以静态链接它,以便将其包含到我的输出模块中?

我在这里看到一个帖子,我只需要将.so版本更改为静态库的.a版本即可: https://github.com/nodejs/node-gyp/issues/328#issuecomment-24335081

但是如果我用这个替换它:“/usr/lib/x86_64-linux-gnu/libboost_regex.a”

我现在得到这个错误:

/usr/bin/ld: /usr/lib/x86_64-linux-gnu/libboost_regex.a(instances.o): relocation R_X86_64_32 against `.rodata.str1.8' can not be used when making a shared object; recompile with -fPIC
/usr/lib/x86_64-linux-gnu/libboost_regex.a: error adding symbols: Bad value
collect2: error: ld returned 1 exit status
utils.target.mk:125: recipe for target 'Release/obj.target/utils.node' failed
make: *** [Release/obj.target/utils.node] Error 1

如果我将 -static 添加到链接器选项,也会出现上述错误。

另一个尝试:

{
"targets": [
{
"libraries": [
"-ludev", "-lboost_regex"
],
"target_name": "utils",
"cflags!": ["-fPIC"],
"ldflags" : [ "-Wl,-static" ],
"sources": [ "src/native/utils.cpp" ]
}
]
}

导致类似的错误:

/usr/bin/ld: Release/obj.target/utils/src/native/utils.o: relocation R_X86_64_32 against `.rodata' can not be used when making a shared object; recompile with -fPIC
Release/obj.target/utils/src/native/utils.o: error adding symbols: Bad value
collect2: error: ld returned 1 exit status
utils.target.mk:123: recipe for target 'Release/obj.target/utils.node' failed

如有任何帮助,我们将不胜感激。

谢谢!

最佳答案

通常,.a 文件是.o 文件的压缩包,编译时没有使用-fPIC 标记。而共享库的代码必须使用 -fPIC 编译。这就是您无法将共享库与 libboost_regex.a 链接的原因。

Boost 静态库需要用-fPIC 标志重新编译,以便.a 文件可以链接到与位置无关的共享库中。使用 boost b2 构建工具,它是 cxxflags='-fPIC' 命令行选项。

或者,您可以仅使用共享库构建 boost,然后将您的共享库链接到用于链接 boost 共享库的单个 .o 文件。

关于c++ - Node native 模块 - 链接静态库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49115403/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com