How to define rules in the Makefile to compile only that *.cpp files which was modified (and their dependencies), not all *.cpp files

后端 未结 3 642
陌清茗
陌清茗 2021-02-08 22:56

Lets say I have files:

Libs:

  • one.cpp, one.h
  • two.cpp, two.h
  • three.cpp, three.h

Program:

  • program.cpp
相关标签:
3条回答
  • 2021-02-08 23:09

    Add the files a command depends upon to run to the right of the target name.

    Example:

    default: hello.c
       gcc -o hello.bin hello.c
    
    install: hello.bin
       cp hello.bin ../
    
    0 讨论(0)
  • 2021-02-08 23:11

    All you need to do is tell make that the .o file depends on the .cpp file:

    %.cpp.o: %.cpp
        g++ -Wall -c -o $@ $<
    
    0 讨论(0)
  • 2021-02-08 23:16

    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.

    0 讨论(0)
提交回复
热议问题