11

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?

2
  • Why not simlply call mkdir abc -p in the same target where you call gcc? Commented Mar 7, 2015 at 20:43
  • 1
    @Sebastian Stigler: I can, I may be able to come up with some script to do that automatically, I just want to make sure if I missed simpler way to go. Commented Mar 7, 2015 at 20:44

3 Answers 3

5

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)
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

1

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 $@
  • The "@" before mkdir silent the output of mkdir (we don't want a message for each directory created).
  • The "-p" option tell mkdir to create all intermediate directories in path if they do not exist.
  • The "dir" method takes the file path ("$@") and keep only the file directory path.

1 Comment

You can use $(dir $@) instead of $(shell dirname $@).

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.