如何在下面的 C 程序中访问来自其他文件的静态变量?

问题描述

#include <stdio.h>
#include <stdlib.h>
int function(int);

int main()
{
    int a=1;
    extern b;//can be only declared
    printf("a=%d\n",function(a));
    printf("b=%d\n",value());
    return 0;
}
int function(int v)
{
    return v+1;
}

file1.c中:

static int b=20;

int value() //can't be used on a static function
{
    return b;
}

在上面的代码中,虽然我将变量 b 设为 static,但它可以从其他文件访问。如何访问它,因为 static 关键字不应允许从其他文件访问该变量,对吗?我有点糊涂了。

解决方法

本声明

static int b=20;

表示变量 b 仅在其翻译单元中可见,即在您定义它的 file1.c 中。

在应该位于不同文件中的 main() 中,您只声明了 b 但没有使用它。尝试使用它,你会发现链接器会失败,因为它找不到b的定义。

int main()
{
    int a=1;
    extern int b;    // note the type int in declaration. You have missed it.
    printf("access b = %d\n",b);   // <==== this won't work
    return 0;
}

尝试使用上述更改编译您的程序,您将看到链接器将抛出错误。

main() 中进行上述更改后,只需从 static 文件中的变量 b 定义中删除 file1.c 关键字,上述程序将成功链接,因为 {{1} } 将是一个具有外部链接的全局变量。

b 返回变量 value() 持有的,这与 b 是否为静态无关> 或 非静态

静态变量的生命周期是程序的整个运行时间。如果您拥有该静态变量的地址,则可以访问其作用域/翻译单元之外的静态变量。检查这个:

文件b

file1.c

文件#include <stdio.h> static int b = 20; int * retaddr_b (void) { return &b; } void print_b (void) { printf ("b = %d\n",b); }

main.c

输出:

int * retaddr_b (void);
void print_b (void);

int main(void)
{
    print_b();                 // print static variable b value 
    int * ptr_b = retaddr_b(); // ptr_b pointing to b
    *ptr_b = 99;               // dereference ptr_b and assign different value
    print_b();                 // print static variable b value
    return 0;
}
,

它并没有真正在那里访问,编译时你会看到下面的警告:

warning: type defaults to ‘int’ in declaration of ‘b’ [-Wimplicit-int]

您所做的只是打印函数 value 的返回值。

如果你真的想看看它是否被访问,请检查如下:

评论您的 printf("b = %d\n",value()); 并使用 printf("b = %d\n",b);
在它的位置然后编译和检查。