admin 管理员组

文章数量: 1086019

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?

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?

Share Improve this question asked Mar 27 at 10:52 Engineer999Engineer999 4,0478 gold badges42 silver badges95 bronze badges 1
  • The other option is to add the directory creation into the %.o rule; before the g++ command you add a command line mkdir -p $(@D) – MadScientist Commented Mar 27 at 13:49
Add a comment  | 

1 Answer 1

Reset to default 6

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.

本文标签: C Makefile object file doesn39t exist It needs to be manually createdStack Overflow