5

可能重复:
静态变量

如何从 C 中的另一个文件访问静态变量?由于静态变量具有文件范围,我认为我们无法在文件之外访问它。但我仍然觉得可能有一些技巧或方法可以做到这一点。

4

3 回答 3

5

I don't think there is a easy way. If you can change the file with the static variable you can do something like:

static int hiddenVar; // The static var you want to get at

// A new function you write
int * getHiddenVar() {
   return &hiddenVar;
}

But of course if you can change the file, you would just drop the static keyword.

Also, I doubt this helps, but I've had to do something like this when writing a kernel module in FreeBSD. I used a trick where I called the kernel's linker functions to find the address of a static function. I doubt you can do this in a normal C program though.

于 2010-02-09T12:27:55.987 回答
4

Use the extern keyword in your declaration to specify that the variable comes from another file (external linkage). Drop the static keyword in your original definition.

The external vs. internal linkage thing is explained in this article.

于 2010-02-09T12:21:41.900 回答
1

You can only do this indirectly, e.g. if a function within the scope of the file containing the static variable passes you a pointer to it.

于 2010-02-09T12:27:16.800 回答