简体   繁体   中英

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

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?

At global scope, the declaration

extern int foo;

declares a variable named foo that has external linkage , meaning that it might be defined in another translation unit.

At block scope ( ie , as a statement in the body of a function), the definition

int foo = 7;

has no linkage . That means that the compiler will never consider this foo to be the same entity as another foo from another scope. Therefore, this simply creates another variable that's unrelated to the global one, and does not initialize the global one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM