Next: , Previous: Foreach Function, Up: Functions


8.6 The file Function

The file function allows the makefile to write to a file. Two modes of writing are supported: overwrite, where the text is written to the beginning of the file and any existing content is lost, and append, where the text is written to the end of the file, preserving the existing content. In all cases the file is created if it does not exist.

The syntax of the file function is:

     $(file op filename,text)

The operator op can be either > which indicates overwrite mode, or >> which indicates append mode. The filename indicates the file to be written to. There may optionally be whitespace between the operator and the file name.

When the file function is expanded all its arguments are expanded first, then the file indicated by filename will be opened in the mode described by op. Finally text will be written to the file. If text does not already end in a newline, a final newline will be written. The result of evaluating the file function is always the empty string.

It is a fatal error if the file cannot be opened for writing, or if the write operation fails.

For example, the file function can be useful if your build system has a limited command line size and your recipe runs a command that can accept arguments from a file as well. Many commands use the convention that an argument prefixed with an @ specifies a file containing more arguments. Then you might write your recipe in this way:

     program: $(OBJECTS)
             $(file >$@.in,$^)
             $(CMD) $(CMDFLAGS) @$@.in
             @rm $@.in

If the command required each argument to be on a separate line of the input file, you might write your recipe like this:

     program: $(OBJECTS)
             $(file >$@.in,) $(foreach O,$^,$(file >>$@.in,$O))
             $(CMD) $(CMDFLAGS) @$@.in
             @rm $@.in