What is the -fPIC flag in GCC and why is it needed when building libraries?
Hello everyone! I started learning C++ and trying to build a dynamic library (.so) on Linux using GCC. I see everywhere that when compiling objects for a library, they add the -fPIC flag, but I don't understand why it's needed.
Here's my simple example. There's a file `math_utils.cpp`:
```cpp
int add(int a, int b) {
return a + b;
}
int multiply(int a, int b) {
return a * b;
}
```
I compile like this:
```bash
g++ -c math_utils.cpp -o math_utils.o
g++ -shared math_utils.o -o libmath.so
```
And it works! The library is created, the program links it and uses the functions. But if I add -fPIC:
```bash
g++ -c -fPIC math_utils.cpp -o math_utils.o
```
The result is the same. What's the difference? When I googled it, they write that without -fPIC on x86_64 there might be an error, but everything compiles for me. Explain
No answers yet.
Log in to leave an answer
Blogs