Makefile syntax Basics

Source: Internet
Author: User

Makefile syntax Basics

In Linux, make is a command tool that explains commands in Makefile. When executing the make command, a Makefile file is required to tell the make command how to compile and link the program.

How make works: By default, only the make command is input:

(1) make will find the file named "Makefile" or "makefile" in the current directory;

(2) If found, it will find the first target file (target) in the file and use this file as the final target file;

(3) If the target file does not exist or is later than the target file. o if the modification time of the object is newer than that of the target file, it will execute the command defined later to generate the target file;

(4) If the target file is dependent on. o file does not exist, so make will find the target in the current file. o file dependency. If found, it will be generated based on that rule. o file;

(5), of course, corresponding. c and. H files exist, so make will generate. o file, and then use. o file to generate the ultimate make task, that is, the execution file (target file.

Makefile consists of five parts:: Display rules, hidden rules, variable definitions, file instructions, and comments

(1) display rules: Display rules explain how to generate one or more target files. This is a command generated by Makefile writers who clearly point out the files to be generated, the dependent files of the files, and the files.

(2) implicit rules: Because make has the function of automatic derivation, implicit rules allow us to write makefiles roughly, which is supported by make.

(3) variable definition: Define a series of variables in Makefile. variables are generally strings. When Makefile is executed, all the variables are extended to the corresponding reference location.

(4) file indication: it consists of three parts. One is to reference another Makefile in one Makefile, just like include in C, the other is to specify the valid part of The Makefile according to some situations, just like pre-compiling # if in C, and defining a multi-line command.

(5). Note: Makefile only contains line comments. Like a UNIX Shell script, the comments use the "#" character, this is like "//" in C/C ++. If you want to use the "#" character in your Makefile, you can escape it with a reverse box, such "\#".

The command in Makefile must start with the [Tab] key..

Makefile file name: By default, the make command searches for files named "GNUmakefile", "makefile", and "Makefile" in sequence in the current directory and finds the file to be interpreted. Among the three file names, it is best to use the "Makefile" file name. It is best not to use "GNUmakefile", which is identified by GNU make. Others make files are only sensitive to all lowercase "makefile" file names. However, most make files basically support the "makefile" and "Makefile" default file names.

Of course, you can use other file names to write Makefile, such as "Make. Linux,To specify a specific Makefile, you can use the "-f" and "-- file" parameters of make.Such as make-f Make. Linux or make -- file Make. Linux.

Reference other makefiles:You can use the include keyword in Makefile to include other makefiles.The contained file is stored in the position where the current file is contained in the original mode.

The include syntax is: include filename

Filename can be the file mode of the current operating system Shell (including paths and wildcards ).

There can be some null characters before include, but it cannot start with the [Tab] key.. Include and filename can be separated by one or more spaces.

When the make command starts, it looks for other makefiles specified by include and places the files in the current location. If no absolute or relative path is specified for the file, make will first search for it in the current directory. If no absolute or relative path is found in the current directory, make will also look for the following directories: (1) if make is executed, there are "-I" or "-- include-dir" parameters, make will search for the directory specified by this parameter; (2) if the directory <prefix>/include (generally: if/usr/local/bin or/usr/include) exists, make will also find it.

If a file is not found, make generates a warning message without a fatal error. It will continue to load other files. Once the makefile is read, make will retry the unfound or unreadable files. If it still does not work, make will produce a fatal message. If you want make to ignore unreadable files and continue execution, you can add a minus sign (-) before include, for example,-include filename, do not report any errors during the include process. The commands related to make compatibility with other versions are sinclude, which serves the same purpose as this one.

Environment Variable MAKEFILES: If you define the environment variable MAKEFILES in your current environment, make will make the value in this variable a similar action similar to include. The values in this variable are other makefiles separated by spaces. However, unlike include, the "target" of Makefile introduced from this environment variable does not work. If an error is found in the file defined in the environment variable, make will not work. We recommend that you do not use this environment variable. As long as this variable is defined, all makefiles will be affected when you use make.

The execution steps of GNU make:

(1) read all makefiles;

(2) read other makefiles included;

(3) initialize the variables in the file;

(4) deduce concealed rules and analyze all rules;

(5) create dependency chains for all target files;

(6) determine the targets to be regenerated Based on the dependency;

(7) execute the command generation.

Makefile file writing rules:

targets:  prerequisitescommand... ...
Or:

targets: prerequisites ; commandcommand... ...

Targets is a file name separated by spaces. Wildcards can be used. Generally, the target is basically a file, but it may also be multiple files.

Command is a command line. If it is not in a line with "targets: prerequisites", it must start with the [Tab] key. If it is in a line with prerequisites, it can be separated by a semicolon.

Prerequisites is the object (or dependency target) on which the target depends ). If a file is newer than the target file, the target is regarded as "outdated" and is considered to need to be regenerated.

