我的编译器给了我这个错误,我不明白为什么。
`P3_A2.o: In function `allocateAlot(_sync*)':
/home/***/workspace_qnx/P3_A2/P3_A2.cpp:69: undefined reference to `int*
StaticMem::allocate<int>(int*)'`
以下是P3_A2.cpp
:
void allocateAlot(sem_t * sleepHere)
{
for (int i = 0; i < 10000; i++)
{
Int32 * t = StaticMem::allocate(t);
}
sem_wait(sleepHere);
}
这是StaticMem.h
:
类StaticMem
{
...
template <class T> static T * allocate(T * ptr);
}
这是StaticMem.cpp
:
template <class T>
T * StaticMem::allocate(T * ptr)
{
ptr = (T*) reserveContiguousMemory(sizeof(T));
return ptr;
}
有人可以解释这个错误的来源吗?
答案 0 :(得分:2)
在C ++中,模板函数与普通函数不同。特别是,您不能将它们放入C ++源文件,单独编译它们,然后期望代码链接。原因是C ++模板不是代码 - 它们是代码的模板 - 并且只在需要时进行实例化和编译。
因为您已将模板函数allocate
的实现放入.cpp文件中,所以程序不会链接。要解决此问题,请将此函数的实现移至StaticMem.h
文件中。这样,包含StaticMem.h
的任何文件都将看到模板的实现,因此在实例化模板时,将生成并编译实现,修复链接器错误。
希望这有帮助!