0% found this document useful (0 votes)
97 views53 pages

Introduction To Makefile

A quick introduction to the GNU make utility, its usage and working principles. Some tips about how to understand and write your own Makefile.

Uploaded by

tusarkar85
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
97 views53 pages

Introduction To Makefile

A quick introduction to the GNU make utility, its usage and working principles. Some tips about how to understand and write your own Makefile.

Uploaded by

tusarkar85
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

Introduction to Makefile

An introduction to the make utility and its working principles

Tusharadri Sarkar
IBM

Tusharadri Sarkar

August 21, 2009

Makefile: The GNU make utility


Automatically determines which pieces of a large

program need to be recompiled and issues the command to recompile them First implemented by Richard Stallman and Ronald McGrath. Development since version 3.76 is handled by Paul D. Smith GNU make conforms to section 6.2 of IEEE Standard 1003.2-1992 (POSIX.2) To build inside ClearCase project use clearmake instead of make
2 Tusharadri Sarkar August 21, 2009

About clearmake
clearmake is the Rational ClearCase variant of

the UNIX make utility Includes most of the features of UNIX System V make It also features compatibility modes, which enables you to use clearmake with makefiles that were constructed for use with other popular make variants, including Gnu make
gmake is gnu variant of make utility

Tusharadri Sarkar

August 21, 2009

About clearmake
clearmake features the following Rational ClearCase

extensions:
Configuration lookup: A build-avoidance scheme that

which uses time stamps of build objects. The automatic detection guarantees correct build behavior in case header files change, even if the header files are not listed as dependencies in the Makefile Derived object sharing: Developers using different views can share files created by clearmake builds Creation of configuration records: Software bill-ofmaterials records that fully document a build and support the ability to rebuild
4 Tusharadri Sarkar August 21, 2009

How make works


To use make, write a file called the Makefile (also,

makefile) that describes the relationships (dependencies) among files in the program and provides commands for updating each file
In a program, typically the executable file is updated

from object files, which are in turn updated (built) by compiling (or, recompiling) source files
The make program uses the Makefile data base and

the last modification times of the files to decide which of the files need to be updated
5 Tusharadri Sarkar August 21, 2009

How make works


For each of those files, it issues the commands

recorded in the data base


You can provide command line arguments to make

to control which files should be compiled, or how the files should be compiled

Tusharadri Sarkar

August 21, 2009

Writing a Makefile
All Makefiles can be described with the following

FIVE components:
Explicit Rules Implicit Rules Variable definitions Directives Comments
7 Tusharadri Sarkar August 21, 2009

Writing a Makefile: Explicit rules


Definition

It says how to make one or more files, called the rule's targets. It lists the other files that the targets depend on, called the prerequisites of the target, and may also specify the commands to create or update the targets
Rule syntax

In general, a rule looks like this:


targets : prerequisites command ...

or like this:
targets : prerequisites ; command1 command2 ...
8 Tusharadri Sarkar August 21, 2009

Writing a Makefile: Explicit rules


The order of the rules are not significant except for

determining the default goal which is the target of the first rule of the first Makefile

Tusharadri Sarkar

August 21, 2009

Writing a Makefile: Explicit rules

The targets are file names, separated by spaces. Wildcard characters may be used Usually there is only one target per rule, but you can have multiple targets The command start with a tab character The first command may appear on the line after the prerequisites, with a tab character, or may appear on the same line, with a semicolon
Tusharadri Sarkar August 21, 2009

10

Writing a Makefile: Explicit rules

A rule tells make two things


when

the targets are out of date how to update them when necessary

The criterion for being out of date is specified in terms of the prerequisites, which consist of file names separated by spaces (Wildcards and archive members are allowed)

11

Tusharadri Sarkar

August 21, 2009

More on Explicit rules


Special in-built targets: .PHONEY A phony target is not really the name of a file, but

just a name for commands to be executed on explicit request Usage of .PHONY


