g++fpic

g++ -shared -fPIC helloworld.cpp -o ./hw, core dumped


I build a hello world program with the following command:

g++ -shared -fPIC helloworld.cpp -o hw

When I try to run it with ./hw I get an

Segmentation fault (core dumped)

Why does it happen?

When I compile it like so:

g++ helloworld.cpp -o hw
./hw 

it works well.


Solution

  • The first command builds a shared library instead of a executable file. Shared libraries are different from normal executable files. They (usually) cannot be executed directly, but can be used by other programs.