【问题标题】:GCC does not throw an error during the compiler stage when a function has not been forward declared当函数未前向声明时,GCC 在编译阶段不会抛出错误
【发布时间】:2013-07-09 07:36:41
【问题描述】:

好的,

我的目录中有 3 个文件。

main.c

#include <stdio.h>
int main(int a, int b, int c)
{
    aprint();
    bprint();
}

交流

#include <stdio.h>

void aprint()
{
    printf("hey This is a.c");
}

b.c

#include <stdio.h>
void bprint()
{
   printf("This is b.c");
}

我还没有创建任何头文件。 我刚刚使用“gcc main.c a.c b.c”编译 我没有收到任何错误。我想知道发生了什么? gcc 是否只是假设在链接阶段一切都会好起来,为什么 gcc 在编译期间没有抛出错误?

【问题讨论】:

  • 你当然启用了所有警告?
  • C 的类型控制不如 C++ 的类型控制严格。 gcc 将假设 aprint();表示 int aprint(void)。因此它是有效的 C。
  • @hetepeperfan 这是 C90 中未定义的行为,用于调用 aprintbprint 的类型不是函数实际具有的类型。它在 C99 及更高版本中无效,因为隐式函数声明已从 C99 中的语言中删除。当然,默认情况下 gcc 在gnu89 模式下编译,然后它假定返回类型为int 而无需事先声明。如果定义在同一个翻译单元中,则需要诊断消息,但由于它们在不同的翻译单元中,编译器不知道类型不兼容。

标签: c unix gcc


【解决方案1】:

使用 -Wall 标志启用警告,您将看到警告:隐式调用函数 bprint() 和隐式调用函数 aprint()。它基本上是编译器在链接器阶段识别这个函数,这不会给出任何错误。

【讨论】:

    【解决方案2】:

    C89/90 版本的 C 语言不要求函数前向声明。 C 语言的 C99 版本确实需要函数进行前向声明。您是在 C89/90 模式还是 C99 模式下编译代码?

    请注意,即使在 C99 模式下,编译器也可能仅将真正的错误(即违反约束)报告为警告。如果您希望 GCC 在将约束违规报告为错误时变得更加严格,请使用-pedantic-errors 开关运行它。

    【讨论】:

      【解决方案3】:

      我给你带来了你的警告:

      notroot@ubuntu:~/qweqwe$ gcc main.c a.c b.c -Wall
      main.c:2:5: warning: second argument of ‘main’ should be ‘char **’ [-Wmain]
      main.c:2:5: warning: third argument of ‘main’ should probably be ‘char **’ [-Wmain]
      main.c: In function ‘main’:
      main.c:4:1: warning: implicit declaration of function ‘aprint’ [-Wimplicit-function-declaration]
      main.c:5:1: warning: implicit declaration of function ‘bprint’ [-Wimplicit-function-declaration]
      main.c:6:1: warning: control reaches end of non-void function [-Wreturn-type]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-09-28
        • 2020-01-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-07-19
        • 1970-01-01
        相关资源
        最近更新 更多