Basics of Makefile

References

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.

  1. Install 'make'
  2. goto any folder where all files are written.
  3. create a Makefile , just write the below content and save it into file named as Makefile. If make is installed it will show syntax highlighting.
  4. 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.

Running a makefile

*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.*

  1. make this command in terminal will only compile the first target which is target1 in our case.
  2. make target1 will only compile the target named as target2
  3. make target1 target2 will only compile the targets named as target1 and target2.

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.

  1. make all will compile all the targets which are mentioned in prerequisite of target all which is target and bla. It is necessary that all is not saved as file, so we say in the end with .PHONY: all that it is just a task and not any filename.
  2. Since make only compiles first target, and if our first target is all, then make is same as make all, else make will run only the first target.
  3. But if we have already compiled the command make all running again with make all won't change anything until we change the file content of targets or prerequisites.
  4. make bla will not run until the prerequisite bla.cpp is created, so it will look for below target bla.cpp and execute it. Once prerequisite is met target bla will run.
  5. make clean will run all the saved files.

Variables

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

Multiple Targets

all: f1.o f2.o
f1.o f2.o:
	echo $@
# Equivalent to:
# f1.o:
#	 echo f1.o
# f2.o:
#	 echo f2.o