SlideShare una empresa de Scribd logo
1 de 53
An introduction to the make utility and its working
principles
Introduction to Makefile
Tusharadri Sarkar
IBM
August 21, 20091 Tusharadri Sarkar
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’
August 21, 20092 Tusharadri Sarkar
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
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’ 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
August 21, 20095 Tusharadri Sarkar
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
August 21, 20096 Tusharadri Sarkar
Writing a Makefile
All 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 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 ...
August 21, 20098 Tusharadri Sarkar
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
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 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
August 21, 200912 Tusharadri Sarkar
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
August 21, 200913 Tusharadri Sarkar
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
August 21, 200914 Tusharadri Sarkar
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
August 21, 200915 Tusharadri Sarkar
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
August 21, 200916 Tusharadri Sarkar
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
August 21, 200917 Tusharadri Sarkar
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)
August 21, 200918 Tusharadri Sarkar
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
August 21, 200919 Tusharadri Sarkar
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
August 21, 200920 Tusharadri Sarkar
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
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 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
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 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.
August 21, 200926 Tusharadri Sarkar
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
August 21, 200927 Tusharadri Sarkar
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
August 21, 200928 Tusharadri Sarkar
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)
August 21, 200929 Tusharadri Sarkar
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’
August 21, 200930 Tusharadri Sarkar
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
August 21, 200931 Tusharadri Sarkar
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
August 21, 200932 Tusharadri Sarkar
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
August 21, 200933 Tusharadri Sarkar
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'
August 21, 200934 Tusharadri Sarkar
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
August 21, 200935 Tusharadri Sarkar
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
August 21, 200936 Tusharadri Sarkar
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
August 21, 200937 Tusharadri Sarkar
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
August 21, 200938 Tusharadri Sarkar
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
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: Directives
Example:
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: 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)
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 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
August 21, 200944 Tusharadri Sarkar
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)
August 21, 200945 Tusharadri Sarkar
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)
August 21, 200946 Tusharadri Sarkar
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
August 21, 200947 Tusharadri Sarkar
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
August 21, 200948 Tusharadri Sarkar
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
August 21, 200949 Tusharadri Sarkar
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
August 21, 200950 Tusharadri Sarkar
Running make
Common 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#Ru
nning
http://www.cs.duke.edu/~ola/courses/programming/Make
files/Makefiles.html
http://publib.boulder.ibm.com/infocenter/cchelp/v7r0m0/in
dex.jsp?
topic=/com.ibm.rational.clearcase.cc_ref.doc/topics/clear
make.options.htm
http://ftp.gnu.org/gnu/make/  make repository
August 21, 200952 Tusharadri Sarkar
Thank You !!
August 21, 200953 Tusharadri Sarkar

Más contenido relacionado

La actualidad más candente

Process Scheduler and Balancer in Linux Kernel
Process Scheduler and Balancer in Linux KernelProcess Scheduler and Balancer in Linux Kernel
Process Scheduler and Balancer in Linux KernelHaifeng Li
 
Part 02 Linux Kernel Module Programming
Part 02 Linux Kernel Module ProgrammingPart 02 Linux Kernel Module Programming
Part 02 Linux Kernel Module ProgrammingTushar B Kute
 
Introduction to GNU Make Programming Language
Introduction to GNU Make Programming LanguageIntroduction to GNU Make Programming Language
Introduction to GNU Make Programming LanguageShih-Hsiang Lin
 
The Linux Kernel Implementation of Pipes and FIFOs
The Linux Kernel Implementation of Pipes and FIFOsThe Linux Kernel Implementation of Pipes and FIFOs
The Linux Kernel Implementation of Pipes and FIFOsDivye Kapoor
 
Linux MMAP & Ioremap introduction
Linux MMAP & Ioremap introductionLinux MMAP & Ioremap introduction
Linux MMAP & Ioremap introductionGene Chang
 
Linux architecture
Linux architectureLinux architecture
Linux architecturemcganesh
 
