Commenting C code, header and source files [closed] - c

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
I'm looking for a "best practice" to document my C code. Like in any project I have some header files ".h" and the respective source file ".c"
In the header file what kind of comment you put in? And in source files?
The question arise up because since I commented well my header files, the c files looks like a mess.
What's your best practices in keeping the code well commented?

The header is meant for users of the code. So in there I document the interface: how to use it, preconditions and postconditions, etcetera.
The .c file is for maintainers. In there, I document the implementation: how things work internally, and why they work that way.

I suggest adopting the conventions imposed by a tool like Doxygen. Then instead of just code comments, you can also generate HTML/PDF/Latex etc documentation and its gives you good conventions.
Agree with Thomas about the cpp files

If this is a personal project I'd suggest there are plenty of coding standards out there you could adopt (almost all include sections on how to lay out comments).
If not, I would imagine your company / teaam / project already has something in place so use that.

For source files I suggest you create a comment template for File Header and Function Header.
In case of File Header Comments, you should have a brief description of the file, function names, author, date of creation and history to record modifications.
Incase of function header, you can explain the logic and purpose of the function and various parameters. Please ensure that any complex logic or deviation from common behaviour is well documented through comments.

Related

Why does the standard C library feature multiple header files instead of consolidating the contents into a single header? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 months ago.
Improve this question
Why does the standard C library need to feature multiple header files? Would it not be more user friendly to consolidate it into one header file?
I understand that it is unnecessary to include function prototypes / global variables that go unused, however, won't the compiler eventually remove all of these references if they're unused?
Maybe I'm underestimating the size of contents spanning all of the header files. But it seems like I'm always googling to figure out what header I need to #include.
Edit: The top comment references a size of 50MB which appears to be untrue. The C library is relatively concise compared to other language's standard libraries hence the question.
// sarcasm ON
Build your own #include "monster.h" that includes all you want from the collection.
People write obfuscated code all the time. But, you won't be popular with your cohort.
// sarcasm OFF
The real reason? C was developed when storage was barely beyond punch card technology. A multi-user system might have 1/2Mb of (magnetic) core memory and a cycle time that is now laughable.
Yet, reams of C code was developed (and the story of the popularity of UNIX well known.)
Although new standards could change the details (and C++ has), there is an ocean of code that might/would no longer be able to be compiled.
Look up "Legacy".
There are (too many) examples of code in the world where the usual collection of, say, stdio.h, stdlib.h, etc. have been "hidden" inside #include "myApp.h". Doing so forces the reader to hunt-down a second file to verify what the &^%&%& is going on.
Get used to it. If it was a bad practice, it would not have survived for ~50 years.
EDIT: It is for a similar reason that "functions" have been "grouped together" into different libraries. By extension, pooling those libraries might make things a tiny bit "less cluttered", but the process of linking may require a supercomputer to finish the job before knock-off time.
EDIT2: Brace yourself. Cleanly written C++ code often has a .h and a .cpp for every class used in the app. Sometimes "families" (hierarchies) might live together in a single pair of files, although that can lead to boo-boo's when the coder is having a bad day...

How many headers for a c-module? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
I have a module in my project mymodule.c that provides a lot of functions for the rest of my project.
These function are defined in a mymodule.h header file.
But in mymodule.c there are a lot of other defines or define masks.
For example:
#define STACKSIZE 1024
#define TIMER1 100
#define TCR_MASK 16U
#define TCR 16U
#define TCR_IR (0ULL << 8)
...
100 other defines or typedefs
I could split it up like this:
mymodule.h --->all external functions and declarations used from other places.
Rename this to mymodule_public.h ?
mymodule_config.h ---> configuration like timers, controlparameters or constants.
mymodule_masks.h ---> decsriptors.
There could be more headers.
Another way is to keep all except the external functions in the mymodule.c.
What is best practice for splitting up into headers and giving header names?
Generally, a header file which is the public interface of a library should contain all the things that the caller needs to use the functions.
If you have a bunch of #define that are necessary to use the functions, they need to be in the h file. If they aren't needed but just used internally, you should keep them in the c file.
It is ok to make a 2nd header file which isn't the public API but just contains internal constants used by your c file(s).
As for where to place the #includes, that's a bit subjective. Generally I like to show the user of the library which dependencies the library comes with, so that they can ensure that they have all the necessary files and so that they can trouble-shoot strange linker errors easier. On the other hand, one might feel uneasy about "exposing" includes that are just used privately by the library in the public header (like the 2nd private header mentioned above). There's no obvious right or wrong here, though try to be consistent with where you place the #includes.
Your idea with multiple headers all named with a certain library-specific prefix "mymodule" is pretty sound overall.

