Programming Utilities Guide

Passing Parameters: Simple make Macros

The make macro substitution comes in handy when you want to pass parameters to command lines within a makefile. Suppose that you want to compile an optimized version of the program program, using the cc -O option. You can lend this sort of flexibility to your makefile by adding a macro reference, such as the following example, to the target for functions:

functions: functions.c 
         cc $(CFLAGS) -o functions functions.c

The macro reference acts as a placeholder for a value that you define, either in the makefile itself, or as an argument to the make command. If you then supply make with a definition for the CFLAGS macro, make replaces its references with the value you have defined.

$rm functions 
$ make functions "CFLAGS= -O"
cc -O -o functions functions.c

Note -

There is a reference to the CFLAGS macro in both the .c and the .c.o implicit rules.



Note -

The command-line definition must be a single argument, hence the quotes in this example.


If a macro is undefined, make expands its references to an empty string.

You can also include macro definitions in the makefile itself. A typical use is to set CFLAGS to -O, so that make produces optimized object code by default:

CFLAGS= -O 
functions: functions.c 
         cc $(CFLAGS) -o functions functions.c

A macro definition supplied as a command line argument to make overrides other definitions in the makefile. Conditionally defined macros are an exception to this.

For instance, to compile functions for debugging with dbx or dbxtool, you can define the value of CFLAGS to be -g on the command line:

$ rm functions 
$ make CFLAGS=-g 
cc -g -o functions functions.c

To compile a profiling variant for use with gprof, supply both -O and -pg in the value for CFLAGS.

A macro reference must include parentheses when the name of the macro is longer than one character. If the macro name is only one character, the parentheses can be omitted. You can use curly braces, { and }, instead of parentheses. For example, `$X', `$(X)', and `${X}' are equivalent.