NeonGlow
NeonGlow

Reputation: 1692

Using a make file string variable in CPP file

I am using the following code in a make file to access a variable VENDOR_NAME from a CPP file.

EXTRA_DEFINE += -DVENDOR_NAME=$(VENDOR_NAME) VENDOR_NAME contains a string.

In my cpp file when I try to use this variable I am getting errors as given below.

cout << VENDOR_NAME;

Feature1.cpp.bak.cpp:8: 'Default_Vendor' undeclared (first use this function) Feature1.cpp.bak.cpp:8: (Each undeclared identifier is reported only once for

I guess this is because my string does not contain double quotes and compiler is considering content of VENDOR_NAME as a variable.

How to get this variable as a string in my CPP file so that I can use it like I have #defineed it?

Thanks...

Upvotes: 5

Views: 6063

Answers (2)

Potatoswatter
Potatoswatter

Reputation: 137870

Use the preprocessor to turn it into a string.

#define stringify( x ) stringify_literal( x )
#define stringify_literal( x ) # x

std::cout << stringify( VENDOR_NAME );

Given a preprocessor support for variadic macros (officially C++11, in practice available much longer), VENDOR_NAME may include a comma:

#define stringify( ... ) stringify_literal( __VA_ARGS__ )
#define stringify_literal( ... ) # __VA_ARGS__

std::cout << stringify( VENDOR_NAME );

Upvotes: 3

Jerry Coffin
Jerry Coffin

Reputation: 490348

Your makefile is going to create a command line for the compiler. The problem that arises is that if you just surround the value in quotes:

EXTRA_DEFINE += -DVENDOR_NAME="$(VENDOR_NAME)"

...the shell will see the quotes as simply delineating a command line argument, so it'll probably strip them off (though it can depend on the shell you're using). To prevent that, you'll want to create the argument with escaped quotes:

EXTRA_DEFINE += -DVENDOR_NAME="\"$(VENDOR_NAME)\""

I think most of the typical shells, at least for Windows and Linux, will accept a back-slash as an escape to preserve the quotes, but I'm sure there's at least one around for which you'll have to do the quoting differently.

Upvotes: 10

Related Questions