[Novices] If / then in a makefile?

yvh11a yvh11a at gmail.com
Tue Feb 7 00:48:17 EST 2006


Hello all,

I'm trying to modify a makefile so that it will, with one command, 
compile a C++ program, look to see if it compiles with no errors, and if 
so, run it.  If it does have errors, output the errors.  (obviously, 
this is a learning experience rather than an actual time-saver).  I've 
got a shell script that'll do it:

#!/bin/bash
make &> /dev/null  # <-- attempt a compile, hiding errors
if [ "$?" = "0" ]; then
    ./executable_file   #<-- If no errors, run
else
    make  # <-- if errors, re-run make and output errors
fi

And I've gotten this far in the makefile:

HDR = file1.h file2.h file3.h
SRC = file1.cxx file2.cxx file3.cxx
EXE = executable_file
SUB = executable_file# NO TRAILING SPACES
CCC = g++

OBJ = ${SRC:.cxx=.o}

all : ${EXE}

${EXE} : ${OBJ}
    ${CCC} -g -Wall -o $@ ${OBJ}

andrun : ${EXE}
    ${CCC} -g -Wall -o ${EXE} ${OBJ}
    if [ "$?" = "0" ]; then
        ./${EXE}
    else
        ${EXE}
    fi

clean :
    rm -f ${OBJ} ${EXE} ${SUB}.tar.gz *~ Depends

.SUFFIXES : .o .cxx

.cxx.o:
    ${CCC} -g -Wall -c $<

Depends depend:
    ${CCC} -E -MM ${SRC} > Depends

include Depends

When I do this:
[steve at rosie test]$ make andrun
it gets through the compile, but chokes on the if / then.  Is there a 
way to get make to interpret the if / then statement correctly?  Or can 
it somehow be passed out to bash and interpreted there?  Or am I wasting 
my time altogether and there's a better way to do it that I just haven't 
read about?  :)

Thanks,
Steve V.



More information about the Novices mailing list