It depends on what your makefile looks like. If you have a dedicated rule for the c file that accesses it, you could just add -DCOMMIT_ID=$(COMMIT_ID)
to the recipe as so:
foo.o: foo.c
$(CC) $(CFLAGS) -DCOMMIT_ID=$(COMMIT_ID) $^ -o $@
or, if you're using pattern rules, you could just add it to CFLAGS, and then every .c file would have access to it (assuming of course that the pattern rule makes use of CFLAGS
):
CFLAGS += -DCOMMIT_ID=$(COMMIT_ID)
After you've done this, COMMIT_ID will be a macro in the c file, so you could use the stringify operator #
to access its value:
printf("commit id is " #COMMIT_ID "\n");
----- EDIT -----
Note that this does have a sharp stick involved with it -- specifically, if you build once, and then modify the git repository without modifying foo.c, then make will consider foo.o to be up to date, and will not rebuild it, meaning that foo.o will have the old commit id in it. I'll post a second answer on how you might get around this if this is a concern