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
The clean, reliable way to declare and define global variables is to use a header file to contain an extern declaration of the variable. The header is included by the one source file that defines the variable and by all the source files that reference the variable.
Every C file that wants to use a global variable declared in another file must either #include the appropriate header file or have its own declaration of the variable. Have the variable declared for real in one file only.
ANSWER. Yes. Although this is not necessarily recommended, it can be easily accomplished with the correct set of macros and a header file. Typically, you should declare variables in C files and create extern definitions for them in header files.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With