首页  >  文章  >  后端开发  >  GNU Make 能否简化在目录结构中使用类似规则构建大量可执行文件的过程,从而允许从主目录和各个项目文件夹进行编译?

GNU Make 能否简化在目录结构中使用类似规则构建大量可执行文件的过程,从而允许从主目录和各个项目文件夹进行编译?

Linda Hamilton
Linda Hamilton原创
2024-10-27 16:07:02878浏览

Can GNU Make streamline building numerous executables with similar rules across a directory structure, allowing compilation from both the main directory and individual project folders?

使用 GNU Make 构建具有类似规则的多个可执行文件

问题:

GNU Make 可以吗方便在目录结构中构建具有相似规则的多个可执行文件,从而能够从主目录和各个项目目录进行编译?

答案:

是的,GNU Make 可以处理这项任务采用简洁有效的方法。下面是实现所需功能的两个 makefile:

project.mk:

all :
% : forward_ # build any target by forwarding to the main makefile
    $(MAKE) -C .. project_dirs=$(notdir ${CURDIR}) $@
.PHONY : forward_

Makefile:

# one directory per project, one executable per directory
project_dirs := $(shell find * -maxdepth 0 -type d )

# executables are named after its directory and go into the same directory
exes := $(foreach dir,${project_dirs},${dir}/${dir})

all : ${exes}

#  the rules

.SECONDEXPANSION:

objects = $(patsubst %.cpp,%.o,$(wildcard $(dir )*.cpp))

# link
${exes} : % : $$(call objects,$$*) Makefile
    g++ -o $@ $(filter-out Makefile,$^) ${LDFLAGS} ${LDLIBS}

# compile .o and generate dependencies
%.o : %.cpp Makefile
    g++ -c -o $@ -Wall -Wextra ${CPPFLAGS} ${CXXFLAGS} -MD -MP -MF ${@:.o=.d} $<

.PHONY: clean

clean :
    rm -f $(foreach exe,${exes},$(call objects,${exe})) $(foreach dir,${project_dirs},$(wildcard ${dir}/*.d)) ${exes}

# include auto-generated dependency files
-include $(foreach dir,${project_dirs},$(wildcard ${dir}/*.d))

用法:

  • 创建名为 Makefile 的符号链接到每个项目目录中的 project.mk。
  • 要构建特定项目,请导航到项目目录并运行 make。
  • 要构建所有项目,请从主目录 (all_lessons) 运行 make。
  • 要清理特定项目,请从项目目录运行 make clean。
  • 要清理所有项目,请从主目录运行 make clean。

优点:

  • 易于实现并适合指定的要求。
  • 支持主目录和项目目录的构建和清理。
  • 自动生成依赖项并且完全可并行化。

以上是GNU Make 能否简化在目录结构中使用类似规则构建大量可执行文件的过程,从而允许从主目录和各个项目文件夹进行编译?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn