Search code examples
c++includeextern

LinkingError with extern keyword


I have a trouble about extern variable. I declared engineInstance variable at the beginning of cpp file like in below.

vkWrapper::EngineInstance* engineInstance;

But when I use it in hpp file by using extern keyword I'm taking that linking error.

"1>vkInit.obj : error LNK2001: unresolved external symbol "struct vkWrapper::EngineInstance * vkWrapper::engineInstance" (?engineInstance@vkWrapper@@3PEAUEngineInstance@1@EA)"

namespace vkWrapper
{
    void InitRenderEngine(uint32_t windowWidth, uint32_t windowHeight, const char* winName);
    void TerminateRenderEngine();

    struct EngineInstance
    {
        uint32_t winWidth;
        uint32_t winHeight;

        GLFWwindow* window;
        VkInstance instance;
        VkSurfaceKHR surface;

    private:
        EngineInstance() = default;
        EngineInstance(const EngineInstance& copy) = delete;
        EngineInstance(EngineInstance&& move) noexcept = delete;
        ~EngineInstance() = default;

        friend void InitRenderEngine(uint32_t windowWidth, uint32_t windowHeight, const char* winName);
        friend void TerminateRenderEngine();
    };

    extern EngineInstance* engineInstance;

Solution

  • You need another vkWrapperin the definition in the cpp file

    vkWrapper::EngineInstance* vkWrapper::engineInstance;
    

    otherwise the type will be from the namespace, but not the variable.