【问题标题】:Retrieve a C global variable from a program other than where the variable is defined从未定义变量的程序中检索 C 全局变量
【发布时间】:2015-06-30 07:56:22
【问题描述】:

假设我有一个使用全局变量 'i' 的 C 程序 foo.c

int i;

foo(x){
  i = x*x;
}

在不修改程序 foo.c 的情况下,C/C++ 中是否有一种机制可以让我们为给定的“x”检索 i 的值,例如,通过设计一个包装 foo.c 的 C/C++ 程序,如下所示:

int foo2(x){
  foo(x);
  return the value of i stored in memory when computing foo(x);
}

感谢您的想法。

【问题讨论】:

  • 你的意思是不修改i
  • @imreal。谢谢。我说的是“不修改程序 foo.c”。
  • 我的意思是,不修改i的值?
  • 嘿,你,反对者,学习者想学习。
  • 当然,如果它是一个全局的,你不需要检索它本身,你可以引用它,因为它具有全局范围?

标签: c++ c function return global-variables


【解决方案1】:

我相信,在你的问题中,“程序”指的是“功能”

  1. 如果包装函数存在于同一个编译单元(通常是源文件)中,您可以直接在包装函数内部使用i,如下所述。 i 是一个全局变量。

  2. 要使用来自其他翻译单元的i(例如,其他源文件中存在的其他函数),您可以extern 声明同一变量并使用它。

    extern int i;   //extern declaration of `i` in some other file, 
                    //where the wrapper function is present
    

之后,您可以随时复制操作前i 的值和return 的值。一旦您保留了先前值的副本i 的更改值将不会在那里产生影响。类似的东西

int foo2(x){

  int temp = i;
  foo(x);
  return temp;  //will return the value of i before calling foo()
}

【讨论】:

    【解决方案2】:

    i 已经可以从任何其他编译单元访问,前提是您事先声明它。

    你可以声明它然后访问它:

    extern int i;
    int foo2(/*type*/ x){
      foo(x);
      // i is available here
    }
    

    【讨论】:

    • 您可能想在末尾添加“return i”
    猜你喜欢
    • 1970-01-01
    • 2019-10-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-09
    • 1970-01-01
    • 2019-04-08
    • 2018-09-17
    相关资源
    最近更新 更多