Linux kernel debugging
Linux kernel debuggingLinux kernel debugging
Linux kernel debuggingHao-Ran Liu
 
Kernel Module Programming
Kernel Module ProgrammingKernel Module Programming
Kernel Module ProgrammingSaurabh Bangad
 
U-Boot Porting on New Hardware
U-Boot Porting on New HardwareU-Boot Porting on New Hardware
U-Boot Porting on New HardwareRuggedBoardGroup
 
Linux basic commands
Linux basic commandsLinux basic commands
Linux basic commandsSagar Kumar
 
Lesson 2 Understanding Linux File System
Lesson 2 Understanding Linux File SystemLesson 2 Understanding Linux File System
Lesson 2 Understanding Linux File SystemSadia Bashir
 
Linux kernel tracing
Linux kernel tracingLinux kernel tracing
Linux kernel tracingViller Hsiao
 
Marco Cavallini - Yocto Project, an automatic generator of embedded Linux dis...
Marco Cavallini - Yocto Project, an automatic generator of embedded Linux dis...Marco Cavallini - Yocto Project, an automatic generator of embedded Linux dis...
Marco Cavallini - Yocto Project, an automatic generator of embedded Linux dis...linuxlab_conf
 
Linux Initialization Process (2)
Linux Initialization Process (2)Linux Initialization Process (2)
Linux Initialization Process (2)shimosawa
 

La actualidad más candente (20)

Process scheduling linux
Process scheduling linuxProcess scheduling linux
Process scheduling linux
 
Process Scheduler and Balancer in Linux Kernel
Process Scheduler and Balancer in Linux KernelProcess Scheduler and Balancer in Linux Kernel
Process Scheduler and Balancer in Linux Kernel
 
Embedded Linux on ARM
Embedded Linux on ARMEmbedded Linux on ARM
Embedded Linux on ARM
 
Unix - An Introduction
Unix - An IntroductionUnix - An Introduction
Unix - An Introduction
 
Part 02 Linux Kernel Module Programming
Part 02 Linux Kernel Module ProgrammingPart 02 Linux Kernel Module Programming
Part 02 Linux Kernel Module Programming
 
Introduction to GNU Make Programming Language
Introduction to GNU Make Programming LanguageIntroduction to GNU Make Programming Language
Introduction to GNU Make Programming Language
 
The Linux Kernel Implementation of Pipes and FIFOs
The Linux Kernel Implementation of Pipes and FIFOsThe Linux Kernel Implementation of Pipes and FIFOs
The Linux Kernel Implementation of Pipes and FIFOs
 
Linux scheduler
Linux schedulerLinux scheduler
Linux scheduler
 
Linux MMAP & Ioremap introduction
Linux MMAP & Ioremap introductionLinux MMAP & Ioremap introduction
Linux MMAP & Ioremap introduction
 
Linux architecture
Linux architectureLinux architecture
Linux architecture
 
Linux kernel debugging
Linux kernel debuggingLinux kernel debugging
Linux kernel debugging
 
Kernel Module Programming
Kernel Module ProgrammingKernel Module Programming
Kernel Module Programming
 
Linux systems - Linux Commands and Shell Scripting
Linux systems - Linux Commands and Shell ScriptingLinux systems - Linux Commands and Shell Scripting
Linux systems - Linux Commands and Shell Scripting
 
U-Boot Porting on New Hardware
U-Boot Porting on New HardwareU-Boot Porting on New Hardware
U-Boot Porting on New Hardware
 
Linux basic commands
Linux basic commandsLinux basic commands
Linux basic commands
 
Lesson 2 Understanding Linux File System
Lesson 2 Understanding Linux File SystemLesson 2 Understanding Linux File System
Lesson 2 Understanding Linux File System
 
Linux Internals - Part I
Linux Internals - Part ILinux Internals - Part I
Linux Internals - Part I
 
Linux kernel tracing
Linux kernel tracingLinux kernel tracing
Linux kernel tracing
 
Marco Cavallini - Yocto Project, an automatic generator of embedded Linux dis...
Marco Cavallini - Yocto Project, an automatic generator of embedded Linux dis...Marco Cavallini - Yocto Project, an automatic generator of embedded Linux dis...
Marco Cavallini - Yocto Project, an automatic generator of embedded Linux dis...
 
Linux Initialization Process (2)
Linux Initialization Process (2)Linux Initialization Process (2)
Linux Initialization Process (2)
 

Similar a Introduction to Makefile

LOSS_C11- Programming Linux 20221006.pdf
LOSS_C11- Programming Linux 20221006.pdfLOSS_C11- Programming Linux 20221006.pdf
LOSS_C11- Programming Linux 20221006.pdfThninh2
 
1 CMPS 12M Data Structures Lab Lab Assignment 1 .docx
1 CMPS 12M Data Structures Lab Lab Assignment 1 .docx1 CMPS 12M Data Structures Lab Lab Assignment 1 .docx
1 CMPS 12M Data Structures Lab Lab Assignment 1 .docxtarifarmarie
 
C, C++ Interview Questions Part - 1
C, C++ Interview Questions Part - 1C, C++ Interview Questions Part - 1
C, C++ Interview Questions Part - 1ReKruiTIn.com
 
Apache commons chain in Spring Framework
Apache commons chain in Spring FrameworkApache commons chain in Spring Framework
Apache commons chain in Spring FrameworkNivedita Mondal
 
Hacking Containers - Looking at Cgroups
Hacking Containers - Looking at CgroupsHacking Containers - Looking at Cgroups
Hacking Containers - Looking at CgroupsEng Teong Cheah
 
Bash shell scripting
Bash shell scriptingBash shell scripting
Bash shell scriptingVIKAS TIWARI
 
CMake Tutorial
CMake TutorialCMake Tutorial
CMake TutorialFu Haiping
 
7.-Download_CS201-Solved-Subjective-with-Reference-by-Aqib.doc
7.-Download_CS201-Solved-Subjective-with-Reference-by-Aqib.doc7.-Download_CS201-Solved-Subjective-with-Reference-by-Aqib.doc
7.-Download_CS201-Solved-Subjective-with-Reference-by-Aqib.docabdulhaq467432
 
THE CLR AND THE .NET FRAMEWORK, C#
THE CLR AND THE .NET FRAMEWORK, C#THE CLR AND THE .NET FRAMEWORK, C#
THE CLR AND THE .NET FRAMEWORK, C#MANOJ BURI
 
Autoconf&Automake
Autoconf&AutomakeAutoconf&Automake
Autoconf&Automakeniurui
 
Unix system programming
Unix system programmingUnix system programming
Unix system programmingSyed Mustafa
 
BACKGROUND A shell provides a command-line interface for users. I.docx
BACKGROUND A shell provides a command-line interface for users. I.docxBACKGROUND A shell provides a command-line interface for users. I.docx
BACKGROUND A shell provides a command-line interface for users. I.docxwilcockiris
 

Similar a Introduction to Makefile (20)

Linux intro 5 extra: makefiles
Linux intro 5 extra: makefilesLinux intro 5 extra: makefiles
Linux intro 5 extra: makefiles
 
LOSS_C11- Programming Linux 20221006.pdf
LOSS_C11- Programming Linux 20221006.pdfLOSS_C11- Programming Linux 20221006.pdf
LOSS_C11- Programming Linux 20221006.pdf
 
Basic Make
Basic MakeBasic Make
Basic Make
 
Linux intro 4 awk + makefile
Linux intro 4  awk + makefileLinux intro 4  awk + makefile
Linux intro 4 awk + makefile
 
1 CMPS 12M Data Structures Lab Lab Assignment 1 .docx
1 CMPS 12M Data Structures Lab Lab Assignment 1 .docx1 CMPS 12M Data Structures Lab Lab Assignment 1 .docx
1 CMPS 12M Data Structures Lab Lab Assignment 1 .docx
 
Mbuild help
Mbuild helpMbuild help
Mbuild help
 
C, C++ Interview Questions Part - 1
C, C++ Interview Questions Part - 1C, C++ Interview Questions Part - 1
C, C++ Interview Questions Part - 1
 
Apache commons chain in Spring Framework
Apache commons chain in Spring FrameworkApache commons chain in Spring Framework
Apache commons chain in Spring Framework
 
Hacking Containers - Looking at Cgroups
Hacking Containers - Looking at CgroupsHacking Containers - Looking at Cgroups
Hacking Containers - Looking at Cgroups
 
Bash shell scripting
Bash shell scriptingBash shell scripting
Bash shell scripting
 
Makefiles Bioinfo
Makefiles BioinfoMakefiles Bioinfo
Makefiles Bioinfo
 
CMake Tutorial
CMake TutorialCMake Tutorial
CMake Tutorial
 
Preprocessor
PreprocessorPreprocessor
Preprocessor
 
7.-Download_CS201-Solved-Subjective-with-Reference-by-Aqib.doc
7.-Download_CS201-Solved-Subjective-with-Reference-by-Aqib.doc7.-Download_CS201-Solved-Subjective-with-Reference-by-Aqib.doc
7.-Download_CS201-Solved-Subjective-with-Reference-by-Aqib.doc
 
Ch05
Ch05Ch05
Ch05
 
THE CLR AND THE .NET FRAMEWORK, C#
THE CLR AND THE .NET FRAMEWORK, C#THE CLR AND THE .NET FRAMEWORK, C#
THE CLR AND THE .NET FRAMEWORK, C#
 
Autoconf&Automake
Autoconf&AutomakeAutoconf&Automake
Autoconf&Automake
 
Mex help
Mex helpMex help
Mex help
 
Unix system programming
Unix system programmingUnix system programming
Unix system programming
 
BACKGROUND A shell provides a command-line interface for users. I.docx
BACKGROUND A shell provides a command-line interface for users. I.docxBACKGROUND A shell provides a command-line interface for users. I.docx
BACKGROUND A shell provides a command-line interface for users. I.docx
 

Último

(No.1)↠Young Call Girls in Sikanderpur (Gurgaon) ꧁❤ 9711911712 ❤꧂ Escorts
(No.1)↠Young Call Girls in Sikanderpur (Gurgaon) ꧁❤ 9711911712 ❤꧂ Escorts(No.1)↠Young Call Girls in Sikanderpur (Gurgaon) ꧁❤ 9711911712 ❤꧂ Escorts
(No.1)↠Young Call Girls in Sikanderpur (Gurgaon) ꧁❤ 9711911712 ❤꧂ EscortsDelhi Escorts Service
 
Inspiring Through Words Power of Inspiration.pptx
Inspiring Through Words Power of Inspiration.pptxInspiring Through Words Power of Inspiration.pptx
Inspiring Through Words Power of Inspiration.pptxShubham Rawat
 
E J Waggoner against Kellogg's Pantheism 8.pptx
E J Waggoner against Kellogg's Pantheism 8.pptxE J Waggoner against Kellogg's Pantheism 8.pptx
E J Waggoner against Kellogg's Pantheism 8.pptxJackieSparrow3
 
西伦敦大学毕业证学位证成绩单-怎么样做
西伦敦大学毕业证学位证成绩单-怎么样做西伦敦大学毕业证学位证成绩单-怎么样做
西伦敦大学毕业证学位证成绩单-怎么样做j5bzwet6
 
(南达科他州立大学毕业证学位证成绩单-永久存档)
(南达科他州立大学毕业证学位证成绩单-永久存档)(南达科他州立大学毕业证学位证成绩单-永久存档)
(南达科他州立大学毕业证学位证成绩单-永久存档)oannq
 
