How to declare a static const char* in your header file?

后端 未结 9 1088
盖世英雄少女心
盖世英雄少女心 2021-01-31 13:26

I\'d like to define a constant char* in my header file for my .cpp file to use. So I\'ve tried this:

private:
    static const char *SOMETHING = \"sommething\";         


        
9条回答
  •  感情败类
    2021-01-31 14:28

    If you're using Visual C++, you can non-portably do this using hints to the linker...

    // In foo.h...
    
    class Foo
    {
    public:
       static const char *Bar;
    };
    
    // Still in foo.h; doesn't need to be in a .cpp file...
    
    __declspec(selectany)
    const char *Foo::Bar = "Blah";
    

    __declspec(selectany) means that even though Foo::Bar will get declared in multiple object files, the linker will only pick up one.

    Keep in mind this will only work with the Microsoft toolchain. Don't expect this to be portable.

提交回复
热议问题