Site Tools


c-weak-symbols

Table of Contents

C weak symbols

C weak symbols are linker-level symbols that can be overridden. Declare a function or variable __attribute__((weak)) (GCC/Clang) to allow another compilation unit to provide a strong override. Useful for plugin systems, default implementations, or optional features.

Use weak symbols to provide default implementations that users can override at link time.

Example

// compile: gcc -o weak weak.c default.c plugin.c
// run: ./weak
// description: weak symbols for overridable functions

// weak.c (main program)
#include <stdio.h>

// Declare as weak - can be overridden
void custom_handler(void) __attribute__((weak));

void custom_handler(void) {
    printf("Default handler\n");
}

int main() {
    custom_handler();
    return 0;
}

// default.c (default implementation)
void default_func(void) {
    printf("Default implementation\n");
}

// plugin.c (override)
#include <stdio.h>

void custom_handler(void) {
    printf("Plugin override handler\n");
}

Common patterns

Weak function:

  • Default implementation with __attribute__((weak))
  • Other code can provide strong implementation
  • Linker uses strong if present, otherwise weak

Weak variable:

  • int global __attribute__((weak)) = 0;
  • Can be overridden by strong definition elsewhere
  • Useful for feature flags

Plugin systems:

  • Plugin provides strong symbol
  • Main program calls weak function
  • Linker pulls in appropriate implementation

Portability:

  • GCC/Clang support __attribute__((weak))
  • MSVC: #pragma weak (different syntax)
  • Portable across Unix-like systems

Limitations:

  • Weak symbols are linker-level only
  • Only works with static/dynamic linking
  • Behavior undefined if multiple weaks
  • Symbols must have same type

Best practices:

  • Document which symbols are weak
  • Provide clear default behavior
  • Don't change weak interface arbitrarily
c-weak-symbols.md · Last modified: