J
John Goche
Hello,
The extern keyword can be used in C and C++
to share global variables between files by
declaring the variable in header file and
defining it in only one of the two files.
For example, if x were not declared
extern in the header file below then
the linker would complain about x
being multiply defined.
--------------------
// main.cpp
#include "hello.h"
int x;
int main() {
x = 0;
hello();
}
--------------------
// hello.h
#ifndef HELLO_H
#define HELLO_H
extern int x;
void hello();
#endif // HELLO_H
--------------------
// hello.cpp
#include <iostream>
#include "hello.h"
void hello() {
std::cout << x << std::endl;
}
----------------------------------
output: 0
----------------------------------
However, I don't quite understand how
using the keyword static in the header
file allows us to define the variable
in the header file and include the
header file in multiple files.
After all, both global variables
and static variables are placed
in the static data segment of a
computer program when loaded
into memory so what is the
difference? Also, why is
1 still being printed in
the second case instead
of 0?
--------------------
// main.cpp
#include "hello.h"
int main() {
x = 0;
hello();
}
--------------------
// hello.h
#ifndef HELLO_H
#define HELLO_H
static int x = 1;
void hello();
#endif // HELLO_H
--------------------
// hello.cpp
#include <iostream>
#include "hello.h"
void hello() {
std::cout << x << std::endl;
}
The extern keyword can be used in C and C++
to share global variables between files by
declaring the variable in header file and
defining it in only one of the two files.
For example, if x were not declared
extern in the header file below then
the linker would complain about x
being multiply defined.
--------------------
// main.cpp
#include "hello.h"
int x;
int main() {
x = 0;
hello();
}
--------------------
// hello.h
#ifndef HELLO_H
#define HELLO_H
extern int x;
void hello();
#endif // HELLO_H
--------------------
// hello.cpp
#include <iostream>
#include "hello.h"
void hello() {
std::cout << x << std::endl;
}
----------------------------------
output: 0
----------------------------------
However, I don't quite understand how
using the keyword static in the header
file allows us to define the variable
in the header file and include the
header file in multiple files.
After all, both global variables
and static variables are placed
in the static data segment of a
computer program when loaded
into memory so what is the
difference? Also, why is
1 still being printed in
the second case instead
of 0?
--------------------
// main.cpp
#include "hello.h"
int main() {
x = 0;
hello();
}
--------------------
// hello.h
#ifndef HELLO_H
#define HELLO_H
static int x = 1;
void hello();
#endif // HELLO_H
--------------------
// hello.cpp
#include <iostream>
#include "hello.h"
void hello() {
std::cout << x << std::endl;
}