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)?
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.
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...
Is this because of one of the compiling steps (like link-editing)?
Well yes, the linker tries to resolve the unresolved symbols from the compilation .
s this a bad practice (should have I used a header file with sum's declaration)?
Yes you should, or declare the function before main.
Header files should have been used. That is the way you can export functions/API of your program's libraries in C.
Compiling it works because linker looks for definition of the function in the files that follow the one in which it is used. Since it is found in sum.c, the linker goes ahead and works.
精彩评论