introduction to makefile
DESCRIPTION
A quick introduction to the GNU make utility, its usage and working principles. Some tips about how to understand and write your own Makefile.TRANSCRIPT
An introduction to the make utility and its working principles
Introduction to Makefile
Tusharadri SarkarIBM
August 21, 20091 Tusharadri Sarkar
Makefile: The GNU make utilityAutomatically 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’
August 21, 20092 Tusharadri Sarkar
About ‘clearmake’clearmake is the Rational® ClearCase® variant of
the UNIX make utilityIncludes most of the features of UNIX System V
makeIt 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
August 21, 20093 Tusharadri Sarkar
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-of-materials records that fully document a build and support the ability to rebuild
August 21, 20094 Tusharadri Sarkar
How ‘make’ worksTo 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
August 21, 20095 Tusharadri Sarkar
How ‘make’ worksFor 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
August 21, 20096 Tusharadri Sarkar
Writing a MakefileAll Makefiles can be described with the following
FIVE components:
Explicit Rules
Implicit Rules
Variable definitions
Directives
Comments
August 21, 20097 Tusharadri Sarkar
Writing a Makefile: Explicit rulesDefinition
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 syntaxIn general, a rule looks like this:
targets : prerequisitescommand ...
or like this: targets : prerequisites ; command1
command2 ...
August 21, 20098 Tusharadri Sarkar
Writing a Makefile: Explicit rulesThe 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
August 21, 20099 Tusharadri Sarkar
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
August 21, 200910 Tusharadri Sarkar
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)
August 21, 200911 Tusharadri Sarkar
More on Explicit rulesSpecial in-built targets: .PHONEYA phony target is not really the name of a file, but
just a name for commands to be executed on explicit request
Usage of .PHONYclean:
rm *.o temp
The above rule fails when there is files called ‘clean’ present in the current directory
.PHONY: clean
clean:
rm *.o tempAugust 21, 200912 Tusharadri Sarkar
More on Explicit rulesEmpty 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
August 21, 200913 Tusharadri Sarkar
More on Explicit rulesExample:
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
August 21, 200914 Tusharadri Sarkar
More on Explicit rulesRules 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
August 21, 200915 Tusharadri Sarkar
More on Explicit rulesExample:
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
August 21, 200916 Tusharadri Sarkar
Writing a Makefile: Implicit rulesDefinition
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
August 21, 200917 Tusharadri Sarkar
Writing a Makefile: Implicit rulesExample:
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.occ –g –o foo foo.o bar.o $(CFLAGS) $(LDFLAGS)
August 21, 200918 Tusharadri Sarkar
Writing a Makefile: Implicit rulesChained 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
August 21, 200919 Tusharadri Sarkar
Writing a Makefile: Implicit rulesDefine 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
August 21, 200920 Tusharadri Sarkar
More on implicit rulesRedefining 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 ruleYou can cancel a built-in implicit rule by defining a
pattern rule with the same target and prerequisites, but no commands
Example: %.o : %.sThis would cancel the rule that runs assembler
August 21, 200921 Tusharadri Sarkar
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
August 21, 200922 Tusharadri Sarkar
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)
August 21, 200923 Tusharadri Sarkar
Variables: Two FlavorsThere are two ways to assign value to a variable in
GNU makeRecursively expanded and Simply Expanded
Recursively expanded variablesDefined by lines using `=` or by the define directiveThe 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
August 21, 200924 Tusharadri Sarkar
Example:who = $(are)
are = $(u)
u = $(hiQ)
all: ; echo $(who)
Here, echo will return ‘hiQ’
August 21, 200925 Tusharadri Sarkar
Recursively expanded variables
Recursively expanded variablesAdvantage: Can be used with any other variables
and references easily. For exampleINC_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 permissibleAny function referenced in the definition will be
executed every time the variable is expanded. This will result in slower execution.
August 21, 200926 Tusharadri Sarkar
Simply expanded variablesDefined 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
August 21, 200927 Tusharadri Sarkar
Simply expanded variablesThey 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
August 21, 200928 Tusharadri Sarkar
Advance: Reference to variableSubstitution References
A substitution reference substitutes the value of a variable with alterations that you specify
Example:OBJECTS := a.o b.o c.oSOURCES := $(OBJECTS:.o=.c)
It will set SOURCES = a.c b.c c.cAnother example which is common to Makefile:
OBJS := a.o b.o c.oSRCS := $(OBJS:%.o=%.c)
With the same result, this format actually substitutes the patsubst function: $(patsubst %.c,%.o)
August 21, 200929 Tusharadri Sarkar
Advance: Reference to variable
Computed Variable NamesComputed variable names are a complicated concept
needed only for sophisticated Makefile programming. For most purposes you need not consider them
Example:x = var1var2 := Helloy = $(subst 1,2,$(x))z = ymsg := $($($(z)))
Sets msg to ‘Hello’
August 21, 200930 Tusharadri Sarkar
Advance: Reference to variable
It can also be used in substitution referencesExample:
x_objects := x.oy_objects := y.osources := $($(xy)_objects:.o=.c)
This will define source as either x.c or y.c depending on xy
August 21, 200931 Tusharadri Sarkar
More on variablesAutomatic variable:
Used extensively with pattern rules and implicit rulesExample:
%.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
August 21, 200932 Tusharadri Sarkar
More on variablesAutomatic variables are useful when operating on only
those prerequisites which has changes:Example:
lib: sip.o mgcp.o megaco.o isup.oar 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
August 21, 200933 Tusharadri Sarkar
More on variablesImplicit variables:
Variables used by the implicit rulesCan be modified to modify the way implicit rule works
and uses themExample: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'
August 21, 200934 Tusharadri Sarkar
More on variablesSpecial 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_DIRSExpands 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
August 21, 200935 Tusharadri Sarkar
More on Explicit rulesMultiple 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 > goptwallopt : main.c
$(CC)-c main.c –wall -O > wallopt
August 21, 200936 Tusharadri Sarkar
More on Explicit rulesMultiple 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.omegaco.o : protocol.csip.o : protocol.c threads.c$(objects) : config.h
All of them must be recompiled if config.h changesThis 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
August 21, 200937 Tusharadri Sarkar
Writing a Makefile: DirectivesDefinition
A directive is a command for make to do something special while reading the Makefile
These could beReading 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
August 21, 200938 Tusharadri Sarkar
Writing a Makefile: DirectivesThe 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
August 21, 200939 Tusharadri Sarkar
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
August 21, 200940 Tusharadri Sarkar
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
August 21, 200941 Tusharadri Sarkar
Writing a Makefile: DirectivesExample:
Setting up a compilation flag depending on the condition which platform you are building
Ifeq ($(OS), “SunOS”)
CFLAGS = -g –O –Wall -D_SPARC_NBASE
endif
Ifeq ($(OS), “Linux”)
CFLAGS = -g –O –Wall -D_LINUX_NBASE
endif
August 21, 200942 Tusharadri Sarkar
Writing a Makefile: DirectivesDefining variables verbatim: The define directive:
It creates a recursively-expanded variableThe 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 toTWO_LINES = echo hiQ; echo $(PLTFRM)
August 21, 200943 Tusharadri Sarkar
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 spacesIt will search those paths both for targets and
prerequisitesExample: VPATH = sources:../headers
vpath can hold a list of directories for a class of files that match a particular patternExample: vpath %.h ../headers
This tells make to search for all the files with extension .h inside directory ../headers
August 21, 200944 Tusharadri Sarkar
Makefile FunctionsA 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 functionobjects := $(patsubst %.c,%.o,$(wildcard *.c))
foo : $(objects)
cc -o foo $(objects)
August 21, 200945 Tusharadri Sarkar
Makefile FunctionsFunction shell: Calling shell inside a Makefile is
equivalent to a command substitutioncontent := $(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)
August 21, 200946 Tusharadri Sarkar
Writing a Makefile: Comments`#' in a line of a Makefile starts a commentIt 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
August 21, 200947 Tusharadri Sarkar
Running makeHow 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
August 21, 200948 Tusharadri Sarkar
Running makeTargets for your Makefile
You can specify different targets for your Makefile to run with and produce different result:
–all, -debug, -clean, -release, -installIf no target is mentioned, make will run with the default target
mentioned in the Makefile as default:Avoiding recompilation: The touch ‘–t’ optionRun make to recompile all the filesMake changes in the necessary files and run make –tThis will mark all the object files as ‘up to date’Next time running make will not recompile modified files
August 21, 200949 Tusharadri Sarkar
Running makeExit 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
August 21, 200950 Tusharadri Sarkar
Running makeCommon errors while running make:
“Don’t 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 ***
August 21, 200951 Tusharadri Sarkar
References
http://www.gnu.org/software/make/manual/make.html#Running
http://www.cs.duke.edu/~ola/courses/programming/Makefiles/Makefiles.html
http://publib.boulder.ibm.com/infocenter/cchelp/v7r0m0/index.jsp?topic=/com.ibm.rational.clearcase.cc_ref.doc/topics/clearmake.options.htm
http://ftp.gnu.org/gnu/make/ make repository
August 21, 200952 Tusharadri Sarkar
Thank You !!
August 21, 200953 Tusharadri Sarkar