The Pointer The Pointer - 16 days ago 6
Bash Question

Understanding the role of automatic variables in make/makefile

I've recently started learning about make/makefiles and some of its associated concepts. I have thus far created some basic versions, with targets, dependencies, actions, etc. However, I have been unable to make sense of what automatic variables are in this context, their utility, or how to use them.

I've done a lot of research on this topic. However, I haven't been able to locate any satisfying material. It seems that the most reputable source of information is the following GNU page:
However, I still do not understand exactly what automatic variables are, what their utility is, or how I can practically use them in my makefiles.

I would greatly appreciate it if someone could explain what they are, what their utility is, and how I can practically use them. An example would help to illustrate these ideas. Thank you.


Automatic variables are simply variables for which the value is generated by Make, rather than having to be set explicitly.

If you take a look at existing Makefiles (pick your favorite open source project!), you'll find lots of practical examples to help you out. A common one looks something like this:

%.o: %.c
    gcc -c -o $@ $<

This is a pattern rule that says "to build a file named <something>.o, which depends on <something.c>, use the command gcc -c -o $@ $<. $@ is an automatic variable that evaluates to the target of the rule, and $< is an automatic variable which evaluates to the first prerequisite of the rule. These automatic variables are critical to this sort of pattern rule; they allow you to run make foo.o or make bar.o and have the appropriate values substituted into the command line. E.g., if you type make foo.o, Make will try to run:

gcc -c -o foo.o foo.c

Or consider this example from the git Makefile:

strip: $(PROGRAMS) git$X
    $(STRIP) $(STRIP_OPTS) $^

This is used to strip symbol information from object files. It needs to operate on all of the prerequisites, so it uses $^, which evaluates to...a space-separated list of all the prerequisites.

Does this help out at all?