Dependent Origination

Posts Tagged ‘linker

say I have this template function in a header file.

class A {

template<typename T>

bool my_function(T& t);


And its implementation is in a separate cc file. There has been undefined reference errors during linking and I was puzzled. Luckily, amid the puzzling, I noticed that my class A has other functions, which are not template, and which are compiling and linking fine. So this is no visibility issue but gotta be related to it being a template function.

This realization then makes subsequent googling easy: here is exactly same problem on StackOverflow. The solution is you have to put implementation into the same header file, because the compiler has to see the implementation at the time of compiling — it has to be able to instantiate the function during compiling stage. In other words, it has to produce a compiled version of the instantiation of the templated function. It cannot wait until link time.

Remember I have met the same problem years ago, while I was new at the previous job and spent hours figuring out this. Hopefully now I remember this and won’t be puzzled any more in the future πŸ™‚

Let’s say we have two libraries A and B. They both need library C, which is a header file only library since there are only two simple functions in the header file. Now I am building D, which needs both A and B. The linker is complaining multiple definitions of functions of C since both .o files have them.

Solution: make the functions in the header file (of C) inline. This way, it won’t be compiled as a separate function into the object files. Even if the compiler couldn’t make it inline, compiler will find an anonymous namespace and put the function there.

The other solution we can separate out a .cc file from the header that way we would have a third .o file and that solves everything too. But I find the inline solution better in this case, and it increases my knowledge about compiler too πŸ™‚

May 2020


  • is loving shelter-in-place, in fact 2 days ago
  • is sleeping much better during shelter-in-place 2 weeks ago
  • is emotionally ready for the next chapter of life 7 months ago
  • is memorizing Himalaya keyboards and learning to type Tibetan. So exciting. Chinese, English, Spanish, now my fourth language Tibetan! 8 months ago
  • this is a special summer 11 months ago

Flickr Photos