RSS Amplifier

Jacob Garber · Jun 13, 2021

A Basic C Makefile

0
Sign in to vote or save

This page did not load. You can still read it on the original site — the toolbar below keeps your place in the directory.

These days I usually use Meson for building C and C++ code, but for small projects the simplicity and ubiquity of a Makefile can't be beat. In the past I'd write custom Makefile rules to compile each file individually, but with the power of wildcards we can write a generic Makefile that drops in to any project. Simply set the executable name, customize your compiler options, and off you…

These days I usually use Meson</a> for building C and C++ code, but for small projects the simplicity and ubiquity of a Makefile can't be beat. In the past I'd write custom Makefile rules to compile each file individually, but with the power of wildcards we can write a generic Makefile that drops in to any project. Simply set the executable name, customize your compiler options, and off you go.</p>

# `make` builds the target
# `make file.o` creates the `file` object file
# `make clean` will rm all object files and the target
TARGET = my-executable
# sample settings
CC = gcc
CFLAGS = -std=c11 -Wall -Wextra -Wpedantic -g
LDLIBS = -lpthread
SOURCES = $(wildcard *.c)
HEADERS = $(wildcard *.h)
OBJECTS = $(SOURCES:.c=.o)
# link the object files to create the target
$(TARGET): $(OBJECTS)
	$(CC) $(CFLAGS) $^ -o $@ $(LDLIBS)
# compile rule for the object files
%.o: %.c $(HEADERS)
	$(CC) $(CFLAGS) -c $< -o $@
.PHONY: clean
clean:
	-rm $(OBJECTS) $(TARGET)
</code></pre>

Read on jwgarber.ca

Comments

Nothing yet. Say the first thing.

    Sign in to join the conversation.