Makefile 기본 사용법

2024. 8. 7. 13:14개발/개발도구와 환경

Makefile 작성에 도움이 되는 기본 문법과 예시

 

기본 구조

target: dependencies
	command1
	command2
	...

 

  • target: 빌드하고자 하는 파일 또는 실행 파일 이름
  • dependencies: target을 생성하기 위해 필요한 파일 목록
  • command: target을 생성하기 위한 명령어 (탭으로 시작해야 함)

 

예시:

# 실행 파일 생성 규칙
myprogram: main.o utils.o
	g++ -o myprogram main.o utils.o

# 오브젝트 파일 생성 규칙
main.o: main.cpp
	g++ -c main.cpp

utils.o: utils.cpp
	g++ -c utils.cpp

# 기타 규칙
clean:
	rm -f *.o myprogram

 

 

기본 제공 타겟

.PHONY: all clean

all: build

clean:
    rm -f *.o myprogram

 

 

자주 사용되는 변수

  • $@: target 파일 이름
  • $<: 첫 번째 dependency 파일 이름
  • $^: 모든 dependency 파일 이름 (공백으로 구분)
  • CC: C 컴파일러 (기본값: cc)
  • CXX: C++ 컴파일러 (기본값: g++)
  • CFLAGS: C 컴파일러 옵션
  • CXXFLAGS: C++ 컴파일러 옵션
# 변수 정의
CC = gcc
CFLAGS = -Wall -g

# 변수 사용
all: build

build:
    $(CC) $(CFLAGS) -o myprogram main.c

clean:
    rm -f myprogram

 

# 패턴 규칙 정의
%.o: %.c
    $(CC) $(CFLAGS) -c $< -o $@

# 사용 예시
all: main.o utils.o
    $(CC) $(CFLAGS) -o myprogram main.o utils.o

clean:
    rm -f *.o myprogram

 

자주 사용되는 암묵적 규칙

Makefile은 .c 파일을 .o 파일로 컴파일하는 등의 묵시적 규칙을 제공합니다. 이를 활용하면 Makefile을 더 간결하게 작성할 수 있습니다.

 

예시:

myprogram: main.o utils.o
	g++ -o $@ $^

# 묵시적 규칙을 사용하여 .o 파일 생성 규칙 생략

 

파일 포함

# 다른 Makefile 포함
include another_makefile.mk

 

조건부 실행

# 조건부 변수 정의
ifeq ($(CC),gcc)
    CFLAGS += -D USING_GCC
endif

# 조건부 명령어 실행
debug: CFLAGS += -DDEBUG -g
debug: build

 

유용한 함수

  • wildcard: 특정 패턴에 맞는 파일 목록을 반환합니다.
  • patsubst: 파일 이름의 패턴을 치환합니다.

 

예시:

SRCS := $(wildcard *.cpp)
OBJS := $(patsubst %.cpp, %.o, $(SRCS))

myprogram: $(OBJS)
	g++ -o $@ $^

 

주석

# 이것은 주석입니다

 

 

참고:

 - https://www.gnu.org/software/make/manual/

 

GNU Make Manual - GNU Project - Free Software Foundation

GNU Make Manual Free Software Foundation last updated February 26, 2023 This manual (make) is available in the following formats: You can buy printed copies of some manuals (among other items) from the Free Software Foundation; this helps support FSF activ

www.gnu.org

- https://devhints.io/makefile

 

Makefile cheatsheet

The one-page guide to Makefile: usage, examples, links, snippets, and more.

devhints.io

- https://www.tutorialspoint.com/makefile/index.htm

 

Unix Makefile Tutorial

Unix Makefile Tutorial - Makefile is a program building tool which runs on Unix, Linux, and their flavors. It aids in simplifying building program executables that may need various modules. To determine how the modules need to be compiled or recompiled tog

www.tutorialspoint.com

 

 

주의: Makefile은 탭 문자 대신 공백을 사용하면 오류가 발생할 수 있습니다.