gpt4 book ai didi

c++ - Makefile:为每个包含的头文件自动编译源代码

转载 作者:太空狗 更新时间:2023-10-29 22:56:26 25 4
gpt4 key购买 nike

如果目标包含 #include "foo/bar.hpp",我能否以自动编译和链接 foo/bar.cpp 的方式配置我的 makefile?

详细信息:我有一个结构如下的项目的 makefile:

src/
|-- program1/
| |-- main.cpp
| |-- makefile
|-- modules/
| |-- module1/
| | |-- foo.cpp
| | |-- foo.hpp
| |-- module1/
| | |-- bar.cpp
| | |-- bar.hpp

目前我的 program1 的 makefile 包含它使用的所有模块的所有 *.cpp 文件的列表,这有点难以维护且容易出错并与我的包含保持同步。

但是,在我的代码中,遵循 #include 命令将提供一个精确的依赖树。对于每个 *.hpp,都有一个相应的 *.cpp,我需要对其进行编译和链接。

这个编译过程可以通过 makefile 自动完成吗?自动依赖性可以帮助我吗?

有问题的 makefile:

# compiler settings
CXX = g++
CXXFLAGS = -std=c++14
# object file generation path
tmpDir = .objs
# modules path
modPath = ../modules

# Names of modules and files to be compiled
names := \
main.o \
module1/foo.o \
module2/bar.o

# prepend tmpDir
names := $(addprefix $(tmpDir)/, $(names))

# Linking
main: $(names)
$(CXX) $(CXXFLAGS) -o main $^

# Rule for main file
$(tmpDir)/main.o: main.cpp
@mkdir -p $(tmpDir)
$(CXX) $(CXXFLAGS) -c main.cpp -o $@ -I "$(modPath)"

# rules for module files
$(tmpDir)/%.o: $(modPath)/%.cpp
mkdir -p $(dir $@)
$(CXX) $(CXXFLAGS) -c $< -o $@

clean:
rm -rf *.o main $(tmpDir)

我想避免手动设置 names

最佳答案

自动生成文件名的常用方法是使用 $(wildcard ...) 或一些 $(shell ...) 命令扫描目录.

根据您链接的 Makefile,我认为您可以使用 GCC-MMD -MP 标志跟踪依赖关系,如下所示:

# compiler settings
CXX = g++
# use flags to generate dependency files
CXXFLAGS = -std=c++14 -MMD -MP
# object file generation path
tmpDir = .objs
# modules path
modPath = ../modules

# Names of modules and files to be compiled
names := main.o
names += $(patsubst $(modPath)/%.cpp,%.o,$(shell find $(modPath) -iname "*.cpp"))

# prepend tmpDir
names := $(addprefix $(tmpDir)/, $(names))

# there should be a dep file for every object file
deps := $(patsubst %.o,%.d,$(names))

all: main

# Linking
main: $(names)
$(CXX) $(CXXFLAGS) -o main $^

# Rule for main file
$(tmpDir)/main.o: main.cpp
@mkdir -p $(tmpDir)
$(CXX) $(CXXFLAGS) -c main.cpp -o $@ -I "$(modPath)"

# rules for module files
$(tmpDir)/%.o: $(modPath)/%.cpp
mkdir -p $(dir $@)
$(CXX) $(CXXFLAGS) -c $< -o $@

# include the dependencies if they exist
-include $(deps)

clean:
rm -rf *.o main $(tmpDir) $(deps)

每个使用 -MMD -MP 标志的编译命令都会生成一个与输出文件对应的依赖文件(扩展名为 .d 的除外)。

关于c++ - Makefile:为每个包含的头文件自动编译源代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48266138/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com