Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error in makefile

I am using gnu Make 3.82 and have an annoying problem.

I have a rule setting dependencies between directories.

OBJDIR=../obj

$(objdir)/%.o: %.C
    $(COMPILE) -MM -MT$(objdir)/$(notdir $@) $< -o $(DEPDIR)/$(notdir $(basename $<).d )
$(COMPILE) -o $(objdir)/$(notdir $@ ) -c $<

In order to do this, the obj directory must exist. I want to mkdir the directory as a prerequisite

$(objdir)/%.o: %.C $(objdir)
    $(COMPILE) -MM -MT$(objdir)/$(notdir $@) $< -o $(DEPDIR)/$(notdir $(basename $<).d )
$(COMPILE) -o $(objdir)/$(notdir $@ ) -c $<

$(objdir):
    mkdir $(objdir)

This doesn't work, because it fails when the directory is there and then the make stops I tried shell

if [ ! -d $(objdir) ] ; then  \
  mkdir $(objdir)             \
fi

but obviously I've got something wrong. What's the best way of doing this?

like image 884
Dov Avatar asked May 19 '26 01:05

Dov


1 Answers

One simple way is to use:

mkdir -p ../obj

It doesn't fail when the directory exists.

I usually create a macro, MKPATH, for this:

MKPATH = mkdir -p

and then reference the macro in the rule:

$(objdir):
    $(MKPATH) $(objdir)

That way, I can change the behaviour without changing the makefile if it becomes necessary.


Your shell fragment:

if [ ! -d $(objdir) ] ; then
  mkdir $(objdir)
fi

does not work as written because make executes each line separately.

You could write (note the added semi-colon):

if [ ! -d $(objdir) ] ; then \
  $(MKPATH) $(objdir) ; \
fi

Or:

if [ ! -d $(objdir) ] ; then $(MKPATH) $(objdir); fi

Or:

[ -d $(objdir) ] || $(MKPATH) $(objdir)

Note that the command line must be successful overall, so do not try:

[ ! -d $(objdir) ] && $(MKPATH) $(objdir)

If the directory exists, the first alternative fails, but the shell exits with a non-zero status, thus failing...and causing the build to fail.

like image 178
Jonathan Leffler Avatar answered May 21 '26 21:05

Jonathan Leffler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!