CS253: Software Development with C++

Spring 2020

Header Files

Show Lecture.HeaderFiles as a slide show.

CS253 Header Files

Header Files

Much like Java’s import, C++ uses #include:

    #include <foobar>

This means to compile the file foobar (found on Linux systems somewhere under /usr/include), as if it were part of the source file at this point. It typically contains declarations of functions and classes.

It’s called a header file because you #include it at the beginning, or head, of your .cc file.

C Compatibility

#include <stdio.h>
int main() {
    printf("Hello, world!\n");
    return 0;
}
Hello, world!

Nudging C toward C++

However, in C++, we don’t like putting things into the global namespace unnecessarily. This is called namespace pollution.

#include <stdio.h>symbols ⇒ global namespace
#include <cstdio>symbols ⇒ std namespace

Or, in general:

#include <foo.h>foo symbols ⇒ global namespace
#include <cfoo>foo symbols ⇒ std namespace

Pure C++

Pure C++ header files, such as <iostream>, don’t use .h.

There is no standard <iostream.h>. Some compilers provide it to reduce customer support calls, but it’s non-standard.

#include <iostream.h>
c.cc:1: fatal error: iostream.h: No such file or directory
compilation terminated.

Summary

#include <foo.h>C: foo symbols ⇒ global namespace
#include <cfoo>C compat: foo symbols ⇒ std namespace
#include <foo>C++: foo symbols ⇒ std namespace

This can get a bit confusing if foo starts with the letter c.

Examples

#include <stdio.h>Declare ::printf(), etc.
#include <cstdio>Declare std::printf(), etc.
#include <stdlib.h>Declare ::exit(), etc.
#include <cstdlib>Declare std::exit(), etc.
#include <ctype.h>Declare ::isupper(), etc.
#include <cctype>Declare std::isupper(), etc.
#include <vector>Declare std::vector, the C++ vector class
#include <string.h>Declare ::strlen(), etc.
#include <cstring>Declare std::strlen(), etc.
#include <string>Declare std::string, the C++ string class