Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is extern keyword required here, const in cpp file

Tags:

c++

If I have in header file

namespace Bob
{
    extern const T x;
};

And in source file

extern const T Bob::x = 123;

Is the second extern in the source file required or optional?

I've searched and found conflicting information.

From this webpage: http://msdn.microsoft.com/en-us/library/357syhfh.aspx

But to get the same behavior in C++, you must declare your const variable [in source file] as:

extern const int i = 2;
like image 591
Neil Kirk Avatar asked Oct 21 '22 05:10

Neil Kirk


1 Answers

Usually, the extern keyword tells the compiler not to define a symbol, because it will be defined somewhere else. So writing e.g.

namespace Bob {
    extern T x;
}

does not define the variable x, but rather declares it. You can have as many extern declarations as you like. However, if you do not provide a definition the linking will fail. So you have to define

T Bob::x;

somewhere in the code in order to provide the definition.

The const keyword is a little special here, because it implies internal linkage. This means, that the definition of x will not be visible outside the specific compilation unit where it was defined. To alter this behavior you do need to write

    extern const T Bob::x = 123;

if you want x to be const and also reference it from other compilation units.

----yet another edit----
Just to be absolutely clear: If a const variable is supposed to be referenced outside of its compilation unit, then you must explicitly declare it extern.

However, if the declaration is given separately from the definition, then the definition does not necessarily need to specify the keyword extern again. Yet another example for demonstration:

myheader.h

extern const int i;

This declares i a const integer with external linkage, but does not define it.

main.cpp, version 1

#include "myheader.h" //Through the include, the above declaration of `i` comes before its definition.

const int i=123; // Although the `extern` modifier is omitted here,
                 // it's still in effect because we already declared `i` as `extern`
                 // Therefore it makes no difference here, whether or not you specify `extern` again.
                 // The compiler knows this is a definition either way, because of the initialization.

main.cpp, version 2

//#include "myheader.h"

extern const int i=123; // this line is declaration and definition in one, because we did not include
                        // the declaration from myheader.h. Thus, to tell the compiler that you want
                        // `i` with external linkage, you MUST specify `extern`. Otherwise you'll get
                        // internal linkage.

I hope all this now makes sense to you.

like image 126
Alexander Tobias Bockstaller Avatar answered Oct 23 '22 04:10

Alexander Tobias Bockstaller