Does a static function need the static keyword for the prototype in C?

…衆ロ難τιáo~ 提交于 2019-11-28 18:27:57

问题


My C programming book says that when I want to create a static function, I need to put the static keyword in front of the function definition. It doesn't mention anything explicitly about the prototype. Also, the examples don't use prototypes and simply put the static functions at the top of the file (so that they don't need prototypes I am assuming).

So, does a static function need the static keyword for the prototype? Or do I only put it in front of the definition?


回答1:


No. A function declaration (prototype or even the definition) can omit the keyword static if it comes after another declaration of the same function with static.

If there is one static declaration of a function, its first declaration has to be static.

It is defined in ISO/IEC 9899:1999, 6.7.1:

If the declaration of a file scope identifier for [...] a function contains the storage-class specifier static, the identifier has internal linkage.

[...]

For an identifier declared with the storage-class specifier extern in a scope in which a prior declaration of that identifier is visible, if the prior declaration specifies internal or external linkage, the linkage of the identifier at the later declaration is the same as the linkage specified at the prior declaration.

[...]

If the declaration of an identifier for a function has no storage-class specifier, its linkage is determined exactly as if it were declared with the storage-class specifier extern.

[...]

If, within a translation unit, the same identifier appears with both internal and external linkage, the behavior is undefined.

So, e.g. this is valid:

static void foo(void);
void foo(void);
static void foo(void) { }

This one too:

static void foo(void) { }
void foo(void);

static void bar(void);
void bar(void) {}

But this code is incorrect:

void foo(void);
static void foo(void) { }

Normally you will and should have the static in the prototypes too (because they usually come first).




回答2:


yes, yes you do need to put static in front of the declaration.

type this into ideone.com

int add();
int main(){
    printf("%d",add());
    return 0;
}

static int add(){
    return 1+1;
}

you get this result: http://ideone.com/VzZCiE

now type this

static int add();
int main(){
    printf("%d",add());
    return 0;
}

static int add(){
    return 1+1;
}

you get this: http://ideone.com/sz8HVR

boooom



来源:https://stackoverflow.com/questions/15670010/does-a-static-function-need-the-static-keyword-for-the-prototype-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!