C header file dependencies [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I would always typically include dependencies in my header files so that when adding that header to a source file, I don't need to dig around for the other required headers to make it compile.
However, after reviewing some other coding standards, it appears that this is often banned, with the requirement that a header file will not contain any #include statements.
I can't really find any discussion on this - so what would be the reason for banning such a practice, or is it purely down to preference?
--
E.g.
typedef.h contains a typedef for U8.
my_header.h declares void display_message(U8 arg);
Should the reference to typedef.h go into my_source_file.c or into my_header.h ??
I see no good reason for not allowing headers to include their prerequisites.
Consider deleting an #include from a source file. For example, suppose the code has been modified to no longer use foo.h, so the #include for that is being deleted. But the source files has a dozen #include statements. Which other ones should you delete because they are no longer needed? Hopefully, foo.h documents its prerequisites, so you can identify those candidates for deletion. However, if you delete their #include statements, you might be deleting a prerequisite that is needed by a different header file. So you must check the prerequisites of every header file.
In contrast, if headers include their prerequisites, then you can simply delete #include <foo.h> and be done with it.
Includes should go in the source file. The header should only declare functions and variables of your source code file (that is typically the standard).

Where to document functions in C or C++? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
I have a C program with multiple files, so I have, for example, stuff.c which implements a few functions, and stuff.h with the function prototypes.
How should I go about documenting the functions in comments?
Should I have all the docs in the header file, all the docs in the .c file, or duplicate the docs for both? I like the latter approach, but then I run into problems where I'll update the docs on one of them and not the other (usually the one where I make the first modification, i.e. if I modify the header file first, then its comments will reflect that, but if I update the implementation, only those comments will change).
This question and its answers also apply to C++ code — see also Where should I put documentation comments?
Put the information that people using the functions need to know in the header.
Put the information that maintainers of the functions need to know in the source code.
I like to follow the Google C++ Style Guide.
Which says:
Function Declarations
Every function declaration should
have comments immediately preceding
it that describe what the function
does and how to use it. These
comments should be descriptive
("Opens the file") rather than
imperative ("Open the file"); the
comment describes the function, it
does not tell the function what to
do. In general, these comments do not
describe how the function performs
its task. Instead, that should be
left to comments in the function
definition.
Function Definitions
Each function definition should have
a comment describing what the
function does and anything tricky
about how it does its job. For
example, in the definition comment
you might describe any coding tricks
you use, give an overview of the
steps you go through, or explain why
you chose to implement the function
in the way you did rather than using
a viable alternative. For instance,
you might mention why it must acquire
a lock for the first half of the
function but why it is not needed for
the second half.
Note you should not just repeat the
comments given with the function
declaration, in the .h file or
wherever. It's okay to recapitulate
briefly what the function does, but
the focus of the comments should be
on how it does it.
You should use a tool like doxygen, so the documentation is generated by specially crafted comments in your source code.
I've gone back and forth on this and eventually I settled on documentation in header files. For the vast majority of APIs in C/C++ you have access to the original header file and hence all of the comments that lie within [1]. Putting comments here maximizes the chance developers will see them.
I avoid duplication of comments between header and source files though (it just feels like a waste). It's really annoying when using Vim but most IDEs will pick up the header file comments and put them into things like intellisense or parameter help.
[1] Exceptions to this rule include generated header files from certain COM libraries.
It will often depend on what is set as the coding standard. Many people prefer to put the documentation in the .h file and leave the implementation in the .c file. Many IDE's with code completion will also pick up more easily on this rather than the documentation in the .c file.
But I think the major point in putting the documentation in the .h file deals with writing a library or assembly that will be shared with another program. Imagine that you're writing a .dll (or .so) that contains a component that you will be distributing. Other programmers will include your .h, but they often won't have (nor need) the implementation file behind it. In this case, documentation in the .h file is invaluable.
The same can be said when you're writing a class for use in the same program. If you're working with other programmers, most often those programmers are just looking at the header file for how to interact with your code rather than how the code is implemented. How it is implemented is not the concern of the person or code that will be using the component. So once again, documentation in the header will help that person or those people figure out how to use that code.
Consider that it's possible for people to use these functions while only having the headers and a compiled version of the implementation. Make sure that anything necessary for using your functions is documented in the header. Implementation details can be documented in the source.
The comments in the header vs. the implementation file should reflect the difference in how the two are used.
If you're going to create interface documentation (e.g., to be extracted with Doxygen, on the same general order as JavaDocs) that clearly belongs in the header. Even if you're not going to extract the comments to produce separate documentation, the same general idea applies -- comments that explain the interface/how to use the code, belong primarily or exclusively in the header.
Comments in the implementation should generally relate to the implementation. Contrary to frequent practice, rather than attempting to explain how things work, most should explain why particular decisions were made. This is especially true when you make decisions that make sense, but it might not be obvious that they do (e.g., noting that you did not use a Quicksort, because you need a stable sort).
It's simple really when you think about it.
The API docs absolutely must go in the header file. It's the header file that defines the external interface, so that's where the API docs go.
As a rule, implementation details should be hidden from API users. This includes documentation of implementation (except where it might affect the use e.g. time complexity etc). Thus implementation documentation should go in the implementation file.
Never ever duplicate documentation in multiple places. It will be unmaintainable and will be out of sync almost as soon as somebody has to change it.
I wrote a simple script that takes as input a template header-file with no function declarations and a source-code file with commented functions. The script extracts the commentary before a function definition from the source code file and writes it and the associated function declaration into an output header-file. This ensures that 1) there's only one place where function commentary needs to be written; and 2) the documentation in the header-file and the source code file always remain in sync. Commentary on the implementation of a function is put into the body of the function and is not extracted.
Definitely keep the docs in one place, to avoid the maintenance nightmare. You, personally, might be fastidious enough to keep two copies in sync, but the next person wont.
Use something like doxygen to create a "pretty" version of the docs.

