C 标准 (C99 +) 是否要求实现允许将函数声明放置在 block 内,以将其范围限制在该 block 以及标准中的哪些内容?假设该函数具有外部链接,并在链接时包含的单独源文件中定义。
我注意到编译以下程序时 GCC 会生成错误:
int main(void)
{
void myFunc(void);
myFunc();
return 0;
}
void test2(void)
{
myFunc();
}
错误(这是预期的):
..\main.c: In function 'test2':
..\main.c:12:3: warning: implicit declaration of function 'myFunc' [-Wimplicit-function-declaration]
12 | myFunc();
| ^~~~~~
..\main.c:3:8: note: previous declaration of 'myFunc' was here
3 | void myFunc(void);
| ^~~~~~
..\main.c:12:3: error: incompatible implicit declaration of function 'myFunc'
12 | myFunc();
| ^~~~~~
..\main.c:3:8: note: previous implicit declaration of 'myFunc' was here
3 | void myFunc(void);
| ^~~~~~
这是预期的,因为 myFunc()
是在 main()
范围内声明的。
如果从 test2()
中删除对 myFunc()
的调用,并且 test2()
是在包含以下内容的另一个源文件中定义的链接,然后程序编译并链接,没有错误或警告。
根据这个结果,问题的答案是肯定的,但我想知道这种行为是否在规范中明确定义并且可以被认为是可移植的。
最佳答案
在函数内
void test2(void)
{
myFunc();
}
名称 myFunc
未声明。
函数的声明仅在 main 中可见。
为了向后兼容,编译器认为该函数具有返回类型 int
。
对于你的问题,你可以在 block 作用域内声明一个函数,但没有存储类说明符,除了 extern
(C 标准,6.7.1 存储类说明符):
6 The declaration of an identifier for a function that has block scope shall have no explicit storage-class specifier other than extern.
也就是说,您不能在 block 作用域中声明函数,例如
int main(void)
{
static void myFunc(void);
myFunc();
return 0;
}
关于c - C 中 block 内的函数声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71562764/