C++ extern variable why can’t I define it in main

  c++

use.cpp

#include "my.h"




int main()
{
    int foo = 7;
    
    print_foo();
    print(99);

}
my.h

    #pragma once
    extern int foo;
    void print_foo();
    void print(int i)
my.cpp
#include<iostream>
#include "my.h"

void print_foo()
{
    std::cout << foo;
}

void print(int i)
{
    std::cout << i;
}

So my question is pretty simple I declare an extern int foo in the header file then I DEFINE foo in main, why does this not work? If I don’t define foo in main and define it outside of main in use.cpp then it works but when I define it in main() it doesn’t. Why?

Source: Windows Questions C++

LEAVE A COMMENT