C++ 模板,未定义的引用

2021-12-13 00:00:00 templates g++ c++ undefined-reference

我有一个这样声明的函数:

I have a function declared like so:

template <typename T> 
T read();

并像这样定义:

template <typename T>
T packetreader::read() {
    offset += sizeof(T);
    return *(T*)(buf+offset-sizeof(T)); 
}

但是,当我尝试在 main() 函数中使用它时:

However, when I try to use it in my main() function:

packetreader reader;
reader.read<int>();

我从 g++ 得到以下错误:

I get the following error from g++:

g++ -o main main.o packet.o
main.o: In function `main':
main.cpp:(.text+0xcc): undefined reference to `int packetreader::read<int>()'
collect2: ld returned 1 exit status
make: *** [main] Error 1

谁能指出我正确的方向?

Can anyone point me into the right direction?

推荐答案

您需要使用 export 关键字.但是,我认为 G++ 没有适当的支持,因此您需要在标题中包含模板函数的定义,以便翻译单元可以使用它.这是因为模板的 'version' 还没有被创建,只有 'version.'

You need to use the export keyword. However, I don't think G++ has proper support, so you need to include the template function's definition in the header so the translation unit can use it. This is because the <int> 'version' of the template hasn't been created, only the <typename T> 'version.'

一个简单的方法是#include .cpp 文件.但是,这可能会导致问题,例如当其他函数在 .cpp 文件中时.它也可能会增加编译时间.

An easy way is to #include the .cpp file. However, this can cause problems, e.g. when other functions are in the .cpp file. It will also likely increase the compile time.

一种干净的方法是将您的模板函数移动到它自己的 .cpp 文件中,并将其包含在头文件中或使用 export 关键字并单独编译它.

A clean way is to move your template functions into its own .cpp file, and include that in the header or use the export keyword and compile it separately.

更多关于为什么你应该尝试和的信息将模板函数定义放在其头文件中(并完全忽略 export).

相关文章