Wednesday, 6 July 2016

What happens when extern “C” is used without block in the program?

 
Guess the output?

#include<iostream>

extern "C" int myGlobalVar;

extern "C" int myGlobalVar2;
int myGlobalVar2;


extern "C" { int myGlobalVar3; }


int main()
{
myGlobalVar=25;
myGlobalVar2=50;
myGlobalVar3=100;
std::cout<< myGlobalVar << " " << myGlobalVar2 << " " << myGlobalVar3 << std::endl;
return 0;
}

Output:

Linker error.

Explanation:

All statement in program, except the following lines is fine in the program.

myGlobalVar=25;
std::cout<<  myGlobalVar << " " << myGlobalVar2 << " " << myGlobalVar3 << std::endl;

So, what is the problem in above lines?
myGlobalVar is not defined rather only it is only declared.
Following statement only declares the variable.

extern "C" int myGlobalVar;

To declare and define the variable following statement has to be used or declare the variable again like I did for myGlobalVar2.

extern "C" { int myGlobalVar3; }