HOME

TheInfoList



OR:

In
software development Software development is the process of designing and Implementation, implementing a software solution to Computer user satisfaction, satisfy a User (computing), user. The process is more encompassing than Computer programming, programming, wri ...
, Make is a
command-line interface A command-line interface (CLI) is a means of interacting with software via command (computing), commands each formatted as a line of text. Command-line interfaces emerged in the mid-1960s, on computer terminals, as an interactive and more user ...
software tool A programming tool or software development tool is a computer program that is used to software development, develop another computer program, usually by helping the developer manage computer files. For example, a programmer may use a tool called ...
that performs actions ordered by configured dependencies as defined in a
configuration file A configuration file, a.k.a. config file, is a computer file, file that stores computer data, data used to configure a software system such as an application software, application, a server (computing), server or an operating system. Some applic ...
called a ''makefile''. It is commonly used for
build automation Build automation is the practice of building software systems in a relatively unattended fashion. The build is configured to run with minimized or no software developer interaction and without using a developer's personal computer. Build automati ...
to build
executable code In computer science, 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 instructions", as opposed to a d ...
(such as a program or
library A library is a collection of Book, books, and possibly other Document, materials and Media (communication), media, that is accessible for use by its members and members of allied institutions. Libraries provide physical (hard copies) or electron ...
) from
source code In computing, source code, or simply code or source, is a plain text computer program written in a programming language. A programmer writes the human readable source code to control the behavior of a computer. Since a computer, at base, only ...
. But, not limited to building, Make can perform any operation available via the
operating system shell An operating system shell is a computer program that provides relatively broad and direct access to the system on which it runs. The term ''shell'' refers to how it is a relatively thin layer around an operating system. A shell is generally a ...
. Make is widely used, especially in
Unix Unix (, ; trademarked as UNIX) is a family of multitasking, multi-user 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, *nix 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 Uni ...
operating system An operating system (OS) is system software that manages computer hardware and software resources, and provides common daemon (computing), services for computer programs. Time-sharing operating systems scheduler (computing), schedule tasks for ...
s, even though many competing technologies and tools are available, including similar tools that perform actions based on dependencies, some
compiler In computing, a compiler is a computer program that Translator (computing), translates computer code written in one programming language (the ''source'' language) into another language (the ''target'' language). The name "compiler" is primaril ...
s and interactively via an
integrated development environment An integrated development environment (IDE) is a Application software, software application that provides comprehensive facilities for software development. An IDE normally consists of at least a source-code editor, build automation tools, an ...
. In addition to referring to the original
Unix Unix (, ; trademarked as UNIX) is a family of multitasking, multi-user 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 ...
tool, Make is also a technology since multiple tools have been implemented with roughly the same functionality including similar makefile
syntax In linguistics, syntax ( ) is the study of how words and morphemes combine to form larger units such as phrases and sentences. Central concerns of syntax include word order, grammatical relations, hierarchical sentence structure (constituenc ...
and
semantics Semantics is the study of linguistic Meaning (philosophy), meaning. It examines what meaning is, how words get their meaning, and how the meaning of a complex expression depends on its parts. Part of this process involves the distinction betwee ...
.


Origin

Stuart Feldman created Make while at
Bell Labs Nokia Bell Labs, commonly referred to as ''Bell Labs'', is an American industrial research and development company owned by Finnish technology company Nokia. With headquarters located in Murray Hill, New Jersey, Murray Hill, New Jersey, the compa ...
. An early version was completed in April 1976. 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 b ...
for authoring Make. Feldman describes the inspiration to write Make as arising from a coworker's frustration with the available tooling of the time: Before Make, building on Unix mostly consisted of
shell script A shell script is a computer program designed to be run by a Unix shell, a command-line interpreter. The various dialects of shell scripts are considered to be command languages. Typical operations performed by shell scripts include file manipu ...
s written for each program's codebase. Make's dependency ordering and out-of-date checking makes the build process more robust and more efficient. The makefile allowed for better organization of build logic and often fewer build files. Make is widely used in part due to its early inclusion in
Unix Unix (, ; trademarked as UNIX) is a family of multitasking, multi-user 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
PWB/UNIX The Programmer's Workbench (PWB/UNIX) was an early, now discontinued, version of the Unix operating system that had been created in the Bell Labs Computer Science Research Group of AT&T. Its stated goal was to provide a time-sharing working envi ...
1.0, which featured a variety of software development tools.


Variants

Make has been implemented numerous times, generally using the same makefile format and providing the same features, but some providing enhancements from the original. Examples: * Sun DevPro Make appeared in 1986 with SunOS-3.2. With SunOS-3.2. It was delivered as an 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 Solaris is the Latin word for sun. It may refer to: Arts and entertainment Literature, television and film * ''Solaris'' (novel), a 1961 science fiction novel by Stanisław Lem ** ''Solaris'' (1968 film), directed by Boris Nirenburg ** ''Sol ...
. * 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 software, open-source office suite, office productivity software suite. It is one of the successor projects of OpenOffice.org and the designated successor of IBM Lotus Symphony. It was a close cousin of ...
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 developed by The Document Foundation (TDF). It was created in 2010 as a fork of OpenOffice.org, itself a successor to StarOffice. The suite includes applications ...
only uses the modernized "gbuild" now. *
BSD The Berkeley Software Distribution (BSD), also known as Berkeley Unix or BSD Unix, is a discontinued Unix operating system developed and distributed by the Computer Systems Research Group (CSRG) at the University of California, Berkeley, beginni ...
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-software Unix-like operating system descended from the Berkeley Software Distribution (BSD). The first version was released in 1993 developed from 386BSD, one of the first fully functional and free Unix clones on affordable ...
,
NetBSD NetBSD is a free and open-source Unix-like operating system based on the Berkeley Software Distribution (BSD). It was the first open-source BSD descendant officially released after 386BSD was fork (software development), forked. It continues to ...
and
OpenBSD OpenBSD is a security-focused operating system, security-focused, free software, Unix-like operating system based on the Berkeley Software Distribution (BSD). Theo de Raadt created OpenBSD in 1995 by fork (software development), forking NetBSD ...
. 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 (394 packages ), which can be used as an operating system or can be used in parts with other operating systems. The use of the completed GNU tools led to the family of operating systems popu ...
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
GNU Compiler Collection The GNU Compiler Collection (GCC) is a collection of compilers from the GNU Project that support various programming languages, Computer architecture, hardware architectures, and operating systems. The Free Software Foundation (FSF) distributes ...
(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 curren ...
. * 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'' (unrelated to the same-named Microsoft variant) is incompatible with the UNIX variant, but provides features which, according to some, reduce the size of makefiles by a factor of 10. *
Microsoft Microsoft Corporation is an American multinational corporation and technology company, technology conglomerate headquartered in Redmond, Washington. Founded in 1975, the company became influential in the History of personal computers#The ear ...
''nmake'' is normally installed with
Visual Studio Visual Studio is an integrated development environment (IDE) developed by Microsoft. It is used to develop computer programs including web site, websites, web apps, web services and mobile apps. Visual Studio uses Microsoft software development ...
. 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. * Embarcadero make 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 origina ...
's ''Jom'' tool is a clone of nmake. * ''Mk'' replaced Make in
Research Unix Research Unix refers to the 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). The term ''Research Unix'' first app ...
, 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, Bell Labs' intended successor to Unix. * ''Kati'' is Google's replacement of GNU Make, as of 2020 used in Android OS builds. It translates the makefile into
ninja A , or was a spy and infiltrator in pre-modern Japan. The functions of a ninja included siege and infiltration, ambush, reconnaissance, espionage, deception, and later bodyguarding.Kawakami, pp. 21–22 Antecedents may have existed as ear ...
for faster incremental builds (similar to the cmake metatool). * Snakemake is a Python-driven implementation for compiling and running
bioinformatics Bioinformatics () is an interdisciplinary field of science that develops methods and Bioinformatics software, software tools for understanding biological data, especially when the data sets are large and complex. Bioinformatics uses biology, ...
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 application programming interfaces (APIs), along with comm ...
includes standardization of the basic features and operation of the Make utility, and is implemented with varying degrees of compatibility with 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.


Use

In general, based on a makefile, Make updates target files from source files if any source file has a newer
timestamp A timestamp is a sequence of characters or encoded information identifying when a certain event occurred, usually giving date and time of day, sometimes accurate to a small fraction of a second. Timestamps do not have to be based on some absolu ...
than the target file or the target file does not exist. For example, this could include compiling C files () into
object file An object file is a file that contains machine code or bytecode, as well as other data and metadata, generated by a compiler or assembler from source code during the compilation or assembly process. The machine code that is generated is kno ...
s, then linking the object files into an executable program. Or this could include compiling
TypeScript TypeScript (abbreviated as TS) is a high-level programming language that adds static typing with optional type annotations to JavaScript. It is designed for developing large applications and transpiles to JavaScript. It is developed by Micr ...
files () to
JavaScript JavaScript (), often abbreviated as JS, is a programming language and core technology of the World Wide Web, alongside HTML and CSS. Ninety-nine percent of websites use JavaScript on the client side for webpage behavior. Web browsers have ...
for use in a browser. Other examples include: convert a source image file to another format, copy a file to a content management system, and send e-mail about build status. A makefile defines targets where each is either a file to generate or is a user-defined concept, called a ''phony'' target. Make updates the targets passed as arguments: make f makefile ptions argets If no target is specified, Make updates the first target in the makefile which is often a phony target to perform the most commonly used action. Make skips build actions if the target file timestamp is after that of the source files. Doing so optimizes the build process by skipping actions when the target file is up-to-date, but sometimes updates are skipped erroneously due to file timestamp issues including restoring an older version of a source file, or when a network filesystem is a source of files and its clock or time zone is not synchronized with the machine running Make. Also, if a source file's timestamp is in the future, make repeatedly triggers unnecessary actions, causing longer build time. When Make starts, it uses the makefile specified on the command-line or if not specified, then uses the one found by via specific search rules. Generally, Make defaults to using the file in the
working directory In computing, the working directory of a process is a directory of a hierarchical file system, if any, dynamically associated with the process. It is sometimes called the current working directory (CWD), e.g. the BSD getcwd function, or just c ...
named . GNU Make searches for the first file matching: , , or . Make processes the options of the command-line based on the loaded makefile.


Makefile

The makefile language is partially
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 ap ...
where end conditions are described but the order in which actions are to be taken is not. This type of programming can be confusing to programmers used to
imperative programming In computer science, imperative programming is a programming paradigm of software that uses Statement (computer science), statements that change a program's state (computer science), state. In much the same way that the imperative mood in natural ...
. Makefiles can contain the following constructs: * ''Explicit rule'': defines when and how to update a target, listing ''prerequisites'' (dependent targets) and commands that define the update action, called the ''recipe'' * ''Implicit rule'': defines when and how to remake a class of files based on their names, including how a target depends on a file with a name similar to the target and an update recipe * ''Variable definition'': associates a text value with a name that can be substituted into later text * ''Directive'': instruction to do something special such as include another makefile * '' Comment'': line starting with


Rules

Each rule begins with a ''dependency line'' which consists of the rule's
target Target may refer to: Warfare and shooting * 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 artille ...
name followed by a colon (:), and optionally a list of targets (also known as prerequisites) on which the rule's target depends. target arget ... omponent ... ommand 1 . . . ommand n Usually a rule has a single target, rather than multiple. A dependency line may be followed by a recipe: a series of TAB indented command lines that define how to generate the target from the components (i.e. source files). If any prerequisite has a more recent timestamp than the target file or the target does not exist as a file, the recipe is performed. The first command may appear on the same line after the prerequisites, separated by a semicolon, targets: prerequisites ; command for example, hello: ; @echo "hello" Each command line must begin with a tab character. Even though a
space Space is a three-dimensional continuum containing positions and directions. In classical physics, physical space is often conceived in three linear dimensions. Modern physicists usually consider it, with time, to be part of a boundless ...
is also
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 m ...
, Make requires tab. Since this often leads to confusion and mistakes, this aspect of makefile syntax is subject to criticism.
Eric S. Raymond Eric Steven Raymond (born December 4, 1957), often referred to as ESR, is an American software developer, open-source software advocate, and author of the 1997 essay and 1999 book ''The Cathedral and the Bazaar''. He wrote a guidebook for the R ...
describes it 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 Eric Steven Raymond (born December 4, 1957), often referred to as ESR, is an American software developer, open-source software advocate, and author of the 1997 essay and 1999 book ''The Cathedral and the Bazaar''. He wrote a guidebook for the R ...
2003
and '' The Unix-Haters Handbook'' said "using tabs as part of the syntax is like one of those pungee icstick 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 so ...
for an early implementation difficulty, and preserved by a desire for
backward compatibility In telecommunications and computing, backward compatibility (or backwards compatibility) is a property of an operating system, software, real-world product, or technology that allows for interoperability with an older legacy system, or with Input ...
with the very first users: GNU Make since version 3.82 allows the choice of any symbol (one character) as the recipe prefix using the .RECIPEPREFIX special variable: .RECIPEPREFIX := : all: :@echo "recipe prefix symbol is set to '$(.RECIPEPREFIX)'" Each command is executed in a separate
shell Shell may refer to: Architecture and design * Shell (structure), a thin structure ** Concrete shell, a thin shell of concrete, usually with no interior columns or exterior buttresses Science Biology * Seashell, a hard outer layer of a marine ani ...
. Since operating systems use different shells, this can lead to unportable makefiles. For example, GNU Make (all POSIX Makes) executes commands with /bin/sh by default, where
Unix Unix (, ; trademarked as UNIX) is a family of multitasking, multi-user 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, Microsoft's ''nmake'' executes commands with cmd.exe where batch commands like copy are available but not necessarily cp. Since a recipe is optional, the dependency line can consist solely of components that refer to other targets: realclean: clean distclean The following example rule is evaluated when Make updates target file.txt via . If file.html is newer than file.txt or file.txt does not exist, then the command is run to generate file.txt from file.html. file.txt: file.html lynx -dump file.html > file.txt A command can have one or more of the following prefixes (after the tab): *
minus The plus sign () and the minus sign () are mathematical symbols used to denote positive and negative functions, respectively. In addition, the symbol represents the operation of addition, which results in a sum, while the symbol represent ...
(-) specifies to ignore an error from the command * at (@) specifies to ''not'' output the command before it is executed * plus (+) specifies to execute the command even if Make is invoked in "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 define and use 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 interface (CLI) is a means of interacting with software via command (computing), commands each formatted as a line of text. Command-line interfaces emerged in the mid-1960s, on computer terminals, as an interactive and more user ...
s passed to the Make utility.
Environment variables An environment variable is a user-definable Value (computer science), value that can affect the way running process (computing), processes will behave on a computer. Environment variables are part of the environment in which a process runs. Fo ...
are also available as macros. For example, the macro is frequently used in makefiles to refer to the location of a C compiler. If used consistently throughout the makefile, then the compiler used can be changed by changing the value of the macro rather than changing each rule command that invokes the compiler. Macros are commonly named in
all-caps In typography, text or font in all caps (short for "all capitals") contains capital letters without any lowercase letters. For example: All-caps text can be seen in legal documents, advertisements, newspaper headlines, and the titles on book co ...
: MACRO = definition A macro value can consist of other macro values. The value of macro is expanded on each use lazily. A macro is used by expanding either via $''NAME'' or $(''NAME''). The latter is safer since 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
BSD The Berkeley Software Distribution (BSD), also known as Berkeley Unix or BSD Unix, is a discontinued Unix operating system developed and distributed by the Computer Systems Research Group (CSRG) at the University of California, Berkeley, beginni ...
. NEW_MACRO = $(MACRO)-$(MACRO2) Macros can be composed of shell commands by using the
command substitution In computing, command substitution is a facility that allows a Command-line interpreter, command to be run and its output to be pasted back on the command line as arguments to another command. Command substitution first appeared in the Bourne she ...
operator !=. YYYYMMDD != date The command-line syntax for overriding a macro is: make MACRO="value" ACRO="value" ...TARGET ARGET ... Makefiles can access predefined ''internal macros'', with and being common. target: component1 component2 # echo components YOUNGER than TARGET echo $? # echo TARGET name echo $@ A common syntax when defining macros, which works on BSD and GNU Make, is to use , , and instead of the equal sign ().


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 $< > $@


Comment

Single-line comments are started with the hash symbol (#).


Directive

A directive specifies special behavior such as including another makefile.


Line continuation

Line continuation is indicated with a backslash character at the end of a line. target: component \ component command ; \ command , \ piped-command


Examples

The following commands are in the context of the makefile that follows. make # updates first target, 'all' make help # updates target 'help' to list targets make dist # updates target 'dist' to build for distribution PACKAGE = package VERSION = ` date "+%Y.%m%d%" ` RELEASE_DIR = .. RELEASE_FILE = $(PACKAGE)-$(VERSION) # Default target # note: variable LOGNAME comes from the environment all: echo "Hello $(LOGNAME), nothing to do by default" echo "Try 'make help'" # Display targets by searching this file help: egrep "^# target:" mkefile # Make a release dist: tar -cf $(RELEASE_DIR)/$(RELEASE_FILE) && \ gzip -9 $(RELEASE_DIR)/$(RELEASE_FILE).tar Below is a 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 $(CC) $(LDFLAGS) -o $@ $^ helloworld.o: helloworld.c $(CC) $(CFLAGS) -c -o $@ $< clean: $(RM) helloworld helloworld.o 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: $(RM) helloworld helloworld.o # suffix rule .c.o: $(CC) $(CFLAGS) -c $< .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 # snippet to fail if not GNU 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


Dependency tracking

Makefile consist of dependencies and a forgotten or an extra one may not be immediately obvious to the user and may result in subtle bugs in the generated software that are hard to catch. Various approaches may be used to avoid this problem and keep dependencies in source and makefiles in sync. One approach is using the compiler to keep track of dependencies changes. GCC can statically analyze the source code and produce rules for the given file automatically by using the switch. The other approach would be makefiles or third-party tools that would generate makefiles with dependencies (e.g. Automake toolchain 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 dev ...
, can do so automatically). Another approach is to use meta-build tools like CMake,
Meson In particle physics, a meson () is a type of hadronic subatomic particle composed of an equal number of quarks and antiquarks, usually one of each, bound together by the strong interaction. Because mesons are composed of quark subparticles, the ...
etc.


See also

* *


References


External links


GNU Make homepage
{{Authority control Articles with example code Build automation Compiling tools GNU Project software Unix programming tools Unix SUS2008 utilities