Undefined Reference to Standard Library Function
linker
undefined reference to 'sqrt'
Description
The linker cannot find a standard library function that is used in the code.
Common Causes
- Forgetting to link the math library (
-lm
) - Using a function from a library that isn't linked
- Typo in function name
Example of Error
Error Code
#include <math.h>
#include <stdio.h>
int main() {
double result = sqrt(2.0);
printf("Square root of 2 is %f\n", result);
return 0;
}
// Compiled with: gcc -o program main.c
// Missing -lm flag
Solution
Link the appropriate library when compiling.
Corrected Code
// Compile with:
// gcc -o program main.c -lm
Additional Tips
- The math library requires explicit linking with
-lm
- Some functions may be in libraries other than the standard C library
- Check the documentation to see which library a function belongs to