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]