Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create directories when generating object files in gcc

Tags:

gcc

makefile

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?

like image 381
prosseek Avatar asked Mar 07 '15 20:03

prosseek


People also ask

Where is the gcc build directory?

You need to use the which command to locate c compiler binary called gcc. Usually, it is installed in /usr/bin directory.

How do I create a folder in Makefile?

Solution 1: build the directory when the Makefile is parsed Before any targets are created or commands run the Makefile is read and parsed. If you put $(shell mkdir -p $(OUT)) somewhere in the Makefile then GNU Make will run the mkdir every time the Makefile is loaded.

Can Fopen create a directory?

The fopen can't be used to create directories. This is because fopen function doesn't create or open folders, it only works with files. The above code creates a path to the file named 'filename'. The directory of the 'filename' is obtained using the 'dirname' function.

What is linking gcc?

Linking is performed when the input file are object files " .o " (instead of source file " . cpp " or " . c "). GCC uses a separate linker program (called ld.exe ) to perform the linking.


1 Answers

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)
like image 73
prosseek Avatar answered Oct 06 '22 00:10

prosseek