Quick Makefiles I use

I have a giant pile of tiny stuff in my ~/src/test. Bash and ruby scripts of 3-10 lines long, quick random stuff in C or C++ or Go I want to try out if I don’t remember exactly how something works; it is chaotic to say the least. Most of that stuff builds and runs super straightforward: cc -std=c23 -o stuff stuff.c or something of sorts.

When some of the C/C++ coding I do requires a dedicated folder I usually use one of the two makefile templates to quickly get a reliable build&run system in place.

I use GNU Makefile since it has wildcard helper and it is usually readily available on BSDs was gmake from ports or something.

The only things I change in those makefiles are the source code files extension (.c or .cpp) and sometimes CFLAGS/LDFLAGS depending on desired outcome.

Folder where multiple files = single executable

This works for tiny projects like the Advent of Code puzzles: when I have several files and headers in one folder and I want to build an executable named as the folder we’re in. It compiles each separate C file into an object and then links them all into executable. Since sometimes I do those projects on some old machines having only changed units recompile is neat.

Simple make run is enough to build and run everything.

NAME=$(shell basename ${PWD})
SRC=$(wildcard *.c)
DEPS:=$(wildcard *.h)
OBJ:=$(SRC:.c=.o)
CFLAGS=-O2 -std=gnu23 -Werror -Wall -Wextra -ffast-math -march=native -I.
LDFLAGS=-lc

all: $(NAME)

.PHONY: clean run

clean:
        rm -f $(OBJ) $(NAME)

%.o : %.c $(DEPS)
        $(CC) $(CFLAGS) -c $< -o $@

$(NAME): $(OBJ)
        $(CC) $(OBJ) -o $@ $(LDFLAGS)

run: $(NAME)
        ./$(NAME)

Folder where one file = one executable

Best suited for iterating code, usually when learning something and want to keep previous versions readily available. Every source file (.c or .cpp) compiles into corresponding .bin file, and +run suffix runs that executable binary.

For example if I have shader.c file: make shader builds shader.bin executable, and make shader+run builds (if deemed neccessary by make) and launches it.

.SUFFIXES:
MAKEFLAGS+=-rR
CFLAGS=-O2 -std=gnu23 -Werror -Wall -Wextra -ffast-math -march=native -I.
LDFLAGS=-lc
CC=cc

.PHONY: clean

%+run: %.bin
        ./$<

.SECONDARY:
%: %.bin
        @:

%.bin: %.c
        ${CC} $< $(CFLAGS) $(LDFLAGS) -o $@

clean:
        rm -f ./*.bin