南新罕布什尔大学毕业证学位证成绩单-学历认证
南新罕布什尔大学毕业证学位证成绩单-学历认证南新罕布什尔大学毕业证学位证成绩单-学历认证
南新罕布什尔大学毕业证学位证成绩单-学历认证kbdhl05e
 
Call Girls In Karkardooma 83770 87607 Just-Dial Escorts Service 24X7 Avilable
Call Girls In Karkardooma 83770 87607 Just-Dial Escorts Service 24X7 AvilableCall Girls In Karkardooma 83770 87607 Just-Dial Escorts Service 24X7 Avilable
Call Girls In Karkardooma 83770 87607 Just-Dial Escorts Service 24X7 Avilabledollysharma2066
 
Authentic No 1 Amil Baba In Pakistan Amil Baba In Faisalabad Amil Baba In Kar...
Authentic No 1 Amil Baba In Pakistan Amil Baba In Faisalabad Amil Baba In Kar...Authentic No 1 Amil Baba In Pakistan Amil Baba In Faisalabad Amil Baba In Kar...
Authentic No 1 Amil Baba In Pakistan Amil Baba In Faisalabad Amil Baba In Kar...Authentic No 1 Amil Baba In Pakistan
 

Último (9)

(No.1)↠Young Call Girls in Sikanderpur (Gurgaon) ꧁❤ 9711911712 ❤꧂ Escorts
(No.1)↠Young Call Girls in Sikanderpur (Gurgaon) ꧁❤ 9711911712 ❤꧂ Escorts(No.1)↠Young Call Girls in Sikanderpur (Gurgaon) ꧁❤ 9711911712 ❤꧂ Escorts
(No.1)↠Young Call Girls in Sikanderpur (Gurgaon) ꧁❤ 9711911712 ❤꧂ Escorts
 
Inspiring Through Words Power of Inspiration.pptx
Inspiring Through Words Power of Inspiration.pptxInspiring Through Words Power of Inspiration.pptx
Inspiring Through Words Power of Inspiration.pptx
 
E J Waggoner against Kellogg's Pantheism 8.pptx
E J Waggoner against Kellogg's Pantheism 8.pptxE J Waggoner against Kellogg's Pantheism 8.pptx
E J Waggoner against Kellogg's Pantheism 8.pptx
 
西伦敦大学毕业证学位证成绩单-怎么样做
西伦敦大学毕业证学位证成绩单-怎么样做西伦敦大学毕业证学位证成绩单-怎么样做
西伦敦大学毕业证学位证成绩单-怎么样做
 
Model Call Girl in Lado Sarai Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Lado Sarai Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Lado Sarai Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Lado Sarai Delhi reach out to us at 🔝9953056974🔝
 
(南达科他州立大学毕业证学位证成绩单-永久存档)
(南达科他州立大学毕业证学位证成绩单-永久存档)(南达科他州立大学毕业证学位证成绩单-永久存档)
(南达科他州立大学毕业证学位证成绩单-永久存档)
 
南新罕布什尔大学毕业证学位证成绩单-学历认证
南新罕布什尔大学毕业证学位证成绩单-学历认证南新罕布什尔大学毕业证学位证成绩单-学历认证
南新罕布什尔大学毕业证学位证成绩单-学历认证
 
Call Girls In Karkardooma 83770 87607 Just-Dial Escorts Service 24X7 Avilable
Call Girls In Karkardooma 83770 87607 Just-Dial Escorts Service 24X7 AvilableCall Girls In Karkardooma 83770 87607 Just-Dial Escorts Service 24X7 Avilable
Call Girls In Karkardooma 83770 87607 Just-Dial Escorts Service 24X7 Avilable
 
