Pigpen wrote:
> I firmly believe that
> it is always a bad idea to put code in a header file.
> Nothing ****es me off more than seeing function definitions in a .h
> and I recently was truly blessed
to witness code
> that actually contained #include "foo.c" in a header.
You are confused.
All that is meant by the term "header file" is that
it is meant to be included somewhere near the top (head)
of a source file or another header file.
Header files are commonly used to introduce a *module interface*
into a translation unit. An interface has no substance.
This means that it should *not* contain any definitions
that, by themselves, cause the compiler to emit code or reserve memory.
Any such definitions should be sequestered in a translation unit
which can be compiled separately and linked into the program.
Good C programmers often *do* use the C preprocessor to include
files that contain external function and variable definitions
where they are required in the translation unit.
They probably should *not* call them header files
because other C programmers may think that
they contain a module interface.
> However, I am eliciting responses
> to the thought of putting assertions in a header file.
> I am dealing with a really ugly, really poorly done code base
> and I find myself often thinking,
> "Wtf? Does this mean what I think it does?"
> In such cases, I usually like to throw in an assertion to confirm things.
> My aesthetic sense tells to clean out all of the header files.
> My realistic sense tells me to dump the whole thing and start over.
> But my practical sense tells me that
> either of those solutions will take months.
Does this code belong to you now?
Are you responsible for maintaining and extending the code?
If it belongs to someone else,
you should try to get them to fix and maintain it.
If it belongs to you,
you need to make a plan to fix it no matter how long it takes.
> So I'm putting assertions into header files and it makes me feel dirty.
A cold shower might help.
> Am I compounding an already horrible situation?
> When possible, I use:
>
> #if FOO != BAZ
> #error
> #endif
>
> but, in a case where the header already has run-time code,
> I need to use an assertion.
> Believe me, I would love to simply pull the code out of the headers
> but the build environment is so phenomenally convoluted
> that changing the file structure is a major headache.
> I suppose that, in this situation,
> aesthetics and good style are totally pointless concerns.
> but I still have some dignity.
>
> So, what do you think.
> Is it acceptable to put an assertion into a header file?
I can only assume that you mean the assert macro.
Whether they appear in a header file or not is irrelevant.
Any assert macros must appear in the scope of a function definition.
They are used to trap programming errors at run-time while testing.
They disappear when you define the NDEBUG macro and recompile
just before you deploy your code.