1

how can i access a static vector variable in main file which is declared in header file and populated in source file.Actual code is little bit big so below is an example what i have tried.

class.h

class a{

    private:
      int x;

    public:
      friend void createVec();
};

void createVec();
static std::vector<a> vec;

source.cpp

include"class.h"

extern std::vector<a> vec; //if i remove this line code runs and don't show any error 
                           // -of undefined variable
void createVec()
{
  for(int i=0; i<9; i++)
  {
    vec.push_back(i); //while debugging and watching vec, code is able to populate vec
                      //but i doubt whether is it vector declared in class.h or not
  }
}

main.cpp

#include "class.h"

extern std::vector<a> vec;
int main()
{
  createVec();
  cout<<vec.size() //it prints 0 instead of 10  
}
Rahul
  • 47
  • 1
  • 7

3 Answers3

1

In your example, you're declaring vec to be static. In this context (a global/static variable), this means the variable should exist only in the translation unit (.cpp file) where the declaration is found.

Since you've put this inside the .h file and #included this in several source files, the two .cpp files will both have their own static std::vector<a> vec, rather than sharing the same one. Hence, pushing back in one file does not affect the vector in the other.

The solution here is to remove static from the declaration of vec and move it into one of the cpp files.

To clarify: putting the declaration of a variable in global scope automatically gives it static storage duration, which means its lifetime ends after main returns. Using extern means you specify that the variable has been declared in another .cpp file. Declaring a global variable static only means it will not be available in other .cpp files. Hence, if you want to use a global variable in multiple .cpp files, it should be delared in one, without static, and you should declare it as extern in all other .cpp files where it is used.

Agentlien
  • 4,996
  • 1
  • 16
  • 27
0

in class.h:

extern std::vector<a> vec;

in source.cpp:

std::vector<a> vec;

in main.cpp: remove the declaration, including class.h in enough

Pat
  • 1,726
  • 11
  • 18
0

I would argue against sharing vectors over translation units, because I believe in avoiding global instances when possible.

You can do that by putting the vector in a class, together with the populateVector() and printVector() functions, and then instantiate that class in main and call the functions.

stefaanv
  • 14,072
  • 2
  • 31
  • 53