Before writing the use of multi-directory makefile need to have several functions and symbols
Custom Variables
target=edit
When referenced directly$(target)
A bit like the C language #define
, here $(target)
will be replaced edit
.
You can also replace multiple files, pay attention to space
object=main.o xxx.o xxx.o
Automatic variables
Automatic variables are used in the second row is gcc -c xxx
in
$<
: The first rule of a dependent
$@
: Target rule
$^
: Rule all depends
$(target):$(obj)
gcc \$^ -o \$@
This line means that the rules all the dependencies ($ ^) (. O files) to generate the target ($ @)
$(target)
Auto match
Sub rule:
目标:依赖
%.o:%.c
Rely on automatic matching of the ultimate goal:
main.o: main.c
add.o: add.c
sub.o: sub.c
makefile function
pro=$(wildcard src/*.c)
src=$(wildcard *.c)
obj=$(patsubst %.c,%.o,$(pro) $(src))
wildcard
Find all .c files in the current directory and the src directory, and are returned to the pro src
pro=$(wildcard *.c)
src=$(wildcard src/*.c)
patsubst
replace all .c files to .o files
obj=$(patsubst %.c,%.o,$(pro) $(src))
Note:
I will be here with a space$(pro) $(src)
separated, so at compile time system is notmain.cxxx.c
the case, that is connected to the head and tail.
So, preparatory work is complete.
Code
.
├── main.c
├── makefile
└── src
├── Speak.c
└── Speak.h
main.c
#include <stdio.h>
#include "src/Speak.h"
int main()
{
printf("Helo\n");
Speak();
return 0;
}
src/Speak.c
#include "Speak.h"
void Speak(void)
{
printf("Speak\n");
}
src/Speak.h
#include <stdio.h>
void Speak(void);
Here began to explain the makefile
pro=$(wildcard *.c)
src=$(wildcard src/*.c)
obj=$(patsubst %.c,%.o,$(pro) $(src))
target=edit
$(target):$(obj)
gcc $^ -o $@
%.o:%.c
gcc -c $< -o $@
.PHONY:clean
clean:
rm $(obj) $(target) -f
We will root .c files in the directory (only one main.c) through a wildcard
return to thepro
src
.C files in the directory by wildcard
the return tosrc
By patsubst
replacing all .c files to .o files
By then rely on automatic matching
%.o:%.c
gcc -c $< -o $@
.O files are generated every .c file
The final edit is generated executable file
$(target):$(obj)
gcc $^ -o $@
sort out:
Using the
wildcard
return .c files in each directory,The use of
patsubst
individual .c into .o (This step does not generate .o file, only the equivalent of amain.c
return tomain.o
)- The use of automatic matching to automatically generate various .o (this step is to generate .o file)
All .o executable file edit