Skip to main content

Makefile

automation

Links

A Makefile is a special file used by the make build automation tool to manage the build process of a project. It defines a set of tasks to be executed, specifying how to compile and link the program. Makefile is commonly used in Unix and Linux environments to automate the compilation of large projects, ensuring that only the necessary parts are recompiled when changes occur.

oaicite:0


Usage Example

Here’s a simple example of a Makefile for a C project:

# Compiler
CC = gcc

# Compiler flags
CFLAGS = -Wall -g

# Target executable
TARGET = myprogram

# Source files
SRCS = main.c utils.c

# Object files
OBJS = $(SRCS:.c=.o)

# Default target
all: $(TARGET)

# Link object files to create executable
$(TARGET): $(OBJS)
	$(CC) $(CFLAGS) -o $@ $^

# Compile source files into object files
%.o: %.c
	$(CC) $(CFLAGS) -c $< -o $@

# Clean up generated files
clean:
	rm -f $(OBJS) $(TARGET)

In this example:

  • CC and CFLAGS define the compiler and its flags.
  • TARGET specifies the name of the executable to be generated.
  • SRCS lists the source files, and OBJS defines the corresponding object files.
  • The all target depends on the $(TARGET), which is built by linking the object files.
  • The pattern rule %.o: %.c compiles each .c file into a .o object file.
  • The clean target removes the generated object files and executable.
    oaicite:1

To build the project, run:

make

To clean up the generated files, run:

make clean