-lm compiler switch is used with the
GCC compiler to link the
math library (libm).
Syntax
gcc program.c -lm
Here,
| Part | Description |
|---|---|
gcc |
GNU C Compiler. |
program.c |
Name of the C source file. |
-lm |
Links the mathematical library (libm). |
Example Program
#include
#include
int main()
{
double result;
result = sqrt(64);
printf("Square Root = %.2lf", result);
return 0;
}
Compilation Command
gcc program.c -lm
or
gcc program.c -o program -lm
Run the Program
./program
Output
Square Root = 8.00
Why Is -lm Required?
The mathematical functions declared in the
header file are implemented in a
separate library called libm. Simply including
gives the compiler access to the
function declarations, but the linker still needs to know where the
actual function implementations are located.
Common Math Functions
| Function | Description |
|---|---|
sqrt() |
Calculates the square root. |
pow() |
Calculates the power of a number. |
sin() |
Returns the sine of an angle. |
cos() |
Returns the cosine of an angle. |
tan() |
Returns the tangent of an angle. |
log() |
Calculates the natural logarithm. |
ceil() |
Rounds a number upward. |
floor() |
Rounds a number downward. |
What Happens If -lm Is Not Used?
The program may compile successfully, but the linker will generate an error because it cannot find the implementation of the math functions.
undefined reference to 'sqrt'
collect2: error: ld returned 1 exit status
Common Mistakes
Avoid These Mistakes
- Including
but forgetting to use-lm. - Typing
-1m(digit one) instead of-lm(letter l). - Placing
-lmbefore the source file in complex compile commands. - Assuming all standard libraries are linked automatically.
Best Practices
- Always include
when using mathematical functions. - Link the math library using
-lm. - Place
-lmat the end of the GCC command. - Compile with warning flags such as
-Wallto detect issues.
Prerequisites
Before Learning This Topic
- Basic understanding of C programs.
- Knowledge of the GCC compiler.
- Understanding of header files.
- Basic familiarity with mathematical functions in C.
Interview Questions
- Why is the
-lmcompiler switch used in GCC? - What does the
header file provide? - What happens if
-lmis omitted while usingsqrt()? - What is the purpose of the libm library?
- Write the GCC command to compile a program that uses
pow().
Key Takeaway
When compiling C programs that use mathematical functions from
, the GCC compiler requires the
-lm switch to link the
mathematical library (libm). Without this switch,
the linker cannot locate the implementations of functions such
as sqrt(), pow(), and
sin(), resulting in linker errors.