makefile
A Makefile is a special file used by the make build automation tool to control the generation of executable programs and other non-source files from a computer program's source code. Here's a basic example and explanation of how a simple Makefile works:
Simple Example
Let's say you have a C project with two source files: main.c and helper.c, and you want to compile them into an executable called program.
Your directory structure might look like this:
project/
├── main.c
└── helper.cHere's a simple Makefile for this project:
# Variables
CC = gcc
CFLAGS = -Wall -g
TARGET = program
OBJECTS = main.o helper.o
# Default target
all: $(TARGET)
# Linking objects into the final executable
$(TARGET): $(OBJECTS)
$(CC) $(CFLAGS) -o $(TARGET) $(OBJECTS)
# Compiling .c files into .o files
main.o: main.c
$(CC) $(CFLAGS) -c main.c
helper.o: helper.c
$(CC) $(CFLAGS) -c helper.c
# Clean up build artifacts
clean:
rm -f $(TARGET) $(OBJECTS)Explanation
Variables: The Makefile defines some variables at the beginning to avoid repetition:
CCspecifies the compiler to use (gccin this case).CFLAGSspecifies the flags to pass to the compiler (-Wall -gfor all warnings and debug information).TARGETis the name of the output executable (program).OBJECTSlists the object files needed to build the target (main.oandhelper.o).
- Default Target: The
alltarget is the default goal. When you runmakewithout arguments, it will execute the rules for this target. Here, it depends on the$(TARGET). - Linking: The rule for
$(TARGET)depends on$(OBJECTS). It uses the compiler to link the object files into the final executable. - Compilation: Each
.ofile has a rule that compiles the corresponding.cfile. The-cflag tellsgccto compile the source file into an object file. - Cleaning: The
cleantarget removes the generated binary and object files. You can run this by executingmake clean.
Using the Makefile
To use this Makefile, place it in the same directory as your source files and run:
make # This will build the 'program' executable
make clean # This will remove the 'program' executable and object filesThis is a very basic Makefile meant for illustrative purposes. Makefiles can be much more complex and are often used in larger projects with many source files, directories, and various build configurations.
Prev:从教育大国迈向教育强国:系统推进与全球挑战1000字论文