2

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? *

Alok Save
  • 202,538
  • 53
  • 430
  • 533
Agora
  • 23
  • 1
  • 3
  • 1
    Take this to heart: http://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier – chris May 11 '13 at 05:40
  • This isn't the problem, but names that contain two underscores (`__GAME_STAGES_H__`) and names that begin with an underscore followed by a capital letter are reserved to the implementation. don't use them. – Pete Becker May 11 '13 at 13:08
  • Note that a declaration that includes an initializer (`extern int btn_number = 9;` is a definition, even if it's marked `extern`. – Pete Becker May 11 '13 at 13:09

1 Answers1

10

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"
Community
  • 1
  • 1
Alok Save
  • 202,538
  • 53
  • 430
  • 533