How can I access a shadowed global variable in C?

Solution 1:

If your file-scope variable is not static, then you can use a declaration that uses extern in a nested scope:

int c;

int main() {
    {
        int c = 0;
        // now, c shadows ::c. just re-declare ::c in a 
        // nested scope:
        {
            extern int c;
            c = 1;
        }
        // outputs 0
        printf("%d\n", c);
    }
    // outputs 1
    printf("%d\n", c);
    return 0;
}

If the variable is declared with static, i don't see a way to refer to it.

Solution 2:

There is no :: in c but you can use a getter function

#include <stdio.h>

int L=3;

inline int getL()
{
   return L;
}

int main();
{
   int L = 5;

   printf("%d, %d", L, getL());
}

Solution 3:

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:

int myvar = 5;    // global

{
    int myvar = 6;    // local var shadows global
    int *pglob_myvar = (int *)dlsym(RTLD_NEXT, "myvar");
    printf("Local: %d, global: %d\n", myvar, *pglob_myvar);
}

If you want your code to look sexy, use macro:

#define GLOBAL_ADDR(a,b)  b =(typeof(b))dlsym(RTLD_NEXT, #a)
...
int *pglob_myvar;
GLOBAL_ADDR(myvar, pglob_myvar);
...