In my opinion, learning to write simple makefile, reading more complex makefile, is the basic quality that every Linux programmer must have. Makefile can automatically identify which source files have been changed, need to recompile, those that are not needed. Thus saving the time of large project recompilation. The rules are as follows: If this project has not been compiled, then all of our C files will be compiled and linked. If a few C files of this project are modified, we only compile the modified C file and link the target path. If the header file for this project is changed, we need to compile the C file that references the header files and link the target program.
Learning to write makefile not only helps you write large projects under Linux. It also helps you understand the principles of compiling. Stay away from the IDE and understand the compilation process.
Less nonsense, makefile in fact the most important grammar is only one sentence:
Target ...: Prerequisites
... Command ...
Target is the destination file, and prerequisites represents all the dependent files required to generate the target file. command is the compilation command that generates the target file from a dependent file.
So, for a single. c file, one of the simplest makefile is as follows:
OBJECT:MAIN.C
Gcc-o Object main.c
Of course, there is little point in using Makefile for a single C file.
Let's look at a slightly more complex makefile file:
dir=./
object:main.o 1.o 2.o
gcc-o object main.o 1.o 2.o
1.o:1.c my.h
gcc-c 1.c
2.o:2.c my.h
Gcc-c 2.c
main.o:main.c my.h
gcc-c main.c
. Phony:clean clean
:
RM $ (DIR). O Object
This is a slightly practical value of the makefile, the project is composed of four source files: My.h 1.c 2.c main.c.
Put it in the front.
dir=./
is a variable definition. The variable definitions in makefile are mostly strings, and the main purpose is to avoid repeating long string input.
1.O 2.o main.o are three source file generated link files. If you don't know what the link file is .... Find a mother.
First target is generally the final target file, and the target is usually the process file.
. Phony is used to define pseudo targets. A pseudo target is not the actual file to be generated, typically a parameter that is brought in by the make command. For example, clean in the above file, its corresponding command is to clear all intermediate files and the final target file.
In fact, generally do not define pseudo target is OK, but once the directory appears and pseudo target duplicate files. At this point the makefile executes the pseudo target command and there is an error. Because Makefile does not know that this is a pseudo target, and the pseudo target does not rely on the file, so makefile will skip the pseudo target file corresponding command.
Above, is a simple introduction to makefile, generally, to read most of the makefile is enough. Ask Baidu or Google to delve into it.