Let’s say we have 2 source files:
main.c:
#include <stdio.h>
#define i 2
int main(){
printf("sum(%d) = %d", i, sum(i));
return 0;
}
sum.c:
int sum(int i){
int a, sum;
for(a = 0, sum = 0; a < i; a++)
sum += a;
return sum;
}
If I compile them using
gcc main.c sum.c
I’ll get a working executable file. I’m confused because I thought this shouldn’t work since the sum function comes after main > there’s no hint of the sum function, like it’s declaration before main.
Is this because of one of the compiling steps (like link-editing)? Also, is this a bad practice (should I have used a header file with sum‘s declaration)?
When there is no declaration, the compiler assumes that there is such function which returns an
int(luckily, that’s the case here) and the linker find the needed symbol, but still…Well yes, the linker tries to resolve the unresolved symbols from the compilation .
Yes you should, or declare the function before main.