0

I'm having issues with the GCC linker, specifically using the -lm flag since I'm using some functions from math.h. I get the following errors:

main.c:(.text+0x8e5): undefined reference to `floor'

main.c:(.text+0x901): undefined reference to `ceil'

Here's the relevant portion of my makefile:

myprogram: main.o
    gcc -Wall -pedantic -o myprogram main.o

main.o: main.c foo.h bar.h
    gcc -Wall -pedantic -lm main.c

Probably something silly I'm overlooking, but I'm definitely not an expert when it comes to makefiles.

Tyler Treat
  • 14,640
  • 15
  • 80
  • 115
  • Did you make sure to include math.h? – Nick Feb 11 '11 at 01:38
  • Related: *[Why do you have to link the math library in C?](https://stackoverflow.com/questions/1033898/why-do-you-have-to-link-the-math-library-in-c)* (18 answers. 314 upvotes. 2009.) – Peter Mortensen Oct 27 '22 at 23:46

2 Answers2

5

Furthermore, library specifications have to come after the objects referencing them (cf. Linker flags in wrong place ).

Community
  • 1
  • 1
user611775
  • 1,323
  • 7
  • 11
4

-lm is a linker flag, so you should add it to the linking rule above (i.e., you added it to the wrong rule).

vanza
  • 9,715
  • 2
  • 31
  • 34
  • Knew it was a dumb mistake like that, thanks! Will accept when the time limit is up. – Tyler Treat Feb 11 '11 at 01:40
  • 1
    @Tyler There's more to it than that. -lm must come after the objects, as user611775 notes below. And your main.o rule will produce a.out rather than main.o because you are missing -o $@ ... You should be using default rules and setting CFLAGS=Wall -pedantic instead of putting them in the rules. – Jim Balter Feb 11 '11 at 04:09