Friday, February 10, 2012

Advanced Make

Advanced Make


Note: To see my entire list of tutorials click here.

Note: This post is the continuation of Make for beginners. Please refer it if you dont know the basics.

Make Shortcuts


Macros

To make life easier, we can use the macros provided by make. These are rules inbuilt in make.
data.o: data.c data.h
        gcc -c data.c
How can we reduce the above code???

Make knows that when the target file is a ".o" file, then it must use gcc -c on the corresponding ".c" file. Applying this, we can eliminate the action (gcc -c ...)
data.o: data.c data.h
Make knows that when the target file is a ".h" file, then the target should also contain the corresponding ".c" file. Applying this we can eliminate data.c (since data.h is included)
data.o: data.h

Variables

You can also use variables when writing Makefiles. It comes in handy in situations where you want to change the compiler, or the compiler options.

# The variable CC will denote which compiler to use (for ex. gcc or cc)
CC=gcc

# CFLAGS will be the options passed to the compiler.
CFLAGS=-c -Wall

project1: data.o main.o io.o
        $(CC) data.o main.o io.o -o project1
data.o: data.c data.h
        $(CC) $(CFLAGS) data.c
main.o: data.h io.h main.c
        $(CC) $(CFLAGS) main.c
io.o: io.h io.c
        $(CC) $(CFLAGS) io.c

Note that you can use the Macros provided in the previous section to reduce the code size considerably.

Multiple Targets


We can put more than one file in the target section of the dependency rules. If a file appears as a target more than once in a dependency, all of its source files are included as sources for that target.

Here is our sample Makefile again:
project1: data.o main.o io.o
 gcc data.o main.o io.o -o project1
data.o main.o: data.h
io.o main.o: io.h

This Makefile shows main.o appearing in two places. Make knows by looking at all the dependencies that main.o depends on both data.h and io.h.

Multiple targets

Till now we executed Makefile by typing the command "make". As explained earlier this will execute the default target (the first target in Makefile), in our case project1.
If you just wanted to compile the data.o file (for some reason) you can execute the "make data.o", and only that action will be executed.

One target which is usually give in make is clean (executed by "make clean"), which cleans the installation. Just create a new target called clean and in the action part give the corresponding action. For ours it will be
project1: data.o main.o io.o
 gcc data.o main.o io.o -o project1
data.o main.o: data.h
io.o main.o: io.h

clean:
 rm *.o

Our clean target will just remove all the ".o" files. you can also do other things. For example to display a message
clean:
 rm *.o
 echo "Uninstall complete. Thanks for reading the blog."

No comments: