Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

prototypes for 'static' functions

Tags:

c

standards

I'm not quite sure if it is really necessary to have prototypes for static functions in C. As long as I'm not exporting such functions (i.e. they don't have external linkage), what other benefit can this give?

Thanks.

like image 883
Mark Avatar asked Jan 23 '12 13:01

Mark


People also ask

What is the prototype of a function?

A function prototype is a definition that is used to perform type checking on function calls when the EGL system code does not have access to the function itself. A function prototype begins with the keyword function, then lists the function name, its parameters (if any), and return value (if any).

What is a static function?

A static method (or static function) is a method defined as a member of an object but is accessible directly from an API object's constructor, rather than from an object instance created via the constructor.

Do static functions need declaration?

Unlike global functions in C, access to static functions is restricted to the file where they are declared. Therefore, when we want to restrict access to functions, we make them static. Another reason for making functions static can be reuse of the same function name in other files.

How do you create a static function?

A function can be declared as static function by placing the static keyword before the function name. Now, if the above code is compiled then an error is obtained i.e “undefined reference to staticFunc()”. This happens as the function staticFunc() is a static function and it is only visible in its object file.


2 Answers

To cite some authority, MISRA-C:2004 rule 8.1 enforces prototypes for functions with external linkage, but also mentions internal linkage:

"The provision of a prototype for a function with internal linkage is good programming practice."

I take it this is good practice because it makes your coding style between interal/external linkage functions consistent. And as others have mentioned in their answers, it is convenient as well.

like image 60
Lundin Avatar answered Oct 15 '22 14:10

Lundin


E.g. if you need to ensure that a function has a certain type, it can be useful.

Consider this:

// Define how the functions should be defined.
typedef void * jobfunc(void *);

// Use case
void addjob(jobfunc *);

// Ensure they have the right type. Without this, you only get a warning
// for addjob(job2) (see below) - with it, you get an error for the mismatch.
static jobfunc job1;
static jobfunc job2;

// Define one job
static void * job1(void * arg) {
    return NULL;
}

// Define another job - accidentally wrong.
static void * job2(int accidentally_wrong) {
    return NULL;
}
like image 40
glglgl Avatar answered Oct 15 '22 12:10

glglgl