Compiler Directives Java to C++
There are many things in the way Java declares classes and methods that happen automatically to inform other classes and methods of the information that they need. In C++ the programmer needs to take care of some of these things themselves. A common mechanism is the #include compiler directive and the .h file

C++




What the compiler sees

*C++[4] means C++ example line 4.

Compiler directives all are specified with a # in the very beginning of a line. There are a variety of compiler directives. We are only concerned with #include as in C++[Main.cpp 1]. This line specifies that the entire file "point.h" is to be included or placed at this point. Compiler directives are all processed before the compiler actually starts. What the compiler actually sees is the second version of Main.cpp. Notice that the declaration of the struct named point is now present in the file.

#include can be used for many things but its most important use is for sharing declarations among many files. In the example above, there may be many pieces of software that want to use a point with x and y coordinates. The standard way to do this is with a header file. In C and C++ header files are always followed by the .h extension. In our example the file is "point.h". This file can be included in any piece of software that wants a 2D point and the compiler will know what to do without us repeating the declaration over and over. Java does this automatically by remembering the information it discovered when it compiled a class.

In other examples we saw #include <iostream>. The angle brackets indicate that this is part of the standard library and that C++ should look for the include file in the standard libraries. The iostream.h file is very large and contains information about all of the declarations for doing input and output with streams.