Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shared Vector Variables Among Multiple C++ files

Tags:

c++

variables

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

like image 846
ehsan moghadam Avatar asked May 02 '13 22:05

ehsan moghadam


People also ask

How do you declare global variables in multiple files?

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.

Is it possible to use global variable in another .c file?

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.

Can we declare global variable in header file?

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.


1 Answers

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).

like image 111
Nemanja Boric Avatar answered Sep 28 '22 00:09

Nemanja Boric