Variables in makefiles

Variables in a makefile work much the same as variables in a shell script. They are words to which a string of characters can be assigned. Once a string has been assigned to the variable, every reference to the variable in the rest of the makefile is replaced by the string. Variable names are usually chosen to be in all capital letters for clarity.

The variable is assigned a string value via an assignment statement, such as

	MYFILES=a b c d e

The first assignment above sets the variable "MYFILES" to the character string "a b c d e". The second assignment sets "OUTFILE" to the character string "myfile.c". Variables may also be left unset in the makefile. In this case they are implicitly set to the empty string "". For example,


sets "CFLAGS" to the string "". Referencing a variable before making an assignment to it leaves it set to the empty string until the assignment is made. So references to a variable before its first assignment will be replaced with "". References after the assignment will be replaced with the newly assigned string.

I suggest that you do not place any spaces between the = and the string following it because different versions of make will handle this differntly; some will ignore it, some will take it as part of the string.

Variables are referenced by placing a dollar sign ($) before the variable name and placing the name in braces or parenthesis depending on the version of "make" you are using. Most versions allow you to use just the dollar sign in certain cases, but some require a pair of delimiters (braces, parens, etc) around the name. Therefore, it is safest to always enclose the name in a delimiter pair. Braces and parenthesis also have different meanings in some versions of "make", so you may have to use a particular type of delimeter. See the man page for the version of "make" which you are using. I use GNU make, so I'll just use braces {} for the rest of this tutorial.

Suppose at the top of our makefile we have the line:

	MYFILES=a b c d e

To reference MYFILES later in the makefile we could write:


which would be translated to the string "a b c d e".

Variables may also be used within other variable assignments:


This code segment sets BASEDIR to "/usr/local", HOMEDIR to "/usr/local/pccts", and BINDIR to "/usr/local/bin".

Finally, here is a short example of a makefile using variables:


${INSTDIR}/program: myfile.c
	${CC} ${CFLAGS} -o ${INSTDIR}/program myfile.c

In this example, after making the string substitutions, the command that "make" will use to build "program" from "myfile.c" is:

	/bin/gcc -Wall -o /usr/local/bin/program myfile.c

This allows the user to customize which compiler is used, the options to the compiler, and the directory the executable will be installed in just by changing the strings assigned to the variables.
This page was last modified .