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 πŸ™‚

Advertisements

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 πŸ™‚


September 2019
M T W T F S S
« Jun    
 1
2345678
9101112131415
16171819202122
23242526272829
30  

Twitter

Flickr Photos

Advertisements