3
votes

I am trying to learn what "extern" does. I have a simple program where in main's header, a variable is declared with extern. In main, that variable is defined. Main then calls a method in another class file (that includes main's header so it should have access to the external variable), in order to print the value of that variable. But I get a compiler error: "unresolved external symbol "int myglobal". Can someone help? Thanks!

The code runs fine if I remove the reference to this variable in the source.cpp file.

source.cpp

#include "main.h"
#include <iostream>

void printGlobal()
{
    std::cout << "Global: " << myglobal;
}

source.h

void printGlobal();

main.h

extern int myglobal;

main.cpp

#include "main.h"
#include "Source.h"

int main()
{
    int myglobal = 5;
    printGlobal();
    system("pause");
    return 0;
}
2
You have to define it at file scope.chris

2 Answers

2
votes

extern only works with global scope. if I say extern int myint; that means there is a file somewhere that has int myint; outside any function this is global scope

there is also file scope which is via static int myint; that means other files won't be able to access it via extern

change main.cpp to

#include "main.h"
#include "Source.h"
int myglobal = 5;

int main()
{

    printGlobal();
    system("pause");
    return 0;
}

for file scope

#include "main.h"
#include "Source.h"
static int myglobal = 5;
int main()
{

    printGlobal();
    system("pause");
    return 0;
}
0
votes

extern and static keywords are storage specifiers. Each storage specifiers basically add two properties to a name: 1. Allocation or deallocation of name. 2. Visiblity.

If you add "extern" keyword to name in "C", it only declares a variable so that you can use that name in your program without compiler error. Means extern variable are visible outside the scope where they are defined. This symbol also instructs the linker to find the symbol definition in other object files. Therefore in your case when you added "extern" to myGlobal, you only declared a variable with name "myGlobal " and could use that name in your program. But when linker came, it tried to find the place where that "myGlobal" is defined, but it was unable to find this and gave you "unresolved external symbol" error.

All extern(global) variables are allocated when the program starts and destroyed when program ends.

Another use of "extern" other than what A.H. provided:

test1.c
 int myextern = 10;

test2.c

void func1(){
  int extern myextern;
  printf("%d",myextern);
}


Static:
Allocation/Deallocation of static variables are same as extern variable. Means they are allocated when the program starts and destroyed when program finished. But visibility of the static variables are limited to the lexical scope where they are declared. They are not visible outside their scope.