C++ LNK2001 Error on trying to use External Variable

279 Views Asked by At

I'm trying to create a utility class, that I can use thorough my program like logging, debugging and etc.

In Java, I know I can make it as by declaring the variables and functions static, as I read more how to do it in C++, I should use extern, surrounded by namespace to don't populate too much the files. Upon trying to initialize those extern variables, in the constructor class, I receive the following errors:

application.cpp.obj : error LNK2001: unresolved external symbol "class Application * Lib::app"

application.cpp.obj : error LNK2001: unresolved external symbol "class Graphics * Lib::graphics"

Which doesn't say much to me but that there is a linking problem? I have the following 2 files:

// lib.h
#ifndef LIB_H
#define LIB_H

#include "graphics.h"
#include "application.h"

namespace Lib {
    extern Application *app;
    extern Graphics *graphics;
}

#endif //LIB_H


// application.cpp
#include "include/application.h"
#include "include/lib.h"
.
Application::Application(Listener* listener, Configuration* config, Graphics* graphics) {
    .
    .
    // Our library for graphics
    this->graphics = graphics;
    .
    .
    // creating the environment utils
    Lib::app = this;
    Lib::graphics = graphics;
    .
    .
}
1

There are 1 best solutions below

2
On BEST ANSWER

extern means that you define your variables elsewhere. In your case, you must include the following in lib.cpp:

namespace Lib {
    Application *app;
    Graphics *graphics;
}

That said, your design is questionable:

In Java, I know I can make it as by declaring the variables and functions static

You can do the same in C++, and it would make more sense in this case.