CITS2002 Systems Programming  
prev
CITS2002 CITS2002 schedule  

Employing automatic variables in a Makefile

We further note that each of our object files depends on its C source file, and that it would be handy to reduce these very common lines.

make provides a (wide) variety of filename patterns and automatic variables to considerably simplify our actions:


# A Makefile to build our 'calcmarks' project

PROJECT =  calcmarks
HEADERS =  $(PROJECT).h
OBJ     =  calcmarks.o globals.o readmarks.o correlation.o


C11     =  cc -std=c11
CFLAGS  =  -Wall -Werror 


$(PROJECT) : $(OBJ)
       $(C11) $(CFLAGS) -o $(PROJECT) $(OBJ) -lm


%.o : %.c $(HEADERS)
       $(C11) $(CFLAGS) -c $<

clean:
       rm -f $(PROJECT) $(OBJ)

Of note:

  • the pattern %.o   matches, in turn, each of the 4 object filenames to be considered,
  • the pattern %.c   is "built" from the C file corresponding to the %.o file,
  • the automatic variable $<   is "the reason we're here", and
  • the linker option  -lm  indicates that our project requires something from C's standard maths library (sqrt() ).

make supports many automatic variables, which it "keeps up to date" as its execution proceeds:

$@This will always expand to the current target.
$<The name of the first dependency. This is the first item listed after the colon.
$?The names of all the dependencies that are newer than the target.

Fortunately, we rarely need to remember all of these patterns and variables, and generally just copy and modify existing Makefiles.

 


CITS2002 Systems Programming, Lecture 17, p15, 26th September 2023.