0

I want to create nodejs addon wrapping C++ class template. I converted example class from "Wrapping C++ objects" tutorial to template. It compiles without errors but I get error upon using it.

node: symbol lookup error: /home/me/projects/node-template/build/Release/addon.node: undefined symbol: _ZN8MyObjectIdE4InitEN2v86HandleINS1_6ObjectEEE

addon.cc:

<...>
void InitAll(Handle<Object> exports) {
    MyObject<double>::Init(exports);
}
<...>

myobject.cc:

<...>
template <typename T>
MyObject<T>::MyObject() {};

template <typename T>
MyObject<T>::~MyObject() {};

template <typename T>
void MyObject<T>::Init(Handle<Object> exports) {
<...>

myobject.h:

<...>
template <typename T>
class MyObject : public node::ObjectWrap {
    public:
        static void Init(v8::Handle<v8::Object> exports);

    private:
        MyObject();
        ~MyObject();

        static v8::Handle<v8::Value> New(const v8::Arguments& args);
        static v8::Handle<v8::Value> PlusOne(const v8::Arguments& args);
        T counter_;
};

1 Answers1

0

C++ templates preclude separate compilation units, at least you way you've done here. Your addon.cc wants a MyObject<double>, with the assumption that it will be defined later (and resolved during dynamic linking at runtime). But myobject.cc doesn't know that you want a double-instantiated MyObject, so the compiler doesn't produce it when generating myobject.o.

To solve your dilemma, just put the contents of myobject.cc into myobject.h. That is, place the definition of MyObject in your header file; don't leave it as a separate compilation unit.

chrisaycock
  • 36,470
  • 14
  • 88
  • 125
  • It works this way but shouldn't _definition_ be in .c/cc files and class/function prototypes in .h, should it? I mean your solution works but is it the _right_ way? – susivienijimas Jul 01 '13 at 18:39
  • Nevermind, I've found the answer: http://stackoverflow.com/questions/5612791/c-template-and-header-files – susivienijimas Jul 01 '13 at 18:44