134

I want to create directories using makefile. My project directory is like this

+--Project  
   +--output  
   +--source  
     +Testfile.cpp  
   +Makefile  

I want to put all the objects and output into the respective output folder. I want to create folder structure which would be like this after compiling.

+--Project
   +--output
     +--debug (or release)
       +--objs
         +Testfile.o
       +Testfile (my executable file)
   +--source
     +Testfile.cpp
   +Makefile

I tried with several options, but could not succeed. Please help me to make directories using make file. I'm posting my Makefile for your consideration.

#---------------------------------------------------------------------
# Input dirs, names, files
#---------------------------------------------------------------------
OUTPUT_ROOT := output/

TITLE_NAME := TestProj 

ifdef DEBUG 
    TITLE_NAME += _DEBUG
else
ifdef RELEASE
    TITLE_NAME += _RELEASE
endif
endif


# Include all the source files here with the directory tree
SOURCES := \
        source/TestFile.cpp \

#---------------------------------------------------------------------
# configs
#---------------------------------------------------------------------
ifdef DEBUG
OUT_DIR     := $(OUTPUT_ROOT)debug
CC_FLAGS    := -c -Wall
else
ifdef RELEASE
OUT_DIR     := $(OUTPUT_ROOT)release
CC_FLAGS    := -c -Wall
else
$(error no build type defined)
endif
endif

# Put objects in the output directory.
OUT_O_DIR   := $(OUT_DIR)/objs

#---------------------------------------------------------------------
# settings
#---------------------------------------------------------------------
OBJS = $(SOURCES:.cpp=.o)
DIRS = $(subst /,/,$(sort $(dir $(OBJS))))
DIR_TARGET = $(OUT_DIR)

OUTPUT_TARGET = $(OUT_DIR)/$(TITLE_NAME)

CC_FLAGS +=   

LCF_FLAGS := 

LD_FLAGS := 

#---------------------------------------------------------------------
# executables
#---------------------------------------------------------------------
MD := mkdir
RM := rm
CC := g++

#---------------------------------------------------------------------
# rules
#---------------------------------------------------------------------
.PHONY: all clean title 

all: title 

clean:
    $(RM) -rf $(OUT_DIR)

$(DIR_TARGET):
    $(MD) -p $(DIRS)

.cpp.o: 
    @$(CC) -c $< -o $@

$(OBJS): $(OUT_O_DIR)/%.o: %.cpp
    @$(CC) -c $< -o $@

title: $(DIR_TARGET) $(OBJS)
0

11 Answers 11

174

In my opinion, directories should not be considered targets of your makefile, either in technical or in design sense. You should create files and if a file creation needs a new directory then quietly create the directory within the rule for the relevant file.

If you're targeting a usual or "patterned" file, just use make's internal variable $(@D), that means "the directory the current target resides in" (cmp. with $@ for the target). For example,

$(OUT_O_DIR)/%.o: %.cpp
        @mkdir -p $(@D)
        @$(CC) -c $< -o $@

title: $(OBJS)

Then, you're effectively doing the same: create directories for all $(OBJS), but you'll do it in a less complicated way.

The same policy (files are targets, directories never are) is used in various applications. For example, git revision control system doesn't store directories.


Note: If you're going to use it, it might be useful to introduce a convenience variable and utilize make's expansion rules.

dir_guard=@mkdir -p $(@D)

$(OUT_O_DIR)/%.o: %.cpp
        $(dir_guard)
        @$(CC) -c $< -o $@

$(OUT_O_DIR_DEBUG)/%.o: %.cpp
        $(dir_guard)
        @$(CC) -g -c $< -o $@

title: $(OBJS)
2
  • 24
    While linking the directory requirement to files is a better option in my opinion, your solution also has the significant drawback that the mkdir process will be called by the make file for every single file that's rebuilt, most of which won't need to make the directory again. When adapted to non-Linux build systems like Windows, it actually causes both an unblockable error output since there is no -p equivalent to the mkdir command, and more importantly a gigantic amount of overhead since the shell invocation is not minimally invasive.
    – mtalexan
    Commented Dec 30, 2013 at 18:27
  • 4
    Instead of directly calling mkdir, I did the following to avoid trying to create the directory if it already exists: $(shell [ ! -d $(@D) ] && mkdir -p $(@D))
    – Brady
    Commented Oct 15, 2019 at 13:42
105

This would do it - assuming a Unix-like environment.

MKDIR_P = mkdir -p

.PHONY: directories

all: directories program

directories: ${OUT_DIR}

${OUT_DIR}:
        ${MKDIR_P} ${OUT_DIR}

This would have to be run in the top-level directory - or the definition of ${OUT_DIR} would have to be correct relative to where it is run. Of course, if you follow the edicts of Peter Miller's "Recursive Make Considered Harmful" paper, then you'll be running make in the top-level directory anyway.

I'm playing with this (RMCH) at the moment. It needed a bit of adaptation to the suite of software that I am using as a test ground. The suite has a dozen separate programs built with source spread across 15 directories, some of it shared. But with a bit of care, it can be done. OTOH, it might not be appropriate for a newbie.


As noted in the comments, listing the 'mkdir' command as the action for 'directories' is wrong. As also noted in the comments, there are other ways to fix the 'do not know how to make output/debug' error that results. One is to remove the dependency on the the 'directories' line. This works because 'mkdir -p' does not generate errors if all the directories it is asked to create already exist. The other is the mechanism shown, which will only attempt to create the directory if it does not exist. The 'as amended' version is what I had in mind last night - but both techniques work (and both have problems if output/debug exists but is a file rather than a directory).

6
  • Thank you Jonathan. when i tried that i got an error "make: *** No rule to make target output/debug', needed by directories'. Stop." But i'm not going to worry about that now. will stick with the basic rules. :). Thank you for guiding. And i'm running "make" from toplevel directory only.
    – Jabez
    Commented Dec 23, 2009 at 6:49
  • Just delete the ${OUT_DIR} behind directories:, then it should work.
    – Doc Brown
    Commented Dec 23, 2009 at 7:02
  • 1
    Implementing this requires that you catch every possible case where you use the directories from the command-line though. Furthermore, you can't make any file generating build rules dependant on directories without causing them to always rebuild..
    – mtalexan
    Commented Dec 30, 2013 at 18:30
  • 1
    @mtalexan You've provided a couple of comments explaining what's wrong with some of these answers but you haven't proposed an alternative answer. Anxious to hear your solution for this problem.
    – Samuel
    Commented Sep 22, 2015 at 18:58
  • @Samuel I pointed out the problems without providing a solution because I was looking for the same thing and never found a solution. I ended up just dealing with the fall out of a less than ideal solution.
    – mtalexan
    Commented Jan 26, 2016 at 19:21
37

Or, KISS.

DIRS=build build/bins

... 

$(shell mkdir -p $(DIRS))

This will create all the directories after the Makefile is parsed.

5
  • 3
    I like this approach because I don't have to clutter each target with commands to handle the directories. Commented Nov 28, 2017 at 17:01
  • 1
    I just needed to create directory if it doesn't exist. This answer fits perfect for my issue.
    – Jeff Pal
    Commented May 3, 2018 at 17:21
  • Not only that, this prevents the modified timestamps of each directory from triggering an unnecessary build step. This should be the answer Commented May 24, 2018 at 16:53
  • 17
    This is better: $(info $(shell mkdir -p $(DIRS))) Without the $(info ...), the output of the mkdir command will be pasted into the Makefile, leading to syntax errors at best. The $(info ...) call ensures that a) the errors (if any) are visible to the user, and b) that the function call expands to nothing. Commented Jun 28, 2018 at 11:38
  • 1
    Liked this approach, but didn't work when I ran make clean all since the clean rule removes the directories created when the Makefile was parsed. This command is also commonly used in CI.
    – Graeme
    Commented Aug 21, 2021 at 9:41
37

make in, and off itself, handles directory targets just the same as file targets. So, it's easy to write rules like this:

outDir/someTarget: Makefile outDir
    touch outDir/someTarget

outDir:
    mkdir -p outDir

The only problem with that is, that the directories timestamp depends on what is done to the files inside. For the rules above, this leads to the following result:

$ make
mkdir -p outDir
touch outDir/someTarget
$ make
touch outDir/someTarget
$ make
touch outDir/someTarget
$ make
touch outDir/someTarget

This is most definitely not what you want. Whenever you touch the file, you also touch the directory. And since the file depends on the directory, the file consequently appears to be out of date, forcing it to be rebuilt.

However, you can easily break this loop by telling make to ignore the timestamp of the directory. This is done by declaring the directory as an order-only prerequsite:

# The pipe symbol tells make that the following prerequisites are order-only
#                           |
#                           v
outDir/someTarget: Makefile | outDir
    touch outDir/someTarget

outDir:
    mkdir -p outDir

This correctly yields:

$ make
mkdir -p outDir
touch outDir/someTarget
$ make
make: 'outDir/someTarget' is up to date.

TL;DR:

Write a rule to create the directory:

$(OUT_DIR):
    mkdir -p $(OUT_DIR)

And have the targets for the stuff inside depend on the directory order-only:

$(OUT_DIR)/someTarget: ... | $(OUT_DIR)
6
  • On what broken OS/FS did you see touch modify any stat data on the parent directory? That makes non sense to me. The mtime of a dir only depends on the filenames it contains. I could not reproduce your issue. Commented Apr 11, 2019 at 23:38
  • 2
    @JohanBoulé Debian. Commented Apr 12, 2019 at 6:17
  • 2
    I don't know why this answer is not upvoted enough, because I think that this is a correct answer without issues linked to other answers. Thanks.
    – vbezhenar
    Commented Jul 27, 2021 at 22:59
  • 3
    @vbezhenar Just take a look at the dates under the question and its answers: My answer is not only the last one posted, it is also about a year younger than the most recent answer, and a whopping 9 years younger than the top rated and accepted answers. I was simply late to the party. That is probably the main disadvantage of the SO scoring system: Quick and somewhat right answers are often much higher scored than late and better answer. This is due to the head start that quick answer enjoy, but also due to the reinforcement of high scored answers being more likely to acquire additional votes. Commented Jul 28, 2021 at 7:21
  • 2
    @vbezhenar Btw, the reason that I posted this answer was precisely that I was totally disappointed by the other answers, and I didn't want to make compromises with my own Makefiles. So I dug into the make documentation and ran a few tests to come up with this solution; and I posted it in the hope that other people would be spared of the effort I had to invest, even though I was pretty certain that it would take decades for my answer to rise to the top, if ever. Commented Jul 28, 2021 at 7:27
8

All solutions including the accepted one have some issues as stated in their respective comments. The accepted answer by @jonathan-leffler is already quite good but does not take into effect that prerequisites are not necessarily to be built in order (during make -j for example). However simply moving the directories prerequisite from all to program provokes rebuilds on every run AFAICT. The following solution does not have that problem and AFAICS works as intended.

MKDIR_P := mkdir -p
OUT_DIR := build

.PHONY: directories all clean

all: $(OUT_DIR)/program

directories: $(OUT_DIR)

$(OUT_DIR):
    ${MKDIR_P} $(OUT_DIR)

$(OUT_DIR)/program: | directories
    touch $(OUT_DIR)/program

clean:
    rm -rf $(OUT_DIR)
4

I've just come up with a fairly reasonable solution that lets you define the files to build and have directories be automatically created. First, define a variable ALL_TARGET_FILES that holds the file name of every file that your makefile will be build. Then use the following code:

define depend_on_dir
$(1): | $(dir $(1))

ifndef $(dir $(1))_DIRECTORY_RULE_IS_DEFINED
$(dir $(1)):
    mkdir -p $$@

$(dir $(1))_DIRECTORY_RULE_IS_DEFINED := 1
endif
endef

$(foreach file,$(ALL_TARGET_FILES),$(eval $(call depend_on_dir,$(file))))

Here's how it works. I define a function depend_on_dir which takes a file name and generates a rule that makes the file depend on the directory that contains it and then defines a rule to create that directory if necessary. Then I use foreach to call this function on each file name and eval the result.

Note that you'll need a version of GNU make that supports eval, which I think is versions 3.81 and higher.

1
  • Creating a variable that holds "the file name of every file that your makefile will build" is kind of an onerous requirement - I like to define my top-level targets, then the things they depend on, and so on. Having a flat list of all the target files goes against the hierarchical nature of the makefile specification, and may not be (easily) possible when target files depend on runtime computations. Commented Nov 28, 2017 at 16:59
3

given that you're a newbie, I'd say don't try to do this yet. it's definitely possible, but will needlessly complicate your Makefile. stick to the simple ways until you're more comfortable with make.

that said, one way to build in a directory different from the source directory is VPATH; i prefer pattern rules

0
3

OS independence is critical for me, so mkdir -p is not an option. I created this series of functions that use eval to create directory targets with the prerequisite on the parent directory. This has the benefit that make -j 2 will work without issue since the dependencies are correctly determined.

# convenience function for getting parent directory, will eventually return ./
#     $(call get_parent_dir,somewhere/on/earth/) -> somewhere/on/
get_parent_dir=$(dir $(patsubst %/,%,$1))

# function to create directory targets.
# All directories have order-only-prerequisites on their parent directories
# https://www.gnu.org/software/make/manual/html_node/Prerequisite-Types.html#Prerequisite-Types
TARGET_DIRS:=
define make_dirs_recursively
TARGET_DIRS+=$1
$1: | $(if $(subst ./,,$(call get_parent_dir,$1)),$(call get_parent_dir,$1))
    mkdir $1
endef

# function to recursively get all directories 
#     $(call get_all_dirs,things/and/places/) -> things/ things/and/ things/and/places/
#     $(call get_all_dirs,things/and/places) -> things/ things/and/
get_all_dirs=$(if $(subst ./,,$(dir $1)),$(call get_all_dirs,$(call get_parent_dir,$1)) $1)

# function to turn all targets into directories
#     $(call get_all_target_dirs,obj/a.o obj/three/b.o) -> obj/ obj/three/
get_all_target_dirs=$(sort $(foreach target,$1,$(call get_all_dirs,$(dir $(target)))))

# create target dirs
create_dirs=$(foreach dirname,$(call get_all_target_dirs,$1),$(eval $(call make_dirs_recursively,$(dirname))))

TARGETS := w/h/a/t/e/v/e/r/things.dat w/h/a/t/things.dat

all: $(TARGETS)

# this must be placed after your .DEFAULT_GOAL, or you can manually state what it is
# https://www.gnu.org/software/make/manual/html_node/Special-Variables.html
$(call create_dirs,$(TARGETS))

# $(TARGET_DIRS) needs to be an order-only-prerequisite
w/h/a/t/e/v/e/r/things.dat: w/h/a/t/things.dat | $(TARGET_DIRS)
    echo whatever happens > $@

w/h/a/t/things.dat: | $(TARGET_DIRS)
    echo whatever happens > $@

For example, running the above will create:

$ make
mkdir w/
mkdir w/h/
mkdir w/h/a/
mkdir w/h/a/t/
mkdir w/h/a/t/e/
mkdir w/h/a/t/e/v/
mkdir w/h/a/t/e/v/e/
mkdir w/h/a/t/e/v/e/r/
echo whatever happens > w/h/a/t/things.dat
echo whatever happens > w/h/a/t/e/v/e/r/things.dat
5
  • The command mkdir -p is in the UNIX standard (Open Group Base Specifications Issue 7, 2018 edition aka POSIX). All the unixy OS I'm familiar with are POSIX compliant. I'm curious: What unixy OS you are thinking of that (i) supports the GNU make features you use here, but (ii) doesn't have mkdir -p?
    – MetaEd
    Commented Dec 22, 2022 at 21:01
  • @MetaEd, evidently the one I was using ;-). The question and response do not indicate that this is for a unixy OS. I was using Windows with some version of Make that would run. Commented Jan 4, 2023 at 2:45
  • Writing makefiles portable between Unix and Windows is an admirable goal, possibly even Quixotic. That being said, the OP is asking in the context of Unix without being explicit about it. One clue is their object files are named .o, not .OBJ.
    – MetaEd
    Commented Jan 18, 2023 at 23:48
  • I see this is important to you. Go forth and disparage! I hope it brings you great satisfaction and inner peace. Commented Jan 19, 2023 at 1:54
  • No disparagement intended. I am trying to convey that I too put a high value on portability, and that Unix and Windows are so different that makefile portability between them may be an unreachable star.
    – MetaEd
    Commented Jan 19, 2023 at 5:12
1

See https://www.oreilly.com/library/view/managing-projects-with/0596006101/ch12.html

REQUIRED_DIRS = ...
_MKDIRS := $(shell for d in $(REQUIRED_DIRS); \
             do                               \
               [[ -d $$d ]] || mkdir -p $$d;  \
             done)

$(objects) : $(sources)

As I use Ubuntu, I also needed add this at the top of my Makefile:

SHELL := /bin/bash # Use bash syntax
0

I use the makefiles in windows environment and my simple solution is as follows,

Create a target makedir and add it as a prerequisites to where ever it is required.

# Default goal
all: gccversion makedir build finalize list sizeafter completed

The makedir target is (applicable only in windows environment)

makedir:
    @IF NOT EXIST $(subst /,\,$(BUILD_DIR)) mkdir $(subst /,\,$(BUILD_DIR)) 2> NULL
    @IF NOT EXIST $(subst /,\,$(OUTPUT_DIR)) mkdir $(subst /,\,$(OUTPUT_DIR)) 2> NULL
    @IF NOT EXIST $(subst /,\,$(DEP_DIR)) mkdir $(subst /,\,$(DEP_DIR)) 2> NUL
    @IF NOT EXIST $(subst /,\,$(OBJ_DIR)) mkdir $(subst /,\,$(OBJ_DIR)) 2> NUL

$(subst /,\,$(BUILD_DIR)) converts the directory separator / to \ and mkdir $(subst /,\,$(BUILD_DIR)) 2> NUL redirects the error if any.

0
src_dir := src
obj_dir := obj
build_dir := build

dirs := $(src_dir) $(obj_dir) $(build_dir)   # new variable


all: $(dirs) $(other_dependencies)           # added dependency (*before* any others)

$(dirs):                                     # rule which makes missing directories
    mkdir $@
  1. Won't clutter your terminal with "cannot create directory" error messages. If the directories exist, they don't need to be built.
  2. Works like any other dependency, only requires one rule and one variable.
1
  • I get % make graphs Makefile:73: warning: overriding commands for target graphs' Makefile:69: warning: ignoring old commands for target graphs' make: Circular graphs <- graphs dependency dropped. maybe I'm following your code too literally? Commented Nov 29, 2022 at 18:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.