How to access a static variable from another file in C? [duplicate]

别来无恙 提交于 2019-12-22 07:08:52

问题


Possible Duplicate:
Static variable

How to access a static variable from another file in C? As a Static variable has a file scope, I think there is no way we can access it outside a file. But still I feel there might be some trick or way to do the same.


回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/2228906/how-to-access-a-static-variable-from-another-file-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!