CS 70

Key Points

  • We split our code into multiple files to avoid code duplication.
  • A multifile program contains:
    • One or more source files (.cpp), exactly one of which has a main function.
    • One or more header files (.hpp), which declare functions that are defined in the source files (.cpp).
  • Make sure that every header file (.hpp) has an include guard.

    #ifndef FILENAME_HPP_INCLUDED
    #define FILENAME_HPP_INCLUDED
    
    ...stuff...
    
    #endif
    
    • Include guards prevent multiple definitions when a header file is included more than once in the same source file.
    • Each preprocessor macro we use for an include guard must be unique (otherwise multiple files will be trying to use the same guard and only one of them will be seen), which is why we usually use the filename as part of the name.
  • Make sure that each file uses #include to include any header files (.hpp) that declare things it uses.

    • That often includes a source file's own header file!
    • Sometimes header files need to include other header files!
    • Use #include "filename" for your local files from the current directory.
    • Use #include <filename> for system include files
  • To compile your project:
    • Compile each source file (.cpp) into an object file (.o) using clang++ -c filename.cpp.
      • In practice, you'll probably want other flags too, such as -std=c++17, -g and -Wall -Wextra -pedantic.
      • (Remember from last week that this phase includes preprocessing, compiling the source file into assembly code, and then assembling the assembly code into machine code.)
    • Link object files (.o) together into an executable using clang++ -o executableName file1.o file2.o ...
  • To recompile:
    • If a source file (.cpp) changes, recompile it into an object file (.o) and relink as necessary.
    • If a header file (.hpp) changes, recompile all source files that include it or that include a file that includes it, and so on.
  • Rules of thumb:
    • Don't compile a header file (.hpp).
    • Don't #include a source file (.cpp).

(When logged in, completion status appears here.)