Makefile by Example: Conditional Blocks
Directives like `ifdef`, `ifeq`, and `else` control what part of the Makefile is seen by Make. This example shows conditional configuration.
Code
# Check if a variable is defined
ifdef DEBUG
CFLAGS += -g -DDEBUG_MODE
else
CFLAGS += -O2
endif
# Check for equality
OS := $(shell uname)
ifeq ($(OS),Darwin)
# Mac OS specific flags
LDFLAGS += -framework Cocoa
else
# Linux/Other
LDFLAGS += -lm
endif
all:
@echo "CFLAGS: $(CFLAGS)"
@echo "LDFLAGS: $(LDFLAGS)"Explanation
Conditional directives allow you to control the flow of the Makefile parsing. Unlike the if function (which is for text expansion), directives like ifeq, ifneq, ifdef, and ifndef control which lines of the Makefile are actually read and processed by Make.
This is essential for writing cross-platform Makefiles. You can check the operating system or architecture and set compiler flags accordingly. You can also use it to implement build options, like a "Debug" mode that adds debug symbols (-g) versus a "Release" mode that optimizes code (-O2).
The syntax involves the directive followed by the condition, then the block of code, optional else, and finally endif. Note that conditional directives are processed when the Makefile is read, so they cannot depend on the result of commands in recipes (which run later).
Code Breakdown
ifdef DEBUG checks if the variable DEBUG has a non-empty value. Run make DEBUG=1 to trigger this.ifeq ($(OS),Darwin) compares the value of OS with the string "Darwin".
