c - C 中 block 内的函数声明

标签 c scope c99 function-declaration

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/

相关文章:

c - xcode 体系结构 x86_64 : "_err_quit", 的 undefined symbol 引用自:

R:如果函数内部不存在变量,则不查找函数外部的变量

scope - perl6 subs 真的是词法范围还是有额外的?

c - 如何计算有符号位域的最大支持值?

C linux sem_wait 在线程中(有时)不起作用

c - 根据编译器和声明遇到无限循环

c - 如何使用 fgets 获取数字并在之后清理标准输入,没有其他帮助

javascript - JavaScript 有表达式作用域吗?

c - 使用 arm-gcc 3.3.1 在 32 位 pic 上循环

c - 在结构中分配和访问指向字符串的指针