gpt4 book ai didi

c - 如何区分两个未初始化的静态变量

转载 作者:太空宇宙 更新时间:2023-11-04 02:35:12 25 4
gpt4 key购买 nike

假设我在两个不同的文件中定义了两个静态变量(具有相同的名称),它们将存储在 bss 部分。

//File1.c
static int st;

//File2.c
static int st;

但是在运行时如何区分它们属于哪个文件。

我在这里找到了几个主题,但没有回答我的问题 -

  1. Two static variables in same name(two different file) and extern one of them in any other file

  2. Where are static variables stored (in C/C++)?

最佳答案

运行时不需要名称。该名称仅对您和 C 编译器是必需的。 C 编译器知道它属于哪个文件,即定义它的文件。这些信息足够了。

这两个变量都以各自的名称存储在 .bss 部分中,但位于不同的内存位置。这就是他们的区别所在。

您可以使用 objdump 确认它们是如何存储的:

$ cat foo1.c
static int foo = 1;

$ cat foo2.c
static int foo = 2;

$ cat main.c
int main(void) { return 0; }

$ gcc -g -O0 -o foo foo1.c foo2.c main.c

$ objdump -d -j .data foo
test: file format elf64-x86-64


Disassembly of section .data:

00000000006008a8 <foo>:
6008a8: 01 00 00 00 ....

00000000006008ac <foo>:
6008ac: 02 00 00 00 ....

关于c - 如何区分两个未初始化的静态变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38560050/

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