D&C GLug - Home Page

[ Date Index ] [ Thread Index ] [ <= Previous by date / thread ] [ Next by date / thread => ]

Re: [LUG] c++ preprocessor passing strings

 

Quoting Robin Cornelius <robin.cornelius@xxxxxxxxx>:

> I have some code like this :-
>
> std::string data_location
> data_location = "/usr/local/hardcodedpath"
>
> How can i set "/usr/local/hardcodedpath" at compile time?
>
> Is there an easy C++ way of using preprocessors, i've tried passing
> values over -DMY_LOCATION and using
>
> data_location = MY_LOCATION
>
> but as the string is unquoted this fails. It does not seem possible to
> pass quoted values via the preprocessor.

Firstly, you can include quote marks in a #define, but it might  
require careful quoting in your shell:

g++ '-DMY_LOCATION="/usr/local/hardcodedpath"' file.cpp

A second option is to do the define on the command line without the  
quotes, and use a macro to add the quotes:

g++ -DMY_LOCATION=/usr/local/hardcodedpath file.cpp

where file.cpp contains:

#define STRINGIZE2(x) #x
#define STRINGIZE(x) STRINGIZE2(x)

data_location=STRINGIZE(MY_LOCATION);

The nesting of the function macros is required to ensure that the  
right text gets converted to a string. This doesn't work if  
MY_LOCATION can contain commas.

A third option is to write it to a header file:

echo '#define MY_LOCATION "/usr/local/hardcodedpath"' > mylocation.h

but again, you have to be careful with shell quoting.

Hope that helps.

Anthony
-- 
Anthony Williams            | Just Software Solutions Ltd
Custom Software Development | http://www.justsoftwaresolutions.co.uk
Registered in England, Company Number 5478976.
Registered Office: 15 Carrallack Mews, St Just, Cornwall, TR19 7UL



-- 
The Mailing List for the Devon & Cornwall LUG
http://mailman.dclug.org.uk/listinfo/list
FAQ: http://www.dcglug.org.uk/linux_adm/list-faq.html