simgineer
simgineer

Reputation: 1898

How to pass a string from a make file into a c++ program

It seems on a program I've inherited we can pass in make variables that are numbers but I'd like to pass in a string now. When they are passed in as numbers it is as the following:

CFLAGS += -DBUILD_NUMBER=$(BUILD_NUMBER)

and i can access it as an int like so:

fprintf(stderr, "\n%s v%d.%d.%d.%d\n", APPNAME, MAJOR_VERSION, MINOR_VERSION, PATCH_VERSION, BUILD_NUMBER, MYBRANCH);

but I do not seem to be achieving the same with a string.

CFLAGS += -DMYBRANCH=$(BRANCH)

fprintf(stderr, "\n%s v%d.%d.%d.%d.%s\n", APPNAME, MAJOR_VERSION, MINOR_VERSION, PATCH_VERSION, BUILD_NUMBER, MYBRANCH);

I get this error with the above:

main.cpp: In function ‘int args_parse_cmd_line(int, char**)’:
<command-line>:0:10: error: ‘FIL’ was not declared in this scope
main.cpp:72:114: note: in expansion of macro ‘MYBRANCH’
 %s\n", APPNAME, MAJOR_VERSION, MINOR_VERSION, PATCH_VERSION, BUILD_NUMBER, MYBRANCH);
                                                                            ^~~~~~~~

Can someone give me a tip on what I'm doing wrong? "FIL-1234" is the example of our branch name that I'm trying to add to our build meta data for tractability.

Upvotes: 2

Views: 1564

Answers (2)

simgineer
simgineer

Reputation: 1898

Not sure if this is ideal but it works.

CFLAGS += -DMYBRANCH=\"$(BRANCH)\"

I think John's solution is attractive as I'm not crazy about escaping characters.

Upvotes: 2

john
john

Reputation: 87932

This preprocessor trick should work

#define xstr(s) str(s)
#define str(s) #s

fprintf(stderr, "\n%s v%d.%d.%d.%d.%s\n", APPNAME, MAJOR_VERSION, MINOR_VERSION, PATCH_VERSION, BUILD_NUMBER, xstr(MYBRANCH));

It's clear from your error that MYBRANCH is being expanded into FIL-1234 when, not unreasonably, the compiler looks for a variable FIL. You need to turn the macro expansion into a string literal and the code above should do that. Although I haven't tested anything.

Upvotes: 2

Related Questions