Domanda

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?

È stato utile?

Soluzione

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!

Altri suggerimenti

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top