Skip to content

Instantly share code, notes, and snippets.

@hydrogen602
Created September 23, 2022 02:02
Show Gist options
  • Save hydrogen602/9decf7be6f6d6d83398ccc1a1bfad8ce to your computer and use it in GitHub Desktop.
Save hydrogen602/9decf7be6f6d6d83398ccc1a1bfad8ce to your computer and use it in GitHub Desktop.
C++ makefile that auto finds source code in nested folders
# C++ Flags
CPPFLAGS := -Wall -pedantic -g -std=c++17 # swap -g with -O3 and similar to release builds
CC := g++
LDLIBS := -lm -lstdc++ # libraries go here
INC := # includes go here
# General Notes:
# - run $ make -j <num of cores on your machine>
# Expected file structure:
# - Makefile
# - src
# - your-code.cpp
# - some-dir
# - some-more-code.cpp
#
# Code and header files can be arbitrarely nested in the src folder
# the main function can be in any cpp file
BUILD_DIR := build
# ENDING is cpp, change to *.c++ if preferred
SRCS := $(shell find src -iname '*.cpp' -type f)
# Change *.h to *.hpp or *.h++ if your headers are named that
HEADERS := $(shell find src -iname '*.h' -type f)
OBJS := $(SRCS:src/%.cpp=$(BUILD_DIR)/%.o)
OUT := main # name of executable
.PHONY: clean lines run
# creates executable
$(OUT): $(OBJS)
$(CC) -o $@ $^ $(LDLIBS)
# compile each source file
$(BUILD_DIR)/%.o: src/%.cpp $(HEADERS)
@mkdir -p $(@D)
$(CC) -c $(INC) -o $@ $< $(CPPFLAGS)
# delete all generated files
clean:
rm -rf $(BUILD_DIR) $(OUT)
# get line count of all sources and headers
lines: $(SRCS) $(HEADERS)
wc -l $^ | grep total
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment