Reputation: 29
I have 3 different C files that are in the same directory which I want to compile separately from one another using a Makefile. This is my Makefile:
program1: program1.o
gcc program1.o -o program1
program1.o: program1.c
gcc -c program1.c
program2: program2.o
gcc program2.o -o program2
program2.o: program2.c
gcc -c program2.c
program3: program3.o
gcc program3.o -o program3
program3.o: program3.c
gcc -c program3.c
clean:
rm program1.o program1 program2.o program2 program3.o program3
When I run the Makefile it only makes the file for program1 and this is the output I get when I run the Makefile:
make: 'program1' is up to date.
Upvotes: 0
Views: 881
Reputation: 123458
Mark Tolonen answered your question, but there are some things you can do to clean this up.
make
has a number of implicit (built-in) rules that handle basic stuff like this - you don't need to write an explcit rule to build an executable from a lone C file, make
already knows how to do that. Your makefile can literally be as simple as
#
# The CC variable specifies what compiler should be used by the implicit rule
#
CC=gcc
all: program1 program2 program3
And that's it. If you want to specify parameters for the compiler, you can use the CFLAGS
variable:
CC=gcc
CFLAGS=-std=c11 -pedantic -Wall -Werror
all: program1 program2 program3
So to build an individual program, you type make program1
or make program2
. To build all three, just type make
or make all
.
Upvotes: 1
Reputation: 2703
If what you mean by "compile separately" is that you want to have the ability to compile them one at a time, then you can invoke you makefile with your desired target like this:
~$ make program2
or
~$ make program3
By default, make invokes the first target in the makefile
Upvotes: 0
Reputation: 177665
make
builds the first target given no other arguments, Pass an argument to build a particular target, or add a first line making the executables a dependency of a rule to build them all by default.
all: program1 program2 program3
Upvotes: 2