Why am I getting “undefined reference to sqrt” error even though I include math.h header? [duplicate]

对着背影说爱祢 提交于 2019-11-26 03:35:47

问题


This question already has an answer here:

  • undefined reference to sqrt (or other mathematical functions) 5 answers

I\'m very new to C and I have this code:

#include <stdio.h>
#include <math.h>
int main(void)
{
  double x = 0.5;
  double result = sqrt(x);
  printf(\"The square root of %lf is %lf\\n\", x, result);
  return 0;
}

But when I compile this with:

gcc test.c -o test

I get an error like this:

/tmp/cc58XvyX.o: In function `main\':
test.c:(.text+0x2f): undefined reference to `sqrt\'
collect2: ld returned 1 exit status

Why does this happen? Is sqrt() not in the math.h header file? I get the same error with cosh and other trigonometric functions. Why?


回答1:


The math library must be linked in when building the executable. How to do this varies by environment, but in Linux/Unix, just add -lm to the command:

gcc test.c -o test -lm

The math library is named libm.so, and the -l command option assumes a lib prefix and .a or .so suffix.




回答2:


You need to link the with the -lm linker option

You need to compile as

gcc test.c  -o test -lm

gcc (Not g++) historically would not by default include the mathematical functions while linking. It has also been separated from libc onto a separate library libm. To link with these functions you have to advise the linker to include the library -l linker option followed by the library name m thus -lm.




回答3:


This is a likely a linker error. Add the -lm switch to specify that you want to link against the standard C math library (libm) which has the definition for those functions (the header just has the declaration for them - worth looking up the difference.)




回答4:


Because you didn't tell the linker about location of math library. Compile with gcc test.c -o test -lm




回答5:


Add header:

#include<math.h>

Note: use abs(), sometimes at the time of evaluation sqrt() can take negative values which leave to domain error.

abs()- provides absolute values;

example, abs(-3) =3

Include -lm at the end of your command during compilation time:

gcc <filename.extension> -lm



来源:https://stackoverflow.com/questions/10409032/why-am-i-getting-undefined-reference-to-sqrt-error-even-though-i-include-math

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!