declaring char* in header file

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • iSight
    New Member
    • Jun 2010
    • 1

    declaring char* in header file

    Hi,

    In C++, how can i declare a const char* in header file. Say, i have a header file MyTest.h as under:

    MyTest.h

    const char* temp = "Temp";

    class MyClass
    {
    private:
    public:
    };
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    Do not define variables in header files. When you do you get a new variable every time you include that header. What you want is one variable fro the entire program.

    Header files are for declarations only.

    Define your const in an implementation file:

    Code:
    MyTestGlobals.cpp: 
    
    extern const char* temp = "Temp";
    This will create temp as a sharable const variable.

    Then in your header file:

    Code:
    MyTestGlobals.h
    
    extern const char* temp;
    Finally, include your header:

    #include MyTestGlobals.h

    class MyClass
    {
    private:
    public:
    };

    Comment

    • donbock
      Recognized Expert Top Contributor
      • Mar 2008
      • 2427

      #3
      If you do have a good reason to define this variable in the header file (and there are very few good reasons), then that means that you are trying to define an initialized file-local variable in each source file that includes this header. You need to do this in the header:
      Code:
      static const char* const temp = "Temp";
      • static prevents duplicate definition errors at link time.
      • The first const insures that the string can't be changed.
      • The second const insures that the pointer can't be changed to point at some other string.

      Comment

      • weaknessforcats
        Recognized Expert Expert
        • Mar 2007
        • 9214

        #4
        static prevents duplicate definition errors at link time.
        The static keyword is a compile time directive. It generates code so that the variable is accessible only in the current implementation file. If this definition is in a header you will get a different variable in each implementation file that includes this header.

        You will also get a different string.

        The static keyword is how C developers resolve name re-definitions. The re-definition does not apply because there are separate static variables.

        The linker is not involved.

        The header file should never have code that generates instructions or allocates memory.

        Comment

        Working...