Question

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
  3. The header files are NOT listed in the makefile
  4. The header files are allowed to have different names than the cpp files
  5. Some of the cpp files do not have header files

I have seen instructions for figuring out how to make the make tool figure out header dependencies, but none of these instructions provide anything remotely resembling a working example. A simple example would be as follows: main.cpp C1.cpp C1.h C2.cpp C2.h

Was it helpful?

Solution

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.)

OTHER TIPS

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

add_executable (exec main.cpp C1.cpp C2.cpp)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top