I have a very weird error: I have a pair of .h and .cpp files that contain some functions and constants. When I try to compile it, g++ says "undefined reference" to the function. The function prototype and definition seem to be the same. I have commented everything out except the necessary lines, and g++ still complains about it.
My program is currently (after commenting everything out):
main.cpp
#include "a.h"
int main(){
makehex(10);
return 0;
}
a.h
#include <iostream>
#include <sstream>
#ifndef __A___
static const std::string b = "01";
static const std::string d = b + "23456789";
static const std::string h = d + "abcdef";
template <typename T> std::string makehex(T value, unsigned int size = 2 * sizeof(T));
#endif
a.cpp
#include "a.h"
template <typename T> std::string makehex(T value, unsigned int size){
// Changes a value to its hexadecimal string
if (!size){
std::stringstream out;
out << std::hex << value;
return out.str();
}
std::string out(size, '0');
while (value && size){
out[--size] = h[value & 15];
value >>= 4;
}
return out;
}
There is only 1 function. I dont see how this could error.
Im compiling with g++ -std=c++11 main.cpp a.cpp
and getting the errors:
main.cpp:(.text+0x1a): undefined reference to `std::string makehex<int>(int, unsigned int)'
collect2: error: ld returned 1 exit status
Is it because of the template? If so, how do i fix it?