C编译报错: implicit declaration of function xxx is invalid in C99 [-Wimplicit-function-declaration]

C编译报错: implicit declaration of function xxx is invalid in C99 [-Wimplicit-function-declaration]

代码文件 test.c,内容如下:

#include <stdio.h>

int main()
{
    // 我的第一个 C 程序
    printf("Hello, World! \n"); 

    int result = 0;
    result = sum(1 , 5);

    printf("result = %d \n", result);
 
    return 0;
}

// 两个整数求和 
int sum(int a, int b) 
{
    printf (" a = %d \n",  a);
    printf (" b = %d \n",  b);
 
    return a + b;
}

当前clang版本如下:

$ clang --version
Apple clang version 11.0.0 (clang-1100.0.33.17)
Target:x86_64-apple-darwin19.0.0
Thread model:posix
InstalledDir:../XcodeDefault.xctoolchain/usr/bin

当前gcc版本如下:

$ gcc --version
Configured with: 
--prefix=/Applications/Xcode.app/Contents/Developer/usr 
--with-gxx-include-dir=../Developer/SDKs/MacOSX.sdk/usr/include/c++/4.2.1
Apple clang version 11.0.0 (clang-1100.0.33.17)
Target: x86_64-apple-darwin19.0.0
Thread model: posix
InstalledDir: ../XcodeDefault.xctoolchain/usr/bin

执行编译报错

$ clang test.c
test.c:19:14: warning: implicit declaration of function 'sum' is invalid in C99 
  [-Wimplicit-function-declaration]
    result = sum(1 , 5);
             ^
1 warning generated.
Hello, World! 
 a = 1 
 b = 5 
result = 6

错误: implicit declaration of function ‘sum’ is invalid in C99
即 函数 “sum” 的隐式声明在C99中无效

产生原因:

C语言是过程化的编程语言,程序执行顺序是从上到下。函数调用需要先声明后调用。 C99 默认不允许隐式声明(1999年推出的c语言标准)。
在之前的版本中,在C语言函数在调用前不声明,编译器会自动按照一种隐式声明的规则,为调用函数的C代码产生汇编代码。

解决办法:

在 main 函数调用前声明一下该函数。
(1)直接放到 main 函数前。
(2)或者定义在 .h 头文件中,在main函数前 引入该头文件。
(3)使用老版本编译。 【不推荐】

使用 -std 参数指定c语言版本:

如果是使用 clang 编译:

# 使用 C89 <-- 不报错
$ clang test.c -std=c89

# 使用 C99 <-- 提示不允许隐式声明,报错
$ clang test.c -std=c99

如果是使用 gcc 编译:

# 使用 C89 <-- 不报错
$ gcc test.c -std=c89  

# 使用 C99 <-- 提示不允许隐式声明,报错
$ gcc test.c -std=c99

完整代码:

#include <stdio.h>

// 函数声明 
int sum (int a, int b); // <---- 在main函数前声明

// 主函数入口
int main()
{
    // 我的第一个 C 程序
    printf("Hello, World! \n"); 
    int result = 0;
    result = sum(1 , 5);

    printf("result = %d \n", result);

    return 0;
}

// 添加两个整数的函数 
int sum(int a, int b)
{
    printf (" a = %d \n",  a);
    printf (" b = %d \n",  b);
 
    return a + b;
}

验证:编译执行

使用 clang 编译执行:

$ clang test.c && ./a.out
Hello, World! 
 a = 1 
 b = 5 
result = 6

使用 gcc 编译执行:

$ gcc -o test1 test.c 
$ ./test1 
Hello, World! 
 a = 1 
 b = 5 
result = 6

参考资料:

https://stackoverflow.com/questions/13870227/implicit-declaration-of-function-sum-is-invalid-in-c99
https://blog.csdn.net/passerby_unnamed/article/details/51073296

[END]

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章