我有一个C ++项目的以下目录结构:
.
├── bin
├── build
├── include
│ ├── dir1
│ │ ├── file1.hpp
│ │ └── file2.hpp
│ ├── dir2
│ │ ├── file3.hpp
│ │ └── file4.hpp
│ └── third_party
│ └── catch.hpp
├── Makefile
├── src
│ ├── dir1
│ │ ├── file1.cpp
│ │ └── file2.cpp
│ └── dir2
│ ├── file3.cpp
│ └── file4.cpp
└── test
├── dir1
│ ├── file1.test.cpp
│ └── file2.test.cpp
└── dir2
├── file3.test.cpp
└── file4.test.cpp
如何编写Makefile来编译src
和test
目录中的代码,并获取build
目录中的目标文件和bin
目录中的二进制文件,在其中维护相同的目录结构,,而不必明确命名每个文件及其依赖?在dir*
和src
中的每个test
中使用多个Makefile会更好吗?
我的Makefile目前看起来像这样:(这可能是荒谬的,对不起!)
binaries_dir = bin
build_dir = build
sources_dir = src
include_dir = include
compile_flags = -std=c++14 -Wall
binaries := $(wildcard *.out)
objects := $(wildcard *.o)
sources := $(wildcard *.cpp)
headers := $(wildcard *.hpp)
objects: $(sources)
g++ $(compile_flags) -c $(sources_dir)/$(sources) -I $(include_dir)
binaries: $(objects)
for object in $(objects); do
g++ $(compile_flags) -o $(binaries_dir)/ $(build_dir)/$object
done
答案 0 :(得分:1)
我认为这不是万无一失的,但我认为它几乎可以满足您的需求。你应该研究一下Makefiles的构建,因为它的结果并不完全符合你的需求,你将如何修复它?
CXX := g++
RM := rm -f
MD := mkdir -p
# don't change, this is for dependencies
CXXFLAGS += -MMD -MP
# add compiler flags here
CXXFLAGS += -std=c++14 -pedantic-errors
CXXFLAGS += -Wall -Wextra
CXXFLAGS += -g3 -O0
# add external includes here
CPPFLAGS += -Iinclude
# add library flags here
LDFLAGS +=
DIRS := $(patsubst src/%, %, $(wildcard src/*))
DIRS += $(patsubst test/%, %, $(wildcard test/*))
PROG_SOURCES := $(wildcard src/*/*.cpp)
TEST_SOURCES := $(wildcard test/*/*.cpp)
OBJECTS := $(patsubst src/%.cpp, build/%.o, $(PROG_SOURCES))
OBJECTS += $(patsubst test/%.cpp, build/%.o, $(TEST_SOURCES))
EXECUTABLES := $(patsubst src/%.cpp, bin/%, $(PROG_SOURCES))
EXECUTABLES += $(patsubst test/%.cpp, bin/%, $(TEST_SOURCES))
DEPENDENCIES := $(patsubst src/%.cpp, build/%.d, $(PROG_SOURCES))
DEPENDENCIES += $(patsubst test/%.cpp, build/%.d, $(TEST_SOURCES))
all: dirs $(EXECUTABLES)
build/%.o: src/%.cpp
$(CXX) -c $(CXXFLAGS) $(CPPFLAGS) -o $@ $<
build/%.o: test/%.cpp
$(CXX) -c $(CXXFLAGS) $(CPPFLAGS) -o $@ $<
bin/%: build/%.o
$(CXX) $(CXXFLAGS) -o $@ $< $(LDFLAGS)
-include $(DEPENDENCIES)
clean:
@echo Removing build files
@$(RM) $(EXECUTABLES) $(OBJECTS) $(DEPENDENCIES)
dirs:
@$(MD) $(patsubst %, build/%, $(DIRS)) $(patsubst %, bin/%, $(DIRS))
.PHONY: show dirs
答案 1 :(得分:0)
您可能会从中找到一些灵感:https://github.com/jschmerge/DasBuild