Akshya Rampal
Akshya Rampal

Reputation: 41

Define make variable from $(shell) as a string in C

I am compiling code using a makefile for an embedded application on the STM32f4 family of chips.

When I do:

Makefile:

DEFINES += -DGIT_HASH="test hash"

In my main.c:

const char * git_hash = GIT_HASH;

When I print out git_hash, I get test hash.

What I would like to do is:

Makefile:

COMMIT_HASH = $(shell git rev-parse HEAD)
DEFINES += -DGIT_HASH=$(COMMIT_HASH)

In my main.c:

const char * git_hash = GIT_HASH;

I get an error:

<command-line>:0:10: error: 'c1920a032c487a55b1b109d8774faf05e2ba42d0' undeclared here (not in a function)
src/run/main.c:173:25: note: in expansion of macro 'GIT_HASH'
 const char * git_hash = GIT_HASH;

I am wondering why the COMMIT_HASH is not treated the same way as a string. Any insight would be appreciated.

Upvotes: 3

Views: 6369

Answers (1)

Code-Apprentice
Code-Apprentice

Reputation: 83557

Remember that #define causes the precompiler to do a straight character for character replacement. So in your first example,

const char * git_hash = GIT_HASH;

becomes

const char * git_hash = "test hash";

The compiler is fine with this since it sees a literal string.

However, in your second example, it becomes

const char * git_hash = c1920a032c487a55b1b109d8774faf05e2ba42d0;

Now when the compiler does it's job, it sees a variable name, NOT a string literal, as I think you intend. To fix this, you need to be sure that the hash is enclosed in quotes. One possible solution is to change the Makefile to DEFINES += -DGIT_HASH=\"$(COMMIT_HASH)\".

Upvotes: 9

Related Questions