我是否应该认为声明所有C静态函数是一种好习惯? [英] Should I consider that declaring all C static functions is a good practice?

查看:69
本文介绍了我是否应该认为声明所有C静态函数是一种好习惯?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近写了一段这样的C代码:

I recently wrote a piece of C code like that:

static void func1()
{

}

static void func2()
{

}


typedef void (*func_t)(void);

const func_t lookUpTable[FUNC_COUNT] =
{
    [FUNC1] = &func1,
    [FUNC2] = &func2
}

另一个程序员处理同一文件,并将其更改为:

An other programmer worked on the same file and changed it to:

static void func1();
static void func2();

typedef void (*func_t)(void);

const func_t lookUpTable[FUNC_COUNT] =
{
    [FUNC1] = &func1,
    [FUNC2] = &func2
}

static void func1()
{

}

static void func2()
{

}

由于 funcN 函数仅通过查找表调用,我实际上并不需要这些函数的声明。

Since the funcN functions are only called thru the lookup table, I don't actually need the declarations of those functions.

这是一个品味问题,还是有一种编码风格被认为是好/不好的做法?

Is it a matter of taste, or is there a coding style that is considered as a good/bad practice?

推荐答案

多数情况下,这的确确实是个问题(编码风格始终是 )意见;您的合作伙伴的风格与将所有代码放在其他定义之后的习惯保持一致)。

It is indeed a matter of taste mostly (and coding style is always somehow a matter of opinion; the style of your partner is consistent with the habit of putting all the code after every other definitions).

在实践中,最好确保函数名称在整个程序中是唯一的(它使 grep 变得更容易,而 gdb 会更容易找到它们)在整个程序中,即使它们可见

In practice, you'll better ensure that your function names are unique (it makes grep-ing for them easier, and gdb will find them more easily) in the entire program, even if they are visible or used only inside one translation unit.

BTW,让您的功能为非静态也有一些好处。例如,在Linux上, backtrace(3)& ; dladdr(3)函数对全局命名的函数更满意。

BTW, having your functions being non-static has also some advantages. For example, on Linux, the backtrace(3) & dladdr(3) functions are happier with globally named functions.

此外,有时计算的gotos 线程代码(甚至是普通的 switch ....)比通过指针间接调用 short 函数的表调度要快。 (调用函数的少量开销,例如运行其序言和结语,有时可能对于微小且快速运行的代码很重要)。请参见此处

Also, sometimes computed gotos and threaded code (or even a plain large switch....) are faster than a table dispatch calling short functions indirectly thru a pointer. (The small overhead of calling functions, e.g. running their prologue and epilogue, might sometimes matter for tiny and quickly running code). See references here & there.

这篇关于我是否应该认为声明所有C静态函数是一种好习惯?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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