Global variables and global functions are relative to local variables and local functions, not {} or for, if and so on are global variables or global functions, the simplest is to declare in the same file.
For example, in Mian.cpp
#include <iostream>
int Gresult;
int Gadd (int a, int b) {
return a + B;
}
int main (int argc, const char * argv[]) {
Gresult = Aadd (2, 3);
}
In this case, the main function above is all global variables and global functions, in the entire file can be called to, that is, the global variable is the entire file in which it is located.
But the question is, what do we need to do with global variables in other files, or do we need only one global variable for the entire project.
The declaration of the time is the same, but in the call need to use the extern keyword in the file used to re-declare it.
For example:
We declare a global variable and global function in the base.cpp.
#include <iostream>
#include "base.h"
int Gresult;
int Gadd (int a, int b) {
return a + B;
}
void print () {
std::cout<<gredult<<std::endl;
}
Now we need to call global variables and global functions in mian.cpp;
int mian (int argc, const char * argv[]) {
Re-declare global variables and global functions in base.cpp;
extern int Gresult;
extern int Gadd (int a, int b);
extern void print ();
Gresult = Gadd (2, 3);
You can see that two printing results are all 5, because they operate on the same global variable;
std::cout<<gresult<<std::endl;
Print ();
}
How to access global variables and global functions in C + +