Reputation: 11
For example:
There are 3 source files {main.c
test1.c
test2.c
} in the directory
and a directory file named test3
,
and there is a source file named test.c
in the directory of test3
.
Now I want to create a makefile to compile and link these four source files.
And this is my Makefile:
# Cancel statement "CC=gcc"
src:=$(wildcard *.c) test3.c
obj:=$(patsubst %.c,%.o,$(src))
main:$(obj)
gcc -o main $(obj)
.PHONY:clean
clean:
rm *.o *~
When I called make
to compile them, I got a output like this:
cc -c -o main.o main.c
cc -c -o test1.o test1.c
cc -c -o test2.o test2.c
cc -c -o test3.o test3/test3.c
gcc -o main main.o test1.o test2.o test3.o
I know 'cc' is linked to 'gcc' in Linux.
What I don't understand is why did Make call cc
to compile these four source files, but call gcc
to link the object files?
Upvotes: 1
Views: 1130
Reputation: 30881
You wrote only the rule to link the object files, and allowed Make to use its default rule to decide how to build the object files from the source files.
GNU Make will expose its rules if you ask it with --print-data-base
. In this case, it tells us
%.o: %.c
# recipe to execute (built-in):
$(COMPILE.c) $(OUTPUT_OPTION) $<
and
COMPILE.c = $(CC) $(CFLAGS) $(CPPFLAGS) $(TARGET_ARCH) -c
and finally
CC = cc
This explains why Make uses cc
to compile your C sources. To change that, simply set CC = gcc
. Here's a complete Makefile which does that and also makes best use of Make's built-in rules, to help when you need to extend it:
src := $(wildcard *.c) test3.c
obj := $(patsubst %.c,%.o,$(src))
CC = gcc
main: $(obj)
$(LINK.c) -o $@ $^ $(LDLIBS)
.PHONY: clean
clean:
$(RM) *.o *~
Upvotes: 0
Reputation: 100956
You changed one rule: the one that links the program main
from the object files. And when make did that link, you can see it used gcc
.
You didn't do anything to change the built-in rules that make is using to compile the object files, so they use the default (the value of the variable CC
) which is cc
.
Upvotes: 5