Introduction
Efficient and appropriate use of header files requires a few tricks. If you simply define a set of functions, everything works fine. No problems. If the file is included more than once because of a complex #include
chain, you get redundant declarations. Most compilers, including the Microsoft C/C++ compilers, simply ignore these redundant function and variable declarations. However, if there are any class
, typedef
, struct
, or some other declarations, the compiler will complain bitterly if they are seen twice, claiming they are duplication declarations. It does not choose to see if the structures actually are identical. So there is an idiom to avoid duplication declarations, which is to put the entire contents of the header file in an #ifndef
, skipping the body if a symbol defined within the body is already defined. This works acceptably well for short files, but is a performance disaster for lengthy files, since each line of the file must be read. For standard header files, precompiled headers work well in eliminating this problem, but it is harder to justify putting your own headers into a precompiled header file since the effects of a simple change result in a massive recompilation (stdafx.h has to be recompiled). Microsoft has added a #pragma
that means the header file is read only once. All of this is shown in detail below.
DLL Headers: Additional Complexity
When constructing a DLL, you need a header file to interface to it. However, the obvious solutions do not work as expected. For example, if you declare a function in a fashion so as to export it, you need to add __declspec(dllexport)
to its declaration, and if you don't want name mangling, particularly important if you expect to use the DLL with straight C code as well as C++, you need to define it in the .cpp file as
extern "C" __declspec(dllexport) function-header
{
// ... whatever
}
The problem with this approach is that the obvious solutions to the header file don't work.
The First Wrong Approach
The first attempt you might make is to declare, in the .h file
extern &