加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

为什么’extern’声明不适用于C中的静态函数?

发布时间:2020-12-16 10:53:20 所属栏目:百科 来源:网络整理
导读:假设代码: 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 declaration1.c:1:12: note: previous declaration of ‘foo’ was h
假设代码:

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]

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

解决方法

Why declaration by extern doesn’t work with static functions?

因为extern表示外部链接,而static表示内部链接.显然,你不能同时拥有两个功能.

简单来说,当您在函数上使用静态时,请告诉编译器,请将此函数的范围仅限于此translation unit,并且不允许任何人从其他翻译单元访问此函数.
默认情况下,函数声明是extern,当您明确指定extern时,告诉编译器,请允许其他翻译单元的每个人访问此函数.
很明显,编译器不能同时做到这两点.

因此,无论您是希望功能仅在翻译单元中可见,还要做出选择.
如果前者让它静止而忘记extern.如果后者只是放弃静电.

好读:
What is external linkage and internal linkage?

虽然上面的Q代表C,但讨论的大多数内容也适用于C.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读