m3cu
m3cu

Reputation: 23

Makefile: checking existence of files

I'm working on a makefile that uses c source files and header files.

I would like to check if all those files exist before compiling, so that if one is missing, printing a customized message instead of the usual 'no rule to make target'.

The code is as follows:

PROG1=file1
PROG2=file2
INCLUDE=header
all: $(PROG1).x $(PROG2).x
%.x : %.c $(INCLUDE).c
     $(CC) -o $/$@ $^
     @ echo File $@ has been successfully created from $^;

Where and how should I check that file1.c, file2.c and header.h exist to print a customized error message if any of them is missing?

Upvotes: 1

Views: 660

Answers (1)

ThePosey
ThePosey

Reputation: 2734

PROG1=file1
PROG2=file2
INCLUDE=header

all: $(PROG1).x $(PROG2).x

%.x : %.c $(INCLUDE).c
    $(CC) -o $/$@ $^
    @echo File $@ has been successfully created from $^

%.c :
    @echo Missing $@

%.h :
    @echo Missing $@

Would that work? If those files don't exist you'd get something like the following output:

posey@DEATHSTAR:~$ make all
Missing file1.c
Missing header.c
cc -o file1.x file1.c header.c
cc: error: file1.c: No such file or directory
cc: error: header.c: No such file or directory
cc: fatal error: no input files
compilation terminated.
make: *** [file1.x] Error 4

Upvotes: 1

Related Questions