compile multi files and variable declare and define

I got three files: p1.cpp, p2.cpp and p.h and they are defined as:
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
p.h:
#include <iostream>
using namespace std;
extern int x;
const int z(9);
void display();

p1.cpp:
#include "p.h"
void main()
{
cout<<"enter two int for x"<<endl;
cin>>x;

cout<<"x="<<x<<endl;

cout<<"z="<<z<<endl;
display();
}


p2.cpp:
#include "p.h"
void display()
{
cout<<"display x="<<x<<endl;

cout<<"display z="<<z<<endl;
}


you will find compiler will give an error that "x is undefined", what is the problem?
if I change the "extern" into "static", program can be compiled, while when I input 6 for x, the main() will ouput x=6 and display() will output x=0; what is the problem?

how could I use a single variable in multi files, and they are using really the same one. Thanks.
Last edited on
extern int x; declares x, you need to define it on one of the source files
And use [code][/code] tags please
Thanks, I tried define x in p1.cpp, outside the main() function, it did what I want.

so, What "static" do at all?
static says that it's going to be local to that file
Topic archived. No new replies allowed.