Fix the C 'implicitly declaring library function' warning
By Flavio Copes
Learn how to fix the C 'implicitly declaring library function' warning, shown when you call functions like printf or strlen without including their header.
This warning means you called a standard library function without including the header file that declares it. The fix is to add the right #include at the top of your file.
When compiling a C program you might find that the compiler gives you a warning similar to
hello.c:6:3: warning: implicitly declaring library function
'printf' with type 'int (const char *, ...)'
[-Wimplicit-function-declaration]
printf("Name length: %u", length);
^
or
hello.c:5:16: warning: implicitly declaring library function
'strlen' with type 'unsigned long (const char *)'
[-Wimplicit-function-declaration]
int length = strlen(name);
^
This problem occurs because you used a function from the standard library without first including the appropriate header file.
The compiler will also give you a suggestion, like the following one:
hello.c:5:16: note: include the header <string.h> or
explicitly provide a declaration for 'strlen'
which points you in the right direction.
In this case, adding
#include <stdio.h>
at the top of the C file will solve the issue.
For strlen, the header is a different one:
#include <string.h>
Why does C even compile this?
In old C (the C89 standard), calling an undeclared function was legal. The compiler just assumed it existed and returned an int.
That assumption is dangerous. The compiler doesn’t know the real parameter types or the real return type, so it can’t check your call. If the guess is wrong, the program can misbehave at runtime in ways that are hard to debug.
That’s why the warning exists. C99 removed implicit declarations from the language, and recent versions of Clang and GCC reject them with a hard error instead of a warning. Treat this warning as an error even when your compiler still lets it slide.
Which header do I need?
Each library function is declared in a specific header. The ones you’ll hit most often:
printf,scanfneed<stdio.h>strlen,strcpyneed<string.h>malloc,freeneed<stdlib.h>sqrt,powneed<math.h>
On macOS and Linux you can also ask the manual. Running man 3 strlen shows the synopsis with the exact header to include.
Here is the fixed version of the program from the warnings above:
#include <stdio.h>
#include <string.h>
int main(void) {
char name[] = "Flavio";
int length = strlen(name);
printf("Name length: %d\n", length);
}
Both headers included, both warnings gone.
One thing to watch out for: the program might still appear to work while the warning is there, because the linker often finds the function anyway. Don’t trust that. Without the declaration the compiler can pass arguments the wrong way, and the bug will show up later, somewhere else.