Undefined Reference to sqrt in C

Problem:- Undefined reference to sqrt() in C Programming (or other mathematical functions) even includes math.h header

Windows user doesn’t get any warning and error but Linux/Unix user may get an undefined reference to sqrt. This is a linker error.

In the below program, We used sqrt() function and include math.h

int main()
   int x = 9, result;
   result = sqrt(x);
   printf("Square root = %d\n", result);
   return 0;

If you are using a Linux environment, and when you compile the above program with,

gcc test.c -o test

Then you will get an error like this:-
/tmp/ccstly0l.o: In function main':
test.c:(.text+0xb5): undefined reference tosqrt'
collect2: error: ld returned 1 exit status


This is a likely a linker error. The math library must be linked in when building the executable. So the only other reason we can see is a missing linking information. How to do this varies by environment, but in Linux/Unix, just add -lm to the command. We must link your code with the -lm option. If we are simply trying to compile one file with gcc, just add -lm to your command line, otherwise, give some information about your building process. To get rid of the problem undefined reference to sqrt in C, use below command to compile the program in place of the previous 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. 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.

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or you find anything incorrect? Let us know in the comments. Thank you!

More C programming examples

4 thoughts on “Undefined Reference to sqrt in C”

  1. In my experience, this fix does not do anything to resolve the problem. I get the same feedback after I add -lm command. I am using Ubuntu.

    [email protected]:~/Desktop/learning c$ gcc -g -lm -std=c99 -w buggyApp.c

    /usr/bin/ld: /tmp/ccuhg7Me.o: in function `isPrime':
    /home/cory/Desktop/learning c/buggyApp.c:71: undefined reference to `sqrt'
    collect2: error: ld returned 1 exit status

    1. Thanks for the comment. In this case, you should write your own square root function. So you may not need the extra flag potentially.

Leave a Reply