clean: rm *.o temp

The above rule fails when there is files called clean

present in the current directory


.PHONY: clean clean: rm *.o temp
12 Tusharadri Sarkar August 21, 2009

More on Explicit rules


Empty target: A variant of .PHONY Unlike phony, the target really exists but the content

of the file is generally empty


Purpose: The empty target file records, with its last

modification time, when the rule's commands were last executed. It does so because one of the commands is a touch command to update the target file
13 Tusharadri Sarkar August 21, 2009

More on Explicit rules


Example:
print: foo.c bar.c lpr -p $? touch print

With this rule, make print' will execute the lpr

command if any source file has changed since make print was last run

14

Tusharadri Sarkar

August 21, 2009

More on Explicit rules


Rules without commands or prerequisites: If a rule has no prerequisites or commands, and

the target of the rule is a nonexistent file, then make imagines the target to have been updated whenever its rule is run
This implies that all targets depending on this one

will always have their commands run

15

Tusharadri Sarkar

August 21, 2009

More on Explicit rules


Example:
clean: FORCE rm $(objects) FORCE:

Here the target FORCE satisfies the special

conditions, so the target clean that depends on FORCE is forced to run its commands every time

16

Tusharadri Sarkar

August 21, 2009

Writing a Makefile: Implicit rules


Definition

It says when and how to remake a class of files based on their names. It describes how a target may depend on a file with a name similar to the target and gives make commands to create or update such a target
It helps to avoid writing customary techniques so that

you do not have to specify them in detail when you want to use them

17

Tusharadri Sarkar

August 21, 2009

Writing a Makefile: Implicit rules


Example:

C/C++ compilation typically takes a .c, .cc or .cpp file and makes a .o file. make applies the implicit rule for C/C++ compilation when it sees this combination of file names:
foo : foo.o bar.o cc g o foo foo.o bar.o $(CFLAGS) $(LDFLAGS)

18

Tusharadri Sarkar

August 21, 2009

Writing a Makefile: Implicit rules


Chained rules: A chain of implicit rules can be applied

in sequence; for example, make will remake a .o file from a .y file by way of a .c file
The built-in implicit rules use several variables in their

commands. So, by changing the values of the variables, you can change the way the implicit rule works Example: The variable CFLAGS controls the flags given to the C compiler by the implicit rule for C compilation
19 Tusharadri Sarkar August 21, 2009

Writing a Makefile: Implicit rules


Define your own implicit rules by writing pattern rules Suffix rules are more limited way to define implicit rules Pattern rules are more general and clearer, but suffix

rules are retained for compatibility

20

Tusharadri Sarkar

August 21, 2009

More on implicit rules


Redefining an implicit rule
You can override a built-in implicit rule or by defining a

new pattern rule with the same target and prerequisites, but different commands
Cancelling an implicit rule
You can cancel a built-in implicit rule by defining a

pattern rule with the same target and prerequisites, but no commands
Example: %.o : %.s

This would cancel the rule that runs assembler


21 Tusharadri Sarkar August 21, 2009

Writing a Makefile: Variable Def.


Definition

A line that specifies a text string value for a variable that can be substituted into the text later
Variables make your Makefile simpler and more

compact

22

Tusharadri Sarkar

August 21, 2009

Writing a Makefile: Variable Def.


Example:
edit : main.o kbd.o command.o display.o \ insert.o search.o files.o utils.o cc -o edit main.o kbd.o command.o display.o \ insert.o search.o files.o utils.o

Now with a variable OBJECTS you can write the same as:
OBJECTS = main.o kbd.o command.o display.o \ insert.o search.o files.o utils.o edit : $(OBJECTS) cc -o edit $(OBJECTS)
23 Tusharadri Sarkar August 21, 2009

Variables: Two Flavors


There are two ways to assign value to a variable in

GNU make Recursively expanded and Simply Expanded


