gcc gives error while using fmod()
Asked Answered
D

3

10

Sample code for fmod:

#include <stdio.h>    
#include <math.h>

int main(void)   
{    
  double x = 0.14527, y = 3.14159;   
  printf("fmod(x, y) = %.6lf\n", fmod(x, y));    
  return 0;    
}

Compiling:

$ gcc main.c -o main

I get

/tmp/ccztJO01.o: In function `main':

main.c:(.text+0x4d): undefined reference to `fmod'

collect2: ld returned 1 exit status

Then I found this in Google:

$ gcc -lm main.c -o main

Why should I use -lm, what is it exactly? From where I can get more information about gcc in detail?

Development answered 9/7, 2010 at 3:59 Comment(0)
T
12

-lm is simply telling it to link libm, which contains all the floating point math routines, including (no surprise here) fmod.

Thy answered 9/7, 2010 at 4:1 Comment(0)
D
7

When I input gcc -lm main.c -o main I still get a linker error. I need to write gcc main.c -lm -o main for it work right. If it's working for you the other way, that's a bit odd. I understand that the linker will find the symbol declared in main.c (i.e. double fmod(double,double)), but only resolve it if it finds its definition later on (i.e. in libm.a).

Long story short, the libraries must be placed (at least once) "to the right of" the place where they are used.

Diphenylhydantoin answered 23/12, 2018 at 10:54 Comment(2)
Back in 2010, when this question was asked, most linux distros configured GCC to link shared libraries whether they appeared before or after they were referenced in the linkage sequence. And some still do.Luxuriate
Interesting. I added an answer because I thought it may be useful for someone else looking into this error.Diphenylhydantoin
V
5

It's not the compiler, but the linker, ld, that is complaining. It cannot find the routine fmod in your program. You have to tell it to link with math library libm with the -l flag.

[Much] more info: GCC, the GNU Compiler Collection.

Volsung answered 9/7, 2010 at 4:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.