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?
3 Answers
SRCS = $(wildcard *.c)
PROGS = $(patsubst %.c,%,$(SRCS))
all: $(PROGS)
%: %.c
$(CC) $(CFLAGS) -o $@ $<
-
@Martin brilliant! But I don't understand why you don't call PROGS and SRCS in the main line. Feb 6, 2015 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.– user325117Dec 23, 2015 at 10:55
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.
-
1You should use
.PHONY
for a target likeclean
. See stackoverflow.com/questions/2145590/… for the reason.– user325117Jan 13, 2017 at 16:12 -
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.