Implicit declaration when using a function before it is defined in C, why can't the compiler figure this out?
As the title says, I know what causes this error but I want to know why the compiler gives it in this circumstance.
Eg :
main.c
void test(){
test1();
}
void test1(){
...
}
Would give an implicit declaration warning as the compiler would reach the call to test1() before it has read its declaration, I can see the obvious problems with this (not knowing return type etc), but why can't the compiler do a simple pass to get all function declarations, then compile the code removing these errors? It just seems so simple to do and I don't believe I've seen similar warnings开发者_JAVA百科 in other languages.
Does anyone know if there is a specific purpose for this warning in this situation that I am overlooking?
I'd guess since C is a pretty old language, dating back to 1972, this was an intentional because of memory and speed constraints.
The way it's defined, the compiler has to make one scan of your file to know everything that's needed for compilation. Having to do a two pass would have been more expensive and so this rule has survived to this day.
Also, as peoro noted, this rule makes a compiler writer's life easier. Not to mention an IDE's life for autocompletion will also make it's life easier.
So, a small annoyance for program writers means easing life for compiler writers and IDE makers, among others.
Oh, and your programs will compile faster. Not bad when you've got a multimillion code base on your hands.
That's the way C is defined.
There's a declare before use rule that forces you to declare symbols before using them.
It's mostly to make life easier for compilers.
Short answer: Because C is ooooold. :-)
Long answer: The C compiler and linker are totally separate. You might be defining different functions across different source files, and then linking them together. In this case, say that you were defining test1
in a separate library source file. The compiler wouldn't know about test1
until it has compiled the other file, and it compiles the other file separately so it can't know about it when it's compiling test
. Therefore you have to tell it, 'yes, there really is a test1
defined elsewhere, and here is its signature'. That's why you usually include a header file (.h), for any other source files whose functions you need to use, in this one.
It might not even seem so, but this approach also saves you time! Imagine you are compiling a compilation unit with thousands of files: In your scenario the compiler would first have to pares thousands of files to then see "Oh this function does not exist. Abort." The way that it implemented makes the compilation break as soon as it sees an undefined function. This saves you time.
精彩评论