2011-01-12 4 views
8

여러 실행 파일에서 사용하는 공통 코드 (예 : hello.cpp)가 있습니다. 나는 모두를 구축하는 하나의 Makefile을 사용하고 있습니다 :여러 실행 파일에 대한 Makefile 단순화에 대한 도움말

EXE=app1.out app2.out 
SRC=hello.cpp 
OBJ=$(SRC:.cpp=.o) 
SRC_MAIN=app1.cpp app2.cpp 
OBJ_MAIN=$(SRC_MAIN:.cpp=.o) 
all: $(EXE)  
app1.out: app1.o $(OBJ) 
    g++ $< $(OBJ) -o [email protected]  
app2.out: app2.o $(OBJ) 
    g++ $< $(OBJ) -o [email protected]  
.cpp.o: 
    g++ -c $< -o [email protected]  
clean: 
    rm -f $(EXE) $(OBJ) $(OBJ_MAIN) 

나는 각 실행에 대한 별도의 목표를 가진 매우 행복하지 않다 - 대상은 본질적으로 동일합니다. 모든 실행 파일에 대해 하나의 대상으로이 작업을 수행 할 수있는 방법이 있습니까? 나는이 같은 작업 것이라고 기대했다 :

EXE=app1.out app2.out 
SRC=hello.cpp 
OBJ=$(SRC:.cpp=.o) 
SRC_MAIN=app1.cpp app2.cpp 
OBJ_MAIN=$(SRC_MAIN:.cpp=.o) 
all: $(EXE) 
.o.out: $(OBJ) 
    g++ $< $(OBJ) -o [email protected] 
.cpp.o: 
    g++ -c $< -o [email protected] 
clean: 
    rm -f $(EXE) $(OBJ) $(OBJ_MAIN) 

그러나 나는 연결 오류가 발생합니다 :

[email protected]:~/cpp/stack$ make -f Makefile2 
g++ -c app1.cpp -o app1.o 
g++ app1.o hello.o -o app1.out 
g++: hello.o: No such file or directory 
make: *** [app1.out] Error 1 
rm app1.o 

를 그것의 의존성 hello.o을 구축하지 않고 app1.out를 구축하려고 어떤 이유로. 왜 이것이 작동하지 않는지 설명 할 수있는 사람이 있습니까?

나머지 코드는 다음과 같습니다.

app1.cpp :

#include "hello.h" 
int 
main(void) 
{ 
    print_hello(); 
} 

app2.cpp :

#include "hello.h"  
int 
main(void) 
{ 
    for (int i = 0; i < 4; ++i) 
     print_hello(); 
    return 0; 
} 

아래 hello.c :

#include "hello.h"  
#include <stdio.h>  
void 
print_hello() 
{ 
    printf("hello world!\n"); 
} 

hello.h :

#ifndef HELLO_H 
#define HELLO_H 
void 
print_hello(); 
#endif 

답변

4

이전 스타일의 접미사 규칙을 사용하고있는 것으로 문제가 나타납니다. 메이크 정보에서 :

Suffix rules cannot have any prerequisites of their own. If they have any, they are treated as normal files with funny names, not as suffix rules. Thus, the rule:

.c.o: foo.h 
      $(CC) -c $(CFLAGS) $(CPPFLAGS) -o [email protected] $< 

tells how to make the file '.c.o' from the prerequisite file 'foo.h', and is not at all like the pattern rule:

%.o: %.c foo.h 
      $(CC) -c $(CFLAGS) $(CPPFLAGS) -o [email protected] $< 

which tells how to make '.o' files from '.c' files, and makes all '.o' files using this pattern rule also depend on 'foo.h'.

이 솔루션은 새로운 스타일의 패턴 규칙을 사용하는 것입니다

%.out: %.o $(OBJ) 
    g++ $< $(OBJ) -o [email protected] 
%.o: %.cpp 
    g++ -c $< -o [email protected] 

(또한이 규칙을 .O하는 .CPP을 정의 할 필요가 없습니다 있습니다; make 합리적인 기본값이 있습니다.)

+0

답장을 보내 주셔서 감사합니다. 컴파일러에 커스텀'CPPFLAGS'를 제공하기 위해 .cpp를 .o 규칙에 사용합니다. 내가 간단한 것을 유지하기 때문에 나는 샘플 코드에서 그들을 보여주지 않았다. 기본값을 "make"해도 "default"변수 이름 (예 :'CFLAGS','CPPFLAGS', LDFLAGS' 등)이 포함됩니까? – misha

+1

예, 'CPPFLAGS'는 C 프리 프로세서 용입니다. 'CXXFLAGS'는 C++ 플래그입니다. –