简体   繁体   中英

is it legal to declare inline but not actually inline a function in C++

in header file:

inline void func(void); // declare only, with `inline`

in impl source file:

void func(void) { balabala(); }

in other source file:

func(); // call the func

Question: Is it legal to declare inline function, even if it's not actually inlined in header file?

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

It's not legal. From 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).

Whether or not it's legal I'm not sure how useful it is. Inline functions must be defined in the same translation units where they're used. That is, the second file should give a linker error because you only defined it in the impl file.

[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]).

If your compiler does LTO (or GL ) you might get away with it, otherwise unless you're redefining the same inline function in every TU (or just using it in a single one), this is not legal.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM