gpt4 book ai didi

c++ - 外部变量的内存将存储在哪个文件中

转载 作者:可可西里 更新时间:2023-11-01 17:37:06 25 4
gpt4 key购买 nike

我阅读了有关 extern 变量的信息,但没有找到与它的内存分配相关的答案,我的问题是谁将为 Extern 变量分配内存,以及在哪个内存段。

int a; // file 1

extern int a; // file 2

这里文件1会为a或文件2分配内存,在数据段还是在堆栈?

谢谢。

最佳答案

The extern keyword means "declare without defining". In other words, it is a way to explicitly declare a variable, or to force a declaration without a definition.

所以在 file2 中,您只是声明了没有定义的变量(没有分配内存)。在 file1 中,您声明并定义了一个 integer 类型的变量。在这里,您在 BSS segment 上分配了内存因为你有一个未初始化的全局(对于 C)。

在 C++ 中,全局变量存储在每个进程的数据区域


声明和定义的区别:

To understand how external variables relate to the extern keyword, it is necessary to know the difference between defining and declaring a variable.

When a variable is defined, the compiler allocates memory for that variable and possibly also initializes its contents to some value. When a variable is declared, the compiler requires that the variable be defined elsewhere.

The declaration informs the compiler that a variable by that name and type exists, but the compiler need not allocate memory for it since it is allocated elsewhere.

关于c++ - 外部变量的内存将存储在哪个文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18009880/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com