c++objectmakefilelinkerexecutable

C++ Makefile object file doesn't exist. It needs to be manually created


I have the following Makefile for building my C++ application :

SRC_DIR := ./src
OBJ_DIR := ./obj
INC_DIR := -I./include
SRC_FILES := $(wildcard $(SRC_DIR)/*.cpp)
OBJ_FILES := $(patsubst $(SRC_DIR)/%.cpp,$(OBJ_DIR)/%.o,$(SRC_FILES))
CXXFLAGS := -Wall -g

main.exe: $(OBJ_FILES)
    g++ $(LDFLAGS) -o $@ $^

$(OBJ_DIR)/%.o: $(SRC_DIR)/%.cpp
    g++ $(CPPFLAGS) $(CXXFLAGS) $(INC_DIR) -c -o $@ $<

The problem is that I must manually create an obj directory each time. Otherwise make fails on a fresh build with with :

Fatal error: can't create obj/Myclass.o: No such file or directory

How could I solve this so that make can create an obj directory if it doesn't exist?


Solution

  • You can write a makefile rule for that, same as for other files:

    $(OBJ_DIR)/%.o: $(SRC_DIR)/%.cpp | $(OBJ_DIR)
        g++ $(CPPFLAGS) $(CXXFLAGS) $(INC_DIR) -c -o $@ $<
    
    $(OBJ_DIR):
        mkdir -p $@
    

    Putting the dependency after | ensures that it is not part of $^ expansion, should you need it, and its timestamp does not trigger rebuilds.