C++: zero-cost static initialization
10 months ago
- #static-variables
- #C++
- #optimization
- Static variables in C and C++ can be defined within function scope, with static storage duration.
- In C, static variable initializers must be compile-time constants, embedding values directly in the binary.
- C++ has complex initialization rules for static variables, including dynamic initialization for block-scope variables.
- Block-scope static variables in C++ are initialized the first time control passes through their declaration, with thread-safe mechanisms.
- Accessing static variables incurs overhead due to guard checks and synchronization mechanisms.
- A method to eliminate this overhead involves using linker features to pre-initialize static variables in dedicated sections.
- The solution uses `__attribute__((section))` and linker symbols `__start_SECNAME` and `__stop_SECNAME` for efficient initialization.
- Challenges include section attribute conflicts in inline functions and template members, requiring workarounds.
- The final solution involves using embedded assembler directives and unique symbol naming to avoid conflicts.
- The approach significantly reduces access overhead, making block-level static variables as efficient as file-level ones.