Compilation and Makefiles

COMP2521 20T2 ♢ Compilation and Makefiles ♢ [0/10]
❖ Compilers

Compilers are programs that

The Gnu C compiler (gcc)

clang is an alternative C compiler  (also available in CSE)

Note that dcc and 3c are wrappers around gcc/clang

COMP2521 20T2 ♢ Compilation and Makefiles ♢ [1/10]
❖ ... Compilers


Stages in C compilation:  pre-processing, compilation, linking

[Diagram:Pics/c-stages.png]

COMP2521 20T2 ♢ Compilation and Makefiles ♢ [2/10]
❖ ... Compilers


When multiple C files are involved:

[Diagram:Pics/gcc.png]

COMP2521 20T2 ♢ Compilation and Makefiles ♢ [3/10]
❖ ... Compilers

Compilation/linking with gcc

gcc -c Stack.c
produces Stack.o, from Stack.c and Stack.h
gcc -c bracket.c
produces bracket.o, from bracket.c and Stack.h
gcc -o rbt bracket.o Stack.o
links bracket.o, Stack.o and libraries
producing executable program called rbt

Note that stdio,assert included implicitly.

gcc is a multi-purpose tool

COMP2521 20T2 ♢ Compilation and Makefiles ♢ [4/10]
❖ Make/Makefiles


Compilation process is complex for large systems.

How much to compile?

The make command assists by allowing
COMP2521 20T2 ♢ Compilation and Makefiles ♢ [5/10]
❖ ... Make/Makefiles

Example multi-module program …

COMP2521 20T2 ♢ Compilation and Makefiles ♢ [6/10]
❖ ... Make/Makefiles

make is driven by dependencies given in a Makefile

A dependency specifies

target : source1 source2commands to build target from sources

e.g.

game : main.o graphics.o world.o
	gcc -o game main.o graphics.o world.o


Rule: target is rebuilt if older than any sourcei   (applied recursively)

COMP2521 20T2 ♢ Compilation and Makefiles ♢ [7/10]
❖ ... Make/Makefiles

game : main.o  graphics.o  world.o
	gcc -o game main.o graphics.o world.o

main.o : main.c graphics.h world.h
	gcc -Wall -Werror -c main.c

graphics.o : graphics.c world.h 
	gcc -Wall -Werror -c graphics.c

world.o : world.c
	gcc -Wall -Werror -c world.c

Things to note:
COMP2521 20T2 ♢ Compilation and Makefiles ♢ [8/10]
❖ ... Make/Makefiles


If make arguments are targets, build just those targets:

prompt$ make world.o
gcc -Wall -Werror -c world.c

If no args, build first target in the Makefile.

prompt$ make
gcc -Wall -Werror -c main.c
gcc -Wall -Werror -c graphics.c
gcc -Wall -Werror -c world.c
gcc -o game main.o graphics.o world.o

COMP2521 20T2 ♢ Compilation and Makefiles ♢ [9/10]
❖ ... Make/Makefiles

Makefiles can contain "variables"


make has rules, which allow it to interpret e.g.

Stack.o : Stack.c Stack.h

as

Stack.o : Stack.c Stack.h
        $(CC) $(CFLAGS) -c Stack.c

COMP2521 20T2 ♢ Compilation and Makefiles ♢ [10/10]


Produced: 6 Jun 2020