我一直在研究如何在节点项目中使用c库。经过一点点调查,我发现了淋巴结。
我成功地执行了示例,但是当我试图在代码中使用第三方c库函数时,它在运行时给了我链接错误。
图书馆可以在这里找到http://bibutils.refbase.org/bibutils_3.40_src.tgz
我独立编译了这个库以拥有*.a对象
我用下面的例子
https://github.com/nodejs/node-addon-examples/tree/master/5_function_factory/node_0.12
所以我可以推断出以下问题
我可以把布丁从make改成gyp吗?
我是否应该将每个源文件转换为使用V8?我不知道怎么做。
如何轻松地将此项目链接到噪声较少的节点gyp?
下面可以找到与脚本相关的详细信息。bibutils文件夹与addon.cc一起放置
binding.gyp看起来像

{
  "targets": [
    {
      "target_name": "addon",
      "sources": [ "addon.cc" ],
      "include_dirs": ["bibutils/lib"],
      "library_dirs": ["bibutils/lib/libbibutil.a","bibutils/lib/libbibprogs.a"]
    }
  ]
}

修改的addon.cc
#include <node.h>
#include "bibutils.h"
#include "bibprogs.h"

using namespace v8;

void MyFunction(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = Isolate::GetCurrent();
  HandleScope scope(isolate);
      /****This is not production code just to check the execution***/
      bibl b;
      bibl_init( &b );
      bibl_free( &b );
      /**************************************************************/
  args.GetReturnValue().Set(String::NewFromUtf8(isolate, "hello world"));
}

void CreateFunction(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = Isolate::GetCurrent();
  HandleScope scope(isolate);

  Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, MyFunction);
  Local<Function> fn = tpl->GetFunction();

  // omit this to make it anonymous
  fn->SetName(String::NewFromUtf8(isolate, "theFunction"));

  args.GetReturnValue().Set(fn);
}

编译结果
user1@ubuntu:~/node-addon-examples/5_function_factory/node_0.12$ npm install

> function_factory@0.0.0 install /home/user1/node-addon-examples/5_function_factory/node_0.12
> node-gyp rebuild

make: Entering directory `/home/user1/node-addon-examples/5_function_factory/node_0.12/build'
  CXX(target) Release/obj.target/addon/addon.o
  SOLINK_MODULE(target) Release/obj.target/addon.node
  COPY Release/addon.node
make: Leaving directory `/home/user1/node-addon-examples/5_function_factory/node_0.12/build'

执行时
user1@ubuntu:~/node-addon-examples/5_function_factory/node_0.12$ node addon.js
node: symbol lookup error: /home/user1/node-addon-examples/5_function_factory/node_0.12/build/Release/addon.node: undefined symbol: _Z9bibl_initP4bibl

调试信息:
user1@ubuntu:~/node-addon-examples/5_function_factory/node_0.12$ nm -C build/Release/addon.node | grep bibl_init
                 U bibl_init(bibl*)

最佳答案

问题是C++和C之间的通信。在上述情况下,C头文件包含在C++代码中。编译是期待C++代码。因此,由于编译的代码不匹配,编译链接器被阻塞。
所以我使用了extern“C”指令,通过下面的代码告诉编译器有关C头文件的信息。

extern "C" {
    #include "bibutils.h"
    #include "bibprogs.h"
}

07-28 03:03
查看更多