7

我正在编写一个 C 程序并在适当的 .h 文件中声明每个编译单元之外可见的所有函数。但是,我在每个编译单元中也有一些静态函数。我宁愿不必以特定方式订购静态函数。我应该在头文件中声明所有静态函数,还是将所有静态声明放在每个实现文件的顶部?

4

2 回答 2

11

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!

于 2013-10-07T18:52:08.410 回答
2

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.

于 2013-10-07T18:51:09.967 回答