-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathmain.cpp
executable file
·83 lines (61 loc) · 1.65 KB
/
main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/*
* Extern.cpp
*
* Created on: Feb 22, 2012
* Author: behnam
*/
#include <iostream>
/*http://www.learncpp.com/cpp-tutorial/42-global-variables/
* Variables declared outside of a block are called global variables. Global
variables have program scope,
* which means they can be accessed everywhere in the program, and they are only
destroyed when the program ends.
int g_nX; // global variable
int main()
{
int nY; // local variable nY
// global vars can be seen everywhere in program
// so we can change their values here
g_nX = 5;
} // nY is destroyed here
*/
/*
In order to use a global variable that has been declared in another file, you
have to use a forward declaration or a header file, along with the extern
keyword.
global.cpp:
// declaration of g_nValue
int g_nValue = 5;
main.cpp:
// extern tells the compiler this variable is declared elsewhere
extern int g_nValue;
int main()
{
g_nValue = 7;
return 0;
}
_________________________________________________________________________________________________________________
Here is an example of using a header file extern:
global.cpp:
// declaration of g_nValue
int g_nValue = 5;
global.h:
#ifndef GLOBAL_H // header guards
#define GLOBAL_H
// extern tells the compiler this variable is declared elsewhere
extern int g_nValue;
#endif
main.cpp:
#include "global.h"
int main()
{
g_nValue = 7;
return 0;
}
*/
using namespace std;
int Externmain()
// in main()
{
return 0;
}