6

To clarify, this is a question about binary Linux executables, not scripts, which can also be executable and also often lack an extension.

In my experience, most Linux binary executables lack a file extension; e.g. most of the files in the /bin directory on Linux systems lack an extension.

On the other hand, most of the files in the /lib directory have .so in their file extension, and also have executable permissions. Trying to execute an .so file directly usually results in seg fault or some error, which makes sense because shared libraries are usually intended to be dynamically linked. But as I understand it, if the .so file has a main() entrypoint, then you can run it as an executable as you would a normal executable (i.e. a file without an extension).

My questions:

  1. What is the difference between a shared library (.so extension) and an executable file ([none] extension)? Is it just whether a main() entrypoint is defined?
  2. In C++, is there any difference (i.e. flags passed to the compiler) in compiling code into a shared library (.so extension) and compiling code into a Linux executable ([none] extension).

Edit: This question talks about how to build an .so file using gcc command line, but doesn't identify the differences between building an .so versus a normal executable.

Jacob Stern
  • 3,758
  • 3
  • 32
  • 54
  • You can read [ELF](https://en.m.wikipedia.org/wiki/Executable_and_Linkable_Format) and [Build .so file from .c file using gcc command line](https://stackoverflow.com/questions/14884126/build-so-file-from-c-file-using-gcc-command-line) – Thomas Sablik Jun 16 '20 at 18:23

1 Answers1

2
  1. One of the main differences is that a shared library does not have a main() function. It also contains position independent code that may or may not be the case for executables. If you do put a main() function in the library, you still need to link it with a normal object file (containing no main() function).
  2. Yes. To create a shared library you compile your code with -fpic or -fPIC to generate position-independent code (PIC) suitable for use in a shared library.

Nothing prevents you from creating an executable called myexe.so though, but it can't be used as a shared library.

Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
  • 1
    Afaik, nowadays executables are also position independent by default (at least on x86-64 without explicit `-no-pie` option) to support address space layout randomization. For example, on my machine, `gcc -v` outputs: `Target: x86_64-linux-gnu Configured with: ... --enable-default-pie ...`. – Evg Jun 16 '20 at 19:03
  • @Evg I see. On my system it's not (`Target: x86_64-redhat-linux`), but I made a note about it in the answer. – Ted Lyngmo Jun 16 '20 at 19:04