I am currently learning C and now I am upto the tutorial where I need to write the Makefile but I am difficulty writing a Makefile for multiple sources. Can someone tell me how I can correct my code for the Makefile for multiple sources? All of the files are in the same directory and there are a total of 3 C source files as indicated by filename1/2/3 etc. I am trying to build 3 separate programs with 3 source files in a single makefile
OPT = -O4
all: filename1
filename1: filename1.o
gcc $(OPT) -o filename1 filename1.o
filename1.o: filename1.c
gcc $(OPT) -c filename1.c
filename2: filename2.o
gcc $(OPT) -o filename2 filename2.o
filename2.o: filename2.c
gcc $(OPT) -c filename2.c
filename3: filename3.o
gcc $(OPT) -o filename3 filename3.o
filename3.o: filename3.c
gcc $(OPT) -c filename3.c
clean:
rm -f *.o
rm -f filename1
rm -f filename2
rm -f filename3
Or is my code fine for what I want it to do?
Okay, so there doesn't appear to be anything wrong with the makefile, given that you're making three different programs. It should work.
Some suggestions for making it a little more usable:
1) Declare the "all" and "clean" targets to be phony. This will prevent Make from trying to make files called "all" and "clean".
.PHONY: all clean
2) You probably want your "all" target to build all three of your programs, not just one, so change that to:
all: filename1 filename2 filename3
3) If you end up using this to make more than three programs, and they all share similar build procedures, you can collapse your rules into a smaller set using pattern matches. See Martin Beckett's answer for an example. But, that's not necessary.
Your makefile should work, but it could be simplified.
The make
utility supports implicit rules. This can simplify common operations, such as compiling a C source code file into an object file and compiling an object file into an executable.
CC=gcc
CFLAGS=-O4
all: filename1 filename2 filename3
%.o: %.c
$(CC) $(CFLAGS) -c $<
%: %.o
$(CC) $(CFLAGS) -o $* $<
clean:
rm -f *.o
rm -f filename1
rm -f filename2
rm -f filename3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With