extern int x;
tells the compiler: “I will provide you a int x
in some other compilation unit”. Please expect to find it at link time.
So, you need another file:
example8b.cpp
int x = 0;
int y = 0;
int z = 0;
and you need to link both files in your project.
But most importantly:
What made you choose to put x
, y
and z
as extern in the first place ?
To end the discussion below:
extern int x;
means “There will be an x somewhere”int x;
means “please put anx
here”undefined reference to x
means “I did not find where you wanted x to be”
The compiler needs a place to put your x
. You did not give it such place, because extern
specifically asks the compiler not to put x
there. The error is the compiler telling you to put x
somewhere.
The doubts are cleared. The solved problem(Code Edited)
#include<iostream>
extern int x = 0;
extern int y = 0;
extern int z = 0;
int main(){
x = 10;
y = 15;
z = (x>y ? x: y);
std::cout<<z;
return 0;
}
or
#include<iostream>
extern int x;
extern int y;
extern int z;
int main(){
int x = 10;
int y = 15;
int z = (x>y ? x: y);
std::cout<<z;
return 0;
}
Reference:
Example 1:
extern int var;
int main(void)
{
var = 10;
return 0;
}
This program throws an error in compilation because var is declared but not defined anywhere. Essentially, the var isn’t allocated any memory. And the program is trying to change the value to 10 of a variable that doesn’t exist at all.
Example 2:
#include "somefile.h"
extern int var;
int main(void)
{
var = 10;
return 0;
}
Assuming that somefile.h contains the definition of var, this program will compile successfully.
Source: geeksforgeeks: Link, suggested by: @Calculuswhiz
Thanks to @Jeffrey