Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.3k views
in Technique[技术] by (71.8m points)

Automating makefile for all files in a certain directory

I have a folder (./tests/) that contains a bunch of c files, a.c, b.c, d.c, ..., y.z, z.c. They all contain a main function. I want to write a Makefile that will compile all of the files in that directory independently. Something like this:

test_a: ./tests/a.c $(STUFF)
    gcc $< $(STUFF) $(OTHERSTUFF)

test_b: ./tests/b.c $(STUFF)
    gcc $< $(STUFF) $(OTHERSTUFF)

test_c: ./tests/c.c $(STUFF)
    gcc $< $(STUFF) $(OTHERSTUFF)

test_d: ./tests/d.c $(STUFF)
    gcc $< $(STUFF) $(OTHERSTUFF)

...


test_z: ./tests/z.c $(STUFF)
    gcc $< $(STUFF) $(OTHERSTUFF)

The only difference between all of these targets is the letter in the target name (test_X), and the letter in the first prerequisite (./tests/X.c), which is the same X. So, how could I automate this process so that I dont need to copy and paste the same target a bunch of times?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Assuming you have GNU make, it's pretty simple:

SRCS := $(wildcard tests/*.c)
TARGETS := $(notdir $(SRCS:.c=))

all: $(TARGETS)

$(TARGETS): $(STUFF)

test_%: tests/%.c
        $(CC) -o $@ $^ $(OTHERSTUFF)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...