Prefix header

In computer programming, a prefix header is a feature found in some C or C++ compilers used to ensure that a certain snippet of code is inserted at the beginning of every file.

Overview

In the C and C++ programming languages, a header file is a file whose text is included in another source file by the compiler, usually by the use of compiler directives at the beginning of the source file. A prefix header differs from a normal header file in that it is automatically included at the beginning of every source file by the compiler, without the use of any compiler directives.

Prefix headers are usually pre-compiled in order to reduce compilation times. Use of prefix headers outside of this purpose can make your code more difficult to maintain & less re-usable.[1] Prefix headers can also be used for cross-platform support. On *NIX systems, it is common to have a config.h header file generated at build time (via something like autoconf) that describes the capabilities of the system. However, when using certain build systems such as Visual Studio or Xcode, this config.h may be unavailable. One technique to solve this is to have HAVE_CONFIG_H be a pre-defined macro in the build-system that generates a config.h so that code knows whether it needs to #include config.h (& is safe for use by build systems that do not have it). An alternative, would be for the build system to add config.h as a prefix header instead of defining HAVE_CONFIG_H. Of course the downside is that this header will be added to every compilation unit, not just the ones that include it explicitly.

Example

On Mac OS X, the Xcode build system generates prefix headers automatically for new projects. A new Cocoa project, for instance, gets a prefix header that looks like this:

#ifdef __OBJC__
    #import <Cocoa/Cocoa.h>
#endif

As a result, explicit includes of the above header files in any Objective-C code file do not imply a second inclusion because of the #import directive of Objective-C, or more generally with #include because of the use of include guards; hence, these includes can be forgotten, but it is advocated[1] to have them explicitly written in order to keep the source code autonomous and reusable, and make the library dependencies clear.

Similar prefix headers are generated for other types of project.

See also

References

  1. "4 Ways Precompiled Headers Cripple Your Code • Quality Coding". Quality Coding. 28 February 2012. Retrieved 17 August 2018.
This article is issued from Wikipedia. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.