Though some posts exist about the -fPIC
effect (see this SO post for example) most of them are unclear. I wrote an extremely simple example and I still can't figure out what happens w/o -fPIC
regarding the location of global variables. Here is my C file:
$ cat main.c
#include <stdio.h>
int var1 = 94;
int var2 = 76;
int main(int argc, char **argv)
{
int var1Loc = (int) &var1;
int var2Loc = (int) &var2;
printf("var1 address is: %d\n",var1Loc);
printf("var2 address is: %d\n",var2Loc);
printf("diff is: %d\n",var2Loc-var1Loc);
return var1+var2;
}
Then I compile it with -fPIC
and run it twice:
$ gcc -Wno-pointer-to-int-cast -O0 -g -o main main.c
$ ./main
var1 address is: -2019672048
var2 address is: -2019672044
diff is: 4
$ ./main
var1 address is: 1441697808
var2 address is: 1441697812
diff is: 4
When I do the exact same thing without -fPIC
I get similar results. I thought that without the -fPIC
the addresses
should be identical across runs no?