Sun Studio 12: C++ User's Guide

2.1 Getting Started

This section gives you a brief overview of how to use the C++ compiler to compile and run C++ programs. See 16.8 Using dlopen to Access a C++ Library From a C Program for a full reference to the command-line options.


Note –

The command-line examples in this chapter show CC usages. Printed output might be slightly different.


The basic steps for building and running a C++ program involve:

  1. Using an editor to create a C++ source file with one of the valid suffixes listed in Table 2–1

  2. Invoking the compiler to produce an executable file

  3. Launching the program into execution by typing the name of the executable file

The following program displays a message on the screen:


example% cat greetings.cc
    #include <iostream>
    int main()  {
      std::cout << “Real programmers write C++!” << std::endl;
      return 0;
    }
example% CC greetings.cc
example% a.out
 Real programmers write C++!
example%

In this example, CC compiles the source file greetings.cc and, by default, compiles the executable program onto the file, a.out. To launch the program, type the name of the executable file, a.out, at the command prompt.

Traditionally, UNIX compilers name the executable file a.out. It can be awkward to have each compilation write to the same file. Moreover, if such a file already exists, it will be overwritten the next time you run the compiler. Instead, use the -o compiler option to specify the name of the executable output file, as in the following example:


example% CC– o greetings greetings.cc

In this example, the -o option tells the compiler to write the executable code to the file greetings. (It is common to give a program consisting of a single source file the name of the source file without the suffix.)

Alternatively, you could rename the default a.out file using the mv command after each compilation. Either way, run the program by typing the name of the executable file:


example% greetings
Real programmers write C++!
example%