Expanding macros inside string literals

I have some numeric version macros, let's take for example __GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__, which I want to convert into a string literal like "4.7.8."

Is there any way to make this happen at compile time, seeing as macros don't expand inside string literals?

EDIT: And as I want the string to be the value of the macro, not its name, I don't suppose the stringzing operator # would help.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <string>
#include <boost/preprocessor/stringize.hpp>

int main()
{
    std::string gcc_version = "gcc version: " ;
    gcc_version += BOOST_PP_STRINGIZE( __GNUC__ ) ;
    gcc_version += '.' ;
    gcc_version += BOOST_PP_STRINGIZE( __GNUC_MINOR__ ) ;
    gcc_version += '.' ;
    gcc_version += BOOST_PP_STRINGIZE( __GNUC_PATCHLEVEL__ ) ;
    std::cout << gcc_version << '\n' ; // prints: gcc version: 4.7.0
}


http://www.boost.org/doc/libs/1_48_0/libs/preprocessor/doc/index.html
Last edited on
Thanks.
1
2
3
4
5
6
7
8
9
10
#include <iostream>

#define STR_EXPAND(tok) #tok
#define STR(tok) STR_EXPAND(tok)
#define GCC_VERSION STR(__GNUC__) "." STR(__GNUC_MINOR__) "." STR(__GNUC_PATCHLEVEL__)

int main()
{
	std::cout << GCC_VERSION << std::endl;
}
Last edited on
This is how BOOST_PP_STRINGIZE is defined:

1
2
3
4
5
6
7
8
9
10
11
12
13
 /* BOOST_PP_STRINGIZE */

 if BOOST_PP_CONFIG_FLAGS() & BOOST_PP_CONFIG_MSVC()
    define BOOST_PP_STRINGIZE(text) BOOST_PP_STRINGIZE_A((text))
    define BOOST_PP_STRINGIZE_A(arg) BOOST_PP_STRINGIZE_I arg
 elif BOOST_PP_CONFIG_FLAGS() & BOOST_PP_CONFIG_MWCC()
    define BOOST_PP_STRINGIZE(text) BOOST_PP_STRINGIZE_OO((text))
    define BOOST_PP_STRINGIZE_OO(par) BOOST_PP_STRINGIZE_I ## par
 else
    define BOOST_PP_STRINGIZE(text) BOOST_PP_STRINGIZE_I(text)
 endif

 define BOOST_PP_STRINGIZE_I(text) #text 


Seems to have work-arounds for Microsoft C++ and CodeWarrior.
Topic archived. No new replies allowed.