File Function (GNU make)

From Get docs
Make/docs/latest/File-Function

Next: Call Function, Previous: Foreach Function, Up: Functions   [Contents][Index]



8.6 The file Function

The file function allows the makefile to write to or read from 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 both cases the file is created if it does not exist. It is a fatal error if the file cannot be opened for writing, or if the write operation fails. The file function expands to the empty string when writing to a file.

When reading from a file, the file function expands to the verbatim contents of the file, except that the final newline (if there is one) will be stripped. Attempting to read from a non-existent file expands to the empty string.

The syntax of the file function is:

$(file op filename[,text])

When the file function is evaluated all its arguments are expanded first, then the file indicated by filename will be opened in the mode described by op.

The operator op can be > to indicate the file will be overwritten with new content, >> to indicate the current contents of the file will be appended to, or < to indicate the contents of the file will be read in. The filename specifies the file to be written to or read from. There may optionally be whitespace between the operator and the file name.

When reading files, it is an error to provide a text value.

When writing files, text will be written to the file. If text does not already end in a newline a final newline will be written (even if text is the empty string). If the text argument is not given at all, nothing will be written.

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 >[email protected],$^)
        $(CMD) $(CMDFLAGS) @[email protected]
        @rm [email protected]

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 >[email protected]) $(foreach O,$^,$(file >>[email protected],$O))
        $(CMD) $(CMDFLAGS) @[email protected]
        @rm [email protected]

Next: Call Function, Previous: Foreach Function, Up: Functions   [Contents][Index]