Is Link-Time Dependency Injection possible in any common linkers?

2026-09-09

Stack Overflow: View Question

Tags: c++, dependency-injection, linker, best-practices

Score: 0 | Views: 147

The asker is coming from Java's Dagger2 world, where the DI framework wires up a graph of collaborators at compile time. They want the same in C++: class A emits FooEvents via a FooEventDispatcher, and class B (a FooListener) should register itself with that dispatcher — without A or the dispatcher knowing B exists at compile time, and ideally with zero runtime overhead. The question is whether the linker can do this wiring.

Why it's interesting: most C++ DI answers reach for runtime service locators, static initializers with self-registration tricks (the classic __attribute__((constructor)) + registry pattern), or template metaprogramming. None of those are truly link-time — they defer to program startup or push complexity into headers. A real link-time answer has to lean on linker mechanics that most developers never touch.

Approach — three linker features worth exploring:

Gotchas:

So the honest answer is: yes, but it's not a general framework, it's a pattern built from weak symbols and linker sets. It gets you the "zero runtime overhead" property Dagger fans want, at the cost of ABI portability and some linker-flag hygiene.

The challenge: True link-time DI in C++ requires stitching together low-level linker features (weak symbols, section brackets, whole-archive) that have no cross-platform standard — so the design becomes a portability puzzle, not a language one.

All newsletters