EDIT: correct function names, and added #pragma once
This is a very strong simplification of my problem, but if I do this:
A.h
#pragma once
static int testNumber = 10;
void changeTestNumber();
A.cpp
#pragma once
#include "A.h"
void changeTestNumber()
{
testNumber = 15;
}
B.h
#pragma once
#include "A.h"
// some other stuff
B.cpp
#pragma once
#include "B.h"
// some other stuff
main.cpp
#pragma once
#include "B.h"
#include <iostream>
int main(){
changeTestNumber();
std::cout<<testNumber<<std::endl;
return 0;
}
Why am I not getting testNumber = 15 at the call out? What really happens when I use a function that is included in a header of my included header? If I remove the static in from of int testNumber, I will get some error about my testNumber being initialized twice.
So is my header compiled twice when I do this?
Thanks in advance!
Aside from the obvious incorrect naming (which I assume was simply a matter of hastily creating an analogous example and is not the actual issue in your code), you need to declare the variable as extern
in your .h/.hpp file. You cannot have an extern
variable that is also static
since the (one of the) use(s) of static
is to keep the variable contained to within a single .cpp
file.
If you change:
static int testNumber = 10;
in your A.h
file to:
extern int testNumber;
and then in your A.cpp
file do something like:
#include "A.h"
int testNumber = 10;
Now go ahead and run:
int main() {
//changeNumber();
std::cout << testNumber << std::endl; // prints 10
changeTestNumber(); // changes to 15
std::cout << testNumber << std::endl; // prints 15
std::cin.ignore();
return 0;
}
Be sure to fix the function names!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With