Is there a way using GNU Make of compiling all of the C files in a directory into separate programs, with each program named as the source file without the .c extension?
Asked
Active
Viewed 2.8k times
3 Answers
61
SRCS = $(wildcard *.c)
PROGS = $(patsubst %.c,%,$(SRCS))
all: $(PROGS)
%: %.c
$(CC) $(CFLAGS) -o $@ $<

Pascal Cuoq
- 79,187
- 7
- 161
- 281
-
@Martin brilliant! But I don't understand why you don't call PROGS and SRCS in the main line. – Herman Toothrot Feb 06 '15 at 18:12
-
@user4050, sorry, I missed your question. The default `all` target builds `$(PROGS)`, and the main line says how to build files without an extension, which is what `$(PROGS)` are, from `%.c` files, which is what `$(SRCS)` are. – Dec 23 '15 at 10:55
8
SRCS = $(wildcard *.c)
PROGS = $(patsubst %.c,%,$(SRCS))
all: $(PROGS)
%: %.c
$(CC) $(CFLAGS) -o $@ $<
clean:
rm -f $(PROGS)
Improving Martin Broadhurst's answer by adding "clean" target. "make clean" will clean all executable.

Pratik
- 1,596
- 2
- 13
- 10
-
1You should use `.PHONY` for a target like `clean`. See http://stackoverflow.com/questions/2145590/what-is-the-purpose-of-phony-in-a-makefile for the reason. – Jan 13 '17 at 16:12
-
7
I don't think you even need a makefile - the default implicit make rules should do it:
$ ls
src0.c src1.c src2.c src3.c
$ make `basename -s .c *`
cc src0.c -o src0
cc src1.c -o src1
cc src2.c -o src2
cc src3.c -o src3
Edited to make the command line a little simpler.

Carl Norum
- 219,201
- 40
- 422
- 469