How can I access a shadowed global variable in C? In C++ I can use ::
for the global namespace.
相关问题
- Multiple sockets for clients to connect to
- What is the best way to do a search in a large fil
- glDrawElements only draws half a quad
- Index of single bit in long integer (in C) [duplic
- Equivalent of std::pair in C
If you are talking about shadowed global var, then (on Linux) you can use
dlsym()
to find an address of the global variable, like this:If you want your code to look sexy, use macro:
what is a "shielded global variable" in pure C?
in C you have local variables, file local/global variables (static) and global variables (extern)
There is no :: in c but you can use a getter function
Depending on what you call shielded global variable in C, different answers are possible.
If you mean a global variable defined in another source file or a linked library, you only have to declare it again with the
extern
prefix:If you mean a global variable shadowed (or eclipsed, choose the terminology you prefer) by a local variable of the same name), there is no builtin way to do this in C. So you have either not to do it or to work around it. Possible solutions are:
getter/setter functions for accessing global variable (which is a good practice, in particular in multithreaded situations)
aliases to globals by way of a pointer defined before the local variable:
If your file-scope variable is not static, then you can use a declaration that uses extern in a nested scope:
If the variable is declared with static, i don't see a way to refer to it.
Yet another option is to reference the global before defining your local, or at least get a pointer to it first so you can access it after defining your local.