C++ “extern”
“extern” allow us using the same variable among different transition units(cpp files).
Get chuuuing’s stories in your inbox
Join Medium for free to get updates from this writer.
RegisterDay.cpp: here the count is declared & defined the first time in the whole program.
namespace gym {
int count; void FirstTraining() {
count += 1;
}
}
TrainingDay.hpp: I also want to add up to the same variable count, to do so, I need to tell the program this count has already been declared somewhere (in our case, in RegisterDay.cpp).
namespace gym {
extern int count;
}Now in TrainingDay.hpp, I have informed the existence of count, I’m able to use it in all the *.cpp files which include TrainingDay.hpp file. For example:
CardioDay.cpp:
namespace gym {
void run() {
count += 1;
}
}






