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

后端 未结 9 1091
盖世英雄少女心
盖世英雄少女心 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:25

    There is a trick you can use with templates to provide H file only constants.

    (note, this is an ugly example, but works verbatim in at least in g++ 4.6.1.)

    (values.hpp file)

    #include 
    
    template
    class tValues
    {
    public:
       static const char* myValue;
    };
    
    template  const char* tValues::myValue = "This is a value";
    
    typedef tValues<0> Values;
    
    std::string otherCompUnit(); // test from other compilation unit
    

    (main.cpp)

    #include 
    #include "values.hpp"
    
    int main()
    {
       std::cout << "from main: " << Values::myValue << std::endl;
       std::cout << "from other: " << otherCompUnit() << std::endl;
    }
    

    (other.cpp)

    #include "values.hpp"
    
    std::string otherCompUnit () {
       return std::string(Values::myValue);
    }
    

    Compile (e.g. g++ -o main main.cpp other.cpp && ./main) and see two compilation units referencing the same constant declared in a header:

    from main: This is a value
    from other: This is a value
    

    In MSVC, you may instead be able to use __declspec(selectany)

    For example:

    __declspec(selectany) const char* data = "My data";
    

提交回复
热议问题