what is significance of -fPIC flag in gcc


I have following file

1) cat my_file.c

/* Filename: lib_mylib.c */
#include <stdio.h>
int fun()
{
return 2;
}

2)cat my_lib_shared.c

#include "my_lib.h"
int foo(void)
{
return fun()+4;
}


3) cat driver.c
/* filename: driver.c */
#include "my_lib.h"
#include "my_lib_shared.h"
#include <stdio.h>
int main()
{
int x = fun() + foo();
printf("\n===== Final value is %d\n",x);
fflush(stdout);
return x;
}


I have following script to make shared libraries

cc -fPIC -c my_lib.c -o lib_mylib.o
gcc -shared -o libMyLib.so lib_mylib.o
gcc -fPIC -c my_lib_shared.c -o my_lib_shared.o
gcc -shared -o libMyShared2.so my_lib_shared.o
gcc -L. -Wall -o test driver.c -lMyLib -lMyShared2


What is -fPIC flag if I don't give it I am unable to make a shared library


Last edited on
man gcc writes:
       -fPIC
           If supported for the target machine, emit position-independent
           code, suitable for dynamic linking and avoiding any limit on the
           size of the global offset table.  This option makes a difference
           on AArch64, m68k, PowerPC and SPARC.

           Position-independent code requires special support, and therefore
           works only on certain machines.

           When this flag is set, the macros "__pic__" and "__PIC__" are
           defined to 2.

Websearch "man gcc", if you don't have a local copy.
Topic archived. No new replies allowed.