Home > Enterprise >  Why I cannot create directory in makefile?
Why I cannot create directory in makefile?

Time:02-15

ODIR =./obj

SRCS = myfunc.cpp
DEPS = header.h

OBJ = $(patsubst %.cpp, %.o, $(SRCS))
_OBJ = $(ODIR)/$(OBJ)

$(DLL): $(_OBJ)
    if test ! -d $(ODIR); then mkdir $(ODIR); fi
    $(AR) $(CFLAGS) -o $@ $^ 

$(_OBJ): $(SRCS) $(DEPS)
    $(CC) -c -o $@ $< $(INCL) $(LDFLAGS)

I want to put all my object file in a directory ./obj. I want to create it if such a directory is not existing. What is wrong with if test ! -d $(ODIR); then mkdir $(ODIR); fi? The error said

Assembler messages: Fatal error: can't create obj/: Is a directory

CodePudding user response:

The first problem is that DLL isn't defined anywhere.

The second problem is here:

OBJ = $(patsubst %.cpp, %.o, $(SRCS))

See the space after the first comma? It looks innocuous, but it means that the variable OBJ winds up containing myfunc.o, which also looks harmless, until you construct _OBJ which turns out to be ./obj/ myfunc.o, which trips up the compiler.

The third problem is that Make will execute the $(_OBJ) rule before the $(DLL) rule, so the compiler must use the obj/ directory before it exists.

The last problem (I hope) is that you seem to be passing $(CFLAGS) as arguments to the archive-maintaining program, when you should use $(ARFLAGS) (and make sure it actually contains what you intend).

CodePudding user response:

A final problem that isn't a problem yet but will be:

SRCS = myfunc.cpp
OBJ = $(patsubst %.cpp,%.o,$(SRCS))
_OBJ = $(ODIR)/$(OBJ)

As long as SRCS only contains one file, this will be fine. But as soon as you add a second file, the above is wrong.

Suppose SRCS contains myfunc.cpp myother.cpp. Then OBJ contains myfunc.o myother.o. Then _OBJ, which is $(ODIR)/$(OBJ), will be ./obj/myfunc.o myother.o which is not what you want.

Better is to just write it as a single change:

SRCS = myfunc.cpp
_OBJ = $(patsubst %.cpp,$(ODIR)/%.o,$(SRCS))
  • Related