Header files

Objectives

  • Use header files to specify the API of a C++ source file
  • Use header guards to avoid including header contents twice

Header files

  • If located in same directory, use quotes around header file name in include directive.
  • The paths searched by the compiler when quote marks are used is platform-dependent.
  • Header guards use preprocessor directives to make sure the content of a source file is not duplicated if the source file is included by more than one other file.
  • The first step is to pick a unique name for this particular file. The instructor usually uses the uppercase filename with underscores in place of special characters (like periods), and adds two underscores to both the front and back of the name. This means that a file named kishio.h would use the (hopefully) unique name: __KISHIO_H__
  • Near the beginning of the header file include a preprocessor check for the name:
    #ifndef __KISHIO_H__
  • The last line of text in the source file should end the above directive: #endif
  • What the above two directives do is to include the content of the file only if the specified name has not been defined. The first time the file is included, the name will not be defined.
  • The next step is to make sure that the contents of the file will not be used a second time. To do that, just add the following directive immediately after the #ifndef directive: #define __KISHIO_H__
  • The file contents are included the first time because __KISHIO_H__ has not been defined yet. The first thing that hppens then is that __KISHIO_H__ is defined. If any other includes for this file are encountered later, the name will be defined and the contents of the source file will not be included a second time.
  • header file guards will be demonstrated in class
  • see democlass2.cpp, Employee.h, and Employee.cpp examples
  • compile with: g++ -o democlass2 Employee.cpp democlass2.cpp

Additional notes

  • Students often want to use something platform-specific in their code. The most common I have encountered is: system("pause");
  • The problem with including a call to the pause program is that it is not on all platforms. To solve that problem, there is a cross-platform pause function provided on the home page for this course.
  • One problem with the cross-platform approach is that students often want to run pause on Windows, but not on Linux.
  • You can conditionally include code using the same preprocessor directives used for creating header guards.
  • The only real problem is knowing what the name is that you have to check for. That depends upon your compiler. There is a list of OS compiler macros at http://sourceforge.net/p/predef/wiki/OperatingSystems/
  • For most Windows situations, you should be able to use _WIN32
  • The result would look like this: #ifdef _WIN32 system("pause"); #endif