问题描述
如果要将函数定义放在头文件中,则似乎有三种不同的解决方案:
If you want to put function definitions in header files, it appears there are three different solutions:
- 将该功能标记为
inline
- 将功能标记为
static
- 将函数放在匿名名称空间中
- mark the function as
inline
- mark the function as
static
- put the function in an anonymous namespace
(直到最近,我甚至还没有意识到#1.)那么这些解决方案有什么区别,何时应该选择哪种呢?我身处只有标头的世界,所以我确实需要标头文件中的定义.
(Until recently, I wasn't even aware of #1.) So what are the differences to these solutions, and when I should I prefer which? I'm in header-only world, so I really need the definitions in the header files.
推荐答案
static
和未命名的命名空间版本最终是相同的:每个转换单元将包含其自己的函数版本,这意味着给定一个静态变量.在f
函数中,每个翻译单元中的指针&f
将有所不同,并且该程序将包含N个不同的f
版本(二进制文件中包含更多代码).
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).
这不是在标头中提供 a 功能的正确方法,它将提供 N 个不同(完全相等)的功能.如果该函数包含static
个本地变量,那么将有 N 个不同的static
本地变量...
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
.
这篇关于将函数定义放在头文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!