7.1 Compiling a simple C++ program
The procedure for compiling a C++ program is the same as for a C
program, but uses the command g++ instead of gcc. Both
compilers are part of the GNU Compiler Collection.
To demonstrate the use of g++, here is a version of the Hello
World program written in C++:
#include <iostream>
int
main ()
{
std::cout << "Hello, world!\n";
return 0;
}
The program can be compiled with the following command line:
$ g++ -Wall hello.cc -o hello
The C++ frontend of GCC uses many of the same the same options as the C
compiler gcc. It also supports some additional options for
controlling C++ language features, which will be described in this
chapter. Note that C++ source code should be given one of the valid C++
file extensions '.cc', '.cpp', '.cxx' or '.C' rather
than the '.c' extension used for C programs.
The resulting executable can be run in exactly same way as the C
version, simply by typing its filename:
$ ./hello
Hello, world!
The executable produces the same output as the C version of the program,
using std::cout instead of the C printf function. All the
options used in the gcc commands in previous chapters apply to
g++ without change, as do the procedures for compiling and
linking files and libraries (using g++ instead of gcc, of
course). One natural difference is that the -ansi option
requests compliance with the C++ standard, instead of the C standard, when
used with g++.
Note that programs using C++ object files must always be linked with
g++, in order to supply the appropriate C++ libraries.
Attempting to link a C++ object file with the C compiler gcc will
cause "undefined reference" errors for C++ standard library functions:
$ g++ -Wall -c hello.cc
$ gcc hello.o (should use g++)
hello.o: In function `main':
hello.o(.text+0x1b): undefined reference to `std::cout'
.....
hello.o(.eh_frame+0x11):
undefined reference to `__gxx_personality_v0'
Undefined references to internal run-time library functions, such as
__gxx_personality_v0, are also a symptom of linking C++ object
files with gcc instead of g++. Linking the same object
file with g++ supplies all the necessary C++ libraries and will
produce a working executable:
$ g++ hello.o
$ ./a.out
Hello, world!
A point that sometimes causes confusion is that gcc will actually
compile C++ source code when it detects a C++ file extension, but cannot
then link the resulting object files.
$ gcc -Wall -c hello.cc (succeeds, even for C++)
$ gcc hello.o
hello.o: In function `main':
hello.o(.text+0x1b): undefined reference to `std::cout'
To avoid this problem, use g++ consistently for C++
programs and gcc for C programs.