Softpanorama

May the source be with you, but remember the KISS principle ;-)
Home Switchboard Unix Administration Red Hat TCP/IP Networks Neoliberalism Toxic Managers
(slightly skeptical) Educational society promoting "Back to basics" movement against IT overcomplexity and  bastardization of classic Unix

An Introduction to the UNIX Make Utility

News Recommended Links Recommended  Papers Tutorials Reference
Debugging Horror Stories Unix History Humor Etc

On Unix platforms the standard make utility uses a Bourne shell type syntax for carrying out compiling and linking of (usually complicated) source code. The dominant version of make is GNU make implementation sometimes called gmake. There is also different slightly better implementatione from Bell Labs nmake.

Windows compilers "project files" are generally equivalent to Makefiles. Actually most commercial C compiler IDE's contain something like a built-in make using some "project files". (If conducting a port to a Unix platform you might want to disentangle yourself from the non-transportability and awful licensing issues involved with these "project files" though.

Makefile creation has long traditions in Unix environment. It usually has several preconfigured options:

make  # use the default makefile (makefile  or Makefile  ) and first target in it

make clean # removes all packages

make install # install the package into target directories

clean and install are called a phony targets and are discussed later in the section on dependency rules.

Of course a 'make' utility can be simply written in a scripting language. In such cases the syntax of the input Makefile is also somewhat "arbitrary" meaning that it need not follow the command language syntax of the native language interpreter (lex & yacc are helpful here but need not play a role). In fact, Nick Ing-Simmons has written a make-like utility entirely in perl. It is available from CPAN.

perl Makefile.PL

"work" on your platform (i.e. create the right type of Makefile [or equivalent])? This question involves the platform specificity of the Extutils::MakeMaker module.

The make  utility is tool originally created for compiling computer programs but that can be used for various tasks line installing packages. 

Make is controlled by the makefile has is speciali mini-language that consists of rules. By default makefile is a file in the current directory with the name Makefile or makefile. A rule in the makefile tells  make how to execute a series of commands in order to build a target  file from source files. It also specifies a list of dependencies of the target file. This list should include all files (whether source files or other targets) which are used as inputs to the commands in the rule. A simple rule has the following syntax:

target:   dependencies ...
          commands
          ...

Note that commands are arbitrary shell commands. When you run make, you can specify particular targets to update; otherwise, make  updates the first target listed in the makefile. Of course, any other target files needed as input for generating these targets must be updated first.

Make uses the makefile to figure out which target files ought to be brought up to date, and then determines which of them actually need to be updated. If a target file is newer than all of its dependencies, then it is already up to date, and it does not need to be regenerated. The other target files do need to be updated, but in the right order: each target file must be regenerated before it is used in regenerating other targets.

Make  goes through a makefile starting with the target it is going to create. make  looks at each of the target's dependencies to see if they are also listed as targets. It follows the chain of dependencies until it reaches the end of the chain and then begins backing out executing the commands found in each target's rule. Actually every file in the chain may not need to be compiled. Make  looks at the time stamp for each file in the chain and compiles from the point that is required to bring every file in the chain up to date. If any file is missing it is updated if possible.

Make  builds object files from the source files and then links the object files to create the executable. If a source file is changed only its object file needs to be compiled and then linked into the executable instead of recompiling all the source files.

Simple Example

This is an example makefile to build an executable file called prog1. It requires the source files file1.cc, file2.cc, and file3.cc. An include file, mydefs.h, is required by files file1.cc  and file2.cc. If you wanted to compile this file from the command line using C++ the command would be

This command line is rather long to be entered many times as a program is developed and is prone to typing errors. A makefile could run the same command better by using the simple command

or if prog1  is the first target defined in the makefile

This first example makefile is much longer than necessary but is useful for describing what is going on.

 prog1 : file1.o file2.o file3.o CC -o prog1 file1.o file2.o file3.o file1.o : file1.cc mydefs.h CC -c file1.cc file2.o : file2.cc mydefs.h CC -c file2.cc file3.o : file3.cc CC -c file3.cc clean : rm file1.o file2.o file3.o

Let's go through the example to see what make  does by executing with the command make prog1  and assuming the program has never been compiled.

  1. make  finds the target prog1  and sees that it depends on the object files file1.o file2.o file3.o
  2. make  next looks to see if any of the three object files are listed as targets. They are so make  looks at each target to see what it depends on. make  sees that file1.o  depends on the files file1.cc  and mydefs.h.
  3. Now make  looks to see if either of these files are listed as targets and since they aren't it executes the commands given in file1.o's rule and compiles file1.cc  to get the object file.
  4. make  looks at the targets file2.o  and file3.o  and compiles these object files in a similar fashion.
  5. make  now has all the object files required to make prog1  and does so by executing the commands in its rule.

