Consider the code below:
#include <iostream>
template<typename T>
T n;
int main()
{
n<int> = 42;
std::cout << n<int> << std::endl;
}
It compiles and links with g++5.1, and it displays 42
. However, clang++ fails to link it:
undefined reference to n<int>
If I initialize the template variable like
template<typename T> T n{};
then clang++ links it too.
Any idea what's going on? Is clang++ "correct" in failing to link the program? And why does it work if I initialize the template variable?
As far as I know, template variables are just syntactic sugar for template wrappers around static members, so n<int> = 42
is effectively specializing the int
instance. IMO, the code should link.
You can fix the errors by including the source code file that contains the definitions as part of the compilation. Alternatively, you can pass . obj files or . lib files that contain the definitions to the linker.
Linker errors occur when g++ tries to combine all of your .o files into an executable file. Linker errors CANNOT be fixed by guarding header files or by changing which header files are included in your . cpp file. non-aggregate type -- classes and structs are generically called "aggregate" types.
These are the linking errors caused when the compiler tries to link your application with the appropriate libraries that define all the symbols. Just providing the path to these libraries (lib files) is not enough. You will need to add them manually to your Visual Studio project in order to resolve all the symbols.
Yes. Template compilation errors are seriously verbose. There's a lot of information there that's not needed. However, most of them do start with the line number of where the template was used.
This is a bug in clang++ #22825. The bug report has been filed on 2015-03-06 and the bug has not yet been fixed. Richard Smith supposes this definition is incorrectly treated only as a forward-declaration.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With