extern'ing functions

Nov 4, 2009 at 8:31pm
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 Nov 4, 2009 at 8:32pm
Nov 4, 2009 at 9:45pm
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).
Nov 4, 2009 at 9:45pm
Headers are better. Only one place to change the prototype then if the function changes.

Nov 5, 2009 at 8:37am
Oh, I didn't think of that! Thanks :)
Topic archived. No new replies allowed.