What means “obey ODR” in case of inline and constexpr function?

后端 未结 3 538
猫巷女王i
猫巷女王i 2021-01-13 19:22

I just read that constexpr and inline functions obey one-definition rule, but they definition must be identical. So I try it:

inline void foo() {
    return;         


        
3条回答
  •  半阙折子戏
    2021-01-13 20:01

    You are defining functions repeatedly in one translation unit. This is always forbidden:

    No translation unit shall contain more than one definition of any variable, function, class type, enumeration type, or template. (C++11 3.2/1)

    For inline functions, you are allowed to define same function in exactly the same way in more than one translation unit (read: .cpp file). In fact, you must define it in every translation unit (which is usually done by defining it in a header file):

    An inline function shall be defined in every translation unit in which it is odr-used. (C++11 3.2/3)

    For "normal" (non-inline, non-constexpr, non-template, etc.) functions with external linkage (non-static) functions, this will usually (no diagnostic required) lead to a linker error.

    Every program shall contain exactly one definition of every non-inline function or variable that is odr-used in that program; no diagnostic required. (C++11 3.2/3)

    To sum up:

    • Never define anything multiple times in one translation unit (which is a .cpp file and all directly or indirectly included headers).
    • You may put a certain number of things into header files, where they will be included once in several different translation units, for example:
      • inline functions
      • class types and templates
      • static data members of a class template.

提交回复
热议问题