Henry
Henry

Reputation: 6620

Makefile many similar files

With many similar files in a directory:

answer1.c
answer2.c
answer3.c

To be able to run:

# make s1
# ./answer1

Currently I have:

s1:
    gcc -Wall -ansi answer1.c -o answer1
s2:
    gcc -Wall -ansi answer2.c -o answer2

etc.

I know I can put the compiler and the flags in variables, which makes changing things later easier. However, is there a way (some kind of macro expansion) to automate, something like:

#=1 2 3 4 5 6
s#:
    gcc -Wall -ansi answer#.c -o answer#

Or even better

#=range(7)

Or would I be better off using a scripting language, perhaps to write the Makefile?

Upvotes: 0

Views: 59

Answers (2)

reinierpost
reinierpost

Reputation: 8591

You're looking for pattern rules:

s%: answer%
answer%: answer%.c
     gcc -Wall -ansi $< -o $@

Issue make -p | less (at least with GNU make) and you will see that make already has built-in rules very similar to that.

Upvotes: 1

Jonathan Leffler
Jonathan Leffler

Reputation: 753505

I'd use just 3 lines of makefile:

CFLAGS = -Wall -ansi

all: answer1 answer2 answer3

With that, you can simply run make and it knows what you want it to do: it will create program answer1 from answer1.c, and program answer2 from answer2.c, and program answer3 from answer3.c.

To build any one of the programs, simply say:

make answer2

Etc.

Upvotes: 3

Related Questions