It gives me the following error and the truth... after hours looking and looking... I don't understand the reason.
Mistake:
➜ build git:(master) ✗ make [ 20%] Building CXX object src/CMakeFiles/App.dir/App.cpp.o [ 40%] Linking CXX static library libApp.a [ 40%] Built target App [ 60% ] Building CXX object src/CMakeFiles/MLog.dir/MLog.cpp.o [ 80%] Building CXX object src/CMakeFiles/MLog.dir/App.cpp.o [100%] Linking CXX executable MLog CMakeFiles/MLog.dir /App.cpp.o: In function
App::getApp()': App.cpp:(.text+0x50): referencia a
App::app' undefined App.cpp:(.text+0x71): reference toApp::app' sin definir App.cpp:(.text+0x78): referencia a
App::app' undefined collect2: error: ld returned 1 exit status src/CMakeFiles/ MLog.dir/build.make:126: Failed instructions for target 'src/MLog' make[2]: * [src/MLog] Error 1 CMakeFiles/Makefile2:87: Failed instructions for target 'src /CMakeFiles/MLog.dir/all' make[1]: * [src/CMakeFiles/MLog.dir/all] Error 2 Makefile:83: Failed instructions for target 'all' make: *** [all] Error 2
The CMakeList.txt:
add_library(App App)
ADD_EXECUTABLE(MLog MLog App)
target_link_libraries(MLog App)
App.h:
#ifndef _APP
#define _APP
#include <iostream>
class App
{
public:
void getMensaje();
static App *getApp();
protected:
App();
private:
static App *app;
};
#endif
App.cpp:
#include "App.h"
App::App()
{
}
void App::getMensaje()
{
std::cout << "Esta es la url" << std::endl;
}
App *App::getApp()
{
if(!app)
{
app = new App();
}
return app;
}
MLog.cpp:
#include "App.h"
App *monitor = 0;
int main()
{
App *app = monitor->getApp();
app->getMensaje();
}
You have to instantiate the static variable
app
.In C++, the instantiation of static variables takes place in 2 steps:
Statement.
You have it done in the
App.h
.instantiation
It is what you lack. In
App.cpp
, after the includes , dowithout putting
static
or anything, just its type, name, and value. That should be enough.