在 C++ 中声明内联但实际上内联函数是否合法
is it legal to declare inline but not actually inline a function in C++
在头文件中:
inline void func(void); // declare only, with `inline`
在 impl 源文件中:
void func(void) { balabala(); }
在其他源文件中:
func(); // call the func
问题:声明内联函数是否合法,即使它实际上并未内联在头文件中?
PS:
Why need this: I have some macro generated functions, may or may not be declare in header only, so I wish the macro can be used without explicitly specify inline or not
And, I know the function can be wrapped by a wrapper class as static member function in header
the tricky inline solution was tested under MSVC and clang without compile error, simply want to know whether it's legal in C++ standard
是否合法我不确定它有多大用处。内联函数必须在使用它们的相同翻译单元中定义。也就是说,第二个文件应该给出链接器错误,因为您只在 impl 文件中定义了它。
这是不合法的。来自 cppreference.com:
2) The definition of an inline function or variable (since C++17) must
be present in the translation unit where it is accessed (not
necessarily before the point of access).
[dcl.inline]
An inline function or variable shall be defined in every translation unit in which it is odr-used and shall have exactly the same definition in every case ([basic.def.odr]).
如果您的编译器执行 LTO(或 GL),您可能会逃脱它,否则除非您在每个 TU 中重新定义相同的内联函数(或仅在单个 TU 中使用它),否则不合法。
在头文件中:
inline void func(void); // declare only, with `inline`
在 impl 源文件中:
void func(void) { balabala(); }
在其他源文件中:
func(); // call the func
问题:声明内联函数是否合法,即使它实际上并未内联在头文件中?
PS:
Why need this: I have some macro generated functions, may or may not be declare in header only, so I wish the macro can be used without explicitly specify inline or not
And, I know the function can be wrapped by a wrapper class as static member function in header
the tricky inline solution was tested under MSVC and clang without compile error, simply want to know whether it's legal in C++ standard
是否合法我不确定它有多大用处。内联函数必须在使用它们的相同翻译单元中定义。也就是说,第二个文件应该给出链接器错误,因为您只在 impl 文件中定义了它。
这是不合法的。来自 cppreference.com:
2) The definition of an inline function or variable (since C++17) must be present in the translation unit where it is accessed (not necessarily before the point of access).
[dcl.inline]
An inline function or variable shall be defined in every translation unit in which it is odr-used and shall have exactly the same definition in every case ([basic.def.odr]).
如果您的编译器执行 LTO(或 GL),您可能会逃脱它,否则除非您在每个 TU 中重新定义相同的内联函数(或仅在单个 TU 中使用它),否则不合法。