Call make from script, only if main.c is modified

2019-09-08 15:13发布

问题:

The problem: I want to run only a script (e.g. run.sh), which will decide for me if make should be called (and call it if needed) and then run the executable.


My project has only one file, that is main.c. However, just the linking makes me wait a bit, something that I do not like when I debug and I am eager for the program to run. I would like something like this into run.sh:

#!/bin/bash
if[ main.c has changed from the last time make was called] then
  make > compile.txt
fi
./a.out

so that the make is called only if main.c is modified. By modified, one could take that the timestamp is changed (even if that may not the actual criterion). Is this feasible?


If so, I saw this answer, which made me think that every time I enter the body of the if statement that calls make, a copy of main.c would be created, or the timestamp of the file would be stored (in a file maybe), so that the next time the script runs, it will restore that information and check the if condition to see if timestamps differ. So, the second question is, how to do it?

回答1:

Simply

#!/bin/bash

if [ a.out -ot main.c ]; then
    make > compile.txt
fi

./a.out

-ot is equivalent to older than

However, this behaviour is expected from make itself. I would prefer a makefile like

CC = gcc
CFLAGS = -Wall -W

main: main.c
    $(CC) $(CFLAGS) -o $@ $^

The main rule would run only if main.c is updated after last make