Doubt regarding extern usage

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • solita
    New Member
    • Jun 2009
    • 17

    Doubt regarding extern usage

    Will this compile? I have 1 header file , and it is included in 2 source files.
    1. What about re-declaration error ? (for arraysize... )
    2. #include always = textual substitution ??? Or does it have some intelligence ?

    my header file - consts.h:
    const int arraysize = 15;

    my sources file 1 - op1.cpp:

    #include "consts.h"
    char array1[arraysize];

    my source file 2 - op2.cpp:

    #include "consts.h"
    char array2[arraysize];
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    In C++ that is not a problem, a const automatically has static linkage scope so it is fine to put a const like that into a header file.

    Additionally since C++ consts are much more constants than C consts (which are really just read only variables) the compiler is likely to be able to optimise away the variable arraysize away so that you don't end up with multiple copies of it. The cases where it can include places where you take a pointer to a reference to the constant.

    Comment

    • weaknessforcats
      Recognized Expert Expert
      • Mar 2007
      • 9214

      #3
      The better solution is to define a const int that is sharable. That is, one that has external linkage:

      Code:
      //consts.cpp
      
      extern const int arraysize = 15;
      
      
      //consts.h
      my header file - consts.h:
      extern const int arraysize;

      You should never define objects in header files. Every time the header is included you get another object. That may cause the link to fail and it may cause bloat.

      Comment

      • solita
        New Member
        • Jun 2009
        • 17

        #4
        Do we need extern keyword in both cpp and .h file?.

        Comment

        • Banfa
          Recognized Expert Expert
          • Feb 2006
          • 9067

          #5
          You need the extern in the cpp file because constant variables default to static linkage (unlike other variables that default to external linkage). To give the variable defined in the cpp file external linkage it needs to be explicitly stated.

          Or the short version: Yes.

          Comment

          Working...