Recursively expanded variables
Defined by lines using `=` or by the define directive The value specified is installed verbatim; if it contains

references to other variables, these references are expanded whenever this variable is substituted When this happens, it is called recursive expansion
24 Tusharadri Sarkar August 21, 2009

Recursively expanded variables


Example:
who = $(are) are = $(u) u = $(hiQ) all: ; echo $(who)

Here, echo will return hiQ

25

Tusharadri Sarkar

August 21, 2009

Recursively expanded variables


Advantage: Can be used with any other variables

and references easily. For example


INC_DIR = -Isrc Ih -Iplugin CFLAGS = $(INC_DIR) g O

Will expand CFLAGS = -Isrc Ih Iplugin g O Disadvantage: Can not appended any value For example: CFLAGS = $(CFLAGS) wall Is not permissible Any function referenced in the definition will be executed every time the variable is expanded. This will result in slower execution.
26 Tusharadri Sarkar August 21, 2009

Simply expanded variables


Defined by lines using `:=` The value of a simply expanded variable is scanned

once and for all, expanding any references to other variables and functions, when the variable is defined. The actual value of the simply expanded variable is the result of expanding the text that you write. It does not contain any references to other variables; it contains their values as of the time this variable was defined

27

Tusharadri Sarkar

August 21, 2009

Simply expanded variables


They allow you to redefine a variable using its own

value (or its value processed in some way by one of the expansion functions) and to use the expansion functions much more efficiently Example:
CDEFINES := -DSOLID_NBASE D_AVL_H ifeq ($(OS), Linux) CDEFINES = $(CDEFINES) DLINUX_NBASE endif

Two other variable assignment operators are:


?= Assigns a value to a variable conditionally += Appends a value to a variable if it is defined
28 Tusharadri Sarkar August 21, 2009

Advance: Reference to variable


Substitution References
A substitution reference substitutes the value of a variable

with alterations that you specify Example:


OBJECTS := a.o b.o c.o SOURCES := $(OBJECTS:.o=.c)

It will set SOURCES = a.c b.c c.c Another example which is common to Makefile: OBJS := a.o b.o c.o SRCS := $(OBJS:%.o=%.c) With the same result, this format actually substitutes the patsubst function: $(patsubst %.c,%.o)
29 Tusharadri Sarkar August 21, 2009

Advance: Reference to variable


Computed Variable Names
Computed variable names are a complicated concept

needed only for sophisticated Makefile programming. For most purposes you need not consider them
Example:
x = var1 var2 := Hello y = $(subst 1,2,$(x)) z = y msg := $($($(z)))

Sets msg to Hello


30 Tusharadri Sarkar August 21, 2009

Advance: Reference to variable


It can also be used in substitution references Example:
x_objects := x.o y_objects := y.o sources := $($(xy)_objects:.o=.c)

This will define source as either x.c or y.c depending on xy

31

Tusharadri Sarkar

August 21, 2009

More on variables
Automatic variable:
Used extensively with pattern rules and implicit rules Example: %.o : %.c $(CC) -c $(CFLAGS) $(CPPFLAGS) $< -o $@ Builds any file x.o from x.c where $< and $@ substitutes

the names of targets and sources in each case where the rule applies Another example:
% :: SUBDIR/%,v $(CO) $(COFLAGS) $<

Builds any file file x whatsoever from corresponding files

x,v in subdirectory SUBDIR


32 Tusharadri Sarkar August 21, 2009

More on variables
Automatic variables are useful when operating on only

those prerequisites which has changes:


Example: lib: sip.o mgcp.o megaco.o isup.o ar r lib $? This rule copies just the changed object files into the

archive, mentioned by $?
Some other automatic variables: $% The target member name, when the target is an archive member $^ The names of all the prerequisites, with spaces between them $| The names of all the order-only prerequisites, with spaces between them
33 Tusharadri Sarkar August 21, 2009

More on variables
Implicit variables:
Variables used by the implicit rules Can be modified to modify the way implicit rule works