If the command is too long, you can use the backslash ('\') as the line break. Make has no limit on the number of characters in a row.

Use wildcards in rules:Make supports three wildcards: "*" and :"*","?" , "[…]". This is the same as the B-Shell of Unix.

Tilde ("~") Characters are also used in file names. If yes "~ /Test ", which indicates the test directory under the $ HOME directory of the current user. And "~ Spring/test indicates the test directory in the user's spring home directory.

File Search: The special variable "VPATH" in the Makefile file can be used to search for files. If this variable is not specified, make will only search for dependent files and target files in the current directory. If this variable is defined, make will find the file in the specified directory if the current directory cannot be found.

Another way to set the file search path is to use the "vpath" keyword of make (note that it is all in lower case). This is not a variable, but a keyword of make, it is similar to the VPATH variable. It can specify different files in different search directories.

Pseudo target: "Pseudo-target" is not a file, but a tag. Because "pseudo-target" is not a file, make cannot generate its dependency and decide whether to execute it. Only by explicitly specifying this "target" can we make it take effect. Of course, the name of "pseudo-target" cannot be the same as that of the file name, otherwise it will lose the meaning of "pseudo-target. We can use a special tag to avoid the case of duplicate names with files ". "PHONY" indicates that a target is a "pseudo target" and shows to make that whether or not this file exists is a "pseudo target ".

Generally, the pseudo-target has no dependent files. However, we can also specify the dependent files for the pseudo target. A pseudo-target can also be used as the "Default target", as long as it is placed in the first.

Multi-objective:There can be more than one target in the Makefile rule, and multiple targets are supported..

Static mode: it is easier to define rules with multiple targets, which makes our rules more flexible and flexible.

Automatic dependency generation: Most C/C ++ compilers support a "-M" option, that is, to automatically find the header file contained in the source file and generate a dependency. If you use the gnu c/C ++ compiler, you must use the "-MM" parameter. Otherwise, the "-M" parameter will include header files of some standard libraries.

Write command: The command lines in each rule are the same as those in the operating system Shell. Make runs the command one by one in sequence. Each Command must start with a [Tab] key, unless the command is followed by a semicolon after the dependency rule. Space or blank lines between command lines are ignored. However, if the space or blank line starts with the [Tab] key, make considers it an empty command.

By default, make commands are interpreted and executed by "/bin/sh" ---- UNIX standard Shell.. Unless you specify another Shell.

Display command:Generally, make will output the command line to be executed to the screen before the command is executed. When we use the "@" character before the command line, this command will not be displayed by make. If the make parameter "-n" or "-- just-print" is included during the make operation, the command is only displayed, but the command is not executed, this function is very helpful for us to debug our Makefile and see what the commands we write are like or in what order.

Command Execution: When the dependent target is new to the target, that is, when the target of the rule needs to be updated, make will execute the subsequent command one by one. Note that, If you want to apply the result of the previous command to the next command, you should use semicolons to separate the two commands..

# If you want to apply the result of the previous command to the next command, # Use semicolons to separate the two commands. # note the difference between the two commands. exec: @ cd/home/spring; pwd # expected result @ cd/home/springpwd

Make generally uses the system SHELL defined in the environment variable Shell to execute commands. By default, it uses the UNIX standard Shell ----/bin/sh to execute commands.

Ignore Command ErrorsYou can add a minus sign "-" (after the Tab key) in front of the Makefile command line, and mark it as successful regardless of whether the command is error-free. Another global method is to add the "-I" or "-- ignore-errors" parameter to make. Therefore, all commands in Makefile will ignore the error.

Execute make in a nested way:You can use the export command to pass variables to lower-level Makefile.. Note that there are two variables: SHELL and MAKEFLAGS. Whether export or not, these variables are always passed to the lower Makefile, especially the MAKEFLAGS variable, it contains the parameters of make. But several parameters in the make command are not passed down. They are "-C", "-f", "-h", "-o", and "-W "." -W "or" -- print-directory "will output some information during the make process, so that you can see the current working directory.

Definition command package: If the Makefile contains some identical command sequences, we can define a variable for these identical command sequences. The syntax for defining this variable sequence starts with "define" and ends with "endef.

Use variables: variables defined in Makefile are like Macros in C/C ++. They represent a text string, when executed in Makefile, the original mode is automatically expanded in the used place. Unlike C/C ++, you can change the value in Makefile. In Makefile, variables can be used in "target", "dependency target", "command", or other parts of Makefile.

The variable name can contain characters, numbers, and underscores (can start with a number), but should not contain ": "," # "," = ", or an empty character (space, carriage return, etc ).Variables are case sensitive.. In traditional Makefile, variable names are all named in uppercase. However, we recommend that you use a combination of uppercase and lowercase variables to avoid conflicts with system variables and unexpected events.

Basics of variables:The initial value must be given when the variable is declared. When using the variable, you must add "$" before the variable name, but it is best to use parentheses "() "Or braces" {} "to wrap the variable. If you want to use the real "$" character, you need to use "$" to represent.

Variables: When defining the value of a variable, we can use other variables to construct the value of the variable.In Makefile, there are two ways to use variables to define the value of a variable: (1), simple use of the "=" sign, in the "=" left is the variable, the right is the value of the variable, the value of the variable on the right can be defined in any part of the file. That is to say, the variable on the right is not necessarily a defined value, but can also use the value defined later. (2) use the ": =" operator. In this method, the preceding variables cannot use the following variables, but only those defined previously can be used.

# Variable # Use "=". The variable on the right is not necessarily a defined value. You can also use the value foo = $ (bar) defined later) hello bar = $ (ugn) ugn = spring # use the ": =" operator. The preceding variables cannot use the following variables. # You can only use the variables defined earlier, in this case, the value of y is funy: = $ (x) funx: = test exec: echo $ (foo) # spring helloecho $ (y) # fun.

# Define a variable whose value is a space # But this example does not seem to play a role ???? Nullstring: = space :=$ (nullstring) # end of the lineout: = spring $ (space) spring # the following example shows the expected result dir: =/bin/sh # directorypath: = $ (dir)/fileexec: echo $ (out) # springspringecho $ (path) #/bin/sh/file

# Replace variable values # replace all the variables in foo. replace the end of the o string. cfoo: =. o B. o c. obar: = $ (foo :. o =. c) # Replace variable values in static mode: the dependent string has the same pattern bar1 :=$ (foo: %. o = %. c) # Use the variable value as the variable x = $ (y) y = zz = Helloa: = $ (x) exec: echo $ (bar) #. c B. c. cecho $ (bar1) #. c B. c. cecho $ (a) # Hello

AndA useful operator "? =", Such as foo? = Bar: If foo is not defined, the value of the foo variable is bar. If foo is previously defined, this statement will not do anything.

Advanced usage of variables: (1) Replace variable values: replace the common part of a variable in the format of $ (var: a = B) or $ {var: a = B} ", which means to replace all" a "ending with" a "string" in the variable "var" with a "B" string. The "end" here refers to "space" or "Terminator ". Another variable replacement technique is defined by "static mode". Its format is "$ (var: %. a = %. b) ", which relies on the same pattern in the replaced string. (2) treat the value of a variable as a variable.

Append variable value: You can use the "+ =" operator to append a value to a variable.. If the variable has not been defined before, "+ =" will automatically become "=". If there is a variable definition before, "+ =" will inherit the value assignment character of the previous operation. If the previous value is ": =", "+ =" uses ": =" as the starting value.

# Append the variable value objects = main. o foo. o bar. o # The following two statements are equivalent # objects: = $ (objects) another. oobjects + = another. ovariable: = value # The following two statements are equivalent # variable: = $ (variable) morevariable + = moreexec: echo $ (objects) # main. o foo. o bar. o another. oecho $ (variable) # value more

Override indicator: some variables are usually set by the make command line parameter, so the value assignment to this variable in Makefile will be ignored. If you want to set the value of this type of parameter in Makefile, you can use the "override" indicator.

Multiline variables:You can use the define keyword to set a line break for variable values., Which helps to define a series of commands. The define indicator is followed by the variable name, and the variable value is defined in a new line. The definition ends with the endef keyword. It works in the same way as the "=" operator. Variable values can include functions, commands, text, or other variables. Because the command must start with the [Tab] key, if the command variable defined by define does not start with the [Tab] key, make will not regard it as a command.

Environment variable:The system environment variables during the make operation can be loaded into the Makefile when the make operation starts.But if the Makefile has defined this variable, or this variable is carried by the make command line, the value of the system environment variable will be overwritten (if the "-e" parameter is specified by make, the system environment variable will overwrite the variable defined in Makefile ).

Conditional judgment: Make can select different execution branches based on different running conditions.. A conditional expression can be used to compare the value of a variable, or compare the values of a variable and a constant: ifeq, ifneq, ifdef, and ifndef. Note: Make calculates the value of the conditional expression when reading Makefile, and selects the statement based on the value of the conditional expression.Therefore, it is best not to put automation variables (such as "$ @") into conditional expressions, because Automated variables are available at runtime.. In addition, make does not allow the entire Condition Statement to be divided into two parts and placed in different files.

# Use conditional judgment # ifdefbar = foo = $ (bar) ifdef foo frobozz = yeselse frobozz = noendif # ifeqifeq ($ (CC), gcc) B = gccelse B = otherendifexec: echo $ (frobozz) # yesecho $ (B)

Function: Functions can be used in Makefile to process variables. After a function is called, the return value of the function can be used as a variable. Function parameters are separated by commas (,), while function names and parameters are separated by spaces. Function calls start with "$" and enclose function names and parameters in parentheses or curly brackets..

# Use the function # substcomma: =, empty: = space :=$ (empty) $ (empty) foo: = a B cbar: =$ (subst $ (space ), $ (comma), $ (foo) # sortstr: = foo bar losestr :=$ (sort $ (str) # foreachnames: = a B c dfiles: = $ (foreach n, $ (names), $ (n ). o) # shelldirectory :=$ (shell pwd) exec: echo $ (bar) # a, B, cecho $ (str) # bar foo loseecho $ (files) #. o B. o c. o d. oecho $ (directory)

Common string processing functions include subst, patsubst, strip, findstring, filter, filter-out, sort, word, wordlist, words, and firstword.

File Name operation function: each function's parameter string is treated as one or a series of file names. Common functions include dir, notdir, suffix, basename, addsuffix, addprefix, and join.

Foreach function: this function is used for loop usage. The foreach function in Makefile is almost the same as the for statement in the Unix standard Shell (/bin/sh, or a foreach statement in C-Shell (/bin/csh.

If function: the if function is similar to the conditional statement ifeq supported by GNU make. The if function can contain "else" or not. That is, if function parameters can be two or three.

Call function: the only parameter function that can be used to create a new parameter.

Origin function: it does not operate on the value of a variable. It only tells you where the variable comes from.

Shell function: its parameter should be the Shell command of the operating system. It is the same function as the reverse quotation mark. This means that the shell function returns the output after the operating system command is executed. Therefore, you can use the operating system commands and string processing commands such as awk and sed to generate a variable.

Functions that control make: error and warning.

Run make: In general, the simplest thing is to directly input the make command under the command line. The make command will find the Makefile in the current directory for execution, and everything is automatic.

Make exit code: 0, indicating successful execution; 1. If any error occurs during make running, 1 is returned; 2. If you use the "-q" option of make, and make makes some targets do not need to be updated, then 2 is returned.

Specify Makefile: the rule for GNU make to find the default Makefile is to find three files in the current directory in sequence-"GNUmakefile", "makefile", and "Makefile ". These three files are searched in order. Once found, the files are read and executed.

You can also specify a Makefile with a special name for the make command. To achieve this function, you must use the "-f" or "-- file" parameter of make (the "-- makefile" parameter also works ).

Specify a target: In general, the final goal of make is the first goal in makefile, while other goals are generally associated with this goal. This is the default act of make.To instruct make to accomplish the target you specified, you must directly follow the target name after the make command..

Any target in makefile can be specified as the ultimate goal, but except for the "-" header or the target that contains "=", because the target has these characters, will be parsed into command line parameters or variables.

Implicit rules: This is a convention. make runs according to this "Convention", even if such rules are not written in Makefile.

Variables used by implicit rules: The variables used in implicit rules can be divided into two types: Command-related, such as "CC" and parameter-related, such as "CFLAGS ".

Command-related variables:

(1) AR: package program of the function library. The default command is "ar ";

(2) AS: Compile the program in assembly language. The default command is "";

(3) CC: C language Compiling Program. The default command is "cc ";

(4) CXX: Compile the program in C ++ language. The default command is "g ++ ";

(5) CO: extend the file program from the RFM file. The default command is "co ";

(6) CPP: the pre-processor of the C program (the output is a standard output device). The default command is "$ (CC)-E ";

(7) FC: Fortran and Ratfor compilers and preprocessing programs. The default command is "f77 ";

(8) GET: The program that extends the file from the SCCS file. The default command is "get ";

(9) LEX: Lex method analyzer program (for C or Ratfor). The default command is "lex ";

(10) PC: A program compiled in Pascal. The default command is "pc ";

(11) YACC: Yacc grammar analyzer (for C Programs). The default command is "yacc ";

(12) YACCR: Yacc grammar analyzer (for the Ratfor Program). The default command is "yacc-r ";

(13) MAKEINFO: Convert the source file Texinfo (. texi) to the Info file program. The default command is "makeinfo ";

(14). TEX: The program that creates the TeX DVI file from the TeX source file. The default command is "tex ";

(15) TEXI2DVI: The program that creates the TeX DVI file from the Texinfo source file. The default command is "texi2dvi ";

(16) WEAVE: The program that converts Web to TeX. The default command is "weave ";

(17) CWEAVE: The program that converts C Web to TeX. The default command is "cweave ";

(18) TANGLE: a program that converts the Web to Pascal language. The default command is "tangle ";

(19) CTANGLE: converts C Web to C. The default command is "ctangle ";

(20) RM: Command for deleting files. The default command is "rm-f ".

Parameter-related variables: if the default value is not specified, the default value is null.

(1) ARFLAGS: parameter of the AR command of the library package program. The default value is "rv ";

(2) ASFLAGS: Assembly Language compiler parameters (when the ". s" or ". S" file is obviously called );

(3) CFLAGS: C language compiler parameters;

(4) CXXFLAGS: C ++ language compiler parameters;

(5) COFLAGS: RFM command parameter;

(6) CPPFLAGS: C Preprocessor parameters (also used by C and Fortran compilers );

(7) FFLAGS: Fortran compiler parameters;

(8) GFLAGS: SCCS "get" program parameter;

(9) LDFLAGS: Linker parameters, such as "ld ";

(10) LFLAGS: Lex grammar analyzer parameters;

(11) PFLAGS: Pascal Language compiler parameters;

(12) RFLAGS: Fortran compiler parameters of the Ratfor program;

(13) YFLAGS: Yacc grammar analyzer parameters.

Define mode rules: You can use mode rules to define an implicit rule,A pattern rule is like a general rule, but in the rule, the target definition must contain the character "% ".." % "Indicates one or more arbitrary characters. You can also use "%" in the dependency target, but the value of "%" in the dependency target depends on the target. Note:"%" Occurs after variables and functions are expanded. Variables and functions are expanded when make loads Makefile, while "%" in pattern Rules occurs at runtime..

Automated VariablesThis variable automatically removes a series of files defined in the pattern until all files in the pattern are completed. ThisAutomation variables should only appear in Rule commands.

The following describes the automation variables:

(1), $ @: indicates the target file set in the rule. In a pattern rule, if there are multiple targets, "$ @" is the set that matches the schema definition in the target;

(2) $ %: indicates the target member name in the rule only when the target is a function library file. If the target file is not a function library file, its value is blank;

(3) $ <: name of the first target in the dependency target. If the dependency target is defined in the mode (I .e. "%"), "$ <" will be a series of file sets conforming to the mode. Note that it is obtained one by one;

(4), $? : All sets of New dependent targets of the comparison object, separated by spaces;

(5) $ ^: all sets of dependent targets are separated by spaces. If there are multiple repeated dependent targets, the variable will go out to duplicate dependent targets, only one copy is retained;

(6) $ +: this variable is similar to "$ ^". It is also a set of all dependent targets, but it does not remove repeated dependent targets;

(7), $ *: this variable indicates "%" in the target mode and its previous parts. If the target is "dir/. foo. B ", and the target mode is". %. B ", then the value of" $ * "is" dir/. foo ". If there is no schema definition in the target, "$ *" cannot be pushed or exported. However, if the suffix of the target file is what make recognizes, then "$ *" is the part except the suffix. For example, if the target is "foo. c", because ". c" is the suffix that can be identified by make, the value of "$ *" is "foo ". This feature is GNU make and may not be compatible with other versions of make. Therefore, avoid using "$ *" whenever possible *".

Use make to update the library file: the Library file is the package file for the Object file (intermediate file compiled by the Program. In Unix, the "ar" command is generally used to complete packaging.

The above content from Chen Hao's CSDN blog: http://blog.csdn.net/haoel/article/category/9198


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.