# This is a makefile (a script for the ‹make› program) that builds a # simple C program. You should make a copy of this file, along with # ‹getenv.c› and you can then build ‹getenv› using this command: # # $ make -f build.mk # Like shell, make has variables. We will use them from the start, # because they are very useful. One of the common variables we will # encounter is ‹CFLAGS›, which is what ‹make› passes to the C # compiler. We can use the ‹+=› operator to add things to existing # variables. # Here, we will tell the compiler to emit additional warnings and to # switch to C99 mode. CFLAGS += -Wall -std=c99 # Make uses «rules», which describe how to build files from other # files. In ‹make›, the rules have 3 parts: the target (what we # want to build), followed by a colon and a list of ingredients that # are required to build the target (so-called «dependencies» or # «prerequisites»). On the next line, a sequence of shell commands # follows. We will get to those in a short while. # The first rule in the file is special, because it is the one that # executes when we just ‘run’ the makefile. It is often called # ‹all›, so the command then looks as ‹make all› or just ‹make›. In # our case, to make ‹all›, we ask make to build ‹getenv› but nothing # else. This is written so: all: getenv # In this case, ‹all› is a «phony» target: it is not a file. Most # targets in a makefile are, however, files. We will only deal with # files from now on. # For instance, let's describe how to build ‹getenv.o› from # ‹getenv.c›: getenv.o: getenv.c cc $(CFLAGS) -c getenv.c # The ‘body’ (the shell commands) of the rule is like a small shell # script. But you can't use shell variables, because ‹make› runs # each command in a new shell. Each line of the body starts with a # character. Using 8 spaces does «not» work. # Please take note that variable expansion works differently in make # than it does in shell: we write $(VAR). In a shell, this would # mean ‘run the command VAR’, but is just standard variable # expansion in a makefile. While we talk about variables: make # variables are «not» environment variables. Unlike in a shell, we # also can't get environment variables using ‹$›-expansion. # Sorry for the detour. Now we also want to tell ‹make› how to build # ‹getenv› from the object file: getenv: getenv.o cc -o getenv getenv.o # That is all. You should be able to write a simple makefile # yourself. Try ‹3.txt›.