Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create directory if needed?

Tags:

makefile

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?

like image 332
radl Avatar asked May 02 '13 18:05

radl


People also ask

How do you create a directory if it does not exist?

When you want to create a directory in a path that does not exist then an error message also display to inform the user. If you want to create the directory in any non-exist path or omit the default error message then you have to use '-p' option with 'mkdir' command.

How do you create a directory if it does not exist Python?

import os path = '/Users/krunal/Desktop/code/database' os. makedirs(path, exist_ok=False) print("The new directory is created!") So that's how you easily create directories and subdirectories in Python with makedirs(). That's it for creating a directory if not exist in Python.

Which command is used to create a directory?

Use the mkdir command to create one or more directories specified by the Directory parameter.


1 Answers

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.

like image 137
MadScientist Avatar answered Sep 30 '22 18:09

MadScientist