【问题标题】:How to access local static variables and local variables inside a function from other files in C/C++ programming?如何从 C/C++ 编程中的其他文件访问函数内的局部静态变量和局部变量?
【发布时间】:2021-12-27 03:52:17
【问题描述】:
file1.c

int b=2;

void func(){
    int c=10;
    static int d=10;
    int *cp=&c;
}

main.c

#include <stdio.h>
#include <stdlib.h>
extern b;
extern *cp;

int main()
{
    int a=1;
    printf("a=%d\nb=%d\n",a,b);
    printf("c=%d\nd=%d\n",c,*cp);
    return 0;
}

我也无法使用指针“*cp”从其他文件访问局部变量“c”。 我知道默认情况下我们可以在不使用 extern 关键字的情况下访问其他文件中的函数,但是如何访问这些函数中存在的局部变量和静态变量?

【问题讨论】:

    标签: c++ c c++11 static external


    【解决方案1】:

    这是不可能的。该函数中的变量仅限于在该函数中使用。但是,如果您将变量c 设为静态变量,则可以创建一个全局指针,在与b 相同的位置声明。然后你可以在main.c中声明一个extern int *ptr_to_c,并可以通过指针访问变量c

    【讨论】:

    • 所以我们不能访问 file1.c 中的 d,即使它是一个静态变量?尽管我已经将 *cp 作为指向 c 的全局指针,但我得到了“c undeclared”
    • 没有。您不能访问 file1.c 中的d,因为它不是全局的。它是一个局部变量。静态意味着变量在调用之间保留值。它将一直存在到程序结束。函数的“静态”表示仅在此文件中可见。
    【解决方案2】:
    ```c
    file1.c
    
    int b=2;
    
    void func(){
    // local scope, stored ok stack, can only be accessed in this function
        int c=10;
    // stored in RAM, can only be accessed in this function
    // but if you take a pointer to it, it will be valid after this function executes
        static int d=10;
    // the pointer itself, cp is stored on stack and has local scope
        int *cp=&c;
    }
    
    main.c
    
    #include <stdio.h>
    #include <stdlib.h>
    // this will allow you to access "b" in file1.c
    // it should read: extern int b;
    extern b;
    // you will probably get link errors, this does not exist
    extern *cp;
    
    int main()
    {
        int a=1;
        printf("a=%d\nb=%d\n",a,b);
        printf("c=%d\nd=%d\n",c,*cp);
        return 0;
    }
    ```
    

    你可以这样做:

    file1.cpp

    int * cp =0;
    void func() {
      static int c;
      // store c's adress in cp
      cp = &c;
    }
    

    main.c

    extern int *cp;
    int main()
    {
     // you need to call this otherwise cp is null
      func();
      *cp = 5;
    }
    

    但是,这是非常糟糕的 c 代码。您应该简单地在 file1.c 中声明具有文件范围的 int c,就像 b 一样。

    在实践中,如果您认为在函数中需要 static 变量,您应该停止并重新考虑。

    【讨论】:

    • 考虑修改,以便通过函数的int ** 参数而不是全局获取地址
    • 我同意这将是一个更好的解决方案,但是将 '**' 介绍给在范围和简单指针方面苦苦挣扎的人有什么意义?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 2011-10-29
    相关资源
    最近更新 更多