Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why can't i define my previously declared extern variable inside a function?

I’m quite new to programming in general and more specifically to c++. I’ve made a program using the following files:

my.h

extern int foo;
void print_foo();

my.cpp

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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


void print_foo(){
    std::cout << "foo = " << foo <<std::endl;

}

use.cpp

#include "my.h"

int main(){
    int foo = 7;
    print_foo();
}

When i try to compile it I get the error message ‘undefined reference to `foo”, but when i define foo outside of my main() function like below, it works just fine. Why is that?

use.cpp

#include "my.h"

int foo;

int main(){
    foo = 7;
    print_foo();
}

>Solution :

When i try to compile it I get the error message ‘undefined reference to `foo”

Because when you define foo inside main, it is local to the main function. But the foo that you use inside print_foo is a global foo which you’ve not defined(globally).


Basically, extern int foo;(in your program) declares a global variable named foo and the foo used inside print_foo is the globally declared foo which you never define.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading