如何解决C语言中隐式声明库函数的警告?

414 阅读1分钟

学习如何解决C语言中隐式声明库函数的警告

在编译C语言程序时,你可能会发现编译器给你一个类似以下的警告

hello.c:6:3: warning: implicitly declaring library function
      'printf' with type 'int (const char *, ...)'
      [-Wimplicit-function-declaration]
  printf("Name length: %u", length);
  ^

hello.c:5:16: warning: implicitly declaring library function
      'strlen' with type 'unsigned long (const char *)'
      [-Wimplicit-function-declaration]
  int length = strlen(name);
               ^

这个问题的出现是因为你使用了标准库中的一个函数,而没有首先包括相应的头文件。

编译器也会给你一个建议,比如下面这个。

hello.c:5:16: note: include the header <string.h> or
      explicitly provide a declaration for 'strlen'

它为你指出了正确的方向。

在这种情况下,在C文件的顶部添加

在C文件的顶部会解决这个问题。