在C中声明/定义静态、外部和内联函数的常用方法
我知道有多种方法可以实现这一点,即在C中声明/定义静态、外部和内联函数的常用方法,c,C,我知道有多种方法可以实现这一点,即static可以用于声明和定义,也可以仅用于声明 这是常见的做法吗 // `static` on both the declaration and definition. static void f1(); static void f1(){} // `extern` on only the declaration (shared header file). // then define in a single source file. extern void
static
可以用于声明和定义,也可以仅用于声明
这是常见的做法吗
// `static` on both the declaration and definition.
static void f1();
static void f1(){}
// `extern` on only the declaration (shared header file).
// then define in a single source file.
extern void f2();
void f2(){}
// `inline` usually doesn't need a declaration, just define it in a shared header file.
inline int f3(){}
int main(){
return 0;
}
注
extern
是未标记为static
的函数声明的默认值,因此它在f2
上是可选的。假设f2
是一个变量而不是一个函数,那么这种样式会适用吗?实际问题是什么?根据C 2018 6.2.2.4,如果首先使用static
声明函数的标识符,则所有后续声明也将将其视为static
,即使省略了它(只要第一个声明仍然可见)。所以你可以省略它。然而,我认为这是一种糟糕的形式,因为它可能会让读者感到困惑。将static
放在每个声明(包括定义)上会更清晰。我会回答你的问题,但将内联包含在其中会使事情变得复杂。您可能需要编辑此问题,并单独询问内联@EricPostpischil。我认为您所谈论的复杂问题已在此处解释: