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

I have a C ++ class that I use, and there is a function that does not appear when I look at the .o file using `nm --demangle ', and there is no function when the program tries, although everything builds perfectly.

The title is as follows:

#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 with is when I try to inherit this class in another and appear at runtime: undefined symbol: _ZN10CollectionIN4NJSE5TrackEE7addItemEPS1_

I feel like I am missing something simple here, but I can’t say what it is.

+3
source share
4 answers

( ) addItem, , , .. .

Infact ++ .

+2

? - , , , .

+3

, , . ++ ( , ). , .

+3
source

Templates in separate compilation units can be a nightmare and require a serious weightlifting compiler.

Remember that specific versions of your template function must be compiled for each type T for which you are trying to instantiate a template.

For this reason, the easiest way is to put all the definitions of the template functions in the .h header file.

+2
source

Source: https://habr.com/ru/post/1773842/


All Articles