Common vector variables among several C ++ files

I want to share (globalize) some vector variables (V1 and V2) between two cpp files (A.cpp and B.cpp). I have already defined V1 and V2 in Ah with the following commands.

extern vector<uint64_t> V1; extern vector<uint64_t> V2; 

I also added #include "Ah" to A.cpp and B.CPP files. Can someone tell me what else I have to do to have access to elements V1 and V2 in both of these CPP files?

Thanks at Advance

+6
source share
3 answers

First, you need to pick up the place where your vectors should be defined. Let's say you choose A.cpp .

In A.cpp (in only one file - defining the same object in several files will result in the error of several specific characters) define vectors as global variables:

  vector<uint64_t> V1; vector<uint64_t> V2; 

In B.cpp (and in all other files from which you want to access V1 and V2 ) declare vectors as extern . This will tell the linker to look elsewhere for real objects:

  extern vector<uint64_t> V1; extern vector<uint64_t> V2; 

Now, at the linking stage, V1 and V2 from B.cpp will be connected to V1 and V2 from A.cpp (or if these objects are defined ).

+7
source

extern means that it is only a DESCRIPTION of variables, it DOES NOT DEFINE them. You need exactly one DEFINITION of these variables somewhere in some source file (and not in the header). DEFINITION looks exactly like a DECLARATION without extern

+2
source

You created an ad in your header file; Now you need to create the definition in one compilation unit (.cpp file).

So, select the .cpp file and put the definition there. In this case, the definition is the same as the declaration except for the extern keyword.

 vector<uint64_t> V1; vector<uint64_t> V2; 
+2
source

Source: https://habr.com/ru/post/944166/


All Articles