Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying something simple with extern

Tags:

c++

extern

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;
}
like image 403
MathStudent Avatar asked Apr 30 '26 07:04

MathStudent


1 Answers

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;
}
like image 173
A. H. Avatar answered May 02 '26 22:05

A. H.