Tirafesi
Tirafesi

Reputation: 1469

Makefile re-compiles everything

I'm trying to create my first Makefile, however i have a problem: it re-compiles everything, even if nothing is changed. How can i avoid this? Here's the Makefile:

all: rmdup lsall lsdir

rmdup: rmdup.c
  cc -Wall -o ./bin/rmdup rmdup.c

lsall: lsall.c
  cc -Wall -o ./bin/lsall lsall.c

lsdir: lsdir.c
  cc -Wall -o ./bin/lsdir lsdir.c

Also, as you probably noticed already, the results of the compilation need to be inside the directory ./bin

One more question: What's the difference between what i have, and this?

all: rmdup lsall lsdir

rmdup.o: rmdup.c
  cc -Wall -c -o ./bin/rmdup.o rmdup.c
rmdup: rmdup.o
  cc -o ./bin/rmdup ./bin/rmdup.o

lsall.o: lsall.c
  cc -Wall -c -o ./bin/lsall.o lsall.c
lsall: lsall.o
  cc -o ./bin/lsall ./bin/lsall.o

lsdir.o: lsdir.c
  cc -Wall -c -o ./bin/lsdir.o lsdir.c
lsdir: lsdir.o
  cc -o ./bin/lsdir ./bin/lsdir.o

Thanks in advance!

Upvotes: 1

Views: 1684

Answers (1)

jdarthenay
jdarthenay

Reputation: 3147

Answer to first question: your targets don't match the files they produce, fix this way. Also add a .PHONY target to tell make all is not a file.

all: bin/rmdup bin/lsall bin/lsdir

bin/rmdup: rmdup.c
    cc -Wall -o bin/rmdup rmdup.c

bin/lsall: lsall.c
    cc -Wall -o bin/lsall lsall.c

bin/lsdir: lsdir.c
    cc -Wall -o bin/lsdir lsdir.c

.PHONY: all

Answer to second question: the second makefile is designed to compile object file, then link programs. It can be interesting when linking links several object files. It reduces the building time if only few source fiels have been modified.

Edit: to clarify my answer to second question, here is a makefile you could use to compile a program with its main source being main.c and using any number of modules you wrote, each with a header .h and a source file .c

CC=gcc
CFLAGS=-Wall -Wextra -Werror -stg=gnu99
LDFLAGS=-lm

SRCS=$(wildcard *.c)
OBJS=$(SRCS:%c=%.o)
HEADERS=$(wildcard *.h)

.PHONY:all mrproper clean

all:main

main:$(OBJS)
    $(CC) -o $@ $? $(LDFLAGS)

main.o:main.c $(HEADERS)
    $(CC) $(CFLAGS) -o $@ $<

%.o:%.c %.h
    $(CC) $(CFLAGS) -o $@ $<

mrprorer:clean
    rm -f main

clean:
    rm -f $(OBJS)

You build the first time with make all, and if you change only one source file you will only have one object file to generate and the linking to do again.

Upvotes: 6

Related Questions