sqrt from math.h causes linker error “undefined reference to sqrt” only when the argument is not a constant

If you look at the output of the compiler in the case where you used sqrt(10.2), I’ll bet you see that a call to sqrt() isn’t actually made.

This happens because GCC recognizes several functions that it can treat specially. This gives it the ability to do certain optimizations, in this case Constant folding. Such special functions are called Built-ins.

In the case where it must link to the math library (because you’re calling it with a variable), you need to link it explicitly. Some operating systems/compilers do it for you, which is why you might not have noticed in the past.

Leave a Comment