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

3
  • 1
    Take this to heart: stackoverflow.com/questions/228783/… Commented May 11, 2013 at 5: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. Commented May 11, 2013 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. Commented May 11, 2013 at 13:09

1 Answer 1

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"
Sign up to request clarification or add additional context in comments.

2 Comments

Oh, Thanks for your fast answer. Does it break the one definition rule although I used #ifndef and #define at the top of code?
@Agora: Updated to answer your question in detail.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.