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

前端 未结 1 1598
时光说笑
时光说笑 2020-11-27 07:44

I created a small program, as follows:

  #include 
  #include 
  #include 

  int main(int argc, char *argv[])         


        
相关标签:
1条回答
  • 2020-11-27 08:28

    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.

    0 讨论(0)
提交回复
热议问题