在头文件中声明静态全局函数

时间:2022-12-20 00:06:49

I came across a piece of code written by someone else. There are several global functions declared as static in header files. The functions themselves are defined in separate implementation files. AFAIK, static function definition isn't visible outside the translation unit where the function is defined. If so, what is the point of declaring static functions in header files?

我遇到了别人写的一段代码。在头文件中有几个全局函数声明为static。函数本身在单独的实现文件中定义。 AFAIK,静态函数定义在定义函数的转换单元外部不可见。如果是这样,在头文件中声明静态函数有什么意义?

// in some header file
static void foo();


// in some implementation file
static void foo()
{
....
....
}

1 个解决方案

#1


6  

Well, functions declared static are only visible in the source file they are defined in. Though declaring them in a separate header is not a good idea. I too, have seen some cases where developers have done this. They do it in order arrange them in an order so they can call one function from another. Here's what I mean:

那么,声明为static的函数只能在它们定义的源文件中可见。虽然在单独的头文件中声明它们并不是一个好主意。我也看到过一些开发人员已经做过这种情况的案例。他们这样做是为了按顺序排列它们,以便他们可以从另一个函数调用一个函数。这就是我的意思:

/* In header */
static void plus(int);
static void minus(int);
static void multiply(int);

/* In source file */
static void minus(int v)
{
    /* So plus can be called in minus without having to define it
     * before minus */ 
    plus(); 
}

static void plus(int v) { /* code */ }

But IMHO this is a pretty disastrous way to do it. A better solution is to just prototype the static functions in the source file before implementing them.

但恕我直言,这是一个非常灾难性的方法。更好的解决方案是在实现源文件之前对源文件中的静态函数进行原型设计。

#1


6  

Well, functions declared static are only visible in the source file they are defined in. Though declaring them in a separate header is not a good idea. I too, have seen some cases where developers have done this. They do it in order arrange them in an order so they can call one function from another. Here's what I mean:

那么,声明为static的函数只能在它们定义的源文件中可见。虽然在单独的头文件中声明它们并不是一个好主意。我也看到过一些开发人员已经做过这种情况的案例。他们这样做是为了按顺序排列它们,以便他们可以从另一个函数调用一个函数。这就是我的意思:

/* In header */
static void plus(int);
static void minus(int);
static void multiply(int);

/* In source file */
static void minus(int v)
{
    /* So plus can be called in minus without having to define it
     * before minus */ 
    plus(); 
}

static void plus(int v) { /* code */ }

But IMHO this is a pretty disastrous way to do it. A better solution is to just prototype the static functions in the source file before implementing them.

但恕我直言,这是一个非常灾难性的方法。更好的解决方案是在实现源文件之前对源文件中的静态函数进行原型设计。