본문 바로가기
Embedded/Embedded Software

Makefile default grammer - Pattern Rule, Automatic Variable

by aloHyomora 2025. 4. 25.

1️⃣ Pattern Rule?

Used to process similar rules in batches.

%.o: %.c
	command
  • %.o: Any .o file
  • %.c: the corresponding .c file
  • Pattern => Deduplication

2️⃣ Automatic Variable?

Automatically provide specific information within the build command.

automatic variable Meaning
$@ name of current target
$< first dependency (input file)
$^ all of dependencies (deduplication)

 

Example

CC = gcc
CFLAGS = -Wall
OBJS = main.o utils.o

all: program

program: $(OBJS)
    $(CC) $(CFLAGS) -o $@ $^

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

clean:
    rm -f *.o program
.PHONY: clean all

 

  • %.o: %.c → Automatically compile as .o once you have a .c file
  • $@ → current target (program or main.o)
  • $< → .c file
  • $^ → every .o file

Example: Pattern Rule (Create .o)

%.o: %.c 
	$(CC) $(CFLAGS) -c -o $@ $< 
    
%.o: %.s 
	$(CC) $(CFLAGS) -c -o $@ $<
%.o: %.c every .c build to .o 
%.o: %.s every .s build to .o
$@ current target .o
$< source file name (.c or .s)

➡️ main.c → main.o, startup.s → startup.o Automatically Processing.