Home

Make files

Make files are used to automate the building and compiling of a project.

This is most often used for C style languages.

Example: * means a file has changed.

+--------------+      +---------------+
|  *file1.c    |      |    file2.c    |
+--------------+      +---------------+
       |                      |
       v                      v
+--------------+      +---------------+
|  *file1.o    |      |    file2.o    |
+--------------+      +---------------+
        \                     /
          \                 /
            \             /
              v         v
           +---------------+
           |  *executable  |
           +---------------+
  1. Create a file called makefile or Makefile
  2. Add rules
  3. Run make when ready to compile

Comments

Comments start with #

Rules

target: dependencies
    command

# Example:
file1.o: file1.c
    gcc file1.c

Clean

There is often a clean target that usually removes the .o files and the executable.

clean:
    rm -f *.o executable

Variables

   
VAR_NAME = value Creating var
$(VAR_NAME) Using var

Conditional execution

ifeq ($(VAR_NAME), value)
    # code
else ifeq ($(VAR_NAME), value2)
    # code
else
    # code
endif

List of ifs

   
ifeq if equals
ifneq if not equals
ifdef if a variable is defined(non-empty)
ifndef if a variable is not defined

Full Example

CC = gcc
CFLAGS =
LIBS =

executable: file1.o file2.o
    $(CC) $(CFLAGS) file1.o file2.o -o executable $(LIBS)

file1.o: file1.c
    $(CC) $(CFLAGS) -c file1.c $(LIBS)

file2.o: file2.c
    $(CC) $(CFLAGS) -c file2.c $(LIBS)

clean:
    rm -f *.o executable

Variables

$() Is used to de-reference variables.

Variables Description Example
= Verbatim assignment. Doesn’t dereference variables. VAR = val
:= Simple expansion. Does dereference variables. VAR := $(VAR2)
!= Shell output into var VAR != find . -name '*.c'
?= If there isn’t a variable then assign with value. Else don’t. VAR ?= value
+= Append to VAR += another value

You can have spacial keyboard to do things in $().