Software/Dev Tools

GNU make utility 기본 이해 (feat.makefile)

neovaga 2021. 7. 5. 00:21
반응형

makefile 을 읽을 줄 알아야 프로젝트에서 코드를 컴파일 하고 실행파일을 만들수 . 최소한 읽을 줄 알고 자신만의 makefile을 정리해 두고 계속 사용하면 된다.

 

Overview:

GNU make - Richard Stallman, Roland McGrath 구현을 했다. Verisoin 3.76 이후는 Paul D.Smith 가 유지보수를 한다. 

- Make 유틸은 대형 프로젝트에서 재컴파일이 필요한 부분을 자동으로 결정을 해서 빌드를 해 준다.

- makefile 은 make 를 호출 했을때 불려오게 되고 어떻게 컴파일을 하고 링크를 하는지 결정을 하게 된다. 

- Run and compile your programs more efficiently with this handy automation tool. 

 

기본 규칙 makefile: 

target: prerequisites

<TAB> recipe

#makefile
hello:
    echo "Hello. Jay"

//Output:
➜  01_Makefile make
echo "Hello Jay"
Hello Jay

➜  01_Makefile make hello
echo "Hello Jay"
Hello Jay

hello는 동작을 하는 함수이름이라고 보면 되고 prerequisites 가 없다는건 전제조건이 없고 recipe인 명령어를 실행을 하게 된다. 

#target: prerequisites
# recipe
all: hello generate

hello:
@echo "Hello Jay"

generate:
@echo "Creating text files"
touch file-{1..10}.txt
#clean 이란 파일이 존재하면 target clean 은 실행이 안된다.
#.PHONY: clean
clean:
@echo "Cleaning up"
rm *.txt

//Output:
➜  01_Makefile make
Hello Jay
Creating text files
touch file-{1..10}.txt

➜  01_Makefile ls
clean       file-10.txt file-3.txt  file-5.txt  file-7.txt  file-9.txt
file-1.txt  file-2.txt  file-4.txt  file-6.txt  file-8.txt  makefile

➜  01_Makefile make clean
make: `clean' is up to date.

// 해당 문제는 .PHONY: clean 의 주석을 풀어서 선언을 해주면 해결이 된다. 

@ 는 에코를 표시 하지 않게 하는 명령어이다. 

.PHONY 는 가짜를 의미하는 명령어이다. 타켓과 동일한 파일이름이 있으면 make가 실행이 되지 않는다. 그래서 terget 이름을 PHONY: 로 정의를 해주면 파일존재와 상관없이 실행이 가능하다. 

# Usage:
# make 
# make clean # remove ALL binaries and objects

.PHONY = all clean

CC := gcc
#complie option
#CFLAGS = -W
#"-l": link a libarary, "m": the math library
LINKERFLAG = -lm

#wildcard is allowed in target and prerequisites(depencies)
SRCS := $(wildcard *.c)
BINS := $(SRCS:%.c=%)

all: ${BINS}

# "$@": 현재 타켓, The filename representing the target
# "$^": 모든 전제 조건 파일, The filename of all the prerequisites
# "$<": 첫 전제 조건 파일, The filename of the first prerequisite.
%: %.o
@echo "Checking"
${CC} ${LINKERFLAG} $< -o $@

%.o: %.c
@echo "Creating object"
${CC} -c $<

clean:
@echo "Ceaning"
rm -rvf *.o ${BINS}

위와 같이 기존 makefile을 만들어 두면 현재 폴더에 *.c 파일은 한번의 빌드가 끝난 상태에서 *.o 파일이 생성이 되어 있다면 새롭게 변경된 내용을 빌드를 하게 되고 object를 다시 만들어 주게 되는 makefile의 역할을 하게 된다. 

 

전체 메뉴얼은 아래 링크에서 확인하면 된다. 

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

 

반응형