Use of extern

I wrote two programs
#include <iostream>
//#include <string>
using namespace std;
int k=50;
int main()
{
cout << k;
}
& second one
#include <iostream>
#include <string>
using namespace std;
extern int k;
int main()
{

cout << k;
}
But in second one i am getting the error that "Undefined reference to k."Did i do any wrong?
Yes, if you write extern the compiler doesn't resolve the variable because extern says that the variable is defined somewhere else. If the variable isn't defined somewhere else the linker will complain

[EDIT]
And no, the second program doesn't take the variable from the first because they're not linked in any way
Last edited on
By using extern, you are telling the compiler that you don't want to declare a new variable , but want to refer to a variable that has been declared in another file.

An example:
1
2
3
4
5
6
7
8
9
10
11
// main.cpp

void print();
int k;

int main()
{
    k = 50;    
    print();
    return 0;
}

1
2
3
4
5
6
7
8
9
10
// print.cpp

#include <iostream>

extern int k; // refrences global k in main.cpp

void print()
{
    std::cout << k;
}

Output:
50


Edit:
Fixed some mistakes.

Edit 2:
coder777's post showed up for me after I posted mine. After reading their's, I realized that I should clarify that main.cpp and print.cpp in my example are linked, so they are a part of the same program. It wouldn't work to share variables in this way between separate programs.
Last edited on
That it wouldl be clear I will show at first a simple example.

1
2
3
4
5
6
void f();

int main()
{
   f();
}


The compiler will issue the same error as in your example: "Undefined reference to f." Why do the compiler issue the error? Because function void f(); is only declared. It is not defined.

Now let return to your example.

extern int k; is only declaration of variable k It is not a definition of the corresponding object. That to make a definition of the variable you should either initialize it in the same statement as for example

extern int k = 0;

Or include another statement which defines the object

extern int k;
int k;

Last edited on
Topic archived. No new replies allowed.