CS253 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.
#include <stdio.h> int main() { printf("Hello, world!\n"); return 0; }
Hello, world!
using namespace std
, because this is C.
printf
, not std::printf
or
::printf
, because this is C.
#include <stdio.h>
must put its symbols into
the global namespace.
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++ 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.
#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
.
#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 C++ vector class |
#include <string.h> | Declare ::strlen , etc. |
#include <cstring> | Declare std::strlen , etc. |
#include <string> | Declare C++ string class |
Modified: 2017-01-25T14:49 User: Guest Check: HTML CSSEdit History Source |
Apply to CSU |
Contact CSU |
Disclaimer |
Equal Opportunity Colorado State University, Fort Collins, CO 80523 USA © 2015 Colorado State University |