Search code examples
c++pointersheaderextern

How to declare extern class pointers in C++?


The following is declared variable in the cpp file but I get an error, so I have conducted a research and I found that I need to declare it in the header file. therefore how can I declare and an extern class pointer in the header file

 extern AnimationController* g_pAnimationController;

Solution

  • Just like how you have there. Ex:

    // In header file:
    // Declare the pointer with external linkage.
    extern int* my_global_int;
    
    // In source file:
    // Define the pointer so that the linker can link stuff together with the code
    // referencing the `my_global_int` symbol.
    int* my_global_int = 0;
    

    For classes and structs, if the type is unknown, then we need a forward declaration so that the compiler has some idea of what it is. But we can combine it with the declaration, like so:

    // In header file:
    extern class AnimationController* g_pAnimationController;
    

    Or written more verbosely:

    // In header file:
    class AnimationController;
    extern AnimationController* g_pAnimationController;
    

    Update for comment question:

    #include <map>
    #include <string>
    
    // Declare AnimationCallback
    extern std::map<std::string, AnimationCallback*> g_mCallbackMap;