Authentic No 1 Amil Baba In Pakistan Amil Baba In Faisalabad Amil Baba In Kar...
Authentic No 1 Amil Baba In Pakistan Amil Baba In Faisalabad Amil Baba In Kar...Authentic No 1 Amil Baba In Pakistan Amil Baba In Faisalabad Amil Baba In Kar...
Authentic No 1 Amil Baba In Pakistan Amil Baba In Faisalabad Amil Baba In Kar...
 

Introduction to Makefile

  • 1. An introduction to the make utility and its working principles Introduction to Makefile Tusharadri Sarkar IBM August 21, 20091 Tusharadri Sarkar
  • 2. 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’ August 21, 20092 Tusharadri Sarkar
  • 3. 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 August 21, 20093 Tusharadri Sarkar
  • 4. 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
  • 5. 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 August 21, 20095 Tusharadri Sarkar
  • 6. 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 August 21, 20096 Tusharadri Sarkar
  • 7. Writing a Makefile All Makefiles can be described with the following FIVE components: Explicit Rules Implicit Rules Variable definitions Directives Comments August 21, 20097 Tusharadri Sarkar
  • 8. 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 ... August 21, 20098 Tusharadri Sarkar
  • 9. 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 August 21, 20099 Tusharadri Sarkar
  • 10. 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
  • 11. 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
  • 12. 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 August 21, 200912 Tusharadri Sarkar
  • 13. 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 August 21, 200913 Tusharadri Sarkar
  • 14. 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 August 21, 200914 Tusharadri Sarkar
  • 15. 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 August 21, 200915 Tusharadri Sarkar
  • 16. 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 August 21, 200916 Tusharadri Sarkar
  • 17. 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 August 21, 200917 Tusharadri Sarkar
  • 18. 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) August 21, 200918 Tusharadri Sarkar
  • 19. 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 August 21, 200919 Tusharadri Sarkar
  • 20. 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 August 21, 200920 Tusharadri Sarkar
  • 21. 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 August 21, 200921 Tusharadri Sarkar
  • 22. 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
  • 23. 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
  • 24. 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 August 21, 200924 Tusharadri Sarkar
  • 25. Example: who = $(are) are = $(u) u = $(hiQ) all: ; echo $(who) Here, echo will return ‘hiQ’ August 21, 200925 Tusharadri Sarkar Recursively expanded variables
  • 26. 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. August 21, 200926 Tusharadri Sarkar
  • 27. 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 August 21, 200927 Tusharadri Sarkar
  • 28. 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 August 21, 200928 Tusharadri Sarkar
  • 29. 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) August 21, 200929 Tusharadri Sarkar
  • 30. 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’ August 21, 200930 Tusharadri Sarkar
  • 31. 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 August 21, 200931 Tusharadri Sarkar
  • 32. 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 August 21, 200932 Tusharadri Sarkar
  • 33. 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 August 21, 200933 Tusharadri Sarkar
  • 34. 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' August 21, 200934 Tusharadri Sarkar
  • 35. 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 August 21, 200935 Tusharadri Sarkar
  • 36. 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 August 21, 200936 Tusharadri Sarkar
  • 37. 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 August 21, 200937 Tusharadri Sarkar
  • 38. 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 August 21, 200938 Tusharadri Sarkar
  • 39. 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 August 21, 200939 Tusharadri Sarkar
  • 40. 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
  • 41. 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
  • 42. Writing a Makefile: Directives Example: 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
  • 43. 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) August 21, 200943 Tusharadri Sarkar
  • 44. 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 August 21, 200944 Tusharadri Sarkar
  • 45. 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) August 21, 200945 Tusharadri Sarkar
  • 46. 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) August 21, 200946 Tusharadri Sarkar
  • 47. 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 August 21, 200947 Tusharadri Sarkar
  • 48. 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 August 21, 200948 Tusharadri Sarkar
  • 49. 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 August 21, 200949 Tusharadri Sarkar
  • 50. 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 August 21, 200950 Tusharadri Sarkar
  • 51. Running make Common 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
  • 53. Thank You !! August 21, 200953 Tusharadri Sarkar