I have tried to read the content from the link
Makefiles are written in order to only compile the changed file in a large project.
- Install 'make'
- goto any folder where all files are written.
-
create a
Makefile, just write the below content and save it into file named asMakefile. If make is installed it will show syntax highlighting. -
You can also name it anything just call by
make -f makefilename targets
The general syntax is
target1:prerequisite command1 command2 command3 target2:prerequisites1 prerequisite2 command1 command2 ...
Once file is saved with name Makefile, we can run it into all the below types.
*Makefile will only compile the target if either no file named as target1 or target2 exist in the directory or file named target1 or target2 is updated respectively.*
-
makethis command in terminal will only compile the first target which istarget1in our case. -
make target1will only compile the target named astarget2 -
make target1 target2will only compile the targets named astarget1andtarget2.
In order to run all the targets we define a target named as all with prerequisite as name of all targets.
all: target bla
echo "this is one target to compile all targets"
target: program.cpp # if any file with name "target" exists, make won't run this target
g++ program.cpp -o target
bla: bla.cpp
g++ bla.cpp -o bla
bla.cpp:
echo "int main () { return 0; }" > bla.cpp
clean:
rm -rf target bla bla.cpp
.PHONY: all # this ensures that "all" is trated as target and not any file
The above makefile now contains some targets, the following commands will give respective runs.
-
make allwill compile all the targets which are mentioned in prerequisite of targetallwhich istargetandbla. It is necessary thatallis not saved as file, so we say in the end with.PHONY: allthat it is just a task and not any filename. -
Since
makeonly compiles first target, and if our first target isall, thenmakeis same asmake all, elsemakewill run only the firsttarget. -
But if we have already compiled the command
make allrunning again withmake allwon't change anything until we change the file content of targets or prerequisites. -
make blawill not run until the prerequisitebla.cppis created, so it will look for below targetbla.cppand execute it. Once prerequisite is met targetblawill run. -
make cleanwill run all the saved files.
Variables can only be strings, we store the strings in variable with := or =.
Reference variable using \((variable) or \){variable}.
files=file1 file2 file3 file4 file5 somefile: $(files) echo "look at the variable value " $(files) touch somefile file1: touch file1 file2: touch file2 file3: touch file3 file4: touch file4 file5: touch file5
all: f1.o f2.o f1.o f2.o: echo $@ # Equivalent to: # f1.o: # echo f1.o # f2.o: # echo f2.o