Can't initialize a static point in a header?

Hello,
I guess this is not cocos strictly related so I posted in c++ forum.
I am having trouble understanding why this works:

// this is in a gameGlobals.h 
struct GameGlobals
{
public:
    static ParallaxInfiniteNode* level1ParallaxNode;
   //...more code
}

//this is in the source file
#include "gameglobals.h"
USING_NS_CC;

ParallaxInfiniteNode* GameGlobals::level1ParallaxNode = nullptr;  // all good
//...more code

but if I simply add this last line in the header file as so:

// this is in a gameGlobals.h 
struct GameGlobals
{
public:
    static ParallaxInfiniteNode* level1ParallaxNode;
   //...more code
}
ParallaxInfiniteNode* GameGlobals::level1ParallaxNode = nullptr;  // ERROR

I am not sure why assigning nullptr in the source file make everything work ok as expected, but taking that very same line from the source file to the header file fives a linking error (LNK1169: one or more multiply defined symbols found.) It is not possible to initialize a static null pointer in the header?

You can only define/initialize a static member field once in a linked product/target/executable, therefore you must be compiling and linking two or more .cpp files that include gameGlobals.h and thus level1ParallaxNode gets defined as many times as the number of those .cpp files.

So when you only define it in the one .cpp source file it works because you’ve declared it across all .cpp files that include the header (ie: translation units), but you only define it once (and is thus only defined in one .o object file).

Either (1) only initialize it in one .cpp source file like you did in the case that worked, or (2) make it inline and directly initialize the value inside the class field declaration itself, though I believe this requires using c++17?

inline static ParallaxInfiniteNode* level1ParallaxNode = nullptr;
1 Like

Fantastic, thanks for the detailed explanation.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.