and uses them Example:


CC Command for compiling C programs; default cc' CXX Command for compiling C++ programs; default g++' RM Command to remove a file; default rm -f' LDFLAGS Extra flags to give to compilers when they are supposed to

invoke the linker, default ld'


34 Tusharadri Sarkar August 21, 2009

More on variables
Special variables/Environment variables:
They lose their special properties if they are set by a

Makefile or on the command line Example:


.DEFAULT_GOAL Sets the default goal to be used if no targets were specified on

the command line .INCLUDE_DIRS Expands to a list of directories that make searches for included makefiles .SECONDEXPANSION If set as target, all the prerequisites will expand a second times after make reads them in first-phase .NOTPARALLEL If mentioned as target, invocation of make will run serially
35 Tusharadri Sarkar August 21, 2009

More on Explicit rules


Multiple targets in one rule:
A rule with multiple targets is equivalent to writing many

rules, each with one target You can have same commands with different output by substituting target name by $@
Example:
gopt wallopt : main.c $(CC)-c main.c -$(subst opt,,$@) -O > $@

is equivalent to:
gopt : main.cpp $(CC)-c main.c g -O > gopt wallopt : main.c $(CC)-c main.c wall -O > wallopt
36 Tusharadri Sarkar August 21, 2009

More on Explicit rules


Multiple rules for one target:
One file can be the target of several rules. All the

prerequisites mentioned in all the rules are merged into one list of prerequisites for the target. If the target is older than any prerequisite from any rule, the commands are executed
Example:
objects = megaco.o sip.o megaco.o : protocol.c sip.o : protocol.c threads.c $(objects) : config.h
All of them must be recompiled if config.h changes This could be inserted or taken out without changing the rules

that really specify how to make the object files, making it a convenient form to use if you wish to add the additional prerequisites internally
37 Tusharadri Sarkar August 21, 2009

Writing a Makefile: Directives


Definition

A directive is a command for make to do something special while reading the Makefile
These could be
Reading another Makefile: The include directive Deciding (based on the values of variables) whether to

use or ignore a part of the Makefile: Conditionals


Defining a variable from a verbatim string containing

multiple lines: The define directive


38 Tusharadri Sarkar August 21, 2009

Writing a Makefile: Directives


The include directive:
The include directive tells make to suspend reading the

current Makefile and read one or more other makefiles before continuing
Extra spaces are allowed and ignored at the beginning of

the line, but a tab is not allowed


If the file names contain any variable or function

references, they are expanded

39

Tusharadri Sarkar

August 21, 2009

Writing a Makefile: Directives


Example:

If you have three .mk files, a.mk, b.mk, and c.mk, and $(MYFILE) expands to f1.mk and f2.mk, then the following expression
include *.mk $(MYFILE)

is equivalent to
include a.mk b.mk c.mk f1.mk f2.mk

40

Tusharadri Sarkar

August 21, 2009

Writing a Makefile: Directives


The Conditionals:
A conditional causes part of a Makefile to be obeyed or

ignored depending on the values of variables


Conditionals control what make actually sees in the

Makefile, so they cannot be used to control shell commands at the time of execution

41

Tusharadri Sarkar

August 21, 2009

Writing a Makefile: Directives


Example:

Setting up a compilation flag depending on the condition which platform you are building
Ifeq ($(OS), CFLAGS = endif Ifeq ($(OS), CFLAGS = endif SunOS) -g O Wall

-D_SPARC_NBASE

Linux) -g O Wall -D_LINUX_NBASE

42

Tusharadri Sarkar

August 21, 2009

Writing a Makefile: Directives


Defining variables verbatim: The define directive:
It creates a recursively-expanded variable The variable name may contain function and variable

references, which are expanded when the directive is read to find the actual variable name to use
Example:
define TWO_LINES echo hiQ echo $(PLTFRM) endef

When used in a command script, it is equivalent to


TWO_LINES = echo hiQ; echo $(PLTFRM)
43 Tusharadri Sarkar August 21, 2009

Writing a Makefile: Directives


The VPATH variable and vpath directive:
VPATH can hold a list of directories that make will

search, separated by colons or spaces It will search those paths both for targets and prerequisites Example: VPATH = sources:../headers vpath can hold a list of directories for a class of files that match a particular pattern Example: vpath %.h ../headers This tells make to search for all the files with extension .h inside directory ../headers
44 Tusharadri Sarkar August 21, 2009

Makefile Functions
A function call resembles a variable reference. Function

syntax would look like:


$(function arguments)

or ${function arguments}

Function call: You can also create your own functions

by using the built-in call function


$(call variable,param,param,...)

Function wildcard: Wildcard expansion does not

normally take place inside variable, or inside the arguments of a function


objects := $(patsubst %.c,%.o,$(wildcard *.c))

foo : $(objects) cc -o foo $(objects)


45 Tusharadri Sarkar August 21, 2009

Makefile Functions
Function shell: Calling shell inside a Makefile is

equivalent to a command substitution


content := $(shell cat object_list)

Control Function: These functions control the way make

runs. They are used to provide information to the user of the Makefile or to cause make to stop if some sort of environmental error is detected
$(error text ...) or $(warning text ) or $(info text )

Text Function: For text substitution and analysis


$(subst from,to,textstream) $(patsubst pattern,replacement,textstream) $(filter pattern...,textstream)
46 Tusharadri Sarkar August 21, 2009

Writing a Makefile: Comments


`#' in a line of a Makefile starts a comment It and the rest of the line are ignored, except that a

trailing backslash not escaped by another backslash will continue the comment across multiple lines Within a define directive, comments are not ignored during the definition of the variable, but rather kept intact in the value of the variable When the variable is expanded they will either be treated as make comments or as command script text, depending on the context in which the variable is evaluated
47 Tusharadri Sarkar August 21, 2009

Running make
How to name you Makefile?
By default, when make looks for the Makefile, it tries the

following names, in the order: (1)GNUmakefile, (2)makefile and (3)Makefile. The name GNUmakefile is not recommended
If make finds none of them in current directory it will exit

throwing No target to build


For non-standard names of Makefile, run make with

option file | -f as in: make f my_make


48 Tusharadri Sarkar August 21, 2009

Running make
Targets for your Makefile
You can specify different targets for your Makefile to run with

and produce different result:


all, -debug, -clean, -release, -install
If no target is mentioned, make will run with the default target

mentioned in the Makefile as default: Avoiding recompilation: The touch t option


Run make to recompile all the files Make changes in the necessary files and run make t This will mark all the object files as up to date Next time running make will not recompile modified files

49

Tusharadri Sarkar

August 21, 2009

Running make
Exit status of make:
0 The exit status is zero if make is successful. 2 The exit status is two if make encounters any

errors. It will print messages describing the particular errors.


1 The exit status is one if you use the `-q' flag and

make determines that some target is not already up to date


50 Tusharadri Sarkar August 21, 2009

Running make
Common errors while running make:
Dont know how to make <target name> No target specified and no Makefile

found
Syntax error in line no. xxxx.

Possible trailing white space after \


The fatal errors are prefixed with ***
51 Tusharadri Sarkar August 21, 2009

References
http://www.gnu.org/software/make/manual/make.html#Ru

nning http://www.cs.duke.edu/~ola/courses/programming/Makef iles/Makefiles.html http://publib.boulder.ibm.com/infocenter/cchelp/v7r0m0/in dex.jsp?topic=/com.ibm.rational.clearcase.cc_ref.doc/topi cs/clearmake.options.htm http://ftp.gnu.org/gnu/make/ make repository

52

Tusharadri Sarkar

August 21, 2009

Thank You !!

53

Tusharadri Sarkar

August 21, 2009

You might also like