Variables can contain macro definitions of multiple filenames or other text. They are useful for replacing multiple occurrences of the same body of text with references to a variable (macro expansion). A variable is defined in the Makefile with an assignment statement. Only the last assignment of a variable is recognized, because the rules are processed after the entire Makefile has been interpreted into internal rules by the Make program.
In a makefile, the line:
myvariable = source.c header.h
is used to assign the string source.c header.h to the variable named myvariable. In the following rule definition:
target.o: $(myvariable)
the $(myvariable) reference is expanded into the string assigned to myvariable. If the macro expansion contains further references to other variables, then they are also recursively expanded until the resulting string is fully expanded. Undefined macros are expanded to nothing (empty strings). ${myvariable} is equivalent to $(myvariable). For single character variable names, the parentheses or braces are not necessary to expand the macro; the single character may immediately follow the $ .
Additional text can be concatenated to the end of the value of an existing variable by using the += operator, like this:
alpha = abc alpha += def
The result of $(alpha) is now abc def. Notice the space inserted at the point of concatenation. This ensures that filenames are not split between different lines.
It is possible to define a variable which results in an infinitely recursive macro expansion. This is illegal, and it will result in an error when that variable is referenced.
A variable can be defined, such that its value is expanded immediately at the time of assignment. These are called simple variables, and they are assigned with the := operator. Note that when a simple variable is assigned, any other references to variables will expand to their value as assigned above the line of the simple variable being assigned. Here is an example:
simplevar := $(myvariable)
The only difference between an ordinary variable and a simple variable is that the value of the simple variable is expanded only once during its assignment, whereas the value of an ordinary variable needs to be expanded every time it is referenced. Referencing a simple variable requires only a simple substitution, whereas referencing an ordinary variable requires a recursive macro expansion, which requires more work (memory, stack, and CPU instructions).
Variables referenced in the target and dependencies of a rule are expanded during the rule definition. Variables referenced in each command line associated with a rule are expanded when the command line is executed.
Both \$ and $$ expand to the character $, but the latter is recommended.