[英]C++ extern variable why can't I define it in main
使用.cpp
#include "my.h"
int main()
{
int foo = 7;
print_foo();
print(99);
}
我的.h
#pragma once
extern int foo;
void print_foo();
void print(int i);
我的.cpp
#include<iostream>
#include "my.h"
void print_foo()
{
std::cout << foo;
}
void print(int i)
{
std::cout << i;
}
所以我的問題很簡單,我在頭文件中聲明了一個 extern int foo 然后我在 main 中定義了 foo,為什么這不起作用? 如果我沒有在 main 中定義 foo 並在 use.cpp 的 main 之外定義它,那么它可以工作,但是當我在 main() 中定義它時,它沒有。 為什么?
在全局范圍內,聲明
extern int foo;
聲明一個名為foo
的變量,它具有外部鏈接,這意味着它可能在另一個翻譯單元中定義。
在塊范圍內(即,作為函數體中的語句),定義
int foo = 7;
沒有聯系。 這意味着編譯器永遠不會認為這個foo
與來自另一個作用域的另一個foo
是同一個實體。 因此,這只是創建了另一個與全局變量無關的變量,並且不會初始化全局變量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.