在头文件中定义的小功能:inline或静态的? [英] small functions defined in header files: inline or static?

查看:170
本文介绍了在头文件中定义的小功能:inline或静态的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有许多它们在 .H 文件中定义的小功能。这是一个小项目(现在的),我想避免的声明和定义分开,因为他们总是在变化的痛苦。为了避免多重定义的符号,我可以让他们静态在线。应该是什么preferred为什么?

I have a number of small functions which are defined in a .h file. It is a small project (now) and I want to avoid the pain of having declarations and definitions separate, because they change all the time. To avoid multiply-defined symbols, I can either have them static or inline. What should be preferred and why?

我知道这是一般不好的做法在头定义功能。你不必提,在回答这个问题是技术上的意思。

I know it is in general bad practice to define functions in headers. You don't have to mention that in answers, this question is meant technically.

推荐答案

我会使用静态内联,但静态将工作一样好。

I'd use static inline, but static would work just as well.

的extern extern内联是,因为你会得到多个外部定义,如果标题中包含更多不止一个翻译单元,所以你需要考虑静态静态内联在线规范。

extern and extern inline are out because you'd get multiple external definitions if the header is included in more than one translation unit, so you need to consider static, static inline and inline specification.

Heptic在他的答案正确地指出,大多数编译器考虑功能内嵌无论在线指定与否,即内联的主要影响是其联动效应。

Heptic correctly states in his answer that most compilers consider functions for inlining regardless of whether inline is specified or not, ie the main impact of inline is its effect on linkage.

然而,静态定义有内部链接,所以没有静态静态内联;我preFER 静态内联在头文件的函数定义为纯粹的风格的原因(经验法则:头文件应该只包含的extern 的声明,静态常量变量定义和静态内联函数定义)。

However, static definitions have internal linkage, so there's not much difference between static and static inline; I prefer static inline for function definitions in header files for purely stylistic reasons (rule of thumb: header files should only contain extern declarations, static const variable definitions and static inline function definitions).

在线没有静态的extern 导致一个的内联定义的,该标准规定(C99 6.7.4,§6)

inline without static or extern results in an inline definition, which the standard states (C99 6.7.4, §6)

提供到一个外部定义,翻译可使用来实现的替代
  任何呼叫在同一翻译单元的功能。它是不确定是否将呼叫
  函数使用内联定义或外部定义

provides an alternative to an external definition, which a translator may use to implement any call to the function in the same translation unit. It is unspecified whether a call to the function uses the inline definition or the external definition.

即行内定义应始终由外部定义陪同,这是不是你要找的东西。

ie inline definitions should always be accompanied by external definitions, which is not what you're looking for.

约C99直列语义的细微之处的一些详细信息可以在发现这个答案,上的Clang主页和的C99理由(PDF)

Some more information about the subtleties of C99 inline semantics can be found in this answer, on the Clang homepage and the C99 Rationale (PDF).

记住,GCC将只使用C99语义如果 -std = C99 -std = gnu99 是present ...

Keep in mind that GCC will only use C99 semantics if -std=c99 or -std=gnu99 is present...

这篇关于在头文件中定义的小功能:inline或静态的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