Previous Page
Next Page

19.8. Macros

When we talk about macros in make, you should remember that there is really no difference between them and variables. Nonetheless, make provides a directive that allows you to define variables with both newline characters and references to other variables embedded in them. Programmers often use this capability to encapsulate multiline command sequences in a variable, so that the term macro is fairly appropriate. (The GNU make manual calls them "canned command sequences.")

To define a variable containing multiple lines, you must use the define directive. Its syntax is:

define macro_name
macro_value
endef

The line breaks shown in the syntax are significant: define and endef both need to be placed at the beginning of a line, and nothing may follow define on its line except the name of the macro. Within the macro_value, though, any number of newline characters may also occur. These are included literally, along with all other characters between the define and endef lines, in the value of the variable you are defining. Here is a simple example:

define installtarget
 @echo Installing $@ in $(USRBINDIR) ... ;\
 $(MKDIR) -m 7700 $(USRBINDIR)           ;\
 $(CP) $@ $(USRBINDIR)/                  ;\
 @echo ... done.
endef

The variable references contained in the macro installtarget are stored literally as shown here, and expanded only when make expands $(installtarget) itself, in a rule like this for example:

circle: $(OBJ) $(LIB)
        $(CC) $(LDFLAGS) -o $@ $^
ifdef INSTALLTOO
        $(installtarget)
endif


Previous Page
Next Page