nowox
nowox

Reputation: 29178

What would be the minimal Makefile for a C project?

I find plenty of answers such as this one that doesn't use the implicit rules.

The minimum I can write is this:

SRC = $(wildcard *.c)
OBJ = $(patsubst %.c, %.o, $(SRC))

EXEC=a.exe

all: $(EXEC)

$(EXEC): $(OBJ)
    $(CC) $^ -o $@

clean:
    $(RM) $(OBJ)
    $(RM) $(EXEC)

But I am sure I can remove the linking part as well.

Is it possible to reduce this Makefile a bit more?

EDIT

With the help of Maxim Egorushkin I wrote this:

#Makefile
OBJS=$(patsubst %.c,%.o,$(wildcard *.c))

EXEC=a

$(EXEC): $(OBJS)

all : $(EXEC)

clean :
    rm -f $(OBJS)

.PHONY: all clean

It does build my files, but it doesn't link anything:

$ make
cc    -c -o bar.o bar.c
cc    -c -o cow.o cow.c
cc    -c -o foo.o foo.c

What should I change?

The dummy source files are created as follow:

echo "int main() {return 0;}" > cow.c
touch foo.c bar.c cow.c

Upvotes: 0

Views: 685

Answers (1)

Maxim Egorushkin
Maxim Egorushkin

Reputation: 136515

The bare minimum would be:

all : a

a : a.o b.o c.o

clean :
    rm -f a a.o

.PHONY: all clean

It expects source files a.c, b.c and c.c to produce executable a:

$ touch a.c b.c c.c

$ make
cc    -c -o a.o a.c
cc    -c -o b.o b.c
cc    -c -o c.o c.c
cc   a.o b.o c.o   -o a
/usr/lib/gcc/x86_64-redhat-linux/5.3.1/../../../../lib64/crt1.o: In function `_start':
(.text+0x20): undefined reference to `main'
collect2: error: ld returned 1 exit status
<builtin>: recipe for target 'a' failed
make: *** [a] Error 1

However, you do not get automatic header dependency generation with the built-in GNU make rules. Extra 5 lines would be required for that.

Upvotes: 3

Related Questions