4 ms·
Imagine you have a function f in f.c: void f() { puts("hello, world!"); } and you want to call it in main.c: int main() { f();
by umanwizard 6y ago
Imagine you have a function f in f.c:
void f() {
puts("hello, world!");
}
and you want to call it in main.c:
int main() {
f();
}
this is an error because the compiler treats each .c file separately, so when it’s compiling main.c, it isn’t looking at f.c, so it has no way to know the function f exists. So you need to “declare” it at the top of main.c. A declaration is similar to a definition, except it has no code, and just tells the compiler that the function exists:
void f();
But now imagine f.c had many functions. It would be extremely cumbersome to repeat all those declarations in every file that wants to use them. So you can collect all the declarations in some file f.h, and include it from main.c or anywhere else you want to use functions from f.c. When the compiler sees #include "f.h", it operates as if the contents of f.h were copied and pasted at that point.
You might ask “why not just include f.c from main.c instead?” Because then you would have two _definitions_ of f in your program (one in f.c and one in main.c), which is illegal, as opposed to two declarations, which is fine.
- clarry 6y ago> this is an error because the compiler treats each .c file separately, so when it’s compiling main.c, it isn’t looking at f.c, so it has no way to know the function f exists. But it's not an error and the compiler does not need to know the function exists. If there's no declaration, then the function's type is implicit and simply assumed to exist. If the function doesn't actually exist, then it's your linker that will complain.
- umanwizard 6y agoYou're right (even with `gcc --std=c99 --pedantic`, which surprised me!) I should have said that the compiler won't be able to type-check the arguments and return value.