Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extern on function prototypes?

my_math.h

// case 1 
unsigned int add_two_numbers(unsigned char a, unsigned char b);

//case 2 
extern unsigned int add_two_numbers(unsigned char a, unsigned char b); 

What is the difference between case 1 and case 2? I never used extern for function prototypes but looking at someone's code (who is way more experienced than I am) I see extern always used when declaring the function prototype. Can anyone point please point the difference? (or point me to a link where I can find specific information). Google says that is something related to the external linkage. Can anyone point me to an example where one would work and the other wouldn't?

I am using embedded C (KEIL), if it makes any difference.

like image 939
CalinTamaian Avatar asked Dec 12 '14 15:12

CalinTamaian


2 Answers

extern is a linkage specifier for global linkage. Its counterpart is static, which specifies file-local linkage. Since global linkage is the default in C, adding extern to the declaration makes no difference for the declaration of a function. For a variable it prevents automatic memory allocation and using it is the only way to just declare a variable at global scope.

If you just google the keyword, you will find many articles e.g. this one: geeks for geeks

like image 54
midor Avatar answered Oct 17 '22 17:10

midor


For a (non-inline) function, it doesn't make any difference, extern is implicit if no storage-class specifier is given (note, that this applies only to functions, objects are different), so it's only a matter of style what you use.

I've seen both (never use extern for functions/only use it for the declarations in the header), maybe some use extern for symmetry with object identifiers, or to make it easier to grep for external symbols.

Choose whatever you prefer and stay consistent, it doesn't make a difference.

like image 39
mafso Avatar answered Oct 17 '22 18:10

mafso