从定义变量的程序以外的程序中检索 C 全局变量
Retrieve a C global variable from a program other than where the variable is defined
假设我有一个使用全局变量 'i'
的 C 程序 foo.c
int i;
foo(x){
i = x*x;
}
在不修改程序 foo.c 的情况下,C/C++ 中是否有一种机制可以让我们为给定的 'x' 检索 i 的值,例如,通过设计一个 C/C++ 包装 foo.c 的程序,例如:
int foo2(x){
foo(x);
return the value of i stored in memory when computing foo(x);
}
谢谢你的想法。
i
已经可以从任何其他编译单元访问,前提是您事先声明它。
您可以声明它然后访问它:
extern int i;
int foo2(/*type*/ x){
foo(x);
// i is available here
}
我相信,在你的问题中,"program" 指的是 "function"
如果包装函数存在于同一个编译单元(通常是源文件)中,您可以直接在包装函数内部使用i
,如下所述。 i
是全局的。
要使用来自其他翻译单元的 i
(例如其他源文件中存在的其他函数),您可以 extern
相同的声明变量并利用它。
extern int i; //extern declaration of `i` in some other file,
//where the wrapper function is present
之后,您可以随时复制操作前i
的值和return
那个值。一旦您保留了先前值的 copy,i
的更改值将不会在那里产生影响。像
int foo2(x){
int temp = i;
foo(x);
return temp; //will return the value of i before calling foo()
}
假设我有一个使用全局变量 'i'
的 C 程序 foo.cint i;
foo(x){
i = x*x;
}
在不修改程序 foo.c 的情况下,C/C++ 中是否有一种机制可以让我们为给定的 'x' 检索 i 的值,例如,通过设计一个 C/C++ 包装 foo.c 的程序,例如:
int foo2(x){
foo(x);
return the value of i stored in memory when computing foo(x);
}
谢谢你的想法。
i
已经可以从任何其他编译单元访问,前提是您事先声明它。
您可以声明它然后访问它:
extern int i;
int foo2(/*type*/ x){
foo(x);
// i is available here
}
我相信,在你的问题中,"program" 指的是 "function"
如果包装函数存在于同一个编译单元(通常是源文件)中,您可以直接在包装函数内部使用
i
,如下所述。i
是全局的。要使用来自其他翻译单元的
i
(例如其他源文件中存在的其他函数),您可以extern
相同的声明变量并利用它。extern int i; //extern declaration of `i` in some other file, //where the wrapper function is present
之后,您可以随时复制操作前i
的值和return
那个值。一旦您保留了先前值的 copy,i
的更改值将不会在那里产生影响。像
int foo2(x){
int temp = i;
foo(x);
return temp; //will return the value of i before calling foo()
}