Quite often I see, or get asked why certain math functions don’t compile properly when all the necessary includes are correctly applied. For example:
Compiling the above code with the command
#include <stdio.h>
#include <math.h>
int main()
{
double value = 9.0;
double ans = sqrt(value);
char szBuffer[256];
sprintf(szBuffer,"%f",ans);
printf("%s",szBuffer);
return 0;
}Compiling the above code with the command
gcc main.cgives an error indicating that sqrt is undefined.
$ gcc main.c /tmp/ccHazXRB.o: In function `main': main.c:(.text+0x48): undefined reference to `sqrt' collect2: ld returned 1 exit statusThe simple problem here is that the code isn’t linked against the math library so the math functions cannot be resolved. The correct way to compile is using the -lm option which instructs the linker to use the math library.
$ gcc main.c -lmOne thing to remember is the location of the -lm option. This usually has to be placed after the filename that is being compiled or it does not get picked up when using gcc as the compiler. When using g++, the location of the -lm option doesn’t matter.
Comments
Post a Comment