侧边栏壁纸
  • 累计撰写 185 篇文章
  • 累计创建 77 个标签
  • 累计收到 17 条评论

目 录CONTENT

文章目录

执行make时如何自动生成目标文件目录

码峰
2023-03-18 / 0 评论 / 0 点赞 / 800 阅读 / 301 字 / 正在检测是否收录...
广告 广告

概述

在执行make时,如果我们把目标文件objects输出到一个集中的目录,而一个干净的工程(比如刚从git克隆下来的),这个目录可能是不存在的,此时执行make就会报错“Fatal error: can’t create xxx/xxx/xxx.o: No such file or directory”,makefile中可以有两种方法来自动创建这个目录,避免编译报错。

通过目标文件添加依赖

在makefile中给目标文件增加依赖,在依赖中执行mkdir命令来创建目标文件的目录,参考makefile的写法如下:

OBJDIR = obj
MODULES := src src2
...

OBJDIRS := $(patsubst %, $(OBJDIR)/%, $(MODULES))

build: $(OBJDIRS)
    echo $^

$(OBJDIRS):
    mkdir -p $@ 

通过嵌入shell命令

通过在makefile中定义个DUMMY变量,该变量中嵌入shell命令来实现,参考makefile如下:

SOURCES:=$(shell find $(SRC)/ -type f -name '*.c') #Get all the c files

#Get the files they're gonna be compiled to
OBJECTS:=$(patsubst $(SRC)/%.c, $(OBJ)/%.o, $(SOURCES))

#Get just the paths so you can create them in advance
OBJDIRS:=$(dir $(OBJECTS))

#call mkdir with the directories (using a dummy var because too much 
#trouble to deal with priorities) someone could prob do better
#--parents ignores the repeated and already existing errors
DUMMY:=$(shell mkdir --parents $(OBJDIRS))
0
广告 广告

评论区