Compilation / Linking 101
šŸ“’

Compilation / Linking 101

Tags
Published
February 14, 2025

Static Libraries: File Extensions

  1. Linux/Unix/macOS:
      • Static libraries usually have the extensionĀ .aĀ (archive).
      • Example:
        • libprotoc.a
        • libprotobuf.a
  1. Windows:
      • Static libraries typically use the extensionĀ .lib.
      • Example:
        • libprotoc.lib
        • protobuf.lib

How Static Libraries Are Used

  • Static Libraries Are Linked at Compile Time:
    • Static libraries areĀ not standalone files at runtime.
    • During the build process, the compiler/linker embeds the code from the static library directly into the final executable (e.g.,Ā protoc).
    • Once this happens, there is no need to ship theĀ .aĀ orĀ .libĀ file alongside the executable.
  • No Runtime Dependency:
    • Unlike dynamically linked libraries (e.g.,Ā .so,Ā .dll), static libraries are effectively "compiled into" the executable. This means the executable contains everything it needs and does not rely on external libraries at runtime.

How to Identify Static Linking

  1. Inspect the Build Process:
      • If the linker is instructed to use a static library, you'll see flags likeĀ staticĀ orĀ l<library>Ā pointing to aĀ .a(on Linux/Unix) orĀ .libĀ (on Windows) during the build process.
  1. Check for External Dependencies:
      • Use tools likeĀ lddĀ (Linux/macOS) orĀ dumpbinĀ (Windows) on the final executable.
      • If noĀ .soĀ (Linux/macOS) orĀ .dllĀ (Windows) dependencies are listed for a library (likeĀ libprotoc), it’s likely statically linked.

Key Differences Between Static and Dynamic Libraries

Aspect
Static Library
Dynamic Library
Extension
.aĀ (Linux/macOS),Ā .libĀ (Windows)
.soĀ (Linux),Ā .dylibĀ (macOS),Ā .dllĀ (Windows)
Linking Time
Compile time
Runtime
Resulting Executable
Contains all library code
Depends on external shared libraries
File at Runtime
None (library code is embedded)
Shared library must be present
File Size
Larger (includes library code)
Smaller (library is external)

Summary

  • Static librariesĀ do have specific file extensionsĀ (.aĀ on Linux/macOS,Ā .libĀ on Windows) during development and linking.
  • After compilation, the static library isĀ no longer needed, as its contents are embedded into the executable.
  • The resulting program is fully self-contained, unlike dynamically linked executables that rely onĀ .so,Ā .dll, orĀ .dylibĀ files at runtime.