7
votes

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

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

I also have added #include "A.h" to both A.cpp and B.CPP files. Can anyone let me know what else should I do to be able to access the elements of V1 and V2 in both of these CPP files?

Thanks in Advance

3

3 Answers

10
votes

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

In A.cpp (only in one file - defining same object in multiple files will yield multiple defined symbols error) 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 linker to search elsewhere for the actual objects:

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

Now, in the linking step V1 and V2 from B.cpp will be connected to the V1 and V2 from A.cpp (or whereever these objects are defined).

2
votes

extern means that this only DECLARES the variables, it does not DEFINE them. You need exactly one DEFINITION of these variables somewhere in some source file (not header). The DEFINITION looks exactly like the DECLARATION without the extern

2
votes

You've created a declaration in your header file; now you need to create the definition in a single compilation unit (.cpp file).

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

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