Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: Is it good practice to put static function prototypes in implementation files?

I am writing a C program and declaring all functions that are visible outside each compilation unit in the appropriate .h files. However, I also have some static functions in each compilation unit. I would prefer not to have to order the static functions in a particular way. Should I declare all of the static functions in header files, or just put all of the static declarations at the top of each implementation file?

like image 328
Dmitri Avatar asked Oct 07 '13 18:10

Dmitri


2 Answers

Header files should be a sort of "menu" that tells other source files what functions, types, etc. are exported by your module. Whenever possible, you shouldn't leak any information about the internal implementations in the header file, since it makes the code harder to modify (if a client of your header tries to use a function that you later remove) and harder to use (because the reader has to sift through private function prototypes to find the actually exported functions).

Accordingly, it's best to put prototypes for functions that are private to one source file at the top of that source file rather than in the corresponding header file.

Hope this helps!

like image 96
templatetypedef Avatar answered Sep 22 '22 00:09

templatetypedef


In case you need these static functions in more compilation units, place their declarations into the header file, which is included by all files, where you need this functions. Don't copy-paste them to other .c files (Don't Repeat Yourself).

If there's a function, which is used only within a single compilation unit, there's nothing wrong with it being declared and defined in the same .c file. Actually it's even better since you're not exposing what is not meant to be exposed.

like image 42
LihO Avatar answered Sep 18 '22 00:09

LihO