C++ templates, undefined reference(C++ 模板,未定义的引用)
问题描述
我有一个这样声明的函数:
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).
这篇关于C++ 模板,未定义的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ 模板,未定义的引用
基础教程推荐
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 这个宏可以转换成函数吗? 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