This example can be simplified somewhat by defining macros. Macros are useful for replacing duplicate entries. The object files in this example were used three times, creating a macro can save a little typing. Plus and probably more importantly, if the objects change, the makefile can be updated by just changing the object definition.

 OBJS = file1.o file2.o file3.o prog1 : $(OBJS) CC -o prog1 $(OBJS) file1.o : file1.cc mydefs.h CC -c file1.cc file2.o : file2.cc mydefs.h CC -c file2.cc file3.o : file3.cc CC -c file3.cc clean : rm $(OBJS)

This makefile is still longer than necessary and can be shortened by letting make  use its internal macros, special macros, and suffix rules.

 OBJS = file1.o file2.o file3.o prog1 : ${OBJS} ${CXX} -o $@ ${OBJS} file1.o file2.o : mydefs.h clean : rm ${OBJS}

Invoking make

Make  is invoked from a command line with the following format

However from this vast array of possible options only the -f makefile and the names options are used frequently. The table below shows the results of executing make  with these options.

Frequently used make  options
Command Result
make use the default makefile, build the first target in the file
make myprog use the default makefile, build the target myprog
make -f mymakefile use the file mymakefile  as the makefile, build the first target in the file
make -f mymakefile myprog use the file mymakefile  as the makefile, build the target myprog

When using a default makefile make  will search the current working directory for one of the following files in order:

makefile 

Makefile 

Hint: use Makefile  so that it will list near the beginning of the directory and be easy to find.

makefiles

To operate make  needs to know the relationship between your program's component files and the commands to update each file. This information is contained in a makefile you must write called Makefile  or makefile.

Comments

Comments can be entered in the makefile following a pound sign ( #  ) and the remainder of the line will be ignored by make. If multiple lines are needed each line must begin with the pound sign.

 # This is a comment line

Dependency rules

A rule consist of three parts, one or more targets, zero or more dependencies, and zero or more commands in the following form:

 target1 [target2 ...] :[:] [dependency1 ...] [; commands] [<tab> command]

Note: each command line must begin with a tab  as the first character on the line and only command lines may begin with a tab.

Target

A target is usually the name of the file that make  creates, often an object file or executable program.

Phony target

A phony target is one that isn't really the name of a file. It will only have a list of commands and no prerequisites. One common use of phony targets is for removing files that are no longer needed after a program has been made. The following example simply removes all object files found in the directory containing the makefile.

 clean : rm *.o

Dependencies

A dependency identifies a file that is used to create another file. For example a .cc  file is used to create a .o, which is used to create an executable file.

Commands

Each command in a rule is interpreted by a shell to be executed. By default make uses the /bin/sh shell. The default can be over ridden by using the macro SHELL = /bin/sh or equivalent to use the shell of your preference. This macro should be included in every makefile to make sure the same shell is used each time the makefile is executed.

Macros

Macros allow you to define constants. By using macros you can avoid repeating text entries and make makefiles easier to modify. Macro definitions have the form

 NAME1 = text string NAME2 = another string

Macros are referred to by placing the name in either parentheses or curly braces and preceding it with a dollar sign ( $  ). The previous definitions could referenced

 $(NAME1) ${NAME2}

which are interpreted as

 text string another string

Some valid macro definitions are

 LIBS = -lm OBJS = file1.o file2.o $(more_objs) more_objs = file3.o CXX = CC DEBUG_FLAG = # assign -g for debugging

which could be used in a makefile entry like this

 prog1 : ${objs} ${CXX} $(DEBUG_FLAG) -o prog1 ${objs} ${LIBS}

Macro names can use any combination of upper and lowercase letters, digits and underlines. By convention macro names are in uppercase. The text string can also be null as in the DEBUG_FLAG  example which also shows that comments can follow a definition.

You should note from the previous example that the OBJSmacro contains another macro $(MORE_OBJS). The order that the macros are defined in does not matter but if a macro name is defined twice only the last one defined will be used. Macros cannot be undefined and then redefined as something else.

Make  can receive macros from four sources, macros maybe defined in the makefile like we've already seen, internally defined within make, defined in the command line, or inherited from shell environment variables.

Internal macros

Internally defined macros are ones that are predefined in make. You can invoke make  with the -p  option to display a listing of all the macros, suffix rules and targets in effect for the current build. Here is a partial listing with the default macros from MTSU's mainframe frank.

 CXX = CC CXXFLAGS = -O GFLAGS = CFLAGS = -O CC = cc LDFLAGS = LD = ld LFLAGS = MAKE = make MAKEFLAGS = b
Special macros

There are a few special internal macros that make  defines for each dependency line. Most are beyond the scope of this document but one is especially useful in a makefile and you are likely to see it even in simple makefiles.

The macro @  evaluates to the name of the current target. In the following example the target name is prog1  which is also needed in the command line to name the executable file. In this example -o @  evaluates to -o  prog1.

 prog1 : ${objs} ${CXX} -o $@ ${objs}

Command line macros

Macros can be defined on the command line. From the previous example the debug flag, which was null, could be set from the command line with the command

Definitions comprised of several words must be enclosed in single or double quotes so that the shell will pass them as a single argument. For example

could be used to link an executable using the math and X Windows libraries.

Shell variables

Shell variables that have been defined as part of the environment are available to make  as macros within a makefile. C shell users can see the environment variables they have defined from the command line with the command

These variables can be set within the .login  file or from the command line with a command like:

With four sources for macros there is always the possibility of conflicts. There are two orders of priority available for make. The default priority order from least to greatest is:

  1. internal definitions
  2. shell environment variables
  3. makefile definitions
  4. command line macro definitions

If make  is invoked with the -e  option the priority order from least to greatest is

  1. internal definitions
  2. makefile definitions
  3. shell environment variables
  4. command line macro definitions

Suffix rules

Make  has a set of default rules called suffix or implicit rules. These are generalized rules that make  can use to build a program. For example in building a C++ program these rules tell make  that .o  object files are made from .cc  source files. The suffix rule that make  uses for a C++ program is

 .cc.o: $(CXX) $(CXXFLAGS) -c $<

where $<  is a special macro which in this case stands for a .cc  file that is used to produce a particular target .o  file.


Top Visited
Switchboard
Latest
Past week
Past month

NEWS CONTENTS

Old News ;-)

