[ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
룰은 메이크파일에 나타나고, 이것은 언제 어떻게 파일을 다시 만들 것인가에 관해 적혀 있다. 이 만드는 파일을 그 룰의 타겟이라고 한다 (대부분 한 개의 룰에 타겟은 한 개뿐이다). 룰에는 그 타겟의 의존성인 또다른 파일들이 적혀 있고, 그 룰의 타겟을 새로 만들거나 업데이트할 때 쓰는 명령어가 적혀 있다.
기본 골이 결정된다는 점을 제외하면, 룰이 쓰여진 순서는 아무런
의미가 없다: 기본 골은 골을 따로 지정하지 않았을 경우에, make
가
고려하게 되는 타겟이다. 기본 골은 첫번째 메이크파일의 첫번째 룰에 있는
타겟이다. 만약 첫번째 룰에 여러개의 타겟이 있으면, 첫번째 타겟만이
기본으로 취급된다. 여기에 두가지 예외가 있다: 점으로 시작하는 타겟은 그
안에 한개 이상의 슬래쉬(‘/’)가 들어 있지 않는 한 기본 골이 아니다;
또, 패턴 룰을 정의하는 타겟은 기본 골에 영향을 주지 못한다.
(See section 패턴 룰 정의와 재정의.)
그러므로, 우리는 보통 첫번째 룰이 전체 프로그램, 혹은 그 메이크파일에 쓰여진 모든 프로그램을 컴파일하도록 작성한다 (대부분 ‘all’이라고 하는 타겟). See section 골을 지정하는 인자.
[ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
일반적으로, 룰은 다음과 같은 모양이다:
타겟들 : 의존성들 명령어 … |
혹은 다음과 같은 모양이다:
타겟들 : 의존성들 ; 명령어 명령어 … |
타겟들은 공백으로 구분된 파일 이름들이다. 와일드카드 문자도 사용될 수 있고 (see section 파일 이름에 와일드카드 문자 사용하기) ‘a(m)’은 아카이브 파일 a 안의 멤버 m를 뜻한다 (see section 타겟으로 아카이브 멤버). 보통 룰에는 한개의 타겟만이 있지만, 두개 이상의 타겟을 써야 할 필요도 생긴다 (see section 한개의 룰에 여러개의 타겟).
명령어 줄은 탭 문자로 시작한다. 첫번째 명령어가 의존성 다음에 오는 줄에 탭 문자와 함께 나타날 수 있고, 혹은 같은 줄에 세미콜론 다음에 나타날 수 있다. 둘 중에 어떤 방법이든 간에, 그 효과는 동일하다. See section 룰의 명령어 작성하기.
달러 표시는 변수 참조를 시작할 때 쓰이기 때문에, 정말로 룰에 달러 표시를
쓰려면 ‘$$’처럼 달러 문자를 두개 써야 한다 (see section 변수를 사용하는 방법). 백슬래쉬 다음에 줄을 바꾸는 방법으로 긴 줄을
여러개로 쪼갤 수 있지만, 그럴 필요는 없다. make
는 메이크 파일에
있는 줄의 길이에 제한을 두지 않기 때문이다.
룰은 make
에게 두가지 사실을 알려준다: 언제 타겟을 업데이트해야
하는가, 그리고 업데이트해야 할 때 어떻게 그 타겟을 업데이트해야
하는가이다.
업데이트해야 된다는 걸 판단하는 기존은 의존성에서 지정되는데,
의존성은 공백으로 구분된 파일 이름으로 이루어져 있다. (와일드카드와
아카이브 멤버를 (see section Using make
to Update Archive Files) 여기에도 쓸 수 있다.) 타겟은
존재하지 않거나 의존성중의 어느 하나보다도 타겟이 더 오래된 경우에
(최근에 수정된 시각을 비교해서) 그 타겟을 업데이트해야 한다. 타겟
파일의 내용은 의존성에 들어 있는 정보에 기초해서 만들어 진다는 사실에
기초한 것이므로, 의존성중에 하나라도 바뀌면 기존의 타겟 파일의 내용은 더
이상 올바른 내용이 아니다.
업데이트하는 방법은 명령어에 지정되어 있다. 이 명령어 줄은 셸에 의해 (보통 ‘sh’) 실행되지만, 몇가지 추가적인 기능이 있다 (see section 룰의 명령어 작성하기).
[ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
한개의 파일 이름은 와일드카드 문자를 사용해서 여러개의 파일을
지정할 수 있다. make
의 와일드카드 문자는 ‘*’, ‘?’
그리고 ‘[…]’이고, 본 셸(Bourne shell)의 와일드 카드와 동일하다.
예를 들어, ‘*.c’는 파일 이름이 ‘.c’로 끝나는 (현재 디렉토리
안의) 모든 파일들을 나타낸다.
파일이름 맨 앞의 ‘~’ 문자도 특별한 의미를 갖고 있다. 단독으로 쓰이거나, ‘~’ 다음에 슬래쉬가 오면 홈 디렉토리를 나타낸다. 예를 들어 ‘~/bin’은 ‘/home/you/bin’으로 확장된다. ‘~’ 다음에 단어가 오면, 그 문자열은 그 단어와 같은 이름의 사용자의 홈 디렉토리를 뜻한다. 예를 들어 ‘~john/bin’은 ‘/home/john/bin’으로 확장된다. 각 사용자에 대한 홈 디렉토리가 없는 시스템에서는 (MS-DOS나 MS-Windows와 같이), 이 기능은 HOME 환경 변수 값을 통해 가상적으로 동작한다.
와일드카드 확장은 타겟, 의존성, 그리고 명령어에서 자동으로 일어난다
(명령어에서는 셸이 확장한다). 다른 부분에서는, 와일드카드 확장은
명시적으로 wildcard
함수를 사용한 경우에만 일어난다.
와일드 카드의 특별한 기능은 와일드카드 문자 앞에 백슬래쉬를 쓰면 사용하지 않을 수 있다. 즉, ‘foo\*bar’는 ‘foo’, 별표, 그리고 ‘bar’라는 이름의 파일을 뜻한다.
4.2.1 와일드카드 예제 | ||
4.2.2 와일드카드를 사용할 때 함정 | ||
4.2.3 wildcard 함수 |
[ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
와일드카드는 룰의 명령어에서 사용될 수 있는데, 여기서는 셸에 의해서 확장된다. 예를 들어, 다음은 모든 오브젝트 파일을 지우는 룰이다:
clean: rm -f *.o |
와일드카드는 룰의 의존성에서도 유용하다. 메이크 파일에 다음 룰을 쓰면, ‘make print’는 마지막에 프린트한 이후로 바뀐 모든 ‘.c’ 파일을 인쇄한다.
print: *.c lpr -p $? touch print |
이 룰은 ‘print’를 비어 있는 타겟 파일로 사용한다; 이벤트를 기록하는 빈 타겟 파일. (자동 변수 ‘$?’는 바뀐 파일들만을 인쇄하는 데 사용된다; 자동 변수.)
와일드카드 확장은 변수를 정의할 때는 일어나지 않는다. 즉, 다음과 같이 쓰면:
objects = *.o |
변수 objects
의 값은 실제 ‘*.o’라는 문자열이다. 하지만,
objects
의 값을 타겟, 의존성, 혹은 명령어에서 사용하면, 와일드카드
확장이 그 때 일어난다. objects
의 값으로 확장된 값을 넣으려면,
다음과 같이 사용한다:
objects := $(wildcard *.o) |
See section wildcard
함수.
[ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
다음은 와일드카드 확장을 사용하는 단순한 방법으로, 의도한 대로 동작하지 않는다. 실행 파일 ‘foo’가 디렉토리 안의 모든 오브젝트 파일에서부터 만들어 진다고 가정하고, 다음과 같이 쓴다:
objects = *.o foo : $(objects) cc -o foo $(CFLAGS) $(objects) |
objects
의 값은 ‘*.o’라는 실제 문자열이다. 와일드 카드
확장은 ‘foo’를 위한 룰에서 일어나므로, 존재하는 모든
‘.o’ 파일이 ‘foo’의 의존성이 되고, 필요한 경우 재컴파일해야
한다.
하지만 모든 ‘.o’ 파일을 지워버렸다면 어떻게 되는가? 와일드카드가
아무런 파일과도 맞지 않는다면, 그대로 남아 있게 되고, ‘foo’는
‘*.o’라는 잘못된 이름의 파일에 의존하게 된다. 그런 파일은 없을
것이므로, make
는 어떻게 ‘*.o’ 파일을 만들지 모르겠다는 말을
하면서 오류를 낼 것이다. 이것은 원하던 바가 아니다!
실제로 와일드카드 확장에서 원하는 결과를 얻을 수도 있지만,
wildcard
함수와 문자열 치환과 같은 좀더 똑똑한 테크닉이 필요하다.
Microsoft 운영 체제는 (MS-DOS와 MS-Windows) 다음과 같이 경로명에서 디렉토리를 구분하는 데 백슬래쉬를 사용한다:
c:\foo\bar\baz.c |
이것은 유닉스 스타일로 ‘c:/foo/bar/baz.c’와 같다 (‘c:’라는
부분은 소위 말하는 드라이브 문자이다). make
가 이러한 시스템에서
동작할 때, 경로 명에서 유닉스 스타일의 슬래쉬 문자는 물론 백슬래쉬
문자도 지원한다. 하지만, 와일드카드에서는 지원하지 않는다.
와일드카드에서 백슬래쉬는 어떤 문자를 나타내는 이스케이프 문자이다. 즉,
이러한 경우에는 유닉스 스타일의 슬래쉬를 사용해야만 한다.
[ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
wildcard
함수와일드카드 확장은 룰에서 자동으로 일어난다. 하지만 와일드카드 확장은
변수 값을 결정하는 곳이나, 함수의 인자 안에서는 일어나지 않는다. 이러한
장소에서 와일드카드 확장을 하고 싶으면, wildcard
함수를 다음과
같이 사용해야 한다:
$(wildcard 패턴…) |
메이크파일의 어디에서나 사용될 수 있는, 이 문자열은 주어진 파일이름
패턴에 맞는 존재하는 파일들의 이름들을 공백으로 구분한 리스트로
바꾸니다. 어떤 존재하는 파일 이름도 그 패턴과 맞지 않으면, 그 그 패턴은
wildcard
함수의 결과에서 제외된다. 이것은 룰에서 와일드카드가
맞지 않았을 경우의 동작과는 다르다는 점에 주의한다. 룰에서는 맞지 않는
와일드카드는 무시되지 않고, 그 패턴이 그대로 사용된다 (see section 와일드카드를 사용할 때 함정).
wildcard
함수의 한가지 사용예는 디렉토리 내의 모든 C 소스 파일의
리스트를 얻는 것이다. 다음과 같이 한다:
$(wildcard *.c) |
그 결과에서 ‘.c’ 접미어를 ‘.o’로 바꾸면, C 소스 파일의 리스트를 오브젝트 파일의 리스트로 바꿀 수 있다. 다음과 같이 한다:
$(patsubst %.c,%.o,$(wildcard *.c)) |
(여기서 patsubst
라는 또다른 함수를 사용했다. See section 문자열 치환 및 분석을 위한 함수.)
즉, 디렉토리 내의 C 소스 파일을 컴파일해서 링크하는 메이크 파일은 다음과 같다:
objects := $(patsubst %.c,%.o,$(wildcard *.c)) foo : $(objects) cc -o foo $(objects) |
(위의 메이크 파일은 C 프로그램을 컴파일하는 암묵적인 룰을 이용하고 있으므로, 이 C 파일들을 컴파일하는 명시적인 룰을 작성할 필요는 없다. ‘=’의 변형인 ‘:=’에 대한 설명은 See section 변수의 두가지 flavors.)
[ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
큰 시스템에서는, 소스 파일들을 바이너리와는 별도의 디렉토리에 넣는쪽이
좋다. make
의 디렉토리 찾기(directory search) 기능은
의존성을 찾을 때 자동으로 여러개의 디렉토리를 살펴보는 방법으로 이러한
기능을 구현한다. 여러 개의 디렉토리에 파일들을 분산할 때, 각 룰을 바꿀
필요없이, 찾기 경로만 바꾸면 된다.
[ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
VPATH
: 모든 의존성에 대한 찾기 경로make
변수 VPATH
의 값은 make
가 찾아야 할
디렉토리들의 리스트를 지정한다. 가장 많이 쓰이는 것으로, 여기에 있는
디렉토리들은 현재 디렉토리에 없는 의존성 파일이 들어 있을 수 있다;
하지만, VPATH
는 룰의 타겟은 물론이고 make
가 취급하는 모든
파일들을 찾는 데 쓰인다.
즉, 타겟이나 의존성으로 쓰여 있는 파일이 현재 디렉토리에 없으면,
make
는 VPATH
에 쓰인 디렉토리에서 그 이름의 파일을 찾는다.
파일이 이 디렉토리들 중 하나에서 발견되면, 그 파일이 그 의존성이 된다
(아래 참조). 그러면 룰에서 마치 현재 디렉토리에 있는 파일처럼 파일
이름을 의존성으로 쓸 수 있다. See section Writing Shell Commands with Directory Search.
VPATH
변수에서, 디렉토리 이름은 콜론이나 공백으로 구분한다.
디렉토리가 열거된 순서대로 make
는 파일을 찾는다. (MS-DOS와
MS-Windows에서, VPATH
에서 디렉토리 이름을 구분하는 데 세미 콜론이
쓰인다. 왜냐하면 이 시스템에서는 경로명 내에서 드라이브 문자 다음에
콜론이 사용되기 때문이다.)
예를 들어,
VPATH = src:../headers |
는 ‘src’와 ‘../headers’, 두개의 디렉토리를 지정하고,
make
는 이 순서대로 파일을 찾는다.
VPATH
의 값에 따라, 다음 룰,
foo.o : foo.c |
은 다음과 같이 쓰여진 것과 같다:
foo.o : src/foo.c |
이때 ‘foo.c’가 현재 디렉토리에 없고, ‘src’ 디렉토리에 있다고 가정한다
[ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
vpath
DirectiveVPATH
변수와 비슷하지만, 보다 더 선택적인 것츠로 vpath
지시어가 있다 (소문자에 주의). vpath
는 어떤 특정 종류의 파일
이름들(어떤 패턴에 맞는 파일 이름)에 대해서 찾을 경로를 지정한다. 즉,
어떤 종류의 파일 이름에 대해서 찾기 경로를 지정하고, 또 다른 파일 이름은
또 다른 찾기 디렉토리를 지정할 수 있다.
vpath
지시어는 세가지 형태가 있다:
vpath 패턴 디렉토리들
패턴에 맞는 파일 이름들에 대해서 디렉토리들 찾기 경로를 지정한다.
찾기 경로인 디렉토리들은 찾을 디렉토리들의 리스트로, VPATH
변수와 마찬가지로 콜론(MS-DOS와 MS-Windows에선느 세미콜론)이나 공백으로
구분한다.
vpath 패턴
패턴과 관련된 찾기 경로를 지운다.
vpath
vpath
지시어로 전에 지정된 모든 찾기 경로를 지운다.
vpath
의 패턴은 ‘%’ 문자가 들어 있는 문자열이다. 이 문자열은
찾고자 하는 의존성의 파일 이름과 맞아야 하고, ‘%’ 문자는 빈 문자열,
혹은 모든 종류의 문자열에 해당된다 (패턴 룰과 마찬가지이다; see section 패턴 룰 정의 및 재정의). 예를 들어, %.h
는 .h
로
끝나는 모든 파일에 해당된다. (‘%’가 없으면, 패턴은 정확히 같은
의존성에 해당되는데, 이건 대부분의 경우 쓸모가 없다.)
vpath
지시어 패턴의 ‘%’ 문자는 앞에 백슬래쉬(‘\’)를
붙여서 직접 ‘%’ 문자를 쓸 수 있다. ‘%’ 문자를 쓸 때 사용하는
백슬래쉬는 백슬래쉬를 여러개 써서 직접 백슬래쉬 문자를 쓸 수 있다.
‘%’ 문자를 쓰는 백슬래쉬나 그 외의백슬래쉬는 파일 이름과 비교되기
전에 사라진다. ‘%’ 문자를 직접 쓰는데 쓰일 위험이 없는 백슬래쉬는
평온한 상태로 남겨둔다.
어떤 의존성이 현재 디렉토리에 없고, vpath
지시어 내의
패턴이 그 의존성 파일의 이름과 일치한다면, VPATH
변수와
마찬가지로 vpath
지시어 내의 디렉토리들에서 파일을 찾는다.
예를 들어,
vpath %.h ../headers |
라고 쓰면 make
는 ‘.h’로 끝나는 모든 의존성에 대해, 현재
디렉토리 없으면 ‘../headers’ 디렉토리에서 찾는다.
여러개의 vpath
패턴이 해당 의존성 파일이름과 일치한다면,
make
는 각각의 일치하는 vpath
지시어를 하나씩 하나씩
처리해서, 각 지시어에 쓰여 있는 모든 디렉토리에서 그 파일을 찾는다.
make
는 여러개의 vpath
지시어가 있을 때 메이크파일에 나타난
순서로 처리한다; 같은 패턴에 대해 여러개의 지시어를 써도 그 지시어들은
서로 독립적이다.
즉,
vpath %.c foo vpath % blish vpath %.c bar |
라고 쓰면 ‘.c’로 끝나는 파일을, ‘foo’, ‘blish’, 그리고 ‘bar’의 순서대로 찾는다. 한편,
vpath %.c foo:bar vpath % blish |
는 ‘.c’로 끝나는 파일을 ‘foo’, ‘bar’, 그리고 ‘blish’의 순서대로 찾는다.
[ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
어떤 의존성이 디렉토리 찾기를 통해 발견되었을 때, 그 찾기 방법에
관계없이 (일반적인 방법이든 선택적인 방법이든), 찾은 경로명은
make
가 실제로 의존성 리스트에 제공해 주는 경로명이 아닐 수도
있다. 어떤 경우에는 디렉토리 찾기를 통해 발견된 경로가 없어질 수도
있다.
make
가 디렉토리 찾기에서 어떤 경로를 계속 가지고 있을 것인가,
버릴 것인가를 결정하는 알고리즘은 다음과 같다:
make
는 타겟을 다시 빌드할 필요가 없으므로 디렉토리 찾기에서
발견된 경로를 사용한다.
make
가 다시 빌드해야 하는 경우, 그
타겟은 현재 디렉토리에서 만들어 지고, 디렉토리 찾기에서 찾아낸
디렉토리에서 만들어 지지 않는다.
이 알고리즘은 복잡해 보이지만, 실제 대부분의 경우 이것이 사용자가 원하는 동작이다.
다른 버전의 make
는 이보다 간단한 알고리즘을 사용한다: 파일이
없고, 디렉토리 찾기에서 그 파일을 찾으면, 타겟을 다시 빌드해야 하는지
아닌지에 관계없이 언제나 그 경로명이 사용된다. 즉, 타겟을 다시 만들
경우에 디렉토리 찾기에서 발견된 경로에서 그 타겟이 만들어 진다.
사실상 이렇게 동작하는 편이 사용자가 원하는 바일 수도 있다, 이 경우에
GPATH
변수를 사용해서 make
가 이렇게 동작하도록 할 수 있다.
GPATH
는 VPATH
와 문법과 형식이 같다(즉 경로 이름을
공백이나 콜론으로 구분해서 쓴다). 다시 빌드해야 하는 타겟이 디렉토리
찾기에서 발견되고, 그 디렉토리가 GPATH
에 있는 경우, 그 경로명이
버려지지 않는다. 타겟은 디렉토리 찾기에서 발견된 경로에서 다시
빌드된다.
[ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
어떤 디펜던시가 디렉토리 찾기를 통해 찾은 디렉토리 내에 있을 때, 이
디펜던시는 룰의 명령어를 바꿀 수 없다; 다시 말해서 쓰여진 그대로
실행된다. 즉, 명령어를 쓸 때 주의를 기울여 작성해야만 make
가 그
찾아낸 디렉토리 안에 있는 디펜던시를 명령어에 쓸 수 있다.
이런 목적을 위해 ‘$^’와 같은 자동 변수가 있다 (see section Automatic Variables). 예를 들면, ‘$^’의 값은 룰의 모든 디펜던시의 리스트로, 각각의 디펜던시는 디렉토리 찾기를 통해 찾아진 디렉토리의 이름도 포함한다. 또 한가지 예로, 자동 변수 ‘$@’의 값은 타겟이다. 즉:
foo.o : foo.c cc -c $(CFLAGS) $^ -o $@ |
(CFLAGS
변수는 내포적인 룰에서 C 컴파일에 사용할 플래그들을
지정하는 변수이다; 우리는 모든 C 컴파일과정에 적용될 수 있도록 여기서 이
변수를 사용했다;
see section Variables Used by Implicit Rules.)
어떤 경우에는 디펜던시에는 헤더 파일도 포함되어 있고, 이 헤더 파일은 위 명령에서 쓰면 안 된다. 자동 변수 ‘$<’는 첫번째 디펜던시를 가리킨다:
VPATH = src:../headers foo.o : foo.c defs.h hack.h cc -c $(CFLAGS) $< -o $@ |
[ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The search through the directories specified in VPATH
or with
vpath
also happens during consideration of implicit rules
(see section Using Implicit Rules).
For example, when a file ‘foo.o’ has no explicit rule, make
considers implicit rules, such as the built-in rule to compile
‘foo.c’ if that file exists. If such a file is lacking in the
current directory, the appropriate directories are searched for it. If
‘foo.c’ exists (or is mentioned in the makefile) in any of the
directories, the implicit rule for C compilation is applied.
The commands of implicit rules normally use automatic variables as a matter of necessity; consequently they will use the file names found by directory search with no extra effort.
[ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Directory search applies in a special way to libraries used with the linker. This special feature comes into play when you write a dependency whose name is of the form ‘-lname’. (You can tell something strange is going on here because the dependency is normally the name of a file, and the file name of the library looks like ‘libname.a’, not like ‘-lname’.)
When a dependency’s name has the form ‘-lname’, make
handles it specially by searching for the file ‘libname.a’ in
the current directory, in directories specified by matching vpath
search paths and the VPATH
search path, and then in the
directories ‘/lib’, ‘/usr/lib’, and ‘prefix/lib’
(normally ‘/usr/local/lib’, but MS-DOS/MS-Windows versions of
make
behave as if prefix is defined to be the root of the
DJGPP installation tree).
For example,
foo : foo.c -lcurses cc $^ -o $@ |
would cause the command ‘cc foo.c /usr/lib/libcurses.a -o foo’ to be executed when ‘foo’ is older than ‘foo.c’ or than ‘/usr/lib/libcurses.a’.
[ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
포니 타겟은 파일 이름이 아닌 타겟이다.
A phony target is one that is not really the name of a file. It is just a name for some commands to be executed when you make an explicit request. There are two reasons to use a phony target: to avoid a conflict with a file of the same name, and to improve performance.
If you write a rule whose commands will not create the target file, the commands will be executed every time the target comes up for remaking. Here is an example:
clean: rm *.o temp |
Because the rm
command does not create a file named ‘clean’,
probably no such file will ever exist. Therefore, the rm
command
will be executed every time you say ‘make clean’.
The phony target will cease to work if anything ever does create a file
named ‘clean’ in this directory. Since it has no dependencies, the
file ‘clean’ would inevitably be considered up to date, and its
commands would not be executed. To avoid this problem, you can explicitly
declare the target to be phony, using the special target .PHONY
(see section Special Built-in Target Names) as follows:
.PHONY : clean |
Once this is done, ‘make clean’ will run the commands regardless of whether there is a file named ‘clean’.
Since it knows that phony targets do not name actual files that could be
remade from other files, make
skips the implicit rule search for
phony targets (see section 암묵적인 룰 사용하기). This is why declaring a target
phony is good for performance, even if you are not worried about the
actual file existing.
Thus, you first write the line that states that clean
is a
phony target, then you write the rule, like this:
.PHONY: clean clean: rm *.o temp |
A phony target should not be a dependency of a real target file; if it
is, its commands are run every time make
goes to update that
file. As long as a phony target is never a dependency of a real
target, the phony target commands will be executed only when the phony
target is a specified goal (see section Arguments to Specify the Goals).
Phony targets can have dependencies. When one directory contains multiple programs, it is most convenient to describe all of the programs in one makefile ‘./Makefile’. Since the target remade by default will be the first one in the makefile, it is common to make this a phony target named ‘all’ and give it, as dependencies, all the individual programs. For example:
all : prog1 prog2 prog3 .PHONY : all prog1 : prog1.o utils.o cc -o prog1 prog1.o utils.o prog2 : prog2.o cc -o prog2 prog2.o prog3 : prog3.o sort.o utils.o cc -o prog3 prog3.o sort.o utils.o |
Now you can say just ‘make’ to remake all three programs, or specify as arguments the ones to remake (as in ‘make prog1 prog3’).
When one phony target is a dependency of another, it serves as a subroutine of the other. For example, here ‘make cleanall’ will delete the object files, the difference files, and the file ‘program’:
.PHONY: cleanall cleanobj cleandiff cleanall : cleanobj cleandiff rm program cleanobj : rm *.o cleandiff : rm *.diff |
[ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
If a rule has no dependencies or commands, and the target of the rule
is a nonexistent file, then make
imagines this target to have
been updated whenever its rule is run. This implies that all targets
depending on this one will always have their commands run.
An example will illustrate this:
clean: FORCE rm $(objects) FORCE: |
Here the target ‘FORCE’ satisfies the special conditions, so the target ‘clean’ that depends on it is forced to run its commands. There is nothing special about the name ‘FORCE’, but that is one name commonly used this way.
As you can see, using ‘FORCE’ this way has the same results as using ‘.PHONY: clean’.
Using ‘.PHONY’ is more explicit and more efficient. However,
other versions of make
do not support ‘.PHONY’; thus
‘FORCE’ appears in many makefiles. See section 포니 타겟.
[ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The empty target is a variant of the phony target; it is used to hold commands for an action that you request explicitly from time to time. Unlike a phony target, this target file can really exist; but the file’s contents do not matter, and usually are empty.
The purpose of the empty target file is to record, with its
last-modification time, when the rule’s commands were last executed. It
does so because one of the commands is a touch
command to update the
target file.
The empty target file must have some dependencies. When you ask to remake the empty target, the commands are executed if any dependency is more recent than the target; in other words, if a dependency has changed since the last time you remade the target. Here is an example:
print: foo.c bar.c lpr -p $? touch print |
With this rule, ‘make print’ will execute the lpr
command if
either source file has changed since the last ‘make print’. The
automatic variable ‘$?’ is used to print only those files that have
changed (see section Automatic Variables).
[ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Certain names have special meanings if they appear as targets.
.PHONY
The dependencies of the special target .PHONY
are considered to
be phony targets. When it is time to consider such a target,
make
will run its commands unconditionally, regardless of
whether a file with that name exists or what its last-modification
time is. See section Phony Targets.
.SUFFIXES
The dependencies of the special target .SUFFIXES
are the list
of suffixes to be used in checking for suffix rules.
See section Old-Fashioned Suffix Rules.
.DEFAULT
The commands specified for .DEFAULT
are used for any target for
which no rules are found (either explicit rules or implicit rules).
See section Defining Last-Resort Default Rules. If .DEFAULT
commands are specified, every
file mentioned as a dependency, but not as a target in a rule, will have
these commands executed on its behalf. See section Implicit Rule Search Algorithm.
.PRECIOUS
The targets which .PRECIOUS
depends on are given the following
special treatment: if make
is killed or interrupted during the
execution of their commands, the target is not deleted.
See section Interrupting or Killing make
.
Also, if the target is an intermediate file, it will not be deleted
after it is no longer needed, as is normally done.
See section Chains of Implicit Rules.
You can also list the target pattern of an implicit rule (such as
‘%.o’) as a dependency file of the special target .PRECIOUS
to preserve intermediate files created by rules whose target patterns
match that file’s name.
.INTERMEDIATE
The targets which .INTERMEDIATE
depends on are treated as
intermediate files. See section Chains of Implicit Rules.
.INTERMEDIATE
with no dependencies marks all file targets
mentioned in the makefile as intermediate.
.SECONDARY
The targets which .SECONDARY
depends on are treated as
intermediate files, except that they are never automatically deleted.
See section Chains of Implicit Rules.
.SECONDARY
with no dependencies marks all file targets mentioned
in the makefile as secondary.
.IGNORE
If you specify dependencies for .IGNORE
, then make
will
ignore errors in execution of the commands run for those particular
files. The commands for .IGNORE
are not meaningful.
If mentioned as a target with no dependencies, .IGNORE
says to
ignore errors in execution of commands for all files. This usage of
‘.IGNORE’ is supported only for historical compatibility. Since
this affects every command in the makefile, it is not very useful; we
recommend you use the more selective ways to ignore errors in specific
commands. See section Errors in Commands.
.SILENT
If you specify dependencies for .SILENT
, then make
will
not the print commands to remake those particular files before executing
them. The commands for .SILENT
are not meaningful.
If mentioned as a target with no dependencies, .SILENT
says not
to print any commands before executing them. This usage of
‘.SILENT’ is supported only for historical compatibility. We
recommend you use the more selective ways to silence specific commands.
See section Command Echoing. If you want to silence all commands
for a particular run of make
, use the ‘-s’ or
‘--silent’ option (see section Summary of Options).
.EXPORT_ALL_VARIABLES
Simply by being mentioned as a target, this tells make
to
export all variables to child processes by default.
See section Communicating Variables to a Sub-make
.
Any defined implicit rule suffix also counts as a special target if it appears as a target, and so does the concatenation of two suffixes, such as ‘.c.o’. These targets are suffix rules, an obsolete way of defining implicit rules (but a way still widely used). In principle, any target name could be special in this way if you break it in two and add both pieces to the suffix list. In practice, suffixes normally begin with ‘.’, so these special target names also begin with ‘.’. See section Old-Fashioned Suffix Rules.
[ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
A rule with multiple targets is equivalent to writing many rules, each with one target, and all identical aside from that. The same commands apply to all the targets, but their effects may vary because you can substitute the actual target name into the command using ‘$@’. The rule contributes the same dependencies to all the targets also.
This is useful in two cases.
kbd.o command.o files.o: command.h |
gives an additional dependency to each of the three object files mentioned.
bigoutput littleoutput : text.g generate text.g -$(subst output,,$@) > $@ |
is equivalent to
bigoutput : text.g generate text.g -big > bigoutput littleoutput : text.g generate text.g -little > littleoutput |
Here we assume the hypothetical program generate
makes two
types of output, one if given ‘-big’ and one if given
‘-little’.
See section Functions for String Substitution and Analysis,
for an explanation of the subst
function.
Suppose you would like to vary the dependencies according to the target, much as the variable ‘$@’ allows you to vary the commands. You cannot do this with multiple targets in an ordinary rule, but you can do it with a static pattern rule. See section Static Pattern Rules.
[ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
One file can be the target of several rules. All the dependencies mentioned in all the rules are merged into one list of dependencies for the target. If the target is older than any dependency from any rule, the commands are executed.
There can only be one set of commands to be executed for a file.
If more than one rule gives commands for the same file,
make
uses the last set given and prints an error message.
(As a special case, if the file’s name begins with a dot, no
error message is printed. This odd behavior is only for
compatibility with other implementations of make
.)
There is no reason to
write your makefiles this way; that is why make
gives you
an error message.
An extra rule with just dependencies can be used to give a few extra
dependencies to many files at once. For example, one usually has a
variable named objects
containing a list of all the compiler output
files in the system being made. An easy way to say that all of them must
be recompiled if ‘config.h’ changes is to write the following:
objects = foo.o bar.o foo.o : defs.h bar.o : defs.h test.h $(objects) : config.h |
This could be inserted or taken out without changing the rules that really specify how to make the object files, making it a convenient form to use if you wish to add the additional dependency intermittently.
Another wrinkle is that the additional dependencies could be specified with
a variable that you set with a command argument to make
(see section Overriding Variables). For example,
extradeps= $(objects) : $(extradeps) |
means that the command ‘make extradeps=foo.h’ will consider ‘foo.h’ as a dependency of each object file, but plain ‘make’ will not.
If none of the explicit rules for a target has commands, then make
searches for an applicable implicit rule to find some commands
see section Using Implicit Rules).
[ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Static pattern rules are rules which specify multiple targets and construct the dependency names for each target based on the target name. They are more general than ordinary rules with multiple targets because the targets do not have to have identical dependencies. Their dependencies must be analogous, but not necessarily identical.
4.10.1 Syntax of Static Pattern Rules | ||
4.10.2 Static Pattern Rules versus Implicit Rules |
[ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Here is the syntax of a static pattern rule:
targets …: target-pattern: dep-patterns … 명령어 … |
The targets list specifies the targets that the rule applies to. The targets can contain wildcard characters, just like the targets of ordinary rules (see section Using Wildcard Characters in File Names).
The target-pattern and dep-patterns say how to compute the dependencies of each target. Each target is matched against the target-pattern to extract a part of the target name, called the stem. This stem is substituted into each of the dep-patterns to make the dependency names (one from each dep-pattern).
Each pattern normally contains the character ‘%’ just once. When the target-pattern matches a target, the ‘%’ can match any part of the target name; this part is called the stem. The rest of the pattern must match exactly. For example, the target ‘foo.o’ matches the pattern ‘%.o’, with ‘foo’ as the stem. The targets ‘foo.c’ and ‘foo.out’ do not match that pattern.
The dependency names for each target are made by substituting the stem for the ‘%’ in each dependency pattern. For example, if one dependency pattern is ‘%.c’, then substitution of the stem ‘foo’ gives the dependency name ‘foo.c’. It is legitimate to write a dependency pattern that does not contain ‘%’; then this dependency is the same for all targets.
‘%’ characters in pattern rules can be quoted with preceding backslashes (‘\’). Backslashes that would otherwise quote ‘%’ characters can be quoted with more backslashes. Backslashes that quote ‘%’ characters or other backslashes are removed from the pattern before it is compared to file names or has a stem substituted into it. Backslashes that are not in danger of quoting ‘%’ characters go unmolested. For example, the pattern ‘the\%weird\\%pattern\\’ has ‘the%weird\’ preceding the operative ‘%’ character, and ‘pattern\\’ following it. The final two backslashes are left alone because they cannot affect any ‘%’ character.
Here is an example, which compiles each of ‘foo.o’ and ‘bar.o’ from the corresponding ‘.c’ file:
objects = foo.o bar.o all: $(objects) $(objects): %.o: %.c $(CC) -c $(CFLAGS) $< -o $@ |
Here ‘$<’ is the automatic variable that holds the name of the dependency and ‘$@’ is the automatic variable that holds the name of the target; see Automatic Variables.
Each target specified must match the target pattern; a warning is issued
for each target that does not. If you have a list of files, only some of
which will match the pattern, you can use the filter
function to
remove nonmatching file names (see section Functions for String Substitution and Analysis):
files = foo.elc bar.o lose.o $(filter %.o,$(files)): %.o: %.c $(CC) -c $(CFLAGS) $< -o $@ $(filter %.elc,$(files)): %.elc: %.el emacs -f batch-byte-compile $< |
In this example the result of ‘$(filter %.o,$(files))’ is ‘bar.o lose.o’, and the first static pattern rule causes each of these object files to be updated by compiling the corresponding C source file. The result of ‘$(filter %.elc,$(files))’ is ‘foo.elc’, so that file is made from ‘foo.el’.
Another example shows how to use $*
in static pattern rules:
bigoutput littleoutput : %output : text.g generate text.g -$* > $@ |
When the generate
command is run, $*
will expand to the
stem, either ‘big’ or ‘little’.
[ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
A static pattern rule has much in common with an implicit rule defined as a
pattern rule (see section Defining and Redefining Pattern Rules).
Both have a pattern for the target and patterns for constructing the
names of dependencies. The difference is in how make
decides
when the rule applies.
An implicit rule can apply to any target that matches its pattern, but it does apply only when the target has no commands otherwise specified, and only when the dependencies can be found. If more than one implicit rule appears applicable, only one applies; the choice depends on the order of rules.
By contrast, a static pattern rule applies to the precise list of targets that you specify in the rule. It cannot apply to any other target and it invariably does apply to each of the targets specified. If two conflicting rules apply, and both have commands, that’s an error.
The static pattern rule can be better than an implicit rule for these reasons:
make
to use the wrong implicit rule. The choice
might depend on the order in which the implicit rule search is done.
With static pattern rules, there is no uncertainty: each rule applies
to precisely the targets specified.
[ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Double-colon rules are rules written with ‘::’ instead of ‘:’ after the target names. They are handled differently from ordinary rules when the same target appears in more than one rule.
When a target appears in multiple rules, all the rules must be the same type: all ordinary, or all double-colon. If they are double-colon, each of them is independent of the others. Each double-colon rule’s commands are executed if the target is older than any dependencies of that rule. This can result in executing none, any, or all of the double-colon rules.
Double-colon rules with the same target are in fact completely separate from one another. Each double-colon rule is processed individually, just as rules with different targets are processed.
The double-colon rules for a target are executed in the order they appear in the makefile. However, the cases where double-colon rules really make sense are those where the order of executing the commands would not matter.
Double-colon rules are somewhat obscure and not often very useful; they provide a mechanism for cases in which the method used to update a target differs depending on which dependency files caused the update, and such cases are rare.
Each double-colon rule should specify commands; if it does not, an implicit rule will be used if one applies. See section Using Implicit Rules.
[ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
In the makefile for a program, many of the rules you need to write often
say only that some object file depends on some header
file. For example, if ‘main.c’ uses ‘defs.h’ via an
#include
, you would write:
main.o: defs.h |
You need this rule so that make
knows that it must remake
‘main.o’ whenever ‘defs.h’ changes. You can see that for a
large program you would have to write dozens of such rules in your
makefile. And, you must always be very careful to update the makefile
every time you add or remove an #include
.
To avoid this hassle, most modern C compilers can write these rules for
you, by looking at the #include
lines in the source files.
Usually this is done with the ‘-M’ option to the compiler.
For example, the command:
cc -M main.c |
generates the output:
main.o : main.c defs.h |
Thus you no longer have to write all those rules yourself. The compiler will do it for you.
Note that such a dependency constitutes mentioning ‘main.o’ in a
makefile, so it can never be considered an intermediate file by implicit
rule search. This means that make
won’t ever remove the file
after using it; see section Chains of Implicit Rules.
With old make
programs, it was traditional practice to use this
compiler feature to generate dependencies on demand with a command like
‘make depend’. That command would create a file ‘depend’
containing all the automatically-generated dependencies; then the
makefile could use include
to read them in (see section 다른 메이크파일 포함하기).
In GNU make
, the feature of remaking makefiles makes this
practice obsolete—you need never tell make
explicitly to
regenerate the dependencies, because it always regenerates any makefile
that is out of date. See section 메이크파일 다시 만드는 법.
The practice we recommend for automatic dependency generation is to have one makefile corresponding to each source file. For each source file ‘name.c’ there is a makefile ‘name.d’ which lists what files the object file ‘name.o’ depends on. That way only the source files that have changed need to be rescanned to produce the new dependencies.
Here is the pattern rule to generate a file of dependencies (i.e., a makefile) called ‘name.d’ from a C source file called ‘name.c’:
%.d: %.c $(SHELL) -ec '$(CC) -M $(CPPFLAGS) $< \ | sed '\''s/\($*\)\.o[ :]*/\1.o $@ : /g'\'' > $@; \ [ -s $@ ] || rm -f $@' |
See section Defining and Redefining Pattern Rules, for information on defining pattern rules. The
‘-e’ flag to the shell makes it exit immediately if the
$(CC)
command fails (exits with a nonzero status). Normally the
shell exits with the status of the last command in the pipeline
(sed
in this case), so make
would not notice a nonzero
status from the compiler.
With the GNU C compiler, you may wish to use the ‘-MM’ flag instead of ‘-M’. This omits dependencies on system header files. See (gcc.info)Preprocessor Options section ‘Options Controlling the Preprocessor’ in Using GNU CC, for details.
The purpose of the sed
command is to translate (for example):
main.o : main.c defs.h |
into:
main.o main.d : main.c defs.h |
This makes each ‘.d’ file depend on all the source and header files
that the corresponding ‘.o’ file depends on. make
then
knows it must regenerate the dependencies whenever any of the source or
header files changes.
Once you’ve defined the rule to remake the ‘.d’ files,
you then use the include
directive to read them all in.
See section 다른 메이크파일 포함하기. For example:
sources = foo.c bar.c include $(sources:.c=.d) |
(This example uses a substitution variable reference to translate the
list of source files ‘foo.c bar.c’ into a list of dependency
makefiles, ‘foo.d bar.d’. See section Substitution References, for full
information on substitution references.) Since the ‘.d’ files are
makefiles like any others, make
will remake them as necessary
with no further work from you. See section 메이크파일 다시 만드는 법.
[ << ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
This document was generated by Autobuild on June 15, 2016 using texi2html 1.82.