5

假设代码:

extern int foo(void);

static int foo(void)
{
        return 0;
}

尝试用 GCC 编译

$ gcc -Wall -std=c99 1.c 
1.c:3:12: error: static declaration of ‘foo’ follows non-static declaration
1.c:1:12: note: previous declaration of ‘foo’ was here
1.c:3:12: warning: ‘foo’ defined but not used [-Wunused-function]

那么,如何声明静态函数呢?

4

4 回答 4

20

为什么声明 byextern不适用于static函数?

因为extern表示外联,而static表示内联。显然,你不能同时拥有相同的功能。

简单来说,当你static在函数上使用时,你告诉编译器请将此函数的范围仅限于这个翻译单元,并且不允许任何人从另一个翻译单元访问它。
虽然extern默认情况下函数声明,但当您extern明确指定时,您会告诉编译器,请允许其他翻译单元的所有人访问此函数。
很明显,编译器不能同时做这两个。

因此,请做出选择,您是否希望该功能仅在翻译单元中可见。
如果前者成功static而忘记extern。如果后者只是删除static.

好读:
什么是外联和内联?

尽管上面的 Q 是针对 C++ 的,但所讨论的大部分内容也适用于 C。

于 2012-12-09T13:56:08.903 回答
4

你用static

static int foo(void);

static int foo(void)
{
        return 0;
}
于 2012-12-09T13:57:44.613 回答
1

extern表示函数在不同的翻译单元(文件)中定义。 static表示它仅在定义它的翻译单元中使用。两者是互斥的。

于 2012-12-09T14:00:11.490 回答
-1

不是静态可以通过像File1.c这样的外部(al)链接来解决吗?

static int fx(void)
{
    return int;
}

文件2.c

extern int fx(void);

/*call */
fx();
于 2017-07-28T05:53:40.067 回答