# Basic Makefile for C projects

## Makefile:

```plaintext

# ==========================================
# Configuration
# ==========================================

CC       := gcc
TARGET   := hello 

STD      := c11
OPT      := 2

CFLAGS   := -std=$(STD) -O$(OPT) -Wall -Wextra -Wpedantic
CPPFLAGS := -Iinclude -MMD -MP
LDFLAGS  :=
LDLIBS   :=

BUILD    := build

# ==========================================
# Source files
# ==========================================

SOURCES := $(wildcard *.c)

OBJECTS := $(patsubst %.c,$(BUILD)/%.o,$(SOURCES))
DEPS    := $(OBJECTS:.o=.d)

# ==========================================
# Build rules
# ==========================================

.PHONY: all clean rebuild

all: $(TARGET)

# Link executable
$(TARGET): $(OBJECTS)
	@echo "  LINK    $@"
	@$(CC) $(LDFLAGS) -o $@ $^ $(LDLIBS)

# Compile individual source files
$(BUILD)/%.o: %.c | $(BUILD)
	@echo "  CC      $<"
	@$(CC) $(CPPFLAGS) $(CFLAGS) -c $< -o $@

# Create build directory
$(BUILD):
	@mkdir -p $@

# ==========================================
# Utilities
# ==========================================

clean:
	@echo "  CLEAN"
	@rm -rf $(BUILD) $(TARGET)

rebuild: clean all

# ==========================================
# Header dependencies
# ==========================================

-include $(DEPS)
```

The project structure would be like this:

![](https://cdn.hashnode.com/uploads/covers/66b18cb47e7d110d78541fde/16d38755-a4d4-4e30-8b47-7c4ed2524c1f.png align="center")

So, all .c files will be at the root of the project folder.

.h files will be in `include` folder.

All the output files like .o files will go to `build` folder.

The output binary will be created at the root of the project.

## Make Commands

- `make` - Build the project
- `make all` - Same as make
- `make -j$(nproc)` - Build using all available CPU cores
- `make clean` - Remove build/ and the output binary
- `make rebuild` - Clean everything and rebuild
