0

as you know, constants defaults to internal linkage.

const int Buf = 1000;  // defaults to internal linkage

Buf can be defined in a header file, it's visible only within the files where it is defined and cannot be seen at link time by other translation units.

however, if some complicated structure constants are defined as below:

- constants.h
const complicatedClass myObject("I'm a const object","internal linkage",5);

complicatedClass definition:

class complicatedClass
{
private :
    char* charArry;
    std::string strTemp;
    static int numbers;
    int mSize;

public:
    complicatedClass();
    complicatedClass(char* pChrArry, std::string temp, int size);
    ~complicatedClass();

public:
    void print() const;
    std::string getStrTemp() const; 
};

it seems that compile must create storage for complicated structure constants, thus it should be external linkage. however, everything is ok when this constants header file (constants.h) was included in multiple files. I assume the linker error should be raised, myObject shouldn't be defined in many places(in multiple files)

can anyone explain this issue? thanks in advance.

yao
  • 31
  • 3
  • please refer to the section "const in header files" in this link: http://www.mi.uni-koeln.de/c/mirror/www.codeguru.com/cpp/tic/tic_html.zip/tic0092.html – yao Jul 09 '13 at 03:04
  • isn't clear to you? anyone would help this case? – yao Jul 17 '13 at 02:24

1 Answers1

0

Internal linkage does not mean no storage. Rather it means the variable is not visible in other translation units.

In C++ const allows the compiler to either create storage for the variable or not. Whether it does so or not depends on whether it needs it.

So in your example the compiler will create storage for myObject only if it needs it (which it probably does) because it is const. Also because it is const, myObject will also have internal linkage which means each translation unit will have its own copy of myObject if storage is required.

A simple test you can do to see this in action is to take the address of myObject in a number of different translation units (effectively in different cpp files) and print it out. This will do two things: force storage to be created for myObject even if it wasn't already; and you will see two different addresses because of the internal linkage.

Shane
  • 757
  • 3
  • 11