9

ファイルがあるとしましょう:

ライブラリ:

  • one.cpp、one.h
  • 2.cpp、2.h
  • three.cpp、three.h

プログラム:

  • プログラム.cpp

最後のコンパイルから変更された *.cpp のみをコンパイルする Makefile を作成する方法はありますか?

現在、私はそのようなものを持っています:

SRCS = one.cpp two.cpp three.cpp
OBJS = $(SRCS:.cpp=.o)

all: $(OBJS) program

.cpp.o:
    g++ -Wall -c $<

program:
    g++ -Wall $(OBJS) program.cpp -o program

clean:
    rm -f $(OBJS) program

私は問題なく動作しますが、プログラムをコンパイルしてから two.cpp または two.h を変更すると、最初に「make clean」を実行する必要があります。

Nothing to be done for 'all'.

Makefile をそのように変更したいと思います。変更を認識し、そのファイルとその依存関係を再コンパイルします (one.cpp が変更された two.cpp のコードを使用する場合、両方のファイルを再コンパイルする必要があります)。

したがって、two.cpp を変更すると、make は次のようになります。

g++ -Wall -c two.cpp
g++ -Wall $(OBJS) program.cpp -o program

しかし、one.cpp が変更された two.cpp のコードを使用している場合は、次のようにする必要があります。

g++ -Wall -c one.cpp
g++ -Wall -c two.cpp
g++ -Wall $(OBJS) program.cpp -o program
4

3 に答える 3

12

First we make the object files prerequisites of the executable. Once this is done, Make will rebuild program whenever one of the SRCS changes, so we don't need OBJS as an explicit target:

all: program

program: $(OBJS)
  g++ -Wall $(OBJS) program.cpp -o program

Then we make the header files prerequisites of the objects, so that if we change three.h, Make will rebuild three.o:

$(OBJS): %.o : %.h

And finally since one.cpp uses code from two.cpp by means of two.h (I hope), we make two.h a prerequisite of one.o:

one.o: two.h

And to make things cleaner and easier to maintain we use automatic variables:

program: $(OBJS)
  g++ -Wall $^ program.cpp -o $@

Put it all together and we get:

SRCS = one.cpp two.cpp three.cpp
OBJS = $(SRCS:.cpp=.o)

all: program

$(OBJS): %.o : %.h

one.o: two.h

.cpp.o:
  g++ -Wall -c $<

program: $(OBJS)
  g++ -Wall $^ program.cpp -o $@

clean:
  rm -f $(OBJS) program

There are a few more things we could do (like adding program.o to OBJS), but this is enough for today.

于 2010-06-21T19:09:10.123 に答える
1

コマンドが依存して実行するファイルをターゲット名の右側に追加します。

例:

default: hello.c
   gcc -o hello.bin hello.c

install: hello.bin
   cp hello.bin ../
于 2010-06-21T18:44:37.470 に答える
0

必要なのはmake、.o ファイルが .cpp ファイルに依存していることを伝えることだけです。

%.cpp.o: %.cpp
    g++ -Wall -c -o $@ $<
于 2010-06-21T18:56:09.520 に答える