I am creating a C++ addon and I wanted to use a static library. i have a .a library libarith which does simple addition.
-libarith.a
-hello.cc
-hello.js
my binding.gyp file is as follows:-
{ "targets": [
{
"target_name": "addon",
"sources": [ "hello.cc" ],
"libraries": [ "-/home/folder/api/addon/libarith.a" ],
"cflags!": [ "-fno-exceptions" ],
"cflags": [ "-std=c++11" ],
"cflags_cc!": [ "-fno-exceptions" ]
}
]
}
When i compile my hello.cc it compiles well. But when i run my addon , it gives following error:
node: symbol lookup error: /home/folder/api/addon/build/Release/addon.node: undefined symbol: _ZN4demo3sumEii.
I am new to addons, a help would be very much appreciated.
Code Snippet:- libarith.a contains:
int sum(int a ,int b){
return a+b;
}
// hello.cc
#include <node.h>
#include <vector>
#include <iostream>
#include <v8.h>
using namespace std;
using namespace v8;
namespace demo {
using v8::FunctionCallbackInfo;
using v8::Isolate;
using v8::Local;
using v8::Object;
using v8::String;
using v8::Value;
void newmethod(const FunctionCallbackInfo<Value>& args)
{ extern int sum(int,int);
Isolate* isolate = args.GetIsolate();
double abc= sum(4,5);
Local<Number> newnumber =Number::New(isolate,abc);
v8::String::Utf8Value r(args[1]);
std::string rst(*r);
Local<String> first = String::NewFromUtf8(isolate, "firstargument");
Local<String> second = String::NewFromUtf8(isolate, "secondargument");
Local<Object> newobj= Object::New(isolate);
newobj->Set(first,String::NewFromUtf8(isolate, *s));
newobj->Set(second,newnumber);
args.GetReturnValue().Set(newobj);
}
void init(Local<Object> exports) {
NODE_SET_METHOD(exports, "newmethod", newmethod);
}
NODE_MODULE(addon, init)
}
//hello.js
const addon = require('./build/Release/addon');
var ss = "helloo";
var samplestring = "It is not a sample string";
console.log(addon.newmethod(samplestring, ss));
EDIT:- The solution worked as follows. I tried to create a separate directory for the libraries and it worked fine.
It says, it cannot find the declaration(implementation of .h
). I think you give wrong direction to your library. There are two solutions:
binding.gyp
~/whereItIsLocated
, in my case it was ~/CLionProjects/node-player-core/PlayerCore/lib/x64/yourLibraryName.a
/usr/lib
. You can do it with sudo cp ~/whereLibraryLocated /usr/lib
.