Makefile无法为简单项目创建单独的对象文件夹 [英] Makefile cannot create a seperate Object Folder for simple project
问题描述
我正在使用此 Makefile教程来了解如何使用Makefiles.该问题可能是此线程,但我想在这里需要更多说明.
I am using this Makefile Tutorial for understanding how to use Makefiles. This Question might be a duplicate for this thread but I think I need more clarity here.
我的项目结构:
--exercise_14/
--> ex14.c
--> ex14.h
--> main.c
--> Makefile
ex14.*
没什么复杂的,只是带有3个函数声明( ex14.h
)及其实现( ex14.c
)和 main.c
调用它们.
There is nothing complex about ex14.*
, just simple header file with 3 function declarations (ex14.h
) and their implementation (ex14.c
) and main.c
calls them.
我的 Makefile
如下:
CC = gcc
CFLAGS = -Wall -g
DEPS = ex14.h
ODIR=obj
_OBJ=ex14.o main.o
OBJ=$(patsubst %,$(ODIR)/%,$(_OBJ))
all: ex14
$(ODIR)/%.o: %.c $(DEPS)
$(CC) $(CFLAGS) -c -o $@ $<
ex14: $(OBJ)
$(CC) $(CFLAGS) -o $@ $^
clean:
rm -f ex14 $(ODIR)*.o
rm -rf $(ODIR)
我目前正在了解文件中的 patsubst
应该如何工作,以及每次运行时如何运行
I am currently understanding how the patsubst
in the file should work and everytime I run
make clean all
我得到:
gcc -Wall -g -c -o obj/ex14.o ex14.c
Assembler messages:
Fatal error: can't create obj/ex14.o: No such file or directory
Makefile:16: recipe for target 'obj/ex14.o' failed
make: *** [obj/ex14.o] Error 1
有意义的是,没有创建 obj/
文件夹,也没有找到 ex14.o
进行进一步编译.一种解决方法是使用 mkdir obj
然后执行 make
,但我想避免这种情况.
Which makes sense that there is no obj/
folder created and no ex14.o
is found for further compilation. A way around is to use mkdir obj
and then perform make
but I want to avoid that.
应该添加哪些行来让我的 Makefile
创建一个文件夹为 ODIR=obj
并将所有目标文件放入其中?
What lines should be added to let my Makefile
make a folder as ODIR=obj
and put all the object files within it?
推荐答案
The correct solution is to make your object files depend on their directory via order-only dependency:
考虑一个示例,其中将目标放置在单独的目录中,并且在运行make之前该目录可能不存在.在这种情况下,您希望在放置任何目标之前先创建目录,但是由于目录的时间戳会在添加,删除或重命名文件时发生变化,因此,我们当然不希望在以下情况下重建所有目标:目录的时间戳更改.解决此问题的一种方法是使用仅订购的先决条件:使目录成为所有目标上的仅订购的先决条件:
Consider an example where your targets are to be placed in a separate directory, and that directory might not exist before make is run. In this situation, you want the directory to be created before any targets are placed into it but, because the timestamps on directories change whenever a file is added, removed, or renamed, we certainly don’t want to rebuild all the targets whenever the directory’s timestamp changes. One way to manage this is with order-only prerequisites: make the directory an order-only prerequisite on all the targets:
$(ODIR)/%.o: %.c $(DEPS) | $(ODIR)
<same-original-recipe>
$(ODIR):
mkdir -p $@
这篇关于Makefile无法为简单项目创建单独的对象文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!