Makefile detailed

Original link: https://blog.csdn.net/qq_38646470/article/details/79917494
Column link: https://blog.csdn.net/column/details/20028.html
    Maybe many Winodws programmers don't know this Stuff, because those Windows IDEs do the job for you, but I think to be a good and professional programmer, you still need to understand makefiles. When compiling software under Linux, you have to write makefiles yourself. Whether or not you will write makefiles shows from one side whether a person has the ability to complete large-scale projects.
    The makefile is related to the compilation rules of the entire project. The source files in a project are not counted, they are placed in several directories according to type, function and module. The makefile defines a series of rules to specify which files need to be compiled first, which files need to be compiled later, and which files need to be recompiled. Compilation, and even more complex functional operations, because the makefile is like a shell script, which can also execute the commands of the operating system.
    The advantage of makefile is - "automatic compilation", once it is written, only one make command is needed, and the entire project is completely automatically compiled, which greatly improves the efficiency of software development.
Let's see how to write Makefile files:
Makefile file writing specification:

目标:依赖文件                               
 $^  代表所有依赖文件
 $@  代表所有目标文件
 $<  代表第一个依赖文件
 %   代表通配符
 @指令:屏蔽指令
定义变量(变量大写)
变量名=值1 值2 ...
使用变量 $(变量名)

Let's look at the example:
Suppose we have many files (fun1.c fun2.c fun3.c main.h)
Suppose we finally want to get the
primary version of the main file:

.PHONY : clean

main : fun1.o fun2.o fun3.o main.o
    gcc -g fun1.o fun2.o fun3.o main.o -o main
fun1.o : fun1.c main.h
    gcc -Wall -c -g -o fun1.o
fun2.o : fun2.c main.h
    gcc -Wall -c -g -o fun2.o
fun3.o : fun3.c main.h
    gcc -Wall -c -g -o fun3.o

clean :
    rm -rf *.o

Lite

.PHONY : clean

FM=fun1.o fun2.o fun3.o main.o

main : $(FM)
    (前面一个tab键)gcc -g $^ -o $@
%.c : %.o
    (前面一个tab键)gcc -c -g - Wall $< -o $@
clean :
    (前面一个tab键)rm -rf *.o

Take a look at the test effect:
write picture description here
Of course, Makefile has many other uses. For a deeper understanding, please see Makefile in-depth analysis

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325656719&siteId=291194637