After reading 《ProgramPersonnel self-cultivation "is also a preliminary understanding of program compilation, links, and loading principles. I am very ashamed to say that today I want to write a simple makefile myself, which is very vague and cannot be written very freely (I usually use a prepared sample to change it). Here is a reflection.
Suppose there is a. c file. compile it into executable file.
Compilation + assembly:
Try the following three methods:
Gcc-c a. C-o a. o
Gcc-c-o a. o a. c
Gcc-c a. C
The above three statements generate the target file a. o.
To enable GCC to generate debugging information during compilation, we usually add the-g-o-wall compilation option.
Link:
Try the following two methods:
Gcc-o a. o
Gcc a. O-o
Both of the preceding statements generate executable file.
You can also directly use gcc-o a. C to complete the compilation and link process.
Conclusion: In the above compilation commands,-o must be followed by the goal. Other sequences can be arbitrary.
Next, let's review the simple makefile method.
1. Use of variables in makefile. to define a target variable
Target =
When the target variable needs to be referenced, use $ (target)
2. The use of automatic variables mainly includes the following three:
$ @: Indicates the target file set in the rule.
$ <: Name of the first target in the dependency target.
$ ^: A set of all dependent targets.
3. Usage of Pattern Rule %
%. C indicates all files ending with. C, and %. O indicates all files ending with. O.
4. Use of the wildcard keyword and the patsubst keyword
If you want to obtain a specific set, you can use wildcard, such
Source_files = $ (wildcard *. c) indicates that the value of source_files is a set of all. c files.
If you want to replace some parts of a set with others, you can use patsubst, which is a mode string replacement function.
For example, objs =$ (patsubst %. C, %. O, $ (source_files) replaces all. c files in source_files with. O files.
5. Use of pseudo targets
The most typical use of make clean is written as follows:
. Phony: clean:
Clean:
Rm-RF a. o
The following is a simple and commonly used makefile template:
Cc = GCC <br/> cflags =-wall-o-g <br/> source_files = $ (wildcard *. c) <br/> objs =$ (patsubst %. c, %. o, $ (source_files) <br/> Target = A <br/> %. o: %. C %. h <br/> $ (CC)-C $ (cflags) $ <-o $ @ <br/> %. o: %. c <br/> $ (CC)-C $ (cflags) $ <-o $ @ <br/> $ (target): $ (objs) <br/> $ (CC) $ ^-o $ @ <br/>. phony: Clean <br/> clean: <br/> RM-RF $ (target) $ (objs)