Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a directory doesn't exist in make and create it

In my project's directory, I have some subdirs: code/, export/, docs/ and object/. What make does is simply compile all the files from the code dir, and put the .o files into the object dir.

The problem is, I told git to ignore all .o files, because I don't want them uploaded, so it doesn't track the object dir either. I'm actually OK with that, I don't want the object/ uploaded to my GitHub account as well, but with the current solution (which is a simple empty text file inside the object/ dir), the directory does get uploaded and needs to be present before the build (the makefile just assumes it's there).

This doesn't really seem like the best solution, so is there a way to check if a directory doesn't exist before the build in a make file, and create it if so? This would allow for the object dir not to be present when the make command is called, and created afterwards.

like image 842
corazza Avatar asked Sep 26 '12 15:09

corazza


People also ask

How do you create directory if not exist in Linux?

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 doesn't exist in Python?

To create a directory if not exist in Python, check if it already exists using the os. path. exists() method, and then you can create it using the os. makedirs() method.

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

You can use the Java File class to create directories if they don't already exists. The File class contains the method mkdir() and mkdirs() for that purpose. The mkdir() method creates a single directory if it does not already exist.


2 Answers

The only correct way to do this is with order-only-prerequisites, see: https://www.gnu.org/software/make/manual/html_node/Prerequisite-Types.html. Note the | in the snippet.

If you don't use order-only-prerequisites each modification (e.g. coping or creating a file) in that directory will trigger the rule that depends on the directory-creation target again!

object/%.o: code/%.cc | object
    compile $< somehow...

object:
    mkdir -p $@
like image 109
woepaul Avatar answered Sep 18 '22 20:09

woepaul


Just have a target for it:

object/%.o: code/%.cc object
    compile $< somehow...

object:
    mkdir $@

You have to be a little more careful if you want to guard against the possibility of a file called "object", but that's the basic idea.

like image 43
Beta Avatar answered Sep 17 '22 20:09

Beta