best practice for delivering a C API hiding internal functions [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
I have written a C library which consists in a few .h files and .c files. I compile it as a .a static library.
I would like to expose only certain functions to the user and keep the rest as "obscure" as possible to make reverse engineering reasonably difficult.
Ideally my library would consist of:
1- one .h file with only the functions exposed to the user
2- myLibrary.a: as un-reversengineerable as possible
What are the best practices for that? Where should I look, is there a good tutorial/book somewhere?
More specifically:
for - 1
I already have all my .h and .c working and I would like to avoid changing them around, moving function declarations from .h to .c and go into circular references potential pbs. Is That possible?
For instance is it a good idea to create a new .h file which I would use only for distributing with my .a? That .h would contain copies of the functions I want to expose and forward declarations of types I use. Is that a good idea?
for - 2
a) what gcc flags (or xcode) shall I be aware of (for stripping, not having debug symbols etc)
b) a good pointer to learn about how to do code obfuscation?
Any thought will help,
Thanks, baba
The usual practice is to make sure that every function and global variable that is for use only internal to some module is declared static in that module. That limits exposure of internal implementation details from a single module.
If you need internal implementation details that cross between modules, but which are not for public consumption, then declare one or more .h files that are kept private and not delivered to end users. The names of objects defined in that way will still be visible to the linker (and to tools such as objdump and nm) but their detailed signatures will not be.
If you have data structures that are delivered to the end user, but which are opaque, then consider having the API deliver them as pointers to a struct that is declared by not defined in the public API .h file. That will preserve type safety, while concealing the implementation details. Naturally, the complete struct definition is in a private .h file.
With care, you can keep a partially documented publicly known struct that is a type-pun for the real definition but which only exposes the public members. This is more difficult to keep up to date, and if you do it, I would make certain that there are some strong test cases to validate that the public version is in fact equivalent to the private version in all ways that matter.
Naturally, use strip to remove the debug segments so that the internal details are not leaked that way.
There are tools out there that can obfuscate all the names that are intended to be only internal use. If run as part of the build process, you can work with an internal debug build that has sensible names for everything, and ship a build that has named all the internal functions and global variables with names that only a linker can love.
Finally, get used to the fact that anyone that can use your library will be able to reverse engineer your library to some extent. There are anti-debugger measures that can be taken, but IMHO that way lies madness and frustration.
I don't have a quick answer other than to explore the use of "static" functions. I would recommend reading Miro Samek's work on something he calls "C+". Basically object oriented ANSI C. Great read. He owns Quantum leaps software.
Erase headers for this functions, do some obfuscation in exports table and get pack your code and apply some anti debugger algorithm.
http://upx.sourceforge.net/
http://www.oreans.com/

Resources