Home > Software engineering >  How to make two forms access the same variables in c builder
How to make two forms access the same variables in c builder

Time:05-23

I have two forms, both are including the same .cpp file that has these global variables

static vector<News> allNews;
static vector<user> allUsers;
static admin appAdmin("admin", "adminpassword");
static int userIndex =0;

the problem is that when form A adds news to the vector, the second form B seems to be viewing a different vector that is empty.

how can I solve this ?

CodePudding user response:

both are including the same .cpp - never include .cpp files. Make a .h file with the content

extern vector<News> allNews;
extern vector<user> allUsers;
extern admin appAdmin;
extern int userIndex;

And update the .cpp file by removing static

vector<News> allNews;
vector<user> allUsers;
admin appAdmin("admin", "adminpassword");
int userIndex =0;

Include the newly created .h file into the forms.


If you include the .cpp file with the static variables into two forms, you get two translation units each of them gets their unique static variables, not visible to other translation units.

  • Related