[Mar 17, 2011]  Stupid "make" Tricks: Workflow Control with "make" by Mark Leighton Fisher

March 16, 2011 | blogs.perl.org

Following up Stupid Unix Tricks: Workflow Control with GNU Make -- this trick works on any platform with a make(1) program, including Windows, QNX, VMS, and z/OS.

It also serves to de-couple dependency checking and the workflow execution engine from the rest of your program (with the caveat that your program may need to interpret the output from make(1).)

[Oct 27, 2008] remake 3.81-0.1

About: remake is a patched and modernized version of GNU make utility that adds improved error reporting, the ability to trace execution in a comprehensible way, and a debugger.

The debugger lets you set breakpoints on targets, show and set variables in expanded or unexpanded form, inspect target descriptions, see the target call stack, and even execute arbitrary GNU make fragments (e.g. add a dependency to an existing target).

Changes: Changes have been made to bring this up to GNU Make release 3.81. This is alpha code.

[Oct 30, 2006] freshmeat.net Project details for yruba

About: Yruba provides a rule system similar to make or ant for the shell (bash). It provides a clear separation between a list of dependencies that must be up-to-date before the current task can be performed, an explicit test that checks whether the target is really out-of-date, and a command that finally makes the target. Everything is plain bash syntax, so there is no new command language to learn.

[Oct 27, 2006] DeveloperWorks: Debugging make Peter Seebach

"Most UNIX and Linux programs are built by running make. The make utility reads a file (generally named either 'makefile' or 'Makefile,' but hereafter merely referred to as 'a makefile') that contains instructions and performs various actions to build a program. In many build processes, the makefile is itself generated entirely by other software; for instance, the autoconf/automake programs are used to develop build routines. Other programs may ask you to directly edit a makefile, and of course, new development may require you to write one.

"The phrase 'the make utility' is misleading..."

Nmake from Microsoft

See also http://makeashorterlink.com/?S12961445

[1979] Make --- A Program for Maintaining Computer Programs - Feldman (ResearchIndex) - original article by S. I. Feldman  about make.

Abstract: In a programming project, it is easy to lose track of which files need to be reprocessed or recompiled after a change is made in some part of the source. Make provides a simple mechanism for maintaining up-to-date versions of programs that result from many operations on a number of files. It is possible to tell Make the sequence of commands that create certain files, and the list of files that require other files to be current before the operations can be done. Whenever a change is made in any... (Update)

Makefile as a functional language program

The following article describes a real practical application: avoiding the explosion of makefile rules in a project that executes many test cases on many platforms. Each test target is built from its own set of source code files. Each (Scheme) platform has its own particular way of assembling source code files into a project; some source code files might need be omitted from the build for a particular platform. Because GNU make turns out to be a functional programming system, we can reduce the number of rules from <number-of-targets> * <number-of-platforms> to just <number-of-targets> + <number-of-platforms>.

The language of GNU make is indeed functional, complete with combinators (map and filter), applications and anonymous abstractions. GNU make does support lambda-abstractions. The following is one example from the Makefile in question: it is a rule to build a test target for the SCM Scheme system. The list of source code files and the name of the target/root-test-file are passed as two arguments of the rule:

     make-scmi= scm -b -l $(LIBDIR)/myenv-scm.scm \
                $(foreach file,$(1),-l $(LIBDIR)/$(file)) \
                -l $(2).scm
