Search code examples
clinuxgccmakefilepintos

How do I change my makefile to avoid the undefined reference to a function in the maths library?


I'm trying to install PintOS on my local Ubuntu 14.04 machine. When I try to run make to compile the utilities. I get the following error.

ankitkal@ankitkal-Inspiron-5521:~/os/pintos/src/utils$ ls
backtrace  Makefile   pintos   pintos.~1.55.~  pintos-mkdisk             setitimer-helper.o  squish-unix.c
CVS        Makefile~  pintos~  pintos-gdb      setitimer-helper.c         squish-pty.c
ankitkal@ankitkal-Inspiron-5521:~/os/pintos/src/utils$ make
gcc -lm  setitimer-helper.o   -o setitimer-helper
setitimer-helper.o: In function `main':
setitimer-helper.c:(.text+0xbe): undefined reference to `floor'
collect2: error: ld returned 1 exit status
make: *** [setitimer-helper] Error 1
ankitkal@ankitkal-Inspiron-5521:~/os/pintos/src/utils$ 

The maths library (for the <math.h> header which is used in setitimer-helper.c) is not getting linked properly. When I look into the Makefile, this is the output.

ankitkal@ankitkal-Inspiron-5521:~/os/pintos/src/utils$ cat Makefile
all: setitimer-helper squish-pty squish-unix

CC = gcc
CFLAGS = -Wall -W
LDFLAGS = -lm
setitimer-helper: setitimer-helper.o
squish-pty: squish-pty.o
squish-unix: squish-unix.o

clean: 
    rm -f *.o setitimer-helper squish-pty squish-unix

Please tell me how to fix it. I'm using gcc-4.8.6 by the way.


Solution

  • gcc -lm  setitimer-helper.o   -o setitimer-helper
    

    The problem is in the order of your arguments to GCC. Try this:

    gcc -o setitimer-helper setitimer-helper.o  -lm
    

    This is because of the way that ld resolves undefined symbols when linking. Basically, the way you had it before, ld first sees -lm and says "I have no reason to include this library". It then includes your setitimer-helper.o which has an unresolved reference to floor. After that, there are no more libraries to consider, and floor remains unresolved.

    If -lm comes afterward, it is able to resolve the reference to floor.