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
In C++, the keywords
staticandinlinehave different effects on the linkage of a function, sostatic void foo() {}is not always equivalent toinline void foo() {}in terms of linkage.Key Differences:
-
static void foo() {}:- This declares a function with internal linkage. The function is only visible within the translation unit (source file) where it is defined. Other translation units cannot access this function, even if they declare a function with the same name.
- Example:
// file1.cpp static void foo() {} // file2.cpp void foo() {} // This is a different function, not a redefinition error
-
inline void foo() {}:- This declares a function with no linkage if it appears in a block scope (e.g., inside a function), or external linkage if it appears in namespace scope (e.g., at file scope).
- When used at file scope,
inlineallows the function to be defined in multiple translation units without violating the One Definition Rule (ODR), as long as all definitions are identical. - Example:
// file1.cpp inline void foo() {} // file2.cpp inline void foo() {} // Allowed if definitions are identical
Summary:
-
Linkage:
static void foo() {}has internal linkage.inline void foo() {}has external linkage (when at file scope) or no linkage (when in block scope).
-
Visibility:
staticrestricts the function to the current translation unit.inlineallows the function to be defined in multiple translation units (with external linkage).
Thus, they are not equivalent in terms of linkage.
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.