Should I consider that declaring all C static func

2019-06-21 03:27发布

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()
{

}

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?

1条回答
欢心
2楼-- · 2019-06-21 03:55

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).

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, 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.

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.

查看更多
登录 后发表回答