Object-Oriented Programming

Separate Compilation

Michael L. Collard, Ph.D.

Department of Computer Science, The University of Akron

Build: Start

Build: Compile main.cpp

Build: Compile utility.cpp

Build: Link

Separate Compilation

  • Real programs are composed of multiple files
  • Files are compiled separately into object files
  • The object files are linked together using the linker
  • For each application, one file is the main program and contains the main function
  • Separating functions and classes into separate files increases cohesion (good) but also increases coupling (can be bad)

File Structure

Type Purpose Extension Example
Include File Function declarations .hpp Aggregate.hpp
Implementation File Function definitions .cpp Aggregate.cpp

Include File

  • Required header comment, as in any other source file
  • Required include guard to prevent the compiler from seeing these contents more than once
  • Insert only the include of any files needed for the function declarations
  • Insert the function declarations (function prototypes)
  • The code that uses the include file must compile no matter where it is included or which includes precede it

Implementation File

  • Required header comment, as in any other source file
  • Include the related include file first, then when you compile the implementation file, you check that the include file is complete.
  • Insert any included files needed for the implementation
  • An include file is needed in the implementation file if it is used in the implementation of the code, i.e., the function definition
  • Do not include .cpp files
  • In this class including a .cpp file leads to a 0 on the exercise or project

Roles

Type Purpose Extension Example Roles
Include File Function declarations .hpp Aggregate.hpp interface concerns
Implementation File Function definitions .cpp Aggregate.cpp implementation concerns

Design Guideline

Hide as many concerns as possible in the implementation file

  • The only include files in the include file should be those needed for the interface
  • This means the include files needed for code that calls the functions provide by the interface
  • Include files used only in the implementation belong in the implementation file

Indirect Includes

Direct Includes

Self-Sufficiency

  • An include file needs to be self-sufficient
  • It should not depend on previous includes or the order of includes
  • This applies to all include files that we write

IWYU

  • Include What You Use
  • In every .cpp or .hpp, include any needed include files
  • Do not depend on indirect includes
  • This allows implementers of the include files to change their dependencies

Exposing Implementation Concerns

Hiding Implementation Concerns