Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

extern

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

#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();
}
like image 671
eriksson543 Avatar asked May 01 '26 13:05

eriksson543


2 Answers

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.

but when i define foo outside of my main() function like below, it works just fine

In this case, since you've defined foo globally and since foo inside print_foo refers to the globally declared foo, the program works as expected since a global definition of foo is available in this case.

like image 70
Anoop Rana Avatar answered May 04 '26 01:05

Anoop Rana


The short answer to your question is that scope matters. For example, every foo in this program is a variable in their own right, and all of them refer to different things/values/memory locations/whatever you want to call it:

int foo;

void stuff(int foo) { ... }

void thing() {
  int foo;
}

namespace bla {
  int foo;
}

I am not even sure where to start the long answer, and so will instead refer you to The Definitive C++ Book Guide and List

like image 34
Frodyne Avatar answered May 04 '26 01:05

Frodyne



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!