Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compiling multiple sources in C

Tags:

c

gcc

compilation

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)?

like image 288
Mihai Neacsu Avatar asked Jul 02 '26 07:07

Mihai Neacsu


2 Answers

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.

like image 103
MByD Avatar answered Jul 04 '26 20:07

MByD


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.

like image 20
vpit3833 Avatar answered Jul 04 '26 21:07

vpit3833



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!