Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

How do you fix undefined reference error?

So when we try to assign it a value in the main function, the linker doesn't find the symbol and may result in an “unresolved external symbol” or “undefined reference”. The way to fix this error is to explicitly scope the variable using '::' outside the main before using it.

What is the header file for math H?

The C <math. h> header file declares a set of functions to perform mathematical operations such as: sqrt() to calculate the square root, log() to find natural logarithm of a number etc.

How do you use sqrt in GCC?

All you need to do is to use a cast operator to convert the type of double. To work with float numbers simply use the “sqrtf()” function and if you want to deal with long double type then use “sqrtl()”. If you enter any negative value as an input, then the function sqrt() in C shows a domain error.

Which header file is required to use sqrt () function?

The sqrt() function is defined in math. h header file. To find the square root of int , float or long double data types, you can explicitly convert the type to double using cast operator.


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.


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.


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.)


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


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