putting function definitions in header files

后端 未结 4 489
情话喂你
情话喂你 2021-02-05 14:22

If you want to put function definitions in header files, it appears there are three different solutions:

  1. mark the function as inline
  2. mark the
4条回答
  •  南方客
    南方客 (楼主)
    2021-02-05 14:35

    The static and unnamed namespace versions end up being the same: each Translation Unit will contain it's own version of the function, and that means that given a static function f, the pointer &f will be different in each translation unit, and the program will contain N different versions of f (more code in the binary).

    This is not the right approach to provide a function in a header, it will provide N different (exactly equal) functions. If the function contains static locals then there will be N different static local variables...

    EDIT: To make this more explicit: if what you want is to provide the definition of a function in a header without breaking the One Definition Rule, the right approach is to make the function inline.

提交回复
热议问题