-
Template linker error
I'm getting an undefined reference linker error with the following. I understand that the object code is not being generated but I'm not sure how to change that.
templ_main.cpp
Code:
#include "templ.h"
int main (void)
{
print(1);
print('c');
print("Hello World");
return 0;
}
templ.h
Code:
#ifndef TEMPL_H_
#define TEMPL_H_
template <typename T> void print(T);
#endif
templ.cpp
Code:
#include "templ.h"
#include <iostream>
template <typename T> void print(T var)
{
std::cout<<var<<endl;
}
Any ideas on how to force the compiler to generated the needed object code?
-
Put declaration and definition in the same header file.
-
I think you have to put the declaration and definition in the same file. There also may be a compiler-dependent way to make it work in separate files if I remember correctly...
-
No other way? If so that is just another reason for me to hate c++ (having to put code inside a header file)
-
I looked back through posts, and it sounds like there is a keyword export in some versions of MSVC...I don't know what compiler your using though
-
g++, but I'll give it a try. Thanks :)
-
-
Yeah I know it sucks having to do that. The way I and many other people do it is to put the implementation in a "inl" file and then include that in the bottom of the header. That way your header files aren't all cluttered and you kind-of have the implementation separate.
-
Thanks all
Hate_for_cpp++;
-
You don't typically "link" to templated functions or types. The template "instantiation" is done at compile time.
So by the time the linker see's anything, code for print(double), print(int), print(Ojbect), etc... has already been generated and compiled by the compiler.
>> If so, that is just another reason for me to hate c++
You can orginize your code however your want. Just know that any template you use must of already been seen by the compiler or will be seen before the compiler finishes the current unit (see edit).
Go open up your <iostream> and the files that it includes....99% of it is implemented right there in the headers.
[EDIT]
Unless you have the Comeau compiler....
[/EDIT]
gg
-
hmm, I have g++ and it isnt giving me troubles at all with templating outside of the header. The only thing it I am sillyI am sillyI am sillyI am sillyI am sillyes at is constructor implementation has to be done in the header file , in the class declaration no less/
-
>> templating outside of the header.
What exactly does that mean?
You can put templates anywhere you want. For most compilers, template functions and types are fully resolved and instantiated when the unit is compiled.
gg