简体   繁体   中英

Declaring and initializing a static int in a header

If I have the following in a header file:

Foo.h

Foo
{
public:
  static const int BAR = 1234;
  ...
};

Do I also need to define the variable in the .cpp, eg:

Foo.cpp

const int Foo::BAR;

We have an issue where initializing a static in a header seems to work on MS compilers but with gcc on the Mac it seems to give linker errors.

You need both the declaration and the definition, just as you've written them.

Since it is an integer, you can initialise it in the declaration as you've done, and the compiler should treat it as a compile-time constant when it can. But it still needs one (and only one) definition in a source file, or you'll get link errors when it can't be treated as a constant.

Apparently, Microsoft decided that the standard behaviour was too confusing, and "extended" the language to treat a declaration with an initialiser as a definition; see this issue . The result is that you get link errors (multiply defined symbols) if you also define the symbol correctly. You can get the standard behaviour by disabling language extensions ( /Za ).

The first fragment works for some environments but the definition really is required by some compilers and of course if you take the address of your constant.

If you don't like to have to touch header and body to introduce the constant, there still is the old enum-trick:

class A
{
   public:
       enum { someconstant=1234 };
};

makes someconstant available as a compile time constant without the need of a definition in the body.

Declarations should be done in the headers and initializations should be done on the .cpp

There's an interesting article about static member variables here .

The header file

Foo
{
public:
  static const int BAR;
  ...
};

The code file

const int Foo::BAR = 1234;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM