I want to implement a source file that contains a global variable, and I want to do this through inline static. I can change a variable (e.g., i) within the context of a translation unit, but when I call the variable outside of that translation unit, the result will remain unchanged for the caller. It's like there is a copy for each unit. See the below example:
header.h
#ifndef UNTITLED1_TEST_H
#define UNTITLED1_TEST_H
namespace t {
inline static int i{0};
void inc() ;
void print_i() ;
}
#endif //UNTITLED1_TEST_H
header.cpp
#include "header.h"
void t::inc() {
t::i++;
}
void t::print_i() {
std::cout << t::i << std::endl;
}
So let's see how the program performs:
main.cpp
#include "header.h"
int main() {
t::inc();
std::cout << t::i << std::endl; // -> output is: 0
t::print_i(); // -> output is : 1
}
As you can see, the variable i has different values across different translation units, how can this be resolved? I cannot use classes or anything else since the client wants the code in this format.
note
I can do such things as below, but it isn't the main issue, I want a global variable:
t::i++; //instead of t::inc();
std::cout << t::i << std::endl; // it's okay now, but it's not what I wanted
Alternatively, I can use inline instead of inline static. It seems to be working, but my mentor said that I should use inline static instead.