Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
958 views
in Technique[技术] by (71.8m points)

makefile - How to create directory if needed?

I'm trying to use makefile, my problem is that I have a directory, with an src directory and a Makefile. I also use a tmp directory what I also have to create. It has object files in it. And for performance, I try not to delete these when debugging. If I create a rule for tmp to create it, it always rebuilds all the C files. So how to do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There are a number of ways. It depends on what version of make you're using and what operating system you're using.

The one thing you must NEVER do is use a directory as a simple prerequisite. The rules the filesystem uses to update the modified time on directories do not work well with make.

For simple make on a POSIX system, you can pre-create the directory in the rule to perform the compilation:

obj/foo.o: foo.c
        @ mdkir -p obj
        $(CC) $(CPPFLAGS) $(CFLAGS) -c -o $@ $<

If you have GNU make you have two options. The simplest one is simply to force the directory to be created when the makefile is read in before anything else happens, by adding a line like this:

_dummy := $(shell mkdir -p obj)

The is easy, fast, and reliable. Its only downside is that the directory will be created always, even if it's not needed. Nevertheless this is the way I usually do it.

The most fancy way, if you have a new-enough GNU make, is to use order-only prerequisites:

obj/foo.o: foo.c | obj
        $(CC) $(CPPFLAGS) $(CFLAGS) -c -o $@ $<

obj:
        mkdir -p $@

This forces the obj target to be built before the obj/foo.o target, but the timestamp on obj is ignored when determining whether obj/foo.o is out of date.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...