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

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


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