Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is a function not defined in the .o file for this C++ class?

I have a C++ class that I'm using, and there's a function in it that's not showing up when I look at the .o file with `nm --demangle', and the function is missing when the program tries to run, even though everything builds fine.

The header looks like:

#ifndef __COLLECTION_H
#define __COLLECTION_H

#include <vector>

#include "ObjectInstance.h"

using namespace std;

template <class T>
class Collection : public ObjectInstance
{       
protected:
    vector<T*> items;
    void internalInsertAt(T* item, int index);
    void internalRemoveIndex(int index);
    void internalRemoveItem(T* item);

public:
    virtual ~Collection();
    // Specific functions for this interface
    static int item(jsplugin_obj *this_obj, jsplugin_obj *function_obj, int argc, 
    T* internalGetItem(int index);
    int getSize();
    void addItem(T* item);
};

#endif

and the addItem function is implemented as

template <class T>
void Collection<T>::addItem(T* item)
{   
    items.push_back(item);
}   

The error I get is from when I try to inherit this class in another one and shows up at runtime: undefined symbol: _ZN10CollectionIN4NJSE5TrackEE7addItemEPS1_

I feel like I'm missing something simple here, but can't tell what it is.

like image 916
Neth Avatar asked Dec 29 '22 05:12

Neth


2 Answers

Is the function in a header file or source file? The simplest way to deal with templates is to put all template definitions in header files, to guarantee the definition is available to whatever code instantiates it.

like image 154
aschepler Avatar answered Feb 05 '23 19:02

aschepler


Well, I think that's because the function is a member of a template. In C++ you can't compile templates (at least not easily). If you want to distribute template classes, write all the code in the header.

like image 43
kangcz Avatar answered Feb 05 '23 20:02

kangcz