Makefile QuickStart

Makefile QuickStart

Definition: A makefile is a file containing a set of directives used with the make build automation tool. (from Wikipedia)

Main Versions

Makefile Grammars

Basic Format

1
2
3
4
5
6
7
8
# this is a comment
# in case target be ignored, add the following
# .PHONY: <target>
<target> : <prerequisites>
[tab] <commands>
# use '.RECIPEPREFIX = [operator]' to replace [tab]
  • target:
    • filename(s), the one(s) to be constructed
    • name of a operation
    • phony target: If current dir has one file with the same name as the operation, this operation would be ignored. In case, add
      ```
      1
      2
      3
      4
      - **prerequisites**: Check if the files or operations exist
      - **commands**: Tell how, consists of line(s) of Shell instructions
      ### Learn from a example

Var

CXX = g++
OBJS = \
student.o \
one.o \
main.o
EXEC = run

$(var): fetch var

%.o: %.cpp %.h
@# This line won’t be printed
$(CXX) -c $< -o $@

$(EXEC): $(OBJS)
$(CXX) -o $@ $(OBJS)

clean:
rm -rf $(OBJS)
rm -rf $(EXEC)
```

  • Every commands would be printed, plus ‘@’ prefix to avoid
  • Wildcard: (*), (?), […], (%)
  • Assignment: =, :=, ?=, +=
  • Automatic Variables:
    • $@: indicate the target
    • $<: indicate the first prerequisite

More about if-statement, functions in Make 命令教程