What is, in your opinion, the best comment layout to explain and
describe the declarations of functions, macro, variables and so on?
I mean where you explain what is the purpose of the function, what are
the input paramteres (and their constrain) and the return value.
Do you prefer to insert these comments in the .h file (for external
symbols, of course) or in the .c file?
I'm a big fan of Doxygen style comments. The ability to browse
library or application API in a web browser is a huge improvement to
learn someone else's code.
Here is an example style that I use.
/*!
* \brief Determine the length of a string in a fixed width buffer.
* \param str A C string.
* \param n The maximum length of the array pointed to by \c str.
* \return The length of \c str, or \c n if no nul character was
* found in the first \c n characters of \c str.
*
* The \c c_strnlen function returns the number of characters in the
* string pointed to by \c str, not including the terminating nul
* character. In doing this, \c c_strnlen looks only at the first
* \c n characters in \c str and never past <tt>str + n</tt>.
*
* The motivation for \c c_strnlen is to check the string length in
* a fixed width buffer that is filled with arbitrary data that may
* not have a terminating nul character.
*
* \usage
* \include strops/c_strnlen_example.c
*
* The example above should display the following.
*
* \code
*
-------------------------------------------------------------------------
* | Example | strlen | Buffer |
c_strnlen |
*
-------------------------------------------------------------------------
* strnlen 7 strnlen............. 7
* 1234567890 10 1234567890.......... 10
* abcdefghijklmnopqrstuvwxyz 26 abcdefghijklmnopqrst 20
* Real coders don't comment 25 Real coders don't co 20
* 0 .................... 0
* \endcode
*/
size_t c_strnlen( const char* str, size_t n );
The '\usage' is a macro in doxygen to display something to the effect
of '<b>Usage:</b>', and I have example functions that demonstrate how
to use the function in an example folder 'strops/
c_strnlen_example.c' (with Makefiles to build all the example code
source files). I manually place the result text in the documentation
(so the stuff between \code and \endcode is copy pasted from an output
file). In the HTML file, the example code is replaced so you can see
an actual code example in the docs along with the resulting text.
There are other code documentation tools, but choosing one that
supports HTML generation is highly recommended.
The comments exist as part of the public API, which are located in the
header files. But at the same time, there are private comments that
exist in the implementation '.c' that are meant for developers. It's
also possible to place the documentation in separate files, but I
prefer to put it in header files.
Best regards,
John D.