Template operator linker error
- by Dani
I have a linker error I've reduced to a simple example.
The build output is:
debug/main.o: In function main':
C:\Users\Dani\Documents\Projects\Test1/main.cpp:5:
undefined reference tolog&
log::operator<< (char
const (&) [6])'
collect2: ld returned
1 exit status
It looks like the linker ignores the definition in log.cpp.
I also cant put the definition in log.h because I include the file alot of times and it complains about redefinitions.
main.cpp:
#include "log.h"
int main()
{
log() << "hello";
return 0;
}
log.h:
#ifndef LOG_H
#define LOG_H
class log
{
public:
log();
template<typename T>
log &operator <<(T &t);
};
#endif // LOG_H
log.cpp:
#include "log.h"
#include <iostream>
log::log()
{
}
template<typename T>
log &log::operator <<(T &t)
{
std::cout << t << std::endl;
return *this;
}