extern'ing functions

Is using extern a valid and reliable way to have a function in one file access another? Or would I be much better off to make a header file which contains this?

For example:

main.c
1
2
3
4
5
6
7
8
9
#include <stdio.h>

extern int difference(int, int);

int main(void) {
    printf("Difference between 5 and 0 is %d.\n", difference(0, 5));
    
    return 0;
}


difference.c:
1
2
3
int difference(int x, int y) {
    return (x >= y) ? x - y : y - x;
}


It would be compiled with gcc -o differences main.c difference.c.

Would this be a valid way of using difference()? Or would I be better off prototyping it in a header? I'd rather use externs if possible, as it keeps the amount of files down...
Last edited on
I would put it in a header, so then you don't have to go to every program that uses that .c and change the extern(s).
Headers are better. Only one place to change the prototype then if the function changes.

Oh, I didn't think of that! Thanks :)
Topic archived. No new replies allowed.