I am trying to write a makefile which uses macros to create multiple executables from multiple files at once. I tried searching through previously answered questions but, because I am fairly new to programming in C as well as working with gcc, I was not able to find an answer to my question.
Here is what I have so far:
CC=gcc
CFLAGS=-I.
OBJ = ex1.c ex3.c
EXECUTABLE = ex1 ex3
$(EXECUTABLE): $(OBJ)
gcc -o $@ $^ $(CFLAGS)
clean:
rm -f $(EXECUTABLE)
I would like the line
$(EXECUTABLE): $(OBJ)
to create executables ex1 and ex3 from files ex1.c ex3.c respectively.
Some suggestions (assuming you use GNU make, not something else)
First, run once
make -p
, you'll understand what builtin rulesmake
is knowing. Look in particular forCOMPILE.c
andLINK.c
Then, I suggest
(because you really want
-g
for debugging, and-Wall
to get most warnings)And you probably don't need
However, I suggest adding before most other rules
Actually, I would code your
Makefile
(for GNUmake
!) as followRemember that tab is a significant character in
Makefile
-s (action part of rules). In this answer, lines starting with four spaces at least should really start with a tab character.Once everything is debugged consider running
make clean
to clean everything, and thenmake -j CFLAGS=-O2 all
to compile in parallel everything with optimizations.At last, I recommend using
remake
and runningremake -x
to debug complexMakefile
-sOf course, I'm supposing that your directory has only single-file programs.
BTW, there are other builder programs. Perhaps you might consider omake
Don't forget to use a version control system like git for your source files. It is also time to learn such a tool.
For this particular case, where each executable has a single source file with
.c
extension, all you need is a one line Makefile:The built-in default rules for
make
then work already:Behind the scene,
make
is using the POSIXly mandated built-in single suffix ruleVary the command to your liking with
make CC=gcc CFLAGS=-O2 LDFLAGS=-s
and similar.Trivia of the day: in fact, if you are willing to name the targets when invoking
make
, you can use an empty or even run without any Makefile:Make magic!
As a rule of thumb, don't reinvent the wheel (or rules), use the rules that are already there. It simplifies your and make's life a lot. This makes for small and sexy makefiles to impress the ladies with :-)
The following answer includes multiple executable such as initiate, process1, process2, ..., process4.
NOTE: It is a good practice to clean and touch all the executable files before making them again.
You're close, but you need a pattern rule:
And then a default rule to make it build both: