Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linker error with variable templates

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.

like image 867
vsoftco Avatar asked Jun 17 '15 15:06

vsoftco


People also ask

How do you fix a linker error?

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.

What causes a linker error?

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.

How to solve linker error in Visual Studio?

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.

Can using templates lead to errors in the program?

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.


1 Answers

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.

like image 85
dyp Avatar answered Nov 15 '22 17:11

dyp