In this particular case, calculating the year directly in your program is a better solution, as stated in the comments.
In general, though, you'll need to make run
a dependency of year
. Here's a solution that uses an intermediate file, which doesn't overwrite year.c
, but you can modify it to overwrite if you'd like:
year.c
:
#include <stdio.h>
#ifndef YEAR
#define YEAR "2013"
#endif
int main(void)
{
printf("Hello world from " YEAR "\n");
return 0;
}
Makefile
:
year: run
gcc year_manip.c -o year
run:
cat year.c | sed -e 's/3/4/g' > year_manip.c
Sample session:
paul@horus:~/src/sandbox/year$ ls
Makefile year.c
paul@horus:~/src/sandbox/year$ make
cat year.c | sed -e 's/3/4/g' > year_manip.c
gcc year_manip.c -o year
paul@horus:~/src/sandbox/year$ ./year
Hello world from 2014
paul@horus:~/src/sandbox/year$
Note that this solution means your program will always compile, i.e. your run
target is never up-to-date. If you made it dependent on either year.c
or year_manip.c
, then when 2015 came around, it still wouldn't rebuild, which is probably not what you want. You could probably do something more complicated with make
, to overcome this, if necessary.
For this particular problem, when the question is purely one of pre-#define
ing an identifier with a value, the answer to the linked question obviously gives a much simpler method which will work here. For more general code generation, using makefiles in this way can be useful.