skip to content

When building a shared library with GCC, what do -fPIC, -shared and -fvisibility=hidden each contribute?

level: middleimportance: must knowfreq 58%

answer

  1. compile flag versus link flag
  2. code that runs at any address
  3. the global offset table
  4. export only the API
  5. default visibility means public

basics

~20 s

-fPIC compiles position-independent code that reaches globals through a table, so the library can load at any address. -shared makes the linker produce a .so. -fvisibility=hidden keeps symbols private unless marked default, shrinking exports and enabling direct calls.

solid answer

~50 s

The three flags act at different stages. `-fPIC` is a **compile** flag: GCC emits position-independent code that reaches global data and functions through the **global offset table (GOT)**, which the dynamic loader fills in, so one copy of the library can be mapped at any address in each process. `-shared` is a **link** flag: the linker writes a shared object instead of an executable, and the manual asks you to pass the same code-model options there that you compiled with. Without `-fPIC` the objects usually fail to link into a `.so` on x86-64, with a relocation error that suggests recompiling with `-fPIC`. `-fvisibility=hidden` changes the default ELF visibility from `default` (exported) to hidden, so only symbols marked `__attribute__((visibility("default")))` are exported. That shrinks the dynamic symbol table, speeds loading, avoids clashes and lets calls inside the library skip the GOT and PLT.

code

cpp · 2 lines
cpp
int counter = 0;
int bump() { return ++counter; }

go deeper

for a junior

Know that shared libraries are compiled with -fPIC and linked with -shared.

for a middle

Explain the GOT, why shared code must run at any address, and what the relocation error asking for -fPIC means.

for a senior

Ship libraries with hidden default visibility and an explicit export macro, and read the dynamic symbol table to confirm what is exported.

for a principal

Treat the exported symbol set as the library's API contract, owned and reviewed like any other interface.

## Three flags, two stages ```bash g++ -fPIC -fvisibility=hidden -O2 -c geo.cpp -o geo.o # compile: PIC, hidden by default g++ -shared geo.o -o libgeo.so # link: produce a shared object ``` - `-fPIC` and `-fvisibility=hidden` change how **each object** is compiled. - `-shared` changes what the **linker** produces. GCC's manual adds that for predictable results you must also pass the compile-time code model options (`-fpic` or `-fPIC`) when linking with `-shared`, because on some systems the driver picks support libraries and startup code from them. ## Why shared code must be position-independent A shared library is mapped at an address chosen when the process loads it, and the same pages are shared between processes. Code that embeds absolute addresses, or that assumes a global lives at a fixed distance from the code, would need patching per process. **Position-independent code** avoids that: - Accesses to global data and calls to functions that may live elsewhere go through the **global offset table (GOT)**, an array of addresses the dynamic loader fills in. - Calls to functions in other modules go through the **procedure linkage table (PLT)**, small stubs that jump via the GOT. - GCC defines `__PIC__` and `__pic__` to 2 with `-fPIC` and to 1 with `-fpic`. `-fpic` and `-fPIC` differ only in GOT size limits: the manual lists 8k on SPARC and 28k on AArch64, notes that x86 has no such limit, and says to use `-fPIC` when the linker reports that `-fpic` does not work. `-fPIE` and `-fpie` are the variants for executables. Many distributions build executables as PIE by default, but PIE code still assumes its globals are not interposed and cannot go into a shared library, so the fix for the relocation error is `-fPIC`, including for every object inside a static archive that will be linked into a `.so`. ## Visibility: what the library exports By default every non-static symbol has **default visibility**, which the manual stresses always means public: available to be linked against from outside the shared object. A C++ library therefore exports every function, every template instantiation and every inline function's out-of-line copy. That has costs: 1. **Load time**: the dynamic loader resolves and relocates a larger symbol table. 2. **Code quality**: any exported symbol may be **interposed** by another module that defines the same name, so GCC must reach even the library's own globals through the GOT. 3. **Clashes**: two libraries exporting the same internal helper collide. 4. **No real API boundary**: clients can call anything. `-fvisibility=hidden` flips the default. Only declarations marked `__attribute__((visibility("default")))`, usually through an export macro on the public headers, stay exported. The manual strongly recommends this for any shared object you distribute. Supporting tools: - `#pragma GCC visibility push(hidden)` and `pop` for regions of existing code; - `-fvisibility-inlines-hidden` to hide inline member functions, which can shrink the export table dramatically for template-heavy code; - the manual's warning that `operator new` and `operator delete` must keep default visibility, and that third-party headers may not expect non-default visibility. ## Seeing the difference The same function compiled three ways shows what the flags do to one global access: | Build | Access to `counter` | Exported? | |---|---|---| | no `-fPIC` | PC-relative, assumes it lives in this module | yes | | `-fPIC` | load its address from the GOT, then access | yes | | `-fPIC -fvisibility=hidden` | PC-relative again, no GOT | no | Hidden symbols cannot be interposed, so the compiler can bind to them directly. ## Interposition: why exported code is slower ELF lets the dynamic loader **interpose** an exported symbol: if the executable or an earlier library defines the same name, every reference binds to that definition instead. GCC's manual explains the cost under `-fsemantic-interposition`: for symbols exported from a shared object, the compiler cannot perform interprocedural propagation, inlining and similar optimizations, in anticipation that the function or variable may be replaced. Hidden visibility removes the possibility, which is why `-fvisibility=hidden` improves code inside the library and not just its load time. `-fno-semantic-interposition` is a narrower alternative: it keeps symbols exported but lets GCC assume an interposed function would behave the same. ## Checklist for a shared library - Compile every object, including those in static archives you link in, with `-fPIC`. - Link with `g++ -shared` so the C++ runtime is linked correctly. - Build with `-fvisibility=hidden` and export the API explicitly. - Inspect the result: `nm -D --defined-only libgeo.so` lists what is exported.

  • Why must a static library linked into a shared library also be built with -fPIC?
    Its members are copied into the `.so`, so they must meet the same rule as the library's own objects: code that can run at any address and reaches globals through the GOT. Members compiled without `-fPIC` trigger the same relocation errors at the shared link.
  • What does -fvisibility-inlines-hidden add on top of -fvisibility=hidden?
    It hides inline member functions even in classes whose visibility is default, so the many template and inline copies a C++ library emits stop appearing in its export table. The manual notes it can dramatically cut load and link times for template-heavy libraries; the cost is that comparing such functions' addresses across shared objects is not supported.

  • -shared alone makes the code position-independent.
  • -fPIC is only needed for the main executable.
  • Default visibility means a symbol is private to the library.
  • Hidden visibility makes functions slower because they are called through the PLT.
  • -fpic and -fPIC are spelling variants with identical behaviour on every target.