Is static void foo() {} always equivalent to inline void foo() {} in terms of linkage?
- User
Is static void foo() {} always equivalent to inline void foo() {} in terms of linkage?
- Assistant
Short answer
No.
static void foo() {}andinline void foo() {}do very different things with respect to linkage, visibility, and the One‐Definition Rule (ODR).What “linkage” actually means
• internal linkage – the name can be seen only in the current translation unit (TU).
• external linkage – the name is visible to the whole program; the linker must make it unique across TUs.
• (Since C++17) module linkage – ignore for this discussion.How the two keywords play in C++ (the story in C is similar but not identical):
-
staticon a free function – Gives internal linkage.
– Each TU that sees the definition gets its own private copy of the function symbol.
– Other TUs cannot refer to it (they’d need a separate copy). -
inlineon a free function – Keeps external linkage (unless you also addstatic).
– May appear in multiple TUs, but every definition must be textually identical (ODR).
– The linker picks one actual symbol (often via COMDAT/weak symbols) that can be used from any TU.
– Because it still has external linkage, another TU may declare it asextern void foo();and call it even if that TU does not see the definition.Important: “inline” has nothing to do with the optimizer’s decision to inline or not; it is purely an ODR / linkage facility in modern C++.
Where they appear equivalent (but really aren’t)
If every TU that ever callsfoo()also #includes the definition, thenstatic void foo() { … }and
inline void foo() { … }appear to “work the same” because nobody outside the TU tries to see the symbol. Yet:
• The
staticversion generates one symbol per TU (or the compiler might inline and eliminate it).
• Theinlineversion generates at most one symbol for the whole program (linker merges the rest), and it is exportable if someone else merely declares it.Edge cases / mnemonics
spelling linkage multiple defs allowed? visible in other TUs? void foo();external (must be unique) yes static void foo();internal one per TU no inline void foo();external allowed (must be same) yes static inline void foo();internal allowed (one per TU) no So, unless you also write
static inline, aninlinefunction is not the same as astaticfunction. -
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.