0

In my CMake build system, I autogenerate a header file. Previously, I was doing something like this

// old_auto_gen_file.hpp
#define VERSION_STRING "@VERSION_STRING@"
#define VERSION_MAJOR @VERSION_MAJOR@

where the @...@ get filled in through CMake.

I'd like to lose the #define if possible. I was thinking something like this

// new_auto_gen_file.hpp
static const std::string VERSION_STRING("@VERSION_STRING@");
static const int VERSION_MAJOR(@VERSION_MAJOR@);

However, I'm very confused if this is legit or not? Is this cool with c++11?

2
  • 1
    Did you try it? Did it work? Commented Aug 19, 2015 at 2:22
  • Yup, it surprised me that the std::string part worked though. Figured I'd ask y'all to see if there could be potential problems. Commented Aug 19, 2015 at 2:37

2 Answers 2

1

There's nothing wrong with this, except I don't see any reason even to bother with the small overhead of a std::string. A simple char array should be sufficient:

static const char VERSION_STRING[]="@VERSION_STRING@";
static const int VERSION_MAJOR=@VERSION_MAJOR@;
Sign up to request clarification or add additional context in comments.

1 Comment

I'd use a static char const* const instead of an array. That way I know that at least some compilers will a) optimize out the storage for the pointer itself and (more importantly) b) fold/merge/coalesce all the string literals into one ("string pooling"). I'm not sure current compilers will do that for const char arrays. (Indeed I'm pretty sure that the standard doesn't allow it.)
0

Depends on your toolchain, you may get multiple instances of the const, or otherwise the linker might be smart enough to do "merge string".

Either way this should has no visible impact to your code. But I would suggest to put the string in a c/cpp file and have extern reference in the header, which as a side-effect you only need to recompile a small file upon changes.

1 Comment

I've never seen a compiler merge multiple std::string instances into one. You're probably thinking of string pooling, which works for identical string literals, but certainly not for the distinct std::string instances that are then initialized by those identical literals.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.