In
software development
Software development is the process of conceiving, specifying, designing, programming, documenting, testing, and bug fixing involved in creating and maintaining applications, frameworks, or other software components. Software development inv ...
, Make is a
build automation tool that automatically
build
Build may refer to:
* Engineering something
* Construction
* Physical body stature, especially muscle size; usually of the human body
* Build (game engine), a 1995 first-person shooter engine
* "Build" (song), a 1987 song by The Housemartins
* ...
s
executable program
In computing, executable code, an executable file, or an executable program, sometimes simply referred to as an executable or binary, causes a computer "to perform indicated tasks according to encoded instruction (computer science), instructi ...
s and
libraries
A library is a collection of materials, books or media that are accessible for use and not just for display purposes. A library provides physical (hard copies) or digital access (soft copies) materials, and may be a physical location or a vir ...
from
source code
In computing, source code, or simply code, is any collection of code, with or without comment (computer programming), comments, written using a human-readable programming language, usually as plain text. The source code of a Computer program, p ...
by reading
files called ''Makefiles'' which specify how to derive the target program. Though
integrated development environment
An integrated development environment (IDE) is a software application that provides comprehensive facilities to computer programmers for software development. An IDE normally consists of at least a source code editor, build automation tools a ...
s and
language
Language is a structured system of communication. The structure of a language is its grammar and the free components are its vocabulary. Languages are the primary means by which humans communicate, and may be conveyed through a variety of ...
-specific
compiler
In computing, a compiler is a computer program that translates computer code written in one programming language (the ''source'' language) into another language (the ''target'' language). The name "compiler" is primarily used for programs that ...
features can also be used to manage a build process, Make remains widely used, especially in
Unix
Unix (; trademarked as UNIX) is a family of multitasking, multiuser computer operating systems that derive from the original AT&T Unix, whose development started in 1969 at the Bell Labs research center by Ken Thompson, Dennis Ritchie, a ...
and
Unix-like
A Unix-like (sometimes referred to as UN*X or *nix) operating system is one that behaves in a manner similar to a Unix system, although not necessarily conforming to or being certified to any version of the Single UNIX Specification. A Unix-li ...
operating system
An operating system (OS) is system software that manages computer hardware, software resources, and provides common daemon (computing), services for computer programs.
Time-sharing operating systems scheduler (computing), schedule tasks for ef ...
s.
Besides building programs, Make can be used to manage any project where some files must be updated automatically from others whenever the others change.
Origin
There are now a number of dependency-tracking build utilities, but Make is one of the most widespread, primarily due to its inclusion in
Unix
Unix (; trademarked as UNIX) is a family of multitasking, multiuser computer operating systems that derive from the original AT&T Unix, whose development started in 1969 at the Bell Labs research center by Ken Thompson, Dennis Ritchie, a ...
, starting with the
PWB/UNIX 1.0, which featured a variety of tools targeting software development tasks.
It was originally created by
Stuart Feldman in April 1976 at
Bell Labs
Nokia Bell Labs, originally named Bell Telephone Laboratories (1925–1984),
then AT&T Bell Laboratories (1984–1996)
and Bell Labs Innovations (1996–2007),
is an American industrial research and scientific development company owned by mult ...
.
[ Feldman received the 2003 ]ACM Software System Award
The ACM Software System Award is an annual award that honors people or an organization "for developing a software system that has had a lasting influence, reflected in contributions to concepts, in commercial acceptance, or both". It is awarded by ...
for the authoring of this widespread tool.
Feldman was inspired to write Make by the experience of a coworker in futilely debugging a program of his where the executable was accidentally not being updated with changes:
Before Make's introduction, the Unix build system most commonly consisted of operating system
An operating system (OS) is system software that manages computer hardware, software resources, and provides common daemon (computing), services for computer programs.
Time-sharing operating systems scheduler (computing), schedule tasks for ef ...
dependent "make" and "install" shell scripts accompanying their program's source. Being able to combine the commands for the different targets into a single file and being able to abstract out dependency tracking and archive handling was an important step in the direction of modern build environments.
Derivatives
Make has gone through a number of rewrites, including a number of from-scratch variants which used the same file format and basic algorithmic principles and also provided a number of their own non-standard enhancements. Some of them are:
* Sun DevPro Make appeared in 1986 with SunOS-3.2. With SunOS-3.2, It was delivered as optional program; with SunOS-4.0, SunPro Make was made the default Make program. In December 2006, Sun DevPro Make was made open source as part of the efforts to open-source Solaris.
* dmake or Distributed Make that came with Sun Solaris Studio as its default Make, but not the default one on the Solaris Operating System (SunOS). It was originally required to build OpenOffice, but in 2009 the build system was rewritten to use GNU Make. While Apache OpenOffice
Apache OpenOffice (AOO) is an open-source office productivity software suite. It is one of the successor projects of OpenOffice.org and the designated successor of IBM Lotus Symphony. It is a close cousin of LibreOffice, Collabora Online an ...
still contains a mixture of both build systems, the much more actively developed LibreOffice
LibreOffice () is a free and open-source office productivity software suite, a project of The Document Foundation (TDF). It was forked in 2010 from OpenOffice.org, an open-sourced version of the earlier StarOffice. The LibreOffice suite consi ...
only uses the modernized "gbuild" now.
* BSD Make (''pmake'', ''bmake'' or ''fmake''), which is derived from Adam de Boor's work on a version of Make capable of building targets in parallel, and survives with varying degrees of modification in FreeBSD
FreeBSD is a free and open-source Unix-like operating system descended from the Berkeley Software Distribution (BSD), which was based on Research Unix. The first version of FreeBSD was released in 1993. In 2005, FreeBSD was the most popular ...
, NetBSD
NetBSD is a free and open-source Unix operating system based on the Berkeley Software Distribution (BSD). It was the first open-source BSD descendant officially released after 386BSD was forked. It continues to be actively developed and is a ...
and OpenBSD
OpenBSD is a security-focused operating system, security-focused, free and open-source, Unix-like operating system based on the Berkeley Software Distribution (BSD). Theo de Raadt created OpenBSD in 1995 by fork (software development), forking N ...
. Distinctively, it has conditionals and iterative loops which are applied at the parsing stage and may be used to conditionally and programmatically construct the makefile, including generation of targets at runtime.
* GNU
GNU () is an extensive collection of free software
Free software or libre software is computer software distributed under terms that allow users to run the software for any purpose as well as to study, change, and distribute it and any ...
Make (short ''gmake'') is the standard implementation of Make for Linux and macOS. It provides several extensions over the original Make, such as conditionals. It also provides many built-in functions which can be used to eliminate the need for shell-scripting in the makefile rules as well as to manipulate the variables set and used in the makefile. For example, the ''foreach'' function can be used to iterate over a list of values, such as the names of files in a given directory. GNU Make is required for building many software systems, including GCC (since version 3.4), the Linux kernel, Apache OpenOffice, LibreOffice, and Mozilla Firefox
Mozilla Firefox, or simply Firefox, is a free and open-source web browser developed by the Mozilla Foundation and its subsidiary, the Mozilla Corporation. It uses the Gecko rendering engine to display web pages, which implements current a ...
.
* Rocky Bernstein's Remake is a fork of GNU Make and provides several extensions over GNU Make, such as better location and error-location reporting, execution tracing, execution profiling, and it contains a debugger.
* Glenn Fowler's ''nmake'' is unrelated to the Microsoft program of the same name. Its input is similar to Make, but not compatible. This program provides shortcuts and built-in features, which according to its developers reduces the size of makefiles by a factor of 10.
* Microsoft
Microsoft Corporation is an American multinational corporation, multinational technology company, technology corporation producing Software, computer software, consumer electronics, personal computers, and related services headquartered at th ...
''nmake'', a command-line tool which normally is part of Visual Studio
Visual Studio is an integrated development environment (IDE) from Microsoft. It is used to develop computer programs including websites, web apps, web services and mobile apps. Visual Studio uses Microsoft software development platforms such ...
. It supports preprocessor directives such as includes and conditional expressions which use variables set on the command-line or within the makefiles. Inference rules differ from Make; for example they can include search paths. The Make tool supplied with Embarcadero products has a command-line option that "Causes MAKE to mimic Microsoft's NMAKE.". Qt Project
The Qt Project is an open collaboration effort to coordinate the development of the Qt software framework. Initially founded by Nokia in 2011, the project is now led by The Qt Company.
History
Haavard Nord and Eirik Chambe-Eng (the origin ...
's ''Jom'' tool is a clone of nmake.
* ''Mk'' replaced Make in Research Unix
The term "Research Unix" refers to early versions of the Unix operating system for DEC PDP-7, PDP-11, VAX and Interdata 7/32 and 8/32 computers, developed in the Bell Labs Computing Sciences Research Center (CSRC).
History
The term ''Resear ...
, starting from version 9. A redesign of the original tool by Bell Labs programmer Andrew G. Hume, it features a different syntax. Mk became the standard build tool in Plan 9 Plan 9 or Plan Nine may refer to:
Music
* Plan 9 (band), a psychedelic rock band from Rhode Island
* ''Plan 9'', an album by Big Guitars From Memphis with Rick Lindy
* "Plan 9", a song on the 1993 album ''Gorgeous'' by electronica band 808 Stat ...
, Bell Labs' intended successor to Unix.
* ''Kati'' is Google's replacement of GNU Make, used in Android OS
Android is a mobile operating system based on a modified version of the Linux kernel and other open-source software, designed primarily for touchscreen mobile devices such as smartphones and tablets. Android is developed by a consortium of dev ...
builds. It translates the makefile into ninja
A or was a covert agent or mercenary in feudal Japan. The functions of a ninja included reconnaissance, espionage, infiltration, deception, ambush, bodyguarding and their fighting skills in martial arts, including ninjutsu.Kawakami, pp ...
for faster incremental builds.
* Snakemake is a python-driven implementation for compiling and running bioinformatics
Bioinformatics () is an interdisciplinary field that develops methods and software tools for understanding biological data, in particular when the data sets are large and complex. As an interdisciplinary field of science, bioinformatics combin ...
workflows.
POSIX
The Portable Operating System Interface (POSIX) is a family of standards specified by the IEEE Computer Society for maintaining compatibility between operating systems. POSIX defines both the system- and user-level application programming inte ...
includes standardization of the basic features and operation of the Make utility, and is implemented with varying degrees of completeness in Unix-based versions of Make. In general, simple makefiles may be used between various versions of Make with reasonable success. GNU Make, Makepp and some versions of BSD Make default to looking first for files named "GNUmakefile", "Makeppfile" and "BSDmakefile" respectively, which allows one to put makefiles which use implementation-defined behavior in separate locations.
Behavior
Make is typically used to build
Build may refer to:
* Engineering something
* Construction
* Physical body stature, especially muscle size; usually of the human body
* Build (game engine), a 1995 first-person shooter engine
* "Build" (song), a 1987 song by The Housemartins
* ...
executable programs and libraries from source code. Generally though, Make is applicable to any process that involves executing arbitrary commands to transform a source file to a target result. For example, Make could be used to detect a change made to an image file (the source) and the transformation actions might be to convert the file to some specific format, copy the result into a content management system, and then send e-mail to a predefined set of users indicating that the actions above were performed.
Make is invoked with a list of target file names to build as command-line argument
A command-line interpreter or command-line processor uses a command-line interface (CLI) to receive commands from a user in the form of lines of text. This provides a means of setting parameters for the environment, invoking executables and pro ...
s:
make ARGET ...
Without arguments, Make builds the first target that appears in its makefile, which is traditionally a symbolic "phony" target named ''all''.
Make decides whether a target needs to be regenerated by comparing file modification times. This solves the problem of avoiding the building of files which are already up to date, but it fails when a file changes but its modification time stays in the past. Such changes could be caused by restoring an older version of a source file, or when a network filesystem
A clustered file system is a file system which is shared by being simultaneously Mount (computing), mounted on multiple Server (computing), servers. There are several approaches to computer cluster, clustering, most of which do not employ a cl ...
is a source of files and its clock or time zone is not synchronized with the machine running Make. The user must handle this situation by forcing a complete build. Conversely, if a source file's modification time is in the future, it triggers unnecessary rebuilding, which may inconvenience users.
Makefiles are traditionally used for compiling code (*.c, *.cc, *.C, etc.), but they can also be used for providing commands to automate common tasks. One such makefile is called from the command line:
make # Without argument runs first TARGET
make help # Show available TARGETS
make dist # Make a release archive from current dir
make check # Unit testing without installation
Makefile
Make searches the current directory for the makefile to use, e.g. GNU Make searches files in order for a file named one of , , or and then runs the specified (or default) target(s) from (only) that file.
The makefile language is similar to declarative programming
In computer science, declarative programming is a programming paradigm—a style of building the structure and elements of computer programs—that expresses the logic of a computation without describing its control flow.
Many languages that a ...
. This class of language, in which necessary end conditions are described but the order in which actions are to be taken is not important, is sometimes confusing to programmers used to imperative programming
In computer science, imperative programming is a programming paradigm of software that uses statements that change a program's state. In much the same way that the imperative mood in natural languages expresses commands, an imperative program co ...
.
One problem in build automation is the tailoring of a build process to a given platform
Platform may refer to:
Technology
* Computing platform, a framework on which applications may be run
* Platform game, a genre of video games
* Car platform, a set of components shared by several vehicle models
* Weapons platform, a system ...
. For instance, the compiler used on one platform might not accept the same options as the one used on another. This is not well handled by Make. This problem is typically handled by generating platform-specific build instructions, which in turn are processed by Make. Common tools for this process are Autoconf
GNU Autoconf is a tool for producing configure scripts for building, installing, and packaging software on computer systems where a Bourne shell is available.
Autoconf is agnostic about the programming languages used, but it is often used for ...
, CMake
In software development, CMake is cross-platform free and open-source software for build automation, testing, packaging and installation of software by using a compiler-independent method. CMake is not a build system itself; it generates ano ...
or GYP (or more advanced NG).
Makefiles may contain five kinds of things:
# An ''explicit rule'' says when and how to remake 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 give a recipe to use to create or update the targets.
# An ''implicit rule'' 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 a recipe to create or update such a target.
# A ''variable definition'' is a line that specifies a text string value for a variable that can be substituted into the text later.
# A ''directive'' is an instruction for make to do something special while reading the makefile such as reading another makefile.
# Lines starting with are used for comments
Comment may refer to:
* Comment (linguistics) or rheme, that which is said about the topic (theme) of a sentence
* Bernard Comment (born 1960), Swiss writer and publisher
Computing
* Comment (computer programming), explanatory text or informa ...
.
Rules
A makefile consists of ''rules''. Each rule begins with a textual ''dependency line'' which defines a target
Target may refer to:
Physical items
* Shooting target, used in marksmanship training and various shooting sports
** Bullseye (target), the goal one for which one aims in many of these sports
** Aiming point, in field artillery, fi ...
followed by a colon (:) and optionally an enumeration of components (files or other targets) on which the target depends. The dependency line is arranged so that the target (left hand of the colon) depends on components (right hand of the colon). It is common to refer to components as prerequisites of the target.
target arget ... omponent ... ommand 1 .
.
.
ommand n
Usually each rule has a single unique target, rather than multiple targets.
For example, a C .o object file is created from .c files, so .c files come first (i.e. specific object file
An object file is a computer file containing object code, that is, machine code output of an assembler or compiler. The object code is usually relocatable, and not usually directly executable. There are various formats for object files, and the ...
target depends on a C source file and header file
Many programming languages and other computer files have a directive, often called include (sometimes copy or import), that causes the contents of the specified file to be inserted into the original file. These included files are called copybooks ...
s). Because Make itself does not understand, recognize or distinguish different kinds of files, this opens up a possibility for human error. A forgotten or an extra dependency may not be immediately obvious and may result in subtle bugs in the generated software. It is possible to write makefiles which generate these dependencies by calling third-party tools, and some makefile generators, such as the Automake
In software development, GNU Automake is a programming tool to automate parts of the compilation process. It eases usual compilation problems. For example, it points to needed dependencies.
It automatically generates one or more ''Makefile.in' ...
toolchain provided by the GNU Project
The GNU Project () is a free software, mass collaboration project announced by Richard Stallman on September 27, 1983. Its goal is to give computer users freedom and control in their use of their computers and Computer hardware, computing devi ...
, can do so automatically.
Each dependency line may be followed by a series of TAB indented command lines which define how to transform the components (usually source files) into the target (usually the "output"). If any of the prerequisites has a more recent modification time than the target, the command lines are run. The GNU Make documentation refers to the commands associated with a rule as a "recipe".
The first command may appear on the same line after the prerequisites, separated by a semicolon,
targets: prerequisites ; command
for example,
hello: ; @echo "hello"
Make can decide where to start through topological sorting
In computer science, a topological sort or topological ordering of a directed graph is a linear ordering of its vertices such that for every directed edge ''uv'' from vertex ''u'' to vertex ''v'', ''u'' comes before ''v'' in the ordering. For in ...
.
Each command line must begin with a tab character
The tab key (abbreviation of tabulator key or tabular key) on a keyboard is used to advance the cursor to the next tab stop.
History
The word ''tab'' derives from the word ''tabulate'', which means "to arrange data in a tabular, or table, f ...
to be recognized as a command. The tab is a whitespace
White space or whitespace may refer to:
Technology
* Whitespace characters, characters in computing that represent horizontal or vertical space
* White spaces (radio), allocated but locally unused radio frequencies
* TV White Space Database, a mec ...
character, but the space character
In computer programming, whitespace is any character or series of characters that represent horizontal or vertical space in typography. When rendered, a whitespace character does not correspond to a visible mark, but typically does occupy an area ...
does not have the same special meaning. This is problematic, since there may be no visual difference between a tab and a series of space characters. This aspect of the syntax of makefiles is often subject to criticism; it has been described by Eric S. Raymond as "one of the worst design botches in the history of Unix"["Chapter 15. Tools: make: Automating Your Recipes", ''The Art of Unix Programming'', Eric S. Raymond 2003] and '' The Unix-Haters Handbook'' said "using tabs as part of the syntax is like one of those pungee stick traps in ''The Green Berets''". Feldman explains the choice as caused by a workaround
A workaround is a bypass of a recognized problem or limitation in a system or policy. A workaround is typically a temporary fix that implies that a genuine solution to the problem is needed. But workarounds are frequently as creative as true solut ...
for an early implementation difficulty preserved by a desire for backward compatibility
Backward compatibility (sometimes known as backwards compatibility) is a property of an operating system, product, or technology that allows for interoperability with an older legacy system, or with input designed for such a system, especially ...
with the very first users:
However, the GNU Make since version 3.82 allows to choose any symbol (one character) as the recipe prefix using the .RECIPEPREFIX special variable, for example:
.RECIPEPREFIX := :
all:
:@echo "recipe prefix symbol is set to '$(.RECIPEPREFIX)'"
Each command is executed by a separate shell or command-line interpreter
A command-line interpreter or command-line processor uses a command-line interface (CLI) to receive command (computing), commands from a user in the form of lines of text. This provides a means of setting parameters for the environment, invokin ...
instance. Since operating systems use different command-line interpreters this can lead to unportable makefiles. For instance, GNU Make (all POSIX Makes) by default executes commands with /bin/sh, where Unix
Unix (; trademarked as UNIX) is a family of multitasking, multiuser computer operating systems that derive from the original AT&T Unix, whose development started in 1969 at the Bell Labs research center by Ken Thompson, Dennis Ritchie, a ...
commands like cp are normally used. In contrast to that, Microsoft's ''nmake'' executes commands with cmd.exe where batch commands like copy are available but not necessarily cp.
A rule may have no command lines defined. The dependency line can consist solely of components that refer to targets, for example:
realclean: clean distclean
The command lines of a rule are usually arranged so that they generate the target. An example: if is newer, it is converted to text. The contents of the makefile:
file.txt: file.html
lynx -dump file.html > file.txt
The rule above would be triggered when Make updates "file.txt". In the following invocation, Make would typically use this rule to update the "file.txt" target if "file.html" were newer.
make file.txt
Command lines can have one or more of the following three prefixes:
* a hyphen-minus
The hyphen-minus is the most commonly used type of hyphen, widely used in digital documents. It is the only character that looks like a minus sign or a dash in many character sets such as ASCII or on most keyboards, so it is also used as suc ...
(-), specifying that errors are ignored
* an at sign
The at sign, , is normally read aloud as "at"; it is also commonly called the at symbol, commercial at, or address sign. It is used as an accounting and invoice abbreviation meaning "at a rate of" (e.g. 7 widgets @ £2 per widget = £14), but ...
(@), specifying that the command is not printed to standard output before it is executed
* a plus sign
The plus and minus signs, and , are mathematical symbols used to represent the notions of positive and negative, respectively. In addition, represents the operation of addition, which results in a sum, while represents subtraction, resul ...
(+), the command is executed even if Make is invoked in a "do not execute" mode
Ignoring errors and silencing echo can alternatively be obtained via the special targets and .
Microsoft's NMAKE has predefined rules that can be omitted from these makefiles, e.g. .
Macros
A makefile can contain definitions of macros. Macros are usually referred to as ''variables'' when they hold simple string definitions, like . Macros in makefiles may be overridden in the command-line argument
A command-line interpreter or command-line processor uses a command-line interface (CLI) to receive commands from a user in the form of lines of text. This provides a means of setting parameters for the environment, invoking executables and pro ...
s passed to the Make utility. Environment variables are also available as macros.
Macros allow users to specify the programs invoked and other custom behavior during the build process. For example, the macro is frequently used in makefiles to refer to the location of a C compiler, and the user may wish to specify a particular compiler to use.
New macros (or simple "variables") are traditionally defined using capital letters:
MACRO = definition
A macro is used by expanding it. Traditionally this is done by enclosing its name inside . (Omitting the parentheses leads to Make interpreting the next letter after the as the entire variable name.) An equivalent form uses curly braces rather than parentheses, i.e. , which is the style used in the BSDs.
NEW_MACRO = $(MACRO)-$(MACRO2)
Macros can be composed of shell commands by using the command substitution operator, denoted by backticks
The backtick is a typographical mark used mainly in computing. It is also known as backquote, grave, or grave accent.
The character was designed for typewriters to add a grave accent to a (lower-case) base letter, by overtyping it atop that le ...
().
YYYYMMDD = ` date `
The content of the definition is stored "as is". Lazy evaluation
In programming language theory, lazy evaluation, or call-by-need, is an evaluation strategy which delays the evaluation of an expression until its value is needed ( non-strict evaluation) and which also avoids repeated evaluations ( sharing).
T ...
is used, meaning that macros are normally expanded only when their expansions are actually required, such as when used in the command lines of a rule. An extended example:
PACKAGE = package
VERSION = ` date +"%Y.%m.%d" `
ARCHIVE = $(PACKAGE)-$(VERSION)
dist:
# Notice that only now macros are expanded for shell to interpret:
# tar -cf package-`date +"%Y.%m.%d"`.tar
tar -cf $(ARCHIVE).tar .
The generic syntax for overriding macros on the command line is:
make MACRO="value" ACRO="value" ...TARGET ARGET ...
Makefiles can access any of a number of predefined ''internal macros'', with and being the most common.
target: component1 component2
# contains those components which need attention (i.e. they ARE YOUNGER than current TARGET).
echo $?
# evaluates to current TARGET name from among those left of the colon.
echo $@
A somewhat common syntax expansion is the use of , , and instead of the equal sign. It works on BSD and GNU makes alike.
Suffix rules
Suffix rules have "targets" with names in the form and are used to launch actions based on file extension. In the command lines of suffix rules, POSIX specifies that the internal macro refers to the first prerequisite and refers to the target. In this example, which converts any HTML file into text, the shell redirection token is part of the command line whereas is a macro referring to the HTML file:
.SUFFIXES: .txt .html
# From .html to .txt
.html.txt:
lynx -dump $< > $@
When called from the command line, the example above expands.
$ make -n file.txt
lynx -dump file.html > file.txt
Pattern rules
Suffix rules cannot have any prerequisites of their own. If they have any, they are treated as normal files with unusual names, not as suffix rules. GNU Make supports suffix rules for compatibility with old makefiles but otherwise encourages usage of ''pattern rules''.
A pattern rule looks like an ordinary rule, except that its target contains exactly one character within the string. The target is considered a pattern for matching file names: the can match any substring of zero or more characters, while other characters match only themselves. The prerequisites likewise use to show how their names relate to the target name.
The example above of a suffix rule would look like the following pattern rule:
# From %.html to %.txt
%.txt : %.html
lynx -dump $< > $@
Other elements
Single-line comments are started with the hash symbol (#).
Some directives in makefiles can include other makefiles.
Line continuation is indicated with a backslash character at the end of a line.
target: component \
component
command ; \
command , \
piped-command
Example makefiles
The makefile:
PACKAGE = package
VERSION = ` date "+%Y.%m%d%" `
RELEASE_DIR = ..
RELEASE_FILE = $(PACKAGE)-$(VERSION)
# Notice that the variable LOGNAME comes from the environment in
# POSIX shells.
#
# target: all - Default target. Does nothing.
all:
echo "Hello $(LOGNAME), nothing to do by default"
# sometimes: echo "Hello $, nothing to do by default"
echo "Try 'make help'"
# target: help - Display callable targets.
help:
egrep "^# target:" mkefile
# target: list - List source files
list:
# Won't work. Each command is in separate shell
cd src
ls
# Correct, continuation of the same shell
cd src; \
ls
# target: dist - Make a release.
dist:
tar -cf $(RELEASE_DIR)/$(RELEASE_FILE) && \
gzip -9 $(RELEASE_DIR)/$(RELEASE_FILE).tar
Below is a very simple makefile that by default (the "all" rule is listed first) compiles a source file called "helloworld.c" using the system's C compiler and also provides a "clean" target to remove the generated files if the user desires to start over. The and are two of the so-called internal macros (also known as automatic variables) and stand for the target name and "implicit" source, respectively. In the example below, expands to a space delimited list of the prerequisites. There are a number of other internal macros.Automatic Variables
GNU `make'
CFLAGS ?= -g
all: helloworld
helloworld: helloworld.o
# Commands start with TAB not spaces
$(CC) $(LDFLAGS) -o $@ $^
helloworld.o: helloworld.c
$(CC) $(CFLAGS) -c -o $@ $<
clean: FRC
$(RM) helloworld helloworld.o
# This pseudo target causes all targets that depend on FRC
# to be remade even in case a file with the name of the target exists.
# This works with any make implementation under the assumption that
# there is no file FRC in the current directory.
FRC:
Many systems come with predefined Make rules and macros to specify common tasks such as compilation based on file suffix. This lets users omit the actual (often unportable) instructions of how to generate the target from the source(s). On such a system the makefile above could be modified as follows:
all: helloworld
helloworld: helloworld.o
$(CC) $(CFLAGS) $(LDFLAGS) -o $@ $^
clean: FRC
$(RM) helloworld helloworld.o
# This is an explicit suffix rule. It may be omitted on systems
# that handle simple rules like this automatically.
.c.o:
$(CC) $(CFLAGS) -c $<
FRC:
.SUFFIXES: .c
That "helloworld.o" depends on "helloworld.c" is now automatically handled by Make. In such a simple example as the one illustrated here this hardly matters, but the real power of suffix rules becomes evident when the number of source files in a software project starts to grow. One only has to write a rule for the linking step and declare the object files as prerequisites. Make will then implicitly determine how to make all the object files and look for changes in all the source files.
Simple suffix rules work well as long as the source files do not depend on each other and on other files such as header files. Another route to simplify the build process is to use so-called pattern matching rules that can be combined with compiler-assisted dependency generation. As a final example requiring the gcc compiler and GNU Make, here is a generic makefile that compiles all C files in a folder to the corresponding object files and then links them to the final executable. Before compilation takes place, dependencies are gathered in makefile-friendly format into a hidden file ".depend" that is then included to the makefile. Portable programs ought to avoid constructs used below.
# Generic GNUMakefile
# Just a snippet to stop executing under other make(1) commands
# that won't understand these lines
ifneq (,)
This makefile requires GNU Make.
endif
PROGRAM = foo
C_FILES := $(wildcard *.c)
OBJS := $(patsubst %.c, %.o, $(C_FILES))
CC = cc
CFLAGS = -Wall -pedantic
LDFLAGS =
LDLIBS = -lm
all: $(PROGRAM)
$(PROGRAM): .depend $(OBJS)
$(CC) $(CFLAGS) $(OBJS) $(LDFLAGS) -o $(PROGRAM) $(LDLIBS)
depend: .depend
.depend: cmd = gcc -MM -MF depend $(var); cat depend >> .depend;
.depend:
@echo "Generating dependencies..."
@$(foreach var, $(C_FILES), $(cmd))
@rm -f depend
-include .depend
# These are the pattern matching rules. In addition to the automatic
# variables used here, the variable $* that matches whatever % stands for
# can be useful in special cases.
%.o: %.c
$(CC) $(CFLAGS) -c $< -o $@
%: %.o
$(CC) $(CFLAGS) -o $@ $<
clean:
rm -f .depend $(OBJS)
.PHONY: clean depend
See also
*
List of build automation software
Build automation involves scripting or automating the process of compiling computer source code into binary code. Below is a list of notable tools associated with automating build processes.
Make-based
* GNU make, a make implementation with a ...
*
Dependency graph
References
External links
GNU Make homepagePractical Makefiles, by Example"Ask Mr. Make" series of article about GNU Make''Managing Projects with GNU make -- 3.xth edition''''What is wrong with make?''''What’s Wrong With GNU make?''''Recursive Make Considered Harmful''Advanced Auto-Dependency Generation
''Using NMake''written in
Seed7
Seed7 is an extensible general-purpose programming language designed by Thomas Mertes. It is syntactically similar to Pascal and Ada. Along with many other features, it provides an extension mechanism.Daniel Zingaro"Modern Extensible Languages ...
''Microsoft's NMAKE predefined rules''
{{Authority control
Articles with example code
Build automation
Compiling tools
GNU Project software
Unix programming tools
Unix SUS2008 utilities