The rule returns an OS command to interpret or compile the target. The rule can be invoked as $(call make-scmi,util.scm catch-error.scm,vmyenv). As in TeX, the arguments of a function are numbered (it is possible to assign them meaningful symbolic names, too). Makefile's foreach corresponds to Scheme's map. The comparison with the corresponding Scheme code is striking:
     (define make-scmi
        (lambda (arg1 arg2)
             `(scm -b -l ,(mks LIBDIR '/ 'myenv-scm.scm)
                ,@(map (lambda (file) `(-l ,(mks LIBDIR '/ file))) arg1)
               -l ,(mks arg2 '.scm))))
Version
 
The current version is 4.6, Oct 30, 2003.
References
 
SSAX updates; Makefile as a functional program [plain text file]
A message describing the motivation for the functional Makefile to automate regression testing, and a few examples. The message was posted on the SSAX-SXML mailing list on Mon, 18 Nov 2002 12:48:41 -0800

O'Reilly Network Introduction to Make [Jan. 31, 2002]

...A Make rule is composed of:

target: prerequisites
	commands

A target is considered "up to date" if it exists and is newer than its prerequisites.

Make works backwards, starting with the target of the first rule in the file. In our example, that's sample. Make checks the prerequisites for sample -- main.o and example.o -- to see if they have rules. If they do, it recursively checks their rules.

Make walks down the recursion chain until it finds a target that has no prerequisites, or whose prerequisites have no rules. Once it hits one of those, it walks back up its recursion chain and runs commands as necessary. It creates a recursion chain for every prerequisite it encounters that has a rule.

Once all of the prerequisite rules have been run, it eventually returns to sample's rule. If the file doesn't exist, or is older than its prerequisites now are (after their rules have been recursively tested), it runs the commands to generate sample.

In the example makefile, Make:

  1. Runs the first rule it sees -- sample.
  2. Checks to see whether sample's prerequisites have rules. They do.
  3. Runs the rule for the first prerequisite -- main.o.
  4. Checks to see whether main.o's prerequisites have rules. They don't.
  5. Checks whether main.o is up to date. If not, it runs the commands for main.o.
  6. Runs the rule for the second prerequisite -- example.o.
  7. Checks to see whether example.o's prerequisites have rules. They don't.
  8. Checks whether or not example.o is up to date. If not, it runs the commands for example.o.
  9. Returns to sample's rule
  10. Checks whether or not sample is up to date. If not, it runs the commands to update it.

Make can run the prerequisites in any order. The important part of this sequence is that it runs recursively backwards from the first target (or the target named in the command parameters), and tests only the rules that it encounters in the prerequisites chain.

Make aborts compilation if it receives an error. This is usually useful behavior -- it lets you correct compiler-detected problems during a compile-and-test cycle. The option -i tells Make to ignore errors.

In software development, it's very convenient to create a script to remove old compiled code so that the next build recompiles everything. It's also convenient to have a script for installing the code. Make allows scripts like this to be included in the makefile, as phony targets. Phony targets may have prerequisites, and may themselves be prerequisites.

The special rule .PHONY tells Make which targets are not files. This avoids conflict with files of the same name, and improves performance.

If a phony target is included as a prerequisite for another target, it will be run every time that other target is required. Phony targets are never up-to-date.

To run a phony target from the command line, call Make with the name of the phony target, e.g.: make clean.

# Naming our phony targets
.PHONY: clean install

# Removing the executable and the object files
clean: 
		rm sample main.o example.o
		echo clean: make complete

# Installing the final product
install:
		cp sample /usr/local
		echo install: make complete

Makefile Variables

As a project gets larger, more files are usually added. If you repeat a list of files, you can accidentally leave files out of the list. It's simpler to make use of a variable that expands into the list.

The syntax for declaring and setting a makefile variable is varname = variable contents. To call the variable, use $(varname).

# Defining the object files
objects = main.o example.o

# Linking object files
sample: $(objects) 
		cc -o sample $(objects)
		echo sample: make complete

# Compiling source files
main.o: main.c main.h
		cc -c main.c
example.o: example.c defs.h
		cc -c example.c

# Removing the executable and the object files
clean: 
		rm sample $(objects)
		echo clean: make complete

Final Touches

There are a few touches which make the difference between a usable and a professional makefile. The next example adds those extra touches.

# 1
# Defining the compiler:
CC=gcc

# Defining the object files:
objects = main.o example.o

# 2
# The default rule - compiling our main program:
all:	sample
		echo all: make complete

# 3
sample: $(objects)
	# If we get here, all the dependencies are now built.
	# Link it:
	$(CC) -o $@ $+

# 4
# Tell make how to build .o files from .c files:
%.o:%.c
	$(CC) -c $+
	
# 5
#Now make sure that make rebuilds files if included headers change:
main.o: main.h defs.h
example.o: example.h defs.h
  1. Use a variable for the compiler, in case you want to use the same makefile with a different compiler.
  2. When called without a rule parameter, Make runs the first rule it encounters. It is more human-readable to explicitly state your first rule. all is a common name for a first rule.
  3. The automatic variable $@ means "the name of the target." The automatic variable $+ means "all prerequisites, space-separated." Automatic variables are pre-defined in Make.
  4. A pattern rule tells make how to convert the prerequisite to the target. The % in the pattern means "one or more characters," and refers to the same string in the prerequisite and the target. This particular pattern tells make how to convert a *.c file to a *.o file of the same name.

    The automatic variable $+ means "all prerequisites, space-separated."

  5. These rules are relying on "implicit rules." Make has built-in patterns for converting a *.h file to the dependent *.o. These rules are included to define the prerequisites for the relevant *.o files.

 

themestream.com: Inside the make command

(Sep 2, 2000, 18:39 UTC) (449 reads) (0 talkbacks) (Posted by john)

The make program is a very flexible and powerful tool. Most of us have some familiarity with it from using it in the compilation process of the Linux kernel and other source codes that for whatever reason, we choose to compile rather than install the binary version. But what is the make command and what else can it do besides compile programs?

The canonical_documentation (authoritative reference) to the make command is the gnu documentation. If you do decide to read through all of that, you will know alot about make and probably be able to imagine various situations in which it could be used productively. Here are the ideas that I had for using make after reading the docs.

Rebuilding postscript files from tex/latex files

I don't know what your specific needs are but when I create a tex file or latex file, I don't want to have to issue a bunch of commands to get printable output but that is exactly what you have to do if you are doing things from the command line. Let's take a look at a simple example designed to relieve me of this duty:

letter.ps : letter.tex
        latex letter.tex
        dvips -o letter.ps letter.dvi

print : letter.ps
        /usr/bin/gs -q -dSAFER -r360x180 -sDEVICE=epson -dNOPAUSE -sOutputFile=\|lpr letter.ps 

view : letter.ps
	gv letter.ps


So what does this do? Well, let's say I've created a latex file. What I want to do is print it. I don't want to have to do anything else except print it. Of course, it is a good idea to preview things first so that is why I included the "view" rule. The above file would be called "Makefile" and to run it, we would need to make sure the letter.tex file were in the current directory, along with Makefile. Let's run it first with the view option:

Whatcha' gonna make - SunWorld - October 1998

http://www.bell-labs.com/project/nmake/ nmake is not Microsoft nmake

it is the AT&T Bell Labs next-generation make that is way better than standard UNIX make: parallel builds, include file scanning, coshell (instead of fork/exec for every shell command), distributed build support, compiled makefiles, state tracking from one build to the next, etc., etc., etc. When originally developed, it helped cut build times for the AT&T 5ESS switch from 3 days down to

Recommended Links

Google matched content

Softpanorama Recommended

Make - Wikipedia, the free encyclopedia

Introduction to the make Utility

University of Waterloo tutorials

GNU Make - GNU Project - Free Software Foundation (FSF)

GNU make Table of Contents - GNU Project - Free Software Foundation (FSF)

The Make Utility

oreilly.com Managing Projects with GNU Make, Third Edition

 

Alternatives:

Recommended Papers

A Case For Make - http://citeseer.ist.psu.edu/fowler90case.html
Fowler 1990 - Explains many old-make limitations and new-make (Nmake) features including procedure rules, accuracy mechanisms, viewpathing, and semaphores for blocking unwanted parallelism.

An Automatic Make Facility - http://citeseer.ist.psu.edu/holyer00automatic.html
Holyer and Pehlivan 2000 - Program uses no makefile. It records manually-issued compilation commands the first time round, then rebuilds programs using recorded command traces.
Compare and Contrast Lucent Nmake and GNU Make - http://www.bell-labs.com/project/nmake/faq/gmake.html
Lucent FAQ - Summarizes the function and typical syntax of many make features, using a convenient table format.

feldman79make

Recursive Make Considered Harmful by Peter Miller, 1997

For large UNIX projects, the traditional method of building the project is to use recursive make. On some projects, this results in build times which are unacceptably large, when all you want to do is change one file. In examining the source of the overly long build times, it became evident that a number of apparently unrelated problems combine to produce the delay, but on analysis all have the same root cause.

This paper explores an number of problems regarding the use of recursive make, and shows that they are all symptoms of the same problem. Symptoms that the UNIX community have long accepted as a fact of life, but which need not be endured any longer. These problems include recursive makes which take ``forever'' to work out that they need to do nothing, recursive makes which do too much, or too little, recursive makes which are overly sensitive to changes in the source code and require constant Makefile  intervention to keep them working.

The resolution of these problems can be found by looking at what make does, from first principles, and then analyzing the effects of introducing recursive make to this activity. The analysis shows that the problem stems from the artificial partitioning of the build into separate subsets. This, in turn, leads to the symptoms described. To avoid the symptoms, it is only necessary to avoid the separation; to use a single Makefile  for the whole project.

This conclusion runs counter to much accumulated folk wisdom in building large projects on UNIX. Some of the main objections raised by this folk wisdom are examined and shown to be unfounded. The results of actual use are far more encouraging, with routine development performance improvements significantly faster than intuition may indicate. The use of a single project Makefile  is not as difficult to put into practice as it may first appear.

Tutorial - Makefile

Make reads its instructions from text files. An initialization file is read first, followed by the makefile. The initialization file holds instructions for all “makes” and is used to customize the operation of Make. Make automatically reads the initialization file whenever it starts up. Typically the initialization file is named make.ini  and it resides in the directory of make.exe  and mkmf.exe. The name and location of the initialization file is discussed in detail on Page .

The makefile has instructions for a specific project. The default name of the makefile is literally makefile, but the name can be specified with a command-line option.

With a few exceptions, the initialization file holds the same kind of information as does a makefile. Both the initialization file and the makefile are composed of the following components: comments, dependency lines, directives, macros, response files, rules and shell lines.

Tutorials

University  tutorials

C Programming Tutorial Make and Makefiles

Creating Makefiles A Mini Tutorial LG #83

Debugging

oreilly.com Managing Projects with GNU Make, Third Edition

FreeBSD.org/Writing and Debugging a Makefile

CM Crossroads - Makefile Debugging Tracing Macro Values

In the first of these articles I showed a technique for printing the value of any Makefile macro by defining a special rule called print-%. Now I'm going to show how to trace where a macro is used in a Makefile. Consider this simple Makefile:
 
X=$(YS) hate $(ZS)
Y=dog
YS=$(Y)$(S)
Z=cat
ZS=$(Z)$(S)
S=s
all: $(YS) $(ZS)
@echo $(X)
$(YS):
@echo $(Y) $(Y)
$(ZS):
@echo $(Z) $(Z)

When run it prints

dog dog
cat cat
dogs hate cats


Tracing Macro Use

Now try to trace through and see wherethe macro $(Y) is used. It's actually used on lines 8, 9, 11, and 12 (twice). It's amazing how often macros get used! That's because Make defaults to only getting the value of a macro when needed and macros are frequently deeply nested.

Tracing such use for any real Makefile would be an impossible task, but it's possible to get Make to do the work for you. Take a look at the code which should be added to the start of the Makefile to be traced (it'll only get used when explicitly called).
 


ifdef TRACE
.PHONY: _trace _value
_trace: ; @$(MAKE) --no-print-directory TRACE= $(TRACE) ='$$(warning TRACE $(TRACE))$(shell $(MAKE) TRACE=$(TRACE) _value)'
_value: ; @echo '$(value $(TRACE))'
endif

Before diving into understanding how it works, here's an example of using it to trace the value of $(Y) in our example Makefile. To use the tracer you tell GNU Make to run the trace target by setting the TRACE macro to the name of the macro you wanted tracked. In this example we want to watch use of the macro Y:


% gmake TRACE=Y

Makefile:8: TRACE Y
Makefile:11: TRACE Y
Makefile:12: TRACE Y
Makefile:12: TRACE Y
dog dog
cat cat
Makefile:9: TRACE Y
dogs hate cats

From the lines containing the word TRACE you can see Y being used first on line 8 (the definition of the all target references Y via the $(YS)), then on line 11(the definition of the cats target is using $(YS) which uses Y), then twice on line 12 (the two references to $(Y) itself as we execute the rule) and finally on line 9 ($(X) references $(YS) which references $(Y)).

With the power of the tracer we can try another task: finding out where $(S) is used:
 


% gmake TRACE=S

Makefile:8: TRACE S
Makefile:8: TRACE S
Makefile:11: TRACE S
Makefile:14: TRACE S
dog dog
cat cat
Makefile:9: TRACE S
Makefile:9: TRACE S
dogs hate cats

Reference

The make utility executes a list of shell commands associated with each target, typically to create or update a file of the same name. makefile contains entries that describe how to bring a target up to date with respect to those on which it depends, which are called dependencies.

SYNTAX

/usr/ccs/bin/make [ -d ] [ -dd ] [ -D ] [ -DD ] [ -e ] [ -i ] [ -k ] [ -n ] [ -p ] [ -P ] [ -q ] [ -r ] [ -s] [ -S ] [ -t ] [ -V ] [ -f makefile ] ... [-K statefile ] ... [ target ... ] [ macro = value ... ]

/usr/xpg4/bin/make [ -d ] [ -dd ] [ -D ] [ -DD ] [ -e ] [ -i ] [ -k ] [ -n ] [ -p ] [ -P ] [ -q ] [ -r ] [ -s] [ -S ] [ -t ] [ -V ] [ -f makefile ] ... [ target... ] [ macro = value ... ]

-d Displays the reasons why make chooses to rebuild a target; make displays any and all dependencies that are newer. In addition, make displays options read in from the MAKEFLAGS environment variable.
-dd Displays the dependency check and processing in vast detail.
-D Displays the text of the makefiles read in.
-DD Displays the text of the makefiles, make.rules file, the state file, and all hidden-dependency reports.
-e Environment variables override assignments within makefiles.
-i Ignores error codes returned by commands. Equivalent to the special-function target `.IGNORE:'.
-k When a nonzero error status is returned by a rule, or when make cannot find a rule, abandons work on the current target, but continues with other dependency branches that do not depend on it.
-n No execution mode. Prints commands, but does not execute them. Even lines beginning with an @ are printed. However, if a command line contains a reference to the $(MAKE) macro, that line is always executed (see the discussion of MAKEFLAGS in ). When in POSIX mode, lines beginning with a "+" are executed.
-p Prints out the complete set of macro definitions and target descriptions.
-P Merely reports dependencies, rather than building them.
-q Question mode. make returns a zero or nonzero status code depending on whether or not the target file is up to date. When in POSIX mode, lines beginning with a "+" are executed.
-r Does not read in the default makefile /usr/share/lib/make/make.rules.
-s Silent mode. Does not print command lines before executing them. Equivalent to the special-function target .SILENT:.
-S Undoes the effect of the -k option. Stops processing when a non-zero exit status is returned by a command.
-t Touches the target files (bringing them up to date) rather than performing their rules. This can be dangerous when files are maintained by more than one person. When the .KEEP_STATE: target appears in the makefile, this option updates the state file just as if the rules had been performed. When in POSIX mode, lines beginning with a "+" are executed.
-V Puts make into SysV mode. Refer to sysV-make for respective details.
-f makefile Uses the description file makefile. A `-' as the makefile argument denotes the standard input. The contents of makefile, when present, override the standard set of implicit rules and predefined macros. When more than one `-f makefile' argument pair appears, make uses the concatenation of those files, in order of appearance.

When no makefile is specified, /usr/ccs/bin/make tries the following in sequence, except when in POSIX mode (see the .POSIX in the section below):

  • If there is a file named makefile in the working directory, make uses that file. If, however, there is an SCCS history file (SCCS/s.makefile) which is newer, make attempts to retrieve and use the most recent version.
  • In the absence of the above file(s), if a file named Makefile is present in the working directory, make attempts to use it. If there is an SCCS history file (SCCS/s.Makefile) that is newer, make attempts to retrieve and use the most recent version. 

When no makefile is specified, /usr/ccs/bin/make in POSIX mode and /usr/xpg4/bin/make try the following files in sequence:

  • ./makefile, ./Makefile
  • s.makefile, SCCS/s.makefile
  • s.Makefile, SCCS/s.Makefile
-K statefile Uses the state file statefile. A `-' as the statefile argument denotes the standard input. The contents of statefile, when present, override the standard set of implicit rules and predefined macros. When more than one `-K statefile' argument pair appears, make uses the concatenation of those files, in order of appearance. (See also .KEEP_STATE and .KEEP_STATE_FILE in the section).
target Target names, as defined in .
macro =  value Macro definition. This definition overrides any regular definition for the specified macro within the makefile itself, or in the environment. However, this definition can still be overridden by conditional macro assignments.

 

 


Etc

Society

Groupthink : Two Party System as Polyarchy : Corruption of Regulators : Bureaucracies : Understanding Micromanagers and Control Freaks : Toxic Managers :   Harvard Mafia : Diplomatic Communication : Surviving a Bad Performance Review : Insufficient Retirement Funds as Immanent Problem of Neoliberal Regime : PseudoScience : Who Rules America : Neoliberalism  : The Iron Law of Oligarchy : Libertarian Philosophy

Quotes

War and Peace : Skeptical Finance : John Kenneth Galbraith :Talleyrand : Oscar Wilde : Otto Von Bismarck : Keynes : George Carlin : Skeptics : Propaganda  : SE quotes : Language Design and Programming Quotes : Random IT-related quotesSomerset Maugham : Marcus Aurelius : Kurt Vonnegut : Eric Hoffer : Winston Churchill : Napoleon Bonaparte : Ambrose BierceBernard Shaw : Mark Twain Quotes

Bulletin:

Vol 25, No.12 (December, 2013) Rational Fools vs. Efficient Crooks The efficient markets hypothesis : Political Skeptic Bulletin, 2013 : Unemployment Bulletin, 2010 :  Vol 23, No.10 (October, 2011) An observation about corporate security departments : Slightly Skeptical Euromaydan Chronicles, June 2014 : Greenspan legacy bulletin, 2008 : Vol 25, No.10 (October, 2013) Cryptolocker Trojan (Win32/Crilock.A) : Vol 25, No.08 (August, 2013) Cloud providers as intelligence collection hubs : Financial Humor Bulletin, 2010 : Inequality Bulletin, 2009 : Financial Humor Bulletin, 2008 : Copyleft Problems Bulletin, 2004 : Financial Humor Bulletin, 2011 : Energy Bulletin, 2010 : Malware Protection Bulletin, 2010 : Vol 26, No.1 (January, 2013) Object-Oriented Cult : Political Skeptic Bulletin, 2011 : Vol 23, No.11 (November, 2011) Softpanorama classification of sysadmin horror stories : Vol 25, No.05 (May, 2013) Corporate bullshit as a communication method  : Vol 25, No.06 (June, 2013) A Note on the Relationship of Brooks Law and Conway Law

History:

Fifty glorious years (1950-2000): the triumph of the US computer engineering : Donald Knuth : TAoCP and its Influence of Computer Science : Richard Stallman : Linus Torvalds  : Larry Wall  : John K. Ousterhout : CTSS : Multix OS Unix History : Unix shell history : VI editor : History of pipes concept : Solaris : MS DOSProgramming Languages History : PL/1 : Simula 67 : C : History of GCC developmentScripting Languages : Perl history   : OS History : Mail : DNS : SSH : CPU Instruction Sets : SPARC systems 1987-2006 : Norton Commander : Norton Utilities : Norton Ghost : Frontpage history : Malware Defense History : GNU Screen : OSS early history

Classic books:

The Peter Principle : Parkinson Law : 1984 : The Mythical Man-MonthHow to Solve It by George Polya : The Art of Computer Programming : The Elements of Programming Style : The Unix Hater’s Handbook : The Jargon file : The True Believer : Programming Pearls : The Good Soldier Svejk : The Power Elite

Most popular humor pages:

Manifest of the Softpanorama IT Slacker Society : Ten Commandments of the IT Slackers Society : Computer Humor Collection : BSD Logo Story : The Cuckoo's Egg : IT Slang : C++ Humor : ARE YOU A BBS ADDICT? : The Perl Purity Test : Object oriented programmers of all nations : Financial Humor : Financial Humor Bulletin, 2008 : Financial Humor Bulletin, 2010 : The Most Comprehensive Collection of Editor-related Humor : Programming Language Humor : Goldman Sachs related humor : Greenspan humor : C Humor : Scripting Humor : Real Programmers Humor : Web Humor : GPL-related Humor : OFM Humor : Politically Incorrect Humor : IDS Humor : "Linux Sucks" Humor : Russian Musical Humor : Best Russian Programmer Humor : Microsoft plans to buy Catholic Church : Richard Stallman Related Humor : Admin Humor : Perl-related Humor : Linus Torvalds Related humor : PseudoScience Related Humor : Networking Humor : Shell Humor : Financial Humor Bulletin, 2011 : Financial Humor Bulletin, 2012 : Financial Humor Bulletin, 2013 : Java Humor : Software Engineering Humor : Sun Solaris Related Humor : Education Humor : IBM Humor : Assembler-related Humor : VIM Humor : Computer Viruses Humor : Bright tomorrow is rescheduled to a day after tomorrow : Classic Computer Humor

The Last but not Least Technology is dominated by two types of people: those who understand what they do not manage and those who manage what they do not understand ~Archibald Putt. Ph.D


Copyright © 1996-2021 by Softpanorama Society. www.softpanorama.org was initially created as a service to the (now defunct) UN Sustainable Development Networking Programme (SDNP) without any remuneration. This document is an industrial compilation designed and created exclusively for educational use and is distributed under the Softpanorama Content License. Original materials copyright belong to respective owners. Quotes are made for educational purposes only in compliance with the fair use doctrine.

FAIR USE NOTICE This site contains copyrighted material the use of which has not always been specifically authorized by the copyright owner. We are making such material available to advance understanding of computer science, IT technology, economic, scientific, and social issues. We believe this constitutes a 'fair use' of any such copyrighted material as provided by section 107 of the US Copyright Law according to which such material can be distributed without profit exclusively for research and educational purposes.

This is a Spartan WHYFF (We Help You For Free) site written by people for whom English is not a native language. Grammar and spelling errors should be expected. The site contain some broken links as it develops like a living tree...

You can use PayPal to to buy a cup of coffee for authors of this site

Disclaimer:

The statements, views and opinions presented on this web page are those of the author (or referenced source) and are not endorsed by, nor do they necessarily reflect, the opinions of the Softpanorama society. We do not warrant the correctness of the information provided or its fitness for any purpose. The site uses AdSense so you need to be aware of Google privacy policy. You you do not want to be tracked by Google please disable Javascript for this site. This site is perfectly usable without Javascript.

Last modified: February 19, 2014