
The following Makefile is using more variables including automatic variables. The "-" in -rm causes make to continue in spite of errors from rm. To prevent make from getting confused by an actual file called clean, me may use. For example, to make main.o we do not have to specify g++ -c main.cpp:
BASIC MAKEFILE FOR C PROGRAM HOW TO
So, we need to use variables:Īcutally, make has an implicit rule (when and how to remake files based on their names) for updating a *.o file from a correspondingly named *.cpp file, we do not have to put recipes for the compiler.
BASIC MAKEFILE FOR C PROGRAM UPDATE
In short, to update myprogram, we just issue make, to clean *.o and myprogram, we issue make clean.īut there are repeated files, and this makes the make error prone when other files are added later. If we change the file header2.h and run make, make will recompile the object files aa.o and bb.o and then link the file myprogram. Thus, if we change the file aa.cpp and run make, make will compile that file to update aa.o, and then link myprogram. If an object file was just recompiled, it is now newer than myprogram, so myprogram is relinked. This must be done if the file does not exist, or if any of the object files are newer than it. If some other rule is not depended on by the goal, that rule is not processed, unless we tell make to do so with a command such as make clean.Īfter recompiling whichever object files needed, make decides whether to relink myprogram. The other rules are processed because their targets appear as prerequisites of the goal. The recompilation should be done if the source file, or any of the header files named as prerequisites, is more recent than the object file, or if the object file does not exist. Each of these files is processed according to its own rule. However, before make can fully process this rule, it must process the rules for the files that myprogram depends on, which in this case are the object files. In our case, this rule is for relinking myprogram. Make reads the makefile in the current directory and starts by processing the first rule. In the example above, the default goal is to update the executable program myprogram therefore, we put that rule first.

The make starts with the first target (not targets whose names start with "."). īy default, when make looks for the makefile, it tries the following names, in order:
