- Введение в make
- Назначение, история, варианты
- Основные принципы
- Запуск make
- Базовый синтаксис make
- PHONY targets
- Переменные
- Автоматические переменные
- Условное выполнение
- Шаблонные правила
- Включение других файлов make
- Функции
- Собственные функции
- Рекурсивный make
- Параллельный make
- Специальные цели
- Варианты использования
- Linux make command
- Description
- Syntax
- Options
- Typical Use
- Makefiles
- Rules
- Macros
Введение в make
Назначение, история, варианты
Утилита make предназначена для автоматизации сборки проектов. Если какие-либо файлы проекта могут быть сгенерированы из других файлов, утилита позволяет выполнить процесс построения наиболее оптимальным способом, по возможности минимизируя количество обрабатываемых файлов.
Исторически утилита предназначалась для сборки проектов на языке C в операционной системе Unix, однако может быть использоваться для работы с любыми проектами. Первая версия системы была создана в 1977 году.
На сегодняшний день наиболее распространены три варианта утилиты, объединенные общими принципами работы, но отличающиеся синтаксисом языка и возможностями:
Мы работаем с GNU make. На BSD системах (в частности, FreeBSD, он может быть доступен как gmake, на Linux — просто make).
Основные принципы
Утилита make работает по правилам (rules), записанным в специальном конфигурационном файле. Правила определяют цели (targets), завимости между целями и набор команд для выполнения каждой цели.
Цели могут соответствовать определенным файлам. Кроме того, цели могут не соответствовать ни одному файлу и использоваться для группировки других целей или определенной последовательности команд. Такие цели называются phony targets.
Каждая цель может зависеть от выполнения других целей. Выполнение цели требует предварительного выполнения других целей, от которых она зависит.
В случае зависимости между целями, соответствующими файлам, цель выполняется только в том случае, если файлы, от которых она зависит, новее, чем файл, соответствующий цели. Это позволяет перегенерировать только файлы, зависящие от измененных файлов, и не выполнять потенциально долгий процесс пересборки всех файлов проекта.
Таким образом, makefile определяет граф зависимостей, по которому утилита make выполняет ту или иную цель, по возможности минимизируя количество операций сборки.
Запуск make
Несмотря на то, что для make можно указать произвольный файл правил, как правило используют стандартное имя Makefile . Поддерживаются также несколько альтернативных имен по умолчанию, но имеет смысл использовать наиболее распространенное.
будет использовать файл Makefile , находящийся в текущем каталоге.
При запуске make можно указать цель, которая будет выполнена. Если цель не указана, используется цель по умолчанию, которая либо указана в файле правил явно, либо неявно используется первая определенная цель.
Явное указание цели выполняется инструкцией DEFAULT_GOAL в Makefile :
вызовет обработку цели clean файла Makefile , находящегося в текущем каталоге.
Можно указать сразу несколько целей.
Выполнение целей может быть настроено с использованием переменных (о которых ниже). При запуске make можно указать значения переменных:
Значение переменной PREFIX будет доступно в правилах Makefile и может быть использовано при сборке.
Команда поддерживает также ряд дополнительных опций, из которых наиболее важные следующие:
Базовый синтаксис make
Основная конструкция, используемая в файлах make , выглядит следующим образом:
Этот фрагмент определяет, что файл style.css зависит от файла src/less/app.less и для его сборки необходимо выполнить команду lessc src/less/app.less > style.css . Перегенерация файла style.css будет выполняться только в случае,если файл src/less/app.less новее, чем файл style.css (до тех пор, пока при запуске make не будет указан ключ -B ).
Перед каждой командой внутри описания цели должен присутствовать символ табуляции. В принципе, это настраивается, но лучше использовать общепринятые соглашения. Если вместо табуляции используются пробелы, make работать не будет.
В качестве команд обработки целей используются команды shell. Текст команды выводится, для того, чтобы он не выводился, команду необходимо начать с символа @ .
Каждая команда запускается в отдельном интерпретаторе shell, таким образом, команды не связаны друг с другом. Иначе говоря, одна строка команды — один shell. Это поведение может быть переопределено с помощью специальной цели .ONESHELL .
Если команду (или список зависимостей) необходимо записать в несколько строк, используют символ переноса \ .
PHONY targets
Цели, не соответствующие файлам, и предназначенные для выполнения набора команд или группировки завимостей, декларируются следующим образом:
Деклараций .PHONY может быть несколько, обычно определяют одну и прописывают туда все соответствующие цели.
В нашем примере вызов make clean приведет к выполнению цели clean , которая безусловно выполнит удаление временных файлов.
В случае, если у phony target есть зависимость в виде другой phony target, то зависимость выполняется перед зависящей целью. Таким образом, мы получаем механизм, напоминающий подпрограммы. Например, мы можем определить цель all , собирающую все файлы проекта, и отдельные цели css , js и php , собирающие отдельной css -файлы, js -файлы и обрабатывающие php файлы.
Соответственно, в Makefile мы можем написать:
В результате мы можем использовать make all для пересборки всех файлов и, скажем, make css для пересборки только CSS -файлов.
Переменные
В make-файле можно использовать переменные, хотя правильнее сказать, что можно использовать макросы.
Переменные определяются присваиванием в makefile или могут быть переданы извне.
Переменные — это макроопределения, причем вычисление переменной всегда выполняется в самый последний момент перед подстановкой. Макросы могут использовать везде в тексте makefile.
Подстановка выполняется конструкцией $(VAR) в отличие от shell, где используется $VAR .
Если в shell команде используется shell-переменная, необходимо квотить знак $ , дублируя его, например:
Помимо макропеременных существуют и более традиционные, в которых значение устанавливается сразу. Для работы с ними используется оператор := . В наших условиях достаточно использовать обычные переменные.
Часто требуется определить переменную только в том случае, если она еще не была определена. Для этого используется оператор ?= :
Соответственно, если мы вызовем
будет использована кодировка UTF8 , а в случае
будет использована CP1251 .
Если переменная содержит несколько строк, можно использовать синтаксис define :
Автоматические переменные
Make поддерживает набор автоматических переменных, облегчающих написание правил. Например, переменная $@ соответствую текущей цели (то, что слева от : ), а переменная $^ — списку зависимостей (то, что справа от : ). Таким образом, например, можно написать:
В результате www/js/script.js будет результатом объединения трех js-файлов.
Полный список таких переменных приведен в документации, для нас наиболее интересны:
С полным списком можно ознакомиться в документации: Automatic Variables.
Условное выполнение
В Makefile можно использовать условные выражения. Опять же, мы говорим о макрообработке make, соответственно, условные выражения работают на уровне makefile, а не на уровне команд. Обычно условные выражения используются для определения тех или иных целей в зависимости от значения переменных. Например:
В качестве условий можно проверять определенность переменной, а также ее значение:
Полностью с возможностями условных выражений можно ознакомиться в документации: Conditional syntax.
Шаблонные правила
Шаблонные правила (pattern rules) позволяют указать правило преобразования одних файлов в другие на основании зависимостей между их именами. Например, мы можем указать правило для получения объектного файла из файла на языке C:
Обратите внимание на использование переменной % , которая в таких правилах используется для получения имени исходного файла.
Шаблоны не обязаны ограничиваться расширениями файлов. Если исходные и выходные файлы соответствуют друг другу и в их именах есть какая-либо зависимость, можно использовать pattern rule.
Включение других файлов make
Файл make может подключить другие файлы make оператором include :
Таким образом, из файлов можно строить модульную систему, часто имеет смысл выполнять include внутри условного оператора.
Функции
Make определяет большой набор функций, которые могут быть использованы в переменных (макросах). Вызов функции выполняется конструкцией:
Функции позволяют обрабатывать строки, имена файлов, организовывать циклы по набору значений, организовывать условный вызов других функций.
Несколько примеров из hive. Получаем текущее время (обратите внимание на использование := :
Включение файла container.mk только в случае, если он существует:
Добавление префиксов и суффиксов к именам файлов
Подробнее о функциях можно прочитать в документации Functions.
Собственные функции
Можно создавать собственные параметризованные функции путем определения переменных, содержащих специальные переменные $1 , $2 , . соответствующие переданным аргументам. Вызов пользовательской функции производится специальным макросом call :
Очень тупой пример:
Теперь можно написать:
Рекурсивный make
Помимо включения другого файла make, Makefile может выполнить другой файл make в виде отдельного make-процесса.
Это достаточно частая ситуация в случае модульных проектов. Например, для каждой из компонент проекта (сервер, клиент, библиотеки) предусмотрен свой Makefile , при этом есть основной Makefile , задающий набор общих настроек и вызывающий Makefile каждого подпроекта.
Вызов make из Makefile часто называют submake . Для вызова используется переменная $(MAKE) :
Значение этой переменной соответствует пути к программе make , обрабатывающей текущий файл.
Для передачи переменных в вызываемый таким образом файл их необходимо явно экспортировать:
Значение переменной PREFIX будет доступно в subsystem/Makefile .
Параллельный make
Make умеет распараллеливать выполнение правил. Для этого используется опция -j , позволяющая указать количество используемых параллельных процессов. Помимо ускорения процесса сборки эта особенность иногда позволяет реализовывать на коленке очень простые сценарии обработки, подразумевающие многозадачность. Например, можно реализовать простой, но работоспособный менеджер очередей на make, используя файлы для хранения заданий и каталоги для хранения файлов заданий на разных стадиях (ожидание, выполнение, результат).
Параллельное выполнение может быть запрещено с помощью специальной цели .NOTPARALLEL .
Специальные цели
Make поддерживает набор целей, которые могут быть использованы как модификаторы для последующих целей либо как служебные инструкции. Вот некоторые из таких специальных целей:
Варианты использования
Чаще всего о make говорят в контексте сборки программ на C/C++, в конце концов, для этого он изначально предназначался. Однако, make — гораздо более универсальный инструмент. Записывая makefile, мы декларативно описываем определенное состояние отношений между файлами, которое каждый запуск make будет стараться поддерживать. Декларативный характер определения состояния очень удобен, в случае использования какого-либо императивного языка (например, shell) нам приходилось бы выполнять большое количество различных проверок, получая на выходе сложный и запутанный код.
Кроме того, использование зависимостей между phony targets, позволяющии, по сути, декларативно описывать некий (ограниченный) конечный автомат, может быть полезно для написания различных административных сценариев. Используя make в качестве каркаса для выполнения различных shell-команд, мы получаем по сути некий базовый framework для shell с готовым пользовательским интерфейсом (вызов make + передача переменных), встроенными средствами отслеживания зависимостей, параллельного выполнения, макроопределениями и т.д.
Поэтому базовое знание make позволяет в ряде случаев решить проблему пусть и не самым красивым, но зато быстрым и достаточно надежным способом.
Источник
Linux make command
On Unix-like operating systems, make is a utility for building and maintaining groups of programs (and other types of files) from source code.
This page covers the GNU/Linux version of make.
Description
The purpose of the make utility is to determine automatically which pieces of a large program need to be re-compiled, and issue the commands necessary to recompile them. This documentation describes the GNU implementation of make, which was written by Richard Stallman and Roland McGrath, and is currently maintained by Paul Smith. Many of the examples listed below show C programs, since they are most common, but you can use make with any programming language whose compiler can be run with a shell command. In fact, make is not limited to programs. You can use it to describe any task where some files must be updated automatically from others whenever the others change.
To prepare to use make, you must write a file called the makefile that describes the relationships among files in your program, and the states the commands for updating each file. In a program, typically the executable file is updated from object files, which are in turn made by compiling source files.
Once a suitable makefile exists, each time you change some source files, this simple shell command:
suffices to perform all necessary recompilations. The make program uses the makefile data base and the last-modification times of the files to decide which of the files need to be updated. For each of those files, it issues the commands recorded in the database.
make executes commands in the makefile to update one or more target names, where name is typically a program. If no -f option is present, make will look for the makefiles GNUmakefile, makefile, and Makefile, in that order.
Normally you should call your makefile either makefile or Makefile. (The officially recommended name is Makefile because it appears prominently near the beginning of a directory listing, right near other important files such as README.) The first name checked, GNUmakefile, is not recommended for most makefiles. You should use this name if you have a makefile that is specific to GNU make, and will not be understood by other versions of make. If makefile is a dash («—«), the standard input is read.
make updates a target if it depends on prerequisite files that have been modified since the target was last modified, or if the target does not exist.
Syntax
Options
-b, -m | These options are ignored, but included for compatibility with other versions of make. |
-B, —always-make | Unconditionally make all targets. |
-C dir, —directory=dir | Change to directory dir before reading the makefiles or doing anything else. If multiple -C options are specified, each is interpreted relative to the previous one: -C / -C etc is equivalent to -C /etc. This is typically used with recursive invocations of make. |
-d | Print debugging information in addition to normal processing. The debugging information says which files are being considered for remaking, which file-times are being compared and with what results, which files actually need to be remade, which implicit rules are considered and that are applied; everything interesting about how make decides what to do. |
—debug[=FLAGS] | Print debugging information in addition to normal processing. If the FLAGS are omitted, then the behavior is the same as if -d was specified. FLAGS may be a for all debugging output (same as using -d), b for basic debugging, v for more verbose basic debugging, i for showing implicit rules, j for details on invocation of commands, and m for debugging while remaking makefiles. |
-e, —environment-overrides | Give variables taken from the environment precedence over variables from makefiles. |
-f file, —file=file, —makefile=file | Use file as a makefile. |
-i, —ignore-errors | Ignore all errors in commands executed to remake files. |
-I dir, —include-dir=dir | Specifies a directory dir to search for included makefiles. If several -I options are used to specify several directories, the directories are searched in the order specified. Unlike the arguments to other flags of make, directories given with -I flags may come directly after the flag: -Idir is allowed, as well as -I dir. This syntax is allowed for compatibility with the C preprocessor’s -I flag. |
-j [jobs], —jobs[=jobs] | Specifies the number of jobs (commands) to run simultaneously. If there is more than one -j option, the last one is effective. If the -j option is given without an argument, make will not limit the number of jobs that can run simultaneously. |
-k, —keep-going | Continue as much as possible after an error. While the target that failed (and those that depend on it) cannot be remade, the other dependencies of these targets can be processed all the same. |
-l [load], —load-average[=load] | Specifies that no new jobs (commands) should be started if there are others jobs running and the load average is at least load (a floating-point number). With no argument, removes a previous load limit. |
-L, —check-symlink-times | Use whichever is the latest modification time between symlinks and target. |
-n, —just-print, —dry-run, —recon | Print the commands that would be executed, but do not execute them. |
-o file, —old-file=file, —assume-old=file | Do not remake the file file even if it is older than its dependencies, and do not remake anything on account of changes in file. Essentially the file is treated as very old and its rules are ignored. |
-p, —print-data-base | Print the database (rules and variable values) that results from reading the makefiles; then execute as usual or as otherwise specified. This also prints the version information given by the -v switch (see below). To print the database without trying to remake any files, use make -p -f/dev/null. |
-q, —question | «Question mode.» Do not run any commands, or print anything; just return an exit status that is zero if the specified targets are already up to date, nonzero otherwise. |
-r, —no-builtin-rules | Eliminate use of the built-in implicit rules. Also, clear out the default list of suffixes for suffix rules. |
-R, —no-builtin-variables | Don’t define any built-in variables. |
-s, —silent, —quiet | Silent operation; do not print the commands as they are executed. |
-S, —no-keep-going, —stop | Cancel the effect of the -k option. This is never necessary except in a recursive make where -k might be inherited from the top-level make via MAKEFLAGS or if you set -k in MAKEFLAGS in your environment. |
-t, —touch | Touch files (mark them up to date without really changing them) instead of running their commands. This is used to pretend that the commands were done, to fool future invocations of make. |
-v, —version | Print the version of make; also a Copyright, a list of authors and a notice that there is no warranty. |
-w, —print-directory | Print a message containing the working directory before and after other processing. This may be useful for tracking down errors from complicated nests of recursive make commands. |
—no-print-directory | Turn off -w, even if it was turned on implicitly. |
-W file, —what-if=file, —new-file=file, —assume-new=file | Pretend that the target file has just been modified. When used with the -n flag, this shows you what would happen if you were to modify that file. Without -n, it is almost the same as running a touch command on the given file before running make, except that the modification time is changed only internally within make. |
—warn-undefined-variables | Warn when an undefined variable is referenced. |
Typical Use
make is typically used to build executable programs and libraries from source code. Generally speaking, 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 that the above actions were performed.
make is invoked with a list of target file names to build as command-line arguments:
Without arguments, make builds the first target that appears in its makefile, which is traditionally a 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 that 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 is a source of files and its clock or timezone 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 may trigger unnecessary rebuilding.
Makefiles
make searches the current directory for the makefile to use. GNU make searches files for a file named one of GNUmakefile, makefile, and then Makefile, and runs the specified target(s) from that file.
The makefile language is similar to declarative programming, in which necessary end conditions are described but the order in which actions are to be taken is not important. This may be confusing to programmers used to imperative programming, which explicitly describes how the end result will be reached.
One problem in build automation is the tailoring of a build process to a given platform. 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 on its own. This problem is typically handled by generating separate platform-specific build instructions, which in turn may be processed by make. Common tools for this process are autoconf and cmake.
Rules
A makefile essentially consists of rules. Each rule begins with a dependency line which defines a target 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.
Here, is the tab character. 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 target depends on a C source file and header files). Because make itself does not understand, recognize or distinguish different kinds of files, this opens up the 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 GNU automake toolchain, can do so automatically.
After each dependency line, a series of command lines may follow which define how to transform the components (usually source files) into the target (usually the «output»). If any of the components have been modified, the command lines are run.
With GNU make, the first command may appear on the same line after the prerequisites, separated by a semicolon:
Each command line must begin with a tab character to be recognized as a command. The tab is a whitespace character, but the space character 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, and is important to take note.
However, GNU make (since version 3.82) allows the user to choose any symbol (one character) as the recipe prefix using the .RECIPEPREFIX special variable, for example:
Each command is executed by a separate shell or command-line interpreter instance. Since operating systems use different command-line interpreters this can lead to unportable makefiles. For instance, GNU make by default executes commands with /bin/sh, which is the shell where Unix commands like cp are normally used.
A rule may have no command lines defined. The dependency line can consist solely of components that refer to targets, for example:
The command lines of a rule are usually arranged so that they generate the target. An example: if «file.html» is newer, it is converted to text. The contents of the makefile:
The above rule 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:
Command lines can have one or more of the following three prefixes:
- a hyphen-minus (—), specifying that errors are ignored
- an at sign (@), specifying that the command is not printed to standard output before it is executed
- a plus sign (+), the command is executed even if make is invoked in a «do not execute» mode
Ignoring errors and silencing all echo output can also be obtained via the special targets «.IGNORE» and «.SILENT«, respectively.
Macros
A makefile can contain definitions of macros. Macros are usually referred to as variables when they hold simple string definitions, like «CC=clang«, which would specify clang as the C compiler. Macros in makefiles may be overridden in the command-line arguments 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, as just shown, the macro «CC» is frequently used in makefiles to refer to the location of a C compiler.
New macros are traditionally defined using capital letters:
A macro is used by expanding it. Traditionally this is done by enclosing its name inside $(). An equivalent form uses curly braces rather than parenthesis, i.e. $<>, which is the style used in BSD operating systems.
Macros can be composed of shell commands using the command substitution operator, denoted by backticks («` `«).
The content of the definition is stored «as is». Lazy evaluation 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. For example:
The generic syntax for overriding macros on the command line is:
Makefiles can access any of a number of predefined internal macros, with «?» and «@» being the most common.
Источник