C Build Automation: Makefiles, CMake & Git CI/CD Masterclass
Welcome to Phase 21 (Chapter 60): C Build Automation โ Makefiles, CMake & Git CI/CD Masterclass! Automating builds ensures reproducible compilation across development teams. In this guide, you will master GNU Make, modern CMake configuration, and automated GitHub Actions CI/CD pipelines.
CC = gcc
CFLAGS = -Wall -Wextra -Werror -std=c17 -Iinclude
SRC = $(wildcard src/*.c)
OBJ = $(SRC:src/%.c=build/%.o)
TARGET = bin/app
.PHONY: all clean
all: $(TARGET)
$(TARGET): $(OBJ)
@mkdir -p bin
$(CC) $(OBJ) -o $@
build/%.o: src/%.c
@mkdir -p build
$(CC) $(CFLAGS) -c $< -o $@
clean:
rm -rf build bin
cmake_minimum_required(VERSION 3.15)
project(MyCProject VERSION 1.0 LANGUAGES C)
set(CMAKE_C_STANDARD 17)
set(CMAKE_C_STANDARD_REQUIRED ON)
include_directories(include)
file(GLOB SOURCES "src/*.c")
add_executable(my_app ${SOURCES})
Q1: What do automatic variables $@, $<, and $^ mean in Makefiles?
`$@` is the target name, `$<` is the first prerequisite, and `$^` is the list of all prerequisites.
Q2: Why use .PHONY targets in Makefiles?
Declaring `.PHONY: clean all` ensures Make executes targets even if a file named `clean` or `all` exists on disk.
Q3: What is the main advantage of CMake over Makefiles?
CMake generates native build files for any platform (Makefiles for Linux, Visual Studio solutions for Windows, Xcode for macOS).
Q4: Must recipe commands in Makefiles start with a TAB character?
Yes! GNU Make strictly requires commands under targets to be indented with an actual TAB character (spaces will cause a syntax error).
Q5: How do GitHub Actions run automated C builds on push?
A YAML workflow file in `.github/workflows/c-build.yml` triggers a Linux VM that checks out code, runs `make`, and executes test binaries.