Why is the compiler able to locate a function definition in some xyz file if there is a declaration for it but not able to locate the function definition if there is no declaration?
Declaration only stated that there is a function somewhere not its whereabouts.
The compiler is NOT able to locate the definition of a function in another file. It's the linker that does that, and it does it by looking in object files and libraries, not source files.
The prototype does not help to find anything. It's only purpose is to declare that a function by that name exists, returns such-and-such, and needs whatever arguments. With that information the compiler is able to compile the source file into object code. The linker will tie things together at the end.
ok so if I compile the file xyz with the definition in it but I do not declare the function, why is the linker then not able to locate the function in xyz.obj when I call it as it did when I also declared the function?
ok i get it, so in compile level, i need to say that i know what i am doing by declaring
but why should the compiler care is my question since the linker will look for it? The way i see it, it should be able to compile and then the linker look for and be able to find (as you say) the definition when tying things together...
i would understand it if there was no definition at all. in that case, the linker would not be able to find anything...
there is something your not telling me or something im not getting! :)
Problems should be detected as soon as possible. The compiler complains about the missing declaration simply because it can. Not having the prototype means that it cannot know if you called the function properly: correct name, correct use of return value, correct arguments.
Leaving this kind of checking to the linker just makes the linker more complicated. And the linker is not actually part of the language anyway.
i guess this makes sense; the compiler needs to know some minor details of wth f is in order to compile to something meaningful and correct.
btw in case we have f defined in the same file where we call it no need for the declaration - apparently this is more than minor details in this case...
in case we have f defined in the same file where we call it no need for the declaration
Not exactly. If f is defined after the function that calls it then a prototype needs to be declared before the calling function. If f is defined before the function that calls it, then the definition also serves as a declaration. So there is really a declaration in both cases.