Makefile to get source files in multiple subdirectories

  c++, g++, gcc, linux, makefile

I am creating a custom Makefile to to build a C++ Linux application. I have my cpp source files in a folder called src on the same level as the Makefile. So far I have been able to build my object files with the following :

$(OBJ_DIR)/%.o: $(SRC_DIR)/%.cpp | $(OBJ_DIR)
    $(CC) $(CPPFLAGS) $(CFLAGS) -c $< -o [email protected] 

Now my project is starting to get a bit more complicated and I want subdirectories within src , such as src/common , and also, not every file is a cpp file now but also a c file.

I guess having a separate Makefile for each subdirectory is the best way but I am trying to keep this simple for now with just one Makefile.

I tried the following but doesn’t work

$(OBJ_DIR)/%.o: $(SRC_DIR)/%.cpp $(SRC_DIR)/common/%.cpp $(SRC_DIR)/common/%.c | $(OBJ_DIR)
    $(CC) $(CPPFLAGS) $(CFLAGS) -c $< -o [email protected]

I could have the Makefile do a shell find to find all cpp and c files but also trying to avoid this.

I’d appreciate any recommendations.

Source: Windows Questions C++