The context
Consider the following file
$ cat main.c
int main() {
printf("%d", 10);
return 0;
}
If we stop the compiler after the preprocessor stage, we get
$ gcc -E main.c
# 1 "main.c"
# 1 "<built-in>"
# 1 "<command-line>"
# 31 "<command-line>"
# 1 "/usr/include/stdc-predef.h" 1 3 4
# 32 "<command-line>" 2
# 1 "main.c"
int main() {
printf("%d", 10);
return 0;
}
As seen above, the printf
function is not defined. However, gcc
dooesn't throw a compilation error (see below) when we try to compile the source file shown above
$ gcc main.c 2>/dev/null && echo $?
0
Additional context
I know that gcc
warns about this
$ gcc -Wall main.c
main.c: In function ‘main’:
main.c:2:3: warning: implicit declaration of function ‘printf’ [-Wimplicit-function-declaration]
2 | printf("%d", 10);
| ^~~~~~
main.c:2:3: warning: incompatible implicit declaration of built-in function ‘printf’
main.c:1:1: note: include ‘<stdio.h>’ or provide a declaration of ‘printf’
+++ |+#include <stdio.h>
1 | int main() {
The questions
- Why does
gcc
compile the source file when theprintf
function hasn't been defined? Are there files thatgcc
includes in every file by default? - Assuming that
gcc
, by default, includes some header files in every file. Is there any way to disable this behavior so that when a function (such asprintf
) is not found in the preprocessor output, an error is thrown instead of a warning?