5

I need to use logs in a program for an assignment. I ran this test program on my machine to see how the log function works (and if it would), and I get the following error during build.

Code

/* log example */
#include <stdio.h>      /* printf */
#include <math.h>       /* log */

int main()
{
  double param, result;
  param = 5.5;
  result = log (param);
  printf ("log(%f) = %f\n", param, result );
  return 0;
}

ERROR

gcc -Wall -o "test" "test.c" (in directory: /home/linux/Development/codetest)
/tmp/ccCDqX7x.o: In function `main':
test.c:(.text+0x1b): undefined reference to `log'
collect2: ld returned 1 exit status
Compilation failed.

Link

This is C99 code, grabbed from this tutorial site.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278

1 Answers1

5

Add -lm to your compilation command to link in the math library.

gcc -Wall -o "test" "test.c" -lm
jxh
  • 69,070
  • 8
  • 110
  • 193
  • 1
    I've always thought it a bit odd that gcc doesn't just pull in the math lib by default. – Cory Nelson Aug 03 '13 at 02:08
  • Ancient tradition, partly dating back to when not all CPUs had floating point arithmetic built in, so you might need software emulation, etc. FWIW: on Mac OS X (10.8.4, but also earlier versions), you don't need the `-lm` to link the example code. – Jonathan Leffler Aug 03 '13 at 03:08
  • I have the same feeling. `math.h` is not been added to the default linking libs. a little bit unbelievable. – dongrixinyu Mar 01 '23 at 08:22
  • @dongrixinyu There is a practical reason, but it could be accomplished with a compiler flag. There are certain critical systems (like OS kernels) that explicitly disable the FPU. This is to make sure their software will always be able to run on systems that do not have a FPU. So, implicitly linking in a library that uses FPU might cause an unintended crash if the code path that uses it is traversed. So leaving `-lm` off provides some protection. However, a compiler flag that explicitly leaves it out would serve the same purpose for those rare cases. – jxh Mar 01 '23 at 17:07