简体   繁体   English

头文件中的静态const std :: string

[英]static const std::string in header file

In my CMake build system, I autogenerate a header file. 在我的CMake构建系统中,我自动生成一个头文件。 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. @...@是通过CMake填写的。

I'd like to lose the #define if possible. 如果可能,我想丢失#define 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? c ++ 11很棒吗?

There's nothing wrong with this, except I don't see any reason even to bother with the small overhead of a std::string . 这样做没有什么问题,除了我什至看不到任何理由去打扰std::string的小开销。 A simple char array should be sufficient: 一个简单的char数组就足够了:

static const char VERSION_STRING[]="@VERSION_STRING@";
static const int VERSION_MAJOR=@VERSION_MAJOR@;

Depends on your toolchain, you may get multiple instances of the const, or otherwise the linker might be smart enough to do "merge string". 根据您的工具链,您可能会获得const的多个实例,否则链接器可能足够聪明以执行“合并字符串”。

Either way this should has no visible impact to your code. 无论哪种方式,这都不会对您的代码产生可见影响。 But I would suggest to put the string in ac/cpp file and have extern reference in the header, which as a side-effect you only need to recompile a small file upon changes. 但是我建议将字符串放在ac / cpp文件中,并在标头中添加外部引用,这是副作用,您只需要在更改时重新编译一个小文件即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM