Issue declaring extern class object

后端 未结 4 1086
孤街浪徒
孤街浪徒 2020-12-21 12:37

Let me start by saying I\'ve extensively searched for answers on google and more specifically here.

The thing is I actually (at least I think I did) found people wit

相关标签:
4条回答
  • 2020-12-21 12:47

    "extern Player john;" is considered to be undefined identifier as the compiler is unable to understand what Player is, as you have not included the file Player.cpp where the class Player is declared to cc.h . It is always recommended to declare the class and its methods in header files say for example in Player.h and then define these methods in the source file i.e Player.cpp. And to include Player.h in your cc.h so that compiler understands where " Player john;" is declared.

    0 讨论(0)
  • 2020-12-21 12:51
    1. You need to define the Player class, in your header file
    2. Use extern to use variable that has an external linkage, and is already defined in some other file.

    For example: you have file a.cpp, and inside this file has a global variable Player p. If you want to use the same exact instance p of Player in file c.cpp, then inside file c.cpp you write extern Player p.

    I hope i made myself clear.

    0 讨论(0)
  • 2020-12-21 12:59

    You need to put the definition of your Player class in the header file, before you declare the extern variable. Otherwise the compiler has no idea what Player is.

    I suggest something like this:

    player.h

    #ifndef PLAYER_H_
    #define PLAYER_H_
    
    class Player {
        ...
    };
    
    #endif
    

    player.cpp

    #include "player.h"
    
    Player john;
    

    cc.h

    #ifndef CC_H_
    #define CC_H_
    
    #include "player.h"
    
    extern Player john;
    
    #endif
    
    0 讨论(0)
  • 2020-12-21 13:04

    The global declaration in cc.h would not help you, I guess - because you declare it to access it from else where (other than Player.cpp), but for this you need the method signatures - a soon as you want to access john from elsewhere and thus include Player.cpp, you get duplicates symbols.

    Please consider creating a Player.h file where only the class and method signatures are declared - like this:

    #ifndef PLAYER_H_
    #define PLAYER_H_
    
    class Player
    {
         void doSomething();
    };
    #endif
    

    and add this to cc.h:

    #include <Player.h>
    extern Player john;
    

    and in your Player.cpp

    #include <Player.h>
    
    Player john;
    
    void Player::doSomething()
    {
        //...
    }
    

    This makes sure that the Player signatures are known and a valid instance is declared globally.

    0 讨论(0)
提交回复
热议问题