Search

Makefiles: Using variables

Prev: make is smart We can use variables in makefile to prevent typing the same strings over and over and also make the file more easy to understand.

Defining variables: Let us say we have a makefile to compile three independent executables hello_1, hello_2 and hello_3



In the above makefile we use the string "cc -o" repeatedly. Instead of typing the whole string every time we can create a variable for it.
We can create a variable of any name by using the "=" sign. The left hand would be the name of the variable and the right hand side would be the value of the variable.
Any where in the file if we want to use the value of the variable we just have to use the name of the variable in the format $() and make will automatically replace the variable with its value while executing.



In the above file have created a variable CC and used it whenever we needed cc -o.
Note that variables are case sensitive thus "cc" "CC" and "Cc" are all different.
We can also use variables for prefixes of various strings. Like in the example above "hello" is like a prefix to a number of strings, thus we can use a variable for it.



Recursive expanded variables : We can create recursive variables by using one variable while declaring another.



In the above example "targets" is a variable, which is a list of all the targets. The targets variable uses the variable "pf" , thus to find out what $(targets) refers to make will have to expand pf creating a recursion among variables any depth of such recursion is allowed.
The limitation of defining variables using "=" is that a variable can not refer to itself in recursion.



In the above example, the second definition of variable "targets" uses the "targets" itself in recursion. Such usage will result in an infinite loop, which make successfully detects and throws the error.



Simply expanded variables This can be prevented by making use of simply expanded variables which are defined using ":=". The use of ":=" makes the expansion of all the variables in the assignment only once and stop, thus preventing the infinite loop.

Thus in the above example the second definition should be



Now make will not throw any error and will successfully compile the targets.

Using shell in declaration : We can also execute shell commands while defining variables.



In the above example we executed the command "pwd" and assigned the result to the variable "opd" which we used while compiling to indicate the path where the compiled executable needs to be stored.


No comments:

Post a Comment