单个Makefile,用于多个子目录中的源

问题描述 投票:1回答:1

在我的C ++项目中,源代码在src目录中组织。在src目录中是子目录,它们都包含头文件和源文件,例如

project
├── Makefile
│
├── MyBinary
│
├── src
│    │
│    ├── main.cpp
│    │
│    ├── Application
│    │      │
│    │      ├── Application.h
│    │      └── Application.cpp
│    │      
│    │
│    └── Tasks
│           ├── BackgroundWorker.h
│           └── BackgroundWorker.cpp
│
└── obj
     ├── Application.o
     └── BackgroungWorker.o

我正在尝试创建一个Makefile,以便在obj目录中创建所有目标文件,并在src目录上创建可执行文件MyBinary,与Makefile相同。

它不能太复杂或自动化。我不介意手动指定Makefile中的每个.cpp和.h文件。

但我是Makefiles的新手,不幸的是我正在努力尝试这个:

CXX=c++
CXXFLAGS=-Wall -Os -g0

# Name of the output binary
APPNAME=MyBinary

# Source root directory
SRC_ROOT=src

# Object file directory
OBJ_DIR=obj

DEPS=$(SRC_ROOT)/Application/Application.h \
     $(SRC_ROOT)/Tasks/BackgroundWorker.h

_OBJ=$(SRC_ROOT)/Application/Application.o \
    $(SRC_ROOT)/Tasks/BackgroundWorker.o\
    $(SRC_ROOT)/main.o

OBJ=$(patsubst %,$(OBJ_DIR)/%,$(_OBJ))

# This rule says that the .o file depends upon the .c version of the 
# file and the .h files included in the DEPS macro.
$(OBJ_DIR)/%.o: %.cpp $(DEPS)
  $(CXX) -c -o $@ $< $(CXXFLAGS)

# Build the application.
# NOTE: The $@ represents the left side of the colon, here $(APPNAME)
#       The $^ represents the right side of the colon, here $(OBJ)
$(APPNAME): $(OBJ)
  $(CXX) -o $@ $^ $(CXXFLAGS)

clean:
  rm -f $(OBJ_DIR)/*.o $(APPNAME)

调用make时的错误是:致命错误:无法创建obj / src / Application.o:找不到文件或目录。

有人可以帮忙吗?

c++ makefile subdirectory
1个回答
1
投票

OBJ=$(patsubst %,$(OBJ_DIR)/%,$(_OBJ))obj/置于_OBJ的话语之前。你想用src取代obj,你可以做些什么

OBJ=$(patsubst $(SRC_ROOT)/%,$(OBJ_DIR)/%,$(_OBJ))

请注意,您希望子目录ApplicationTasksobj的目录结构必须在调用make或更新Makefile以创建它们之前手动创建它们。

这是预先创建目录结构时的行为。

APPNAME=MyBinary
SRC_ROOT=src
OBJ_DIR=obj

DEPS=$(SRC_ROOT)/Application/Application.h \
     $(SRC_ROOT)/Tasks/BackgroundWorker.h

_OBJ=$(SRC_ROOT)/Application/Application.o \
    $(SRC_ROOT)/Tasks/BackgroundWorker.o\
    $(SRC_ROOT)/main.o

OBJ=$(patsubst $(SRC_ROOT)/%,$(OBJ_DIR)/%,$(_OBJ))

$(OBJ_DIR)/%.o: $(SRC_ROOT)/%.cpp $(DEPS)
    echo Making $@ from $<
    touch $@ 

$(APPNAME): $(OBJ)
    echo Making $@ from $^
    touch $@

请注意,在实践中,您必须更好地使用依赖项,并且可能由编译器生成它们(请参阅-MM和g ++的类似选项),此处在更改标题时重新编译所有内容。

© www.soinside.com 2019 - 2024. All rights reserved.