0. PrefaceFrom the beginning of learning C language began to contact Makefile, consulted a lot of makefile information but always feel no real master makefile, if you write a makefile always feel very laborious. So deliberately using the blog to summarize the relevant knowledge of makefile, through examples to illustrate the specific use of makefile. The example says that makefile roughly divides into 4 parts 1. Only a single C file 2. Contains multiple C files 3. The header file path 4 needs to be included. A more complex example of the "code warehouse"--makefile-example code warehouse is located in BitBucket, You can clone the code with TORTOISEHG (GUI tools) or download the zip package directly from the Web page.
1. Three C filesThree files in the same directory."TEST.c"
#include <stdio.h>int main (void) { int a = 3; int b = 2; printf ("a=%d\n", a); printf ("b=%d\n", b); printf ("a+b=%d\n", a+b); printf ("a-b=%d\n", A-B); return 0;}
"TEST-ADD.C"
int add (int a, int b) { return a+b;}
"TEST-SUB.C"
int sub (int a, int b) {return a-a ;}
2. Review GCC directivesMultiple C files and a single C file are treated similarly, and you can add more than one C file or a target file after-C or-O."Compiling source Files"Gcc-ctest.c TEST-ADD.CTest-sub.c"link destination file"Gcc-o TestTEST.O TEST-ADD.Otest-sub.o"Execute target file"./test"Console Output"A=3 b=2 a+b=5 a-b=1
3. Writing the makefile file"Makefile"Replace [tab] with the makefile file in the code warehouse.
# directive compiler and options cc=gcccflags=-wall-std=gnu99# destination file target=test# source file srcs=test.c test-add.c Test-sub.cobjs = $ (SRCS:.C=.O) $ ( TARGET): $ (OBJS) # @echo Target:[email protected]# @echo objects:$^[tab]$ (CC)-o [email protected] $^CLEAN:[TAB]RM-RF $ ( TARGET) $ (OBJS)%.o:%.c[tab]$ (CC) $ (CFLAGS)-o [email protected]-C $<
"Specific Instructions""1" For more information please refer to: Example makefile--Single file "2" relative to a single file, here only modified srcs=test.c test-add.c TEST-SUB.C, variable SRCs appended more than C files. This line is only modified when compared to a single file. "3" is separated by a space between the file and the file."Execution Process"Make clean && make"Console Output"RM-RF test TEST.O test-add.o test-sub.ogcc-wall-std=gnu99-o test.o-c test.cgcc-wall-std=gnu99-o test-add.o-c test -add.cgcc-wall-std=gnu99-o test-sub.o-c test-sub.cgcc-o Test TEST.O test-add.o test-sub.o from the console output, you can see Clear the last executable and target files, compile each C file in turn, and finally link the 3 target files to the final executable file.