Tell me how to implement the following. There are about 8 pairs of .h and .cpp files, in one of them there is a function that reads the entered data. I need to remember this data so that I can use it in the rest of the files. How to implement it? On the Internet, I found something about extern , but nothing happened.

    2 answers 2

    Wherever you are going to use a global variable, include its declaration (declaration), for example, let it be in some kind of common header. And only in one of the cpp modules define this variable (definition)

    File 1:

     int GlobalVariable; // определение в одном файле. здесь переменная "будет жить" void SomeFunction(); void AnotherFunction(); int main() { GlobalVariable = 1; SomeFunction(); AnotherFunction(); return 0; } 

    File 2:

     extern int GlobalVariable; // декларация во всех пользующихся файлах void SomeFunction() { ++GlobalVariable; } 

    File 3:

     extern int GlobalVariable; // декларация во всех пользующихся файлах void AnotherFunction() { --GlobalVariable; } 
    • Thank you, everything worked! And if I also need to create the type char, then I do this in the main file: char * ci [size], and in all the others this way: extern char * ci [size]. Is this correct? After all, the array itself, I can not perevovat means simply allocate space and create a pointer? - Maxim Ignatiev
    • It depends on what you want to get. char * ci [size] - this will be an array of the size of the elements of pointers to strings. If you want to work with a string, then you need char ci [size]. Yes, in other modules you will need to write extern char * ci [size] or extern char ci [size], respectively. Regarding the transfer of the array, I remind you that the name of the array is a pointer to the beginning of the array. - gecube pm
    • I need to work with a string. If I declare in a clav file like this: char cI [BUF_SIZE]; then the program does not compile and gives the following error: globVars.obj: error LNK2005: "char * cI" (? cI @@ 3PADA) already defined in Diplom.obj I declare a variable in another file as follows (extern char cI [BUF_SIZE]; and I also tried extern char * cI [BUF_SIZE];), but if I do this in the main file: char * cI [BUF_SIZE]; then everything is compiled, but as I understood it will not be what I need. : (tell me what's wrong? - Maxim Ignatiev
    • Everything was decided thanks, he blunted himself. - Maxim Ignatiev

    In general, IMHO, since the problem is solved in C ++, it is better to design it right away, because global variables are still evil. ;) Namely, do the following:

    1. In one source to create a class that manages everything - Manager;
    2. In another, implement a class that reads data and stores it - DataReader;
    3. In the rest - other logic of work that implements everything that you need.

    Proper architecture will solve many problems. Example:

    file "data_reader.h"

     struct MyData { // ... мои данные ... int my_field; }; class DataReader { MyData my_data; public: bool ReadData( const std::string& data_file ) { // ... считываем входные данные в my_data ... return true; } // по требованию использующей стороны отдаём данные TMyData& Data() { return my_data; } }; 

    file "manager.h"

     #include "data_reader.h" #include "mylogic1.h" #include "mylogic2.h" // ... #include "mylogic8.h" #include <string> 

    class Manager { DataReader data_reader; MyLogic1 my_logic1; MyLogic1 my_logic2; // ... MyLogic1 my_logic8; bool init_ok; public: // В конструкторе менеджера сказать всем классам, реализующим мою логику, // откуда брать прочитанные данные Manager(const std::string& data_file) : my_logic1 (data_reader) , my_logic2 (data_reader) // ... , my_logic8 (data_reader) { init_ok = data_reader.ReadData(data_file); } // bool IsInitOk() { return init_ok; } // void Work() { my_logic1.Work(); my_logic2.Work(); // ... my_logic8.Work(); } };

    Implementing my logic "mylogic1.h"

     #include "data_reader.h" 

    class MyLogic1 { DataReader & dr; public: MyLogic1 (TDataReader & data_reader) : dr (data_reader) {} // void Work () { // ... my work logs; when I need read data, I do this: printf ("Readen data:% dn", dr.Data (). my_field); // (!) So we will not need to use any global variables ... } };

    files mylogic2.h ... mylogic8.h

     // Прочие файлы, с реализацией моей логики; они также используют DataReader::Data(), // чтобы получить доступ к считанным данным. 

    file "main.cpp"

     #include "manager.h" 

    int main (int argc, char * argv []) { // Initialize the manager Manager manager ("my.dat"); // If initialization was successful, we work if (manager.IsInitOk ()) { manager.Work (); return 0; } // Mistake return 1; }

    The benefits of implementing non-global variables are many. The main ones are:

    • There will be no confusion of variable names when you develop a complex program;
    • You yourself can choose where to store ALL of the data "en masse" (an instance of the Manager class): on the stack, on the heap or even make it global;
    • You can create many managers (depending on the task) and manipulate them as you like;
    • and much more... :)

    Well, + I propose to read about C ++ design patterns in general, because what I've been doing here is their “bicycle” mix. :)