Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function Prototypes in C

Tags:

c

header

Earlier today I was looking through various header files just to compare them to the ones I was making and noticed that they seem to declare their functions a bit differently.

For example here is the declaration for strlen from string.h:

extern size_t __cdecl strlen(const char *);

Upon doing some research I found that extern is for declaring a variable outside a function block. Is it best practice to declare my functions in header files with extern as well?

I see they use size_t which is unsigned long long here instead of int, I'm assuming that this is because it is more efficient for several reasons (e.g. the length of a string will never be a negative number) but is that the reason they use size_t here? Or am I missing the point completely?

Then finally I see __cdecl which I can't find much information on. What is __cdecl exactly? Should I be using it too?

And finally, I notice that in this declaration there is no variable name for the arguement being passed to strlen. I'm guessing that the reason for this is that this is not a function prototype, just a declaration, and the prototype is elsewhere. Why are there no variable names e.g. strlen(const char *str) in the declaration?

And my last question is what would the function prototype for strlen look like if this is just a declaration? My guess is something like:

size_t strlen(const char *str)

I am just asking because I want to learn and improve my code (assuming I am making function prototypes/declarations in a C file, and then just function declarations in a header file so that other C files can utilize them).

like image 813
Keith Miller Avatar asked Jun 02 '26 04:06

Keith Miller


2 Answers

  1. size_t is more appropriate returned value for strlen rather than int
  2. __cdecl is a calling convention for a function. This signifies who sets up a stack for parameters, return value etc and who clears it. More reference: Calling convention
  3. While declaring a function, you don't really need parameter names. Just parameter type is sufficient.

Update for extern :

  • extern tells to compiler that the statement is just a declaration and not definition. So for functions prototypes, extern doesn't add any value as it already just a definition. Reference: C Extern

Hope this helps.

like image 50
Rohan Avatar answered Jun 04 '26 00:06

Rohan


The extern keyword is redundant when declaring functions, since it is obvious it has to be defined somewhere else. The same is not true for variables where there would be no difference between a declaration and a definition without extern.

like image 27
olovb Avatar answered Jun 03 '26 22:06

olovb



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!