Tom
Tom

Reputation: 43

Do I have to use -fPIC to create a shared object library?

I am using the default gfortran on Ubuntu 18.04.

I used the following commands to create a shared object library.

gfortran -Wall -g -c myMultiply.f90
gfortran -Wall -g -c mySum.f90
gfortran -shared  myMultiply.o mySum.o  -o libSharedLibrary001.so

Note that I did not use -fPIC.

Then, I linked the library to a Fortran program. It ran correctly.

So, my question is whether I have to use -fPIC to create a shared object library?

Upvotes: 3

Views: 762

Answers (1)

Mike Kinghan
Mike Kinghan

Reputation: 61397

Do I have to use -fPIC to create a shared object library?

It depends on your distro and the version of that distro's GCC toolchain that you are using.

Many distros have been moving in recent years to GCC builds that generate position-independent executables by default, in the interest of greater security (such executables can run in the presence of ASLR).

This build configuration effectively makes -fPIC a default in compilation and requires you to specify -fno-pic if you don't want it. The configuration is selected by specifying the configure option --enable-default-pie when building GCC. If you run a gfortran compilation in verbose mode (-v) and examine the output line commencing Configured with:, you should see --enable-default-pie among the listed configuration options.

Position-independent executables aren't universal yet and won't be for at least years. Meantime better use -fPIC appropriately unless you know that target user(s) or reader(s) of your build commands have an --enable-default-pie toolchain. It will do no harm to specify it even if it is unnecessary.

Upvotes: 2

Related Questions