是否应该将小型实用程序函数拆分为标头和标头?源文件还是只添加内联关键字?
我有一些小型实用函数(每个函数 <20 行代码),目前我将它们放入 utils.h
文件中,并在它们前面添加关键字 inline
,以便我没有遇到多个定义
链接错误。这就是我一直为小型功能所做的事情。
我想知道优点和缺点是什么:
使用我的方法
将函数声明放入
utils.h
中并将定义放入utils.cpp
I have some small utility functions (< 20 lines of code per function) that I am currently putting in a utils.h
file with the keyword inline
in front of them so I don't run into multiple definition
linking errors. This is what I have always done for small functions.
I am wondering what the advantages and disadvantages are to:
Using my method
Putting the function declarations in
utils.h
and definitions inutils.cpp
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
内联的缺点:
inline的优点:
Disadvantage of inline:
Advantages of inline:
对于标头与源代码,这里的小函数存在巨大的速度差异。基本上,编译器始终内联的任何内容都是标头中的良好候选者。
内联带来的潜在收益是以编译时间为代价的。如果有一个在二进制文件中调用的实际函数,您可以在其中设置断点,这对于调试目的也很有好处。
一般来说,如果不经常调用的函数将其放在源文件中,这样会更整洁,而且没人会关心。特别是有 20 条线(不包括样板)的东西。这其实并不小。只将时间敏感的内容放入标题中。
并检查您的编译器是否可以执行 LTO(链接时间优化)。因为这样您就可以在源代码中拥有函数,并且在使用 LTO 时仍然可以将它们内联。但在开发时,您可以在没有 LTO 的情况下进行编译并获得快速构建(以及较慢的二进制文件)。因此,有了 LTO,您就可以鱼与熊掌兼得。
总的来说,我会在远低于 20 行的标题中为函数划线。如果您的函数只有 return 语句,则将其放在标头中,否则放在源中,并使用 LTO。这是我的经验法则。
For header vs. source there is a HUGE speed difference for small functions here. Basically anything that the compiler would always inline is a good candidate to be in the header.
The potential gains inlineing gives you come at the cost of compile time. It can also be nice for debugging purposes to have an actual function that gets called in the binary where you can set a breakpoint.
Generally if the function it not called often then put it in the source file, it's just neater and nobody cares. Especially something with 20 lines excluding boiler plate. That's not really small. Only put stuff in the header that is time sensitive.
And do check out if your compiler can do LTO (link time optimization). Because with that you can have functions in the source and still get them inlined when you use LTO. But while developing you can compile without LTO and get quick builds (and slower binaries). So with LTO you can have your cake and eat it too.
Overall I would draw the line for functions in headers far lower than 20 lines. If your function only has a return statement then put it in the header, otherwise the source, and use LTO. That's my rule-of-thumb.