28 February, 2011

Variable name conflicts

Is it possible to declare global and static variable with same name? if yes, static var will be stored in data segments, wont it get conflict?

eg:
#include

static int a = 0;

void func()
{
printf("a = %d\n", a);
}

int main(void)
{
static int a = 10;
printf("a = %d\n", a);
func();
return 0;
}

2 comments:

  1. #include

    static int variable = 0;

    void func()
    {
    printf("a = %d at %p\n", var, &var);
    }

    int main(void)
    {
    static int variable = 10;
    printf("a = %d at %p\n", var, &var);
    func();
    return 0;
    }


    When we check the address of the variables it is clear that they are two different memory locations...

    Output of a.out:
    a = 10
    a = 0x80496b0
    a = 0
    a = 0x80496bc

    The compiler uses a mechanism called name mangling to differentiate the two variables.
    This can be seen by viewing the a.out file using commands like
    nm
    (or)
    objdump -D a.out | less

    output of nm command

    080496bc b var
    080496b0 d var.1699

    We can see that the two instances of var are actually represented by two different addresses.

    But dunno the meaning of the second column in the nm output.

    ReplyDelete
  2. Gives some idea of what happens during linking and runtime...

    www.coralcdn.org/09wi-cs140/notes/l7-print.pdf
    PDF

    ReplyDelete