// a.c
#include <stdio.h>
int main() {
printf("%d", sum());
}
// b.c
int sum() {
return 10;
}
I compile those two files with
gcc a.c b.c normally, it works fine with an implicit declaration warning and this warning disappears if I declare sum in a.c. I've read in another post that it is fine if I don't declare the function and if I call it properly, but it's not advised to do so and I should always declare what I use in each file, and this is fine and understandable.
What I don't understand is why there's a distinction between functions defined in another file and variables. Why can't I use a variable defined in another file in the same manner as above? I can also get it to run by declaring i in the file where I use it, though.
// c.c
#include <stdio.h>
int main() {
printf("%d", i);
return ;
}
// d.c
int i = 12;
compiled with gcc c.c d.c, produces the following error
c.c: In function ‘main’:
c.c:3:19: error: ‘i’ undeclared (first use in this function)
printf("%d", i);
^
c.c:3:19: note: each undeclared identifier is reported only once for each function it appears in