File Input Output in Gnu Make

Published on 13 July 2023 (Updated: 29 July 2023)

Welcome to the File Input Output in Gnu Make page! Here, you'll find the source code for this program as well as a description of how the program works.

Current Solution

define TEXT
Hello from GNU Make
Here are some lines:
This is line 1
This is line 2
Goodbye!
endef

$(file >output.txt,$(TEXT))
$(info $(file <output.txt))

.PHONY: all
all: ;@:

File Input Output in Gnu Make was written by:

This article was written by:

If you see anything you'd like to change or update, please consider contributing.

How to Implement the Solution

The define keyword assigns a multi-line value to a variable. The value is terminated with an endef keyword. For this sample program, this is the text that will be written to the output file:

define TEXT
Hello from GNU Make
Here are some lines:
This is line 1
This is line 2
Goodbye!
endef

The file function allows files to be read and written. The general form of this function is this:

$(file op filename[,text])

where:

This writes the text (stored in the TEXT variable) to a file called output.txt:

$(file >output.txt,$(TEXT))

This reads the text from output.txt and displays it using the info function.

$(info $(file <output.txt))

Since GNU Make is a build system, it needs something to build, or else it will give this error:

make: *** No targets.  Stop.

To give make something to do, a "do nothing" target called all is provided like this:

.PHONY: all
all: ;@:

The .PHONY keyword specifies targets that will always be built, whether or not they exist. In this case, that is the all target. This target is written in the alternate form for brevity:

target: ;command

This means that whenever the target needs to be built, make will execute the command following the semicolon. By default, make echoes each command that it executes. To suppress this, @ may be used before the command. The colon (:) command just exits with non-error status.

How to Run the Solution

To run this program, download and install the latest GNU Make using these instructions:

Download a copy of File Input Output in GNU Make, and run this command:

make -sf file-input-output.mk