Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a make file string variable in CPP file

Tags:

c++

makefile

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...

like image 956
NeonGlow Avatar asked Dec 05 '12 06:12

NeonGlow


People also ask

How read a string from a file in C++?

Call open() method to open a file “tpoint. txt” to perform read operation using object newfile. If file is open then Declare a string “tp”. Read all data of file object newfile using getline() method and put it into the string tp.

What is $@ in makefile?

The file name of the target of the rule. If the target is an archive member, then ' $@ ' is the name of the archive file. In a pattern rule that has multiple targets (see Introduction to Pattern Rules), ' $@ ' is the name of whichever target caused the rule's recipe to be run.


2 Answers

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.

like image 181
Jerry Coffin Avatar answered Oct 03 '22 16:10

Jerry Coffin


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 );
like image 39
Potatoswatter Avatar answered Oct 03 '22 16:10

Potatoswatter