How to make two Forms access the same variables in C++Builder

Viewed 65

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 objects to the vector, the second Form B seems to be viewing a different vector that is empty.

How can I solve this?

1 Answers

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 then 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 where each of them has their own unique static variables, which are not visible to other translation units.

Related