1

My compiler gives me this error, and i do not understand why.

`P3_A2.o: In function `allocateAlot(_sync*)':
/home/***/workspace_qnx/P3_A2/P3_A2.cpp:69: undefined reference to `int* 
StaticMem::allocate<int>(int*)'` 

Here is P3_A2.cpp:

void allocateAlot(sem_t * sleepHere)
{

for (int i = 0; i < 10000; i++)
{

Int32 * t = StaticMem::allocate(t);

}
sem_wait(sleepHere);

}

Here's StaticMem.h:

class StaticMem
{
...

template <class T> static T * allocate(T * ptr);

}

Here's StaticMem.cpp:

template <class T>
T * StaticMem::allocate(T * ptr)
{

ptr = (T*) reserveContiguousMemory(sizeof(T));
return ptr;

}

Can someone explain where this error comes from?

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
user2950911
  • 873
  • 3
  • 12
  • 19
  • Template functions have to be defined in *header* files. The definition has to be visible everywhere it is used. Don't attempt to define template functions in a `.cpp` file (unless this is the only file you use these functions in). – AnT stands with Russia Nov 03 '13 at 23:05

1 Answers1

2

In C++, template functions are different from normal functions. In particular, you can't put them in to a C++ source file, compile them separately, and then expect the code to link. The reason for this is that C++ templates aren't code - they're templates for code - and are only instantiated and compiled when they're needed.

Because you've put the implementation of your template function allocate into a .cpp file, the program won't link. To fix this, move the implementation of this function into the StaticMem.h file. That way, any file that includes StaticMem.h will see the implementation of the template, so when the template is instantiated the implementation will be generated and compiled, fixing your linker error.

Hope this helps!

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065