undefined reference issue in C program



C Program Undefined Reference Issue

Why C program throws undefined reference error?

C programs are used to find the square root value, and throws undefined reference error when compiling the code.

sqrt math function

#include                                                                
#include                                                               
                                                                                
void main()                                                                     
{                                                                               
 float sqrtval, val;                                                            
 val =25.0;                                                                     
 sqrtval = sqrt(val);                                                           
 printf("sqrt of 25 is %f", sqrtval);                                           
}     
Output:
$ cc sqrt-val.c
/tmp/cciHGLUh.o: In function `main':
sqrt-val.c:(.text+0x1b): undefined reference to `sqrt'
collect2: error: ld returned 1 exit status

pow math function

#include                                                                
#include                                                               
                                                                                
void main()                                                                     
{                                                                               
 float sqrtval, val;                                                            
 val =25.0;                                                                     
 sqrtval = pow(val,0.5);                                                        
 printf("sqrt of 25 is %f", sqrtval);                                           
}  
Output:
$ cc sqrt-val.c
/tmp/ccpqCkS1.o: In function `main':
sqrt-val.c:(.text+0x23): undefined reference to `pow'
collect2: error: ld returned 1 exit status

To resolve this issue, we need to use -lm when compiling the code using either cc or gcc compiler.

$ cc sqrt-val.c -lm
$ ./a.out 
sqrt of 25 is 5.000000
or
$ gcc sqrt-val.c -lm
$ ./a.out 
sqrt of 25 is 5.000000

Tamil Daily Calendar (தினசரி தமிழ் காலண்டர்)

Tamil Daily Astrology (இன்றைய ராசிபலன்)

Privacy Policy  |  Copyright@2017 - All Rights Reserved.  |  Contact us   |  Report website issues in Github   |  Facebook page   |  Google+ page

Email Facebook Google LinkedIn Twitter
^