user2203774
user2203774

Reputation: 619

What is missing in my makefile?

I am trying to create my first makefile. I tested my program by using the following commands:

Command 1: gcc -Wall -ggdb3 -std=c99 -o file1 file1.c -lm -lpthread -l
Command 2: gcc -Wall -ggdb3 -std=c99 -o file2 file2.c -lm -lpthread

Everything works great. Then I created a makefile (please see below). I keep getting an error message. Can someone take a look at my code and give me a hint on what the problem is?

file2.o: In function `seed_primes':
file2.c:(.text+0x461): undefined reference to `sqrt'
file2.c:(.text+0x466): undefined reference to `sqrt'
file2:(.text+0x533): undefined reference to `sqrt'
file2.o: In function `create_threads':
file2.c:(.text+0x668): undefined reference to `pthread_create'
file2.c:(.text+0x6b5): undefined reference to `pthread_join'
file2.o: In function `next_seed':
file2.c:(.text+0x860): undefined reference to `sqrt'
collect2: ld returned 1 exit status
make: *** [file2] Error 1

Here is my makefile:

CC=gcc
DEBUG=-ggdb3
CFLAGS=#(DEBUG) -Wall -lm -lpthread -lrt -l

PROGS=file1 file2 

all: $(PROGS) 

file1: file1.o
    $(CC) $(CFLAGS) -o file1 file1.o 

file1.o: file1.c
    $(CC) $(CFLAGS) -c file1.c     

file2: file2.o
    $(CC) $(CFLAGS) -o file2 file2.o 

file2.o: file2.c
    $(CC) $(CFLAGS) -c file2.c  

clean:
    rm -f $(PROGS) *.o *~

Upvotes: 1

Views: 2499

Answers (2)

Carl Norum
Carl Norum

Reputation: 225182

You put all of your flags in CFLAGS which makes them appear before the object files in the command line. Notice that your test commands didn't do that.

Change your flags:

CFLAGS=$(DEBUG) -Wall 
LDFLAGS=-lm -lpthread -lrt

And then in the recipes:

$(CC) $(CFLAGS) -o file1 file1.o $(LDFLAGS)

Upvotes: 1

Jonathan Leffler
Jonathan Leffler

Reputation: 754950

You've set CFLAGS to an empty string because of the # comment character (you probably intended to use a $ instead).

You should not set libraries into CFLAGS; they belong in LDLIBS.

You don't need the file1: rule, the file2: rule, or the object file rules.

CC     = gcc
DEBUG  = -ggdb3
CFLAGS = $(DEBUG) -Wall
LDLIBS = -lm -lpthread -lrt -l

PROGS  = file1 file2 

all: $(PROGS) 

clean:
    rm -f $(PROGS) *.o *~

NB: LDLIBS and the related LDFLAGS are not 100% uniform across variants of make. LDFLAGS should be used for library paths; LDLIBS is for the library names (-lxyz etc).

If you need different libraries for the two programs, you will need to create separate build rules (as you had originally), or use conditional macro assignments (GNU make).

Upvotes: 7

Related Questions