Building with Make
Building with Make
1. How make Works
make manages the build process based on file dependencies and timestamps, following these steps:
- Read the
Makefile:makeparses theMakefileto obtain build rules. - Check target modification times:
makecompares timestamps to decide whether to rebuild. For example, ifsource.cis newer thansource.o,makeconsiderssource.ostale and re-runs the relevant compile command. - Execute build rules: if a target needs rebuilding,
makeruns the compilation and linking commands according to the dependency graph until the final target (executable or library) is produced.
2. Basic Makefile Structure
A Makefile is the configuration file make reads. It defines build rules, targets, dependencies, and commands. A typical Makefile contains:
Basic Syntax
- Target: the file to build (usually an object file or the final executable).
- Dependency: files the target depends on. If a dependency is updated, the target must be rebuilt.
- Command: the shell command that produces the target (e.g., a compile command). Commands must be indented with a TAB character.
target: dependencies
command3. Makefile Example
Suppose we have a simple C++ project with two source files, main.cpp and utils.cpp, which produce object files main.o and utils.o, and are ultimately linked into the executable myapp.
CC = g++ # compiler: g++
CFLAGS = -Wall -g # compile flags: -Wall enables all warnings, -g includes debug info
# object files
OBJS = main.o utils.o
# executable
TARGET = myapp
# default target
all: $(TARGET)
$(TARGET): $(OBJS) # executable depends on object files
$(CC) $(OBJS) -o $(TARGET) # link command: produces the executable
main.o: main.cpp utils.h
$(CC) $(CFLAGS) -c main.cpp # compile command: produces main.o
utils.o: utils.cpp utils.h
$(CC) $(CFLAGS) -c utils.cpp # compile command: produces utils.o
clean:
rm -f $(OBJS) $(TARGET) # remove intermediate and target filesTargets serve as the entry points for execution.
贡献者
这篇文章有帮助吗?
最近更新
Involution Hell© 2026 byCommunityunderCC BY-NC-SA 4.0