Translation(s): none
Theory
make is an utility for automatically building applications. The files specifying the instructions needed for that are usually named "Makefile". make tracks which files have changed since the last time the project was built, and invokes the compiler on only those source code files and their dependencies.
A rule (or target) tells Make both when and how to make a file. The general syntax of a Makefile rule is:
- target [target...] : [dependency ....]
- [TAB][ command ...]
The commands inside each target must be indented by a tabulator, not by spaces. If you ever forget about that, and try to use spaces instead, you'll get an error message.
The make process is recursive, so it'll take care that all the dependences are fulfilled before trying to generate the target, and in case they did not exist, or if any its dependencies are newer than their own timestamps, the rule for generating them will be called first.
The syntax of the command make is: make [ -f makefile ] [ options ] ... [ targets ] ...
When you call the make program, you can select which target you want make to generate. If you don't say any, make will pick the first one automatically for you.
The most important options you'll have to know for using make are:
- -C dir or --directory=dir : Change to directory dir before reading the makefiles or doing anything else.
- -f file, --file=file or --makefile=file : Use file as a makefile, instead of using the default name "Makefile".
Exercises
We're developing a simple Makefile to build the test program we have already made:
$ cat >Makefile
- test: test.o
- [TAB]gcc -o test test.o
- test.o: test.c
- [TAB]gcc -Wall -c -o test.o test.c
To build the program now, we'll only have to execute:
- $ make
$ make
- gcc -Wall -c -o test.o test.c
- gcc -o test test.o
$ make
- make: `test' is up to date.
You can have a more elaborated Makefile that allows you to select the compilation and linking options when make is invoked, and it's also quite usual to add a clean target to remove the files generated by make. Lets go to it:
$ cat >Makefile
- LDFLAGS=
- CFLAGS=-Wall -O0 -g
- test: test.o
- [TAB]gcc -o test test.o $(LDFLAGS)
- test.o: test.c
- [TAB]gcc -Wall -c -o test.o test.c $(CFLAGS)
- clean:
- [TAB]rm -f test test.o
Lets test it:
$ make clean
- rm -f test test.o
$ make
- gcc -Wall -c -o test.o test.c -Wall -O0 -g
- gcc -o test test.o
$ make clean
- rm -f test test.o
$ make CFLAGS="-Wall -O2"
- gcc -Wall -c -o test.o test.c -Wall -O2
- gcc -o test test.o
Links