Forward declaration of functions in header
From Java4c
Current revision as of 08:10, 3 March 2011
[edit] Forward declarations of functions in C-header
The forward declaration assures the correct usage of argument types and defines the return type of a method.
- The forward declaration should be written only 1 time in 1 header-file. It is a bad style to declare a method anywhere where it is used. The chance of mistakes is given then:
- If the forward declaration is read from compiler before the function is compiled the compiler can be check whether it is correct. If the forward declaration isn't contain, because it is written in a foreign headerfile, the compiler can't check the correctness. That is self-fool.
It is a good style that the header which declares the function has the same name as the source-file which contains the implementation:
MyModule_CPN.h ... float myFunction(float* inputs, int nrofInputs);
MyModule_CPN.c ... float myFunction(float* inputs, int nrofInputs) { //implementation }
This approuch is necessary to concluse of the dependencies from included headerfiles to the need compilation units, maybe provided by libraries.
If alternating implementations exists, either they should be contained in files with the same name but in different directories. It is assumed, that this sources are compiled in several libraries. Or a abbreviating but recognize-able name should be used, for example MyModule_A_CMPN.c.
If more as one C-file should be assiciated to one headerfile, it is a issue of sub-modules. Then derived names for the source-files should be used:
MyModule_CPN.h PartA_MyModule_CPN.c PartB_MyModule_CPN.c
In this article a suffix-style for naming is used: CPN is a placeholder for a short identifier for the ComPoNent where it is member of. It is the suffix. A subcomponent is existing in a component, it is written as prefix. In opposite, often a prefix-style is used: CPN_MyModule_PartA.c. The prefix style has the advantage of a better sort in alphabetic order. But the read-ability is wors:
- Suffix-style: ...PartA_MyModu...: okay, it's PartA in the given known environment.
- Prefix-style: ...CPN_MyModu...: what's that, oh, my known component, should read the next ...le_PartA.