Agora
Agora

Reputation: 23

variable already defined error with namespace

I met "already defined error in AppDelegate.obj" with C++/cocos2dx.
This is my code in gamestage.h

#ifndef __GAME_STAGES_H__
#define __GAME_STAGES_H__

// stage 1;
namespace gamestage1
{
    int btn_number = 9;
}

#endif

game.cpp and menu.cpp use this gamestage.h file and there are no gamestage.cpp file.

Actually, I tried to use extern like:

extern int btn_number = 9;

but It didn't work.

*What can cause this? *

Upvotes: 2

Views: 3675

Answers (1)

Alok Save
Alok Save

Reputation: 206508

You should not define a variable in a header file and include that header in multiple translation units. It breaks the One definition rule and hence the error.
Remember that the header guards prevents multiple inclusion of the header within the same translation unit not within different translation units.

If you want to share the same global variable across multiple translation units then you need to use extern.

//gameplan.h

// stage 1;
namespace gamestage1
{
    extern int btn_number;
}

//game.cpp

#include "gameplan.h"
namespace gamestage1
{
    int btn_number = 9;
}

//menu.cpp

#include "gameplan.h"

Upvotes: 10

Related Questions