Answer the question
In order to leave comments, you need to log in
How to create a global object for all project elements?
I want to create a global vector in the project. It is needed so that all forms / classes of the project have access to the same data. The problem is visible on the screenshot:
The screenshot shows part of the code (the global variable declaration itself) of the header.h file, which I include in the files where I want to use this vector.
Answer the question
In order to leave comments, you need to log in
The declaration of the tasks vector must be present in the corresponding cpp file (technically, in any other translation unit) besides extern in the h file in the screenshot. But generally speaking, there is a "singleton" pattern, it is much more feng shui for this situation.
Well , extern tells the compiler that somewhere (in some cpp module) this object is without extern.
In general, you should read about singletons in C ++, but if you are lazy, the safest option is the Myers singleton:
#include <string>
// Синглтон Майерса. Переменная str будет создана один раз при первом вызове getPrefix, начиная с c++11 это ещё и потокобезопастно.
const std::string& getPrefix(){
static std::string str {"pref::"}; // Инициализация должна быть в конструкторе.
return str;
}
// Его использование.
std::string addPrefix(const std::string& str){
return getPrefix() + str;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question