Reputation: 191179
gcc -o abc/def.o def.c
generates def.o
file in a directory abc
; only when there exists a directory abc
.
Is there a way to make gcc to create a directory when the enclosing directory of the generated object file does not exist? If not, what could be the easiest way to make the directory in advance automatically, especially for Makefile?
Upvotes: 11
Views: 8517
Reputation: 1460
In addition to precedent solutions, you can create the directories in your rule for building your .o files
$(OBJ_DIR)/%.o: $(SRCS_DIR)/%.c
@mkdir -p $(dir $@)
$(CC) $(CFLAGS) $(INC) -c $< -o $@
Upvotes: 1
Reputation: 667
The way I do it is I find out what the paths will be, and create the dirs for them:
SOURCES:=$(shell find $(SRC)/ -type f -name '*.c') #Get all the c files
#Get the files they're gonna be compiled to
OBJECTS:=$(patsubst $(SRC)/%.c, $(OBJ)/%.o, $(SOURCES))
#Get just the paths so you can create them in advance
OBJDIRS:=$(dir $(OBJECTS))
#call mkdir with the directories (using a dummy var because too much
#trouble to deal with priorities) someone could prob do better
#--parents ignores the repeated and already existing errors
DUMMY:=$(shell mkdir --parents $(OBJDIRS))
Sauce: https://www.gnu.org/software/make/manual/html_node/File-Name-Functions.html
Upvotes: 3
Reputation: 191179
From this post, it seems like that there is no way to create a directory from gcc
.
For makefile, I can use this code snippet.
OBJDIR = obj
MODULES := src src2
...
OBJDIRS := $(patsubst %, $(OBJDIR)/%, $(MODULES))
build: $(OBJDIRS)
echo $^
$(OBJDIRS):
mkdir -p $@
make build
will create directories, and echo the results.
We also can make the object files are created automatically without invoking the make build
.
PROG := hellomake
LD := gcc
...
$(PROG): $(OBJDIRS) obj/src/hellofunc.o obj/src/hellomake.o
$(LD) $(filter %.o, $^) -o $(PROG)
Upvotes: 5