Hello. I've been learning C++. I've recently decided to try and learn the vital skill of splitting my code between multiple files in a project. However, I'm having an issue.
I declare variables in one cpp. I extern them in it's header. I #include that header in another cpp. I can use the variables right. But here's the problem. If I run a function from the first cpp that assigns values to those variables, when I try to use them in a function from the second file, they're empty. I assume this is an issue with them going out of scope, but how can I prevent it? This issue has had me stumped for days, so I'd really appreciate some help. If this doesn't quite make sense, I can link my source.
I'm guessing that you haven't called the function that assigns the values in your second cpp.
source1.cpp:
1 2 3
#include "header.h"
int a;
void intialize() { a = 0; }
header.h:
1 2
externint a;
void initialize();
source2.cpp:
1 2 3 4 5 6 7 8
#include "header.h"
#include <iostream>
int main()
{
std::cout << a; // will output an uninitialized value
initialize(); // sets a
std::cout << a; // will output 0
}