Rohan G Rohan G - 4 months ago 8
C Question

how to exit and log the data in file at same time in makefile when error occurs

makefile

RUN_EXE = xyz.exe
SOME_DIR_PATH = ../folder1/

ifdef $(MAKECMDGOALS)
ifeq ($(MAKECMDGOALS), "target_1")
ABC = status.log
ARGS_TO_EXE = "argc1"
endif
ifeq ($(MAKECMDGOALS), "target_1")
ABC = file2.txt
ARGS_TO_EXE = "argc2"
endif
else
ABC = status.log file2.txt
ARGS_TO_EXE = ""
endif

# phony define
.PHONY = default target_1 target_2

# if target not mention run default
default: $(ABC)


target_1 target_2:$(ABC)

$(ABC):
$(CD) $(SOME_DIR_PATH) && ( $(RUN_EXE) $(ARGS_TO_EXE) || (exit 1;)) 2>&1 | tee -a ../status.log; \


i have two makefile using the first makefile i am invoking this makefile.
if some error come it should succesfully return to first makefile.

for testing purpose i created a error in executable i am trying to open a file in read mode which doesn't exist. so my executable will through error and it will come out

when i give

make target_1


error: error opening file (using c printf function and same will be in file)

make target_2


error: error opening file (using c printf function and same will be in file)

BUT problem occur here

make


error: error opening file (using c printf function and same will be in file).
error: error opening file (using c printf function and same will be in file).

it should exit after first print with successfully logging in status.log file but it is not happening. AS $(ABC) contain two target status.log and file2.txt so in first run it try to build status.log and in second it try to build file2.txt.

But i want if error is there in first run it should return to first makefile and log the error in status.log also and shouldn't run for file2.txt and come out using exit 1

Answer

if some error come it should succesfully return to first makefile.

Your first makefile can invoke this makefile with - option, e.g.

run_submake:
    -$(MAKE) <arguments>

This way the error from the submake is ignored.


Your rules do not seem to be correct. The recipes must produce a file (or multiple files) or be phony targets. E.g., there should be rules to produce status.log and file2.txt. Your makefile should look like this:

RUN_EXE := xyz.exe
SOME_DIR_PATH := ../folder1/
ARGS_TO_EXE := "argc1"

all : status.log file2.txt # The default target.
target_1: status.log
target_2: file2.txt

.PHONY: all target_1 target_2

status.log:
    ${CD} ${SOME_DIR_PATH} && ( $(RUN_EXE) $(ARGS_TO_EXE) | tee -a $@; exit $${PIPESTATUS[0]} )

file2.txt:
    # Add a recipe to produce file2.txt