Example makefile for building simple c project recompiling when headers change

前端 未结 2 383
梦谈多话
梦谈多话 2021-01-15 00:26

Does anyone have a complete makefile that can do the following:

  1. Rebuilds the project if a HEADER file changes
  2. The cpp files are listed in the makefile
相关标签:
2条回答
  • 2021-01-15 01:00
    CXX = g++
    
    OBJECTS := main.o C1.o C2.o
    
    all: $(OBJECTS)
    
    %.o : %.cpp
        $(CXX) $(CPPFLAGS) -Wall -MMD -c $< -o $@
    
    -include *.d
    

    EDIT: As TobySpeight points out, this won't work if you build an object file, rename or delete one of the prerequisite source or header files, then try to rebuild the object file; the .d file will still require the missing file, and the build will fail. I neglected to include lines to deal with that case:

    %.h: ;
    %.cpp: ;
    

    (This is effective, but crude. The more precise approach is to put some sed commands in the %.o rule, so as to add specific null rules to the .d file, one for each prerequisite, but the sed commands are ugly, and the approach above is good enough for almost all cases.)

    0 讨论(0)
  • 2021-01-15 01:07

    You can also use CMake for this. Everything you need to write is:

    add_executable (exec main.cpp C1.cpp C2.cpp)
    
    0 讨论(0)
提交回复
热议问题