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();
}
 
     
     
    