Datasheet

534
Exploring the Software-Development Tools in Linux
If you have too many source files to compile and link, you can compile the
files individually and generate object files (that have the .o extension). That
way, when you change a source file, you need to compile only that file — you
just link the compiled file to all the object files. The following commands
show how to separate the compile and link steps for the sample program:
gcc -c area.c
gcc -c circle.c
gcc -o area area.o circle.o
The first two commands run gcc with the -c option compiling the source files.
The third gcc command links the object files into an executable named area.
Compiling C++ programs
GNU CC is a combined C and C++ compiler, so the gcc command also can
compile C++ source files. GCC uses the file extension to determine whether a
file is C or C++. C files have a lowercase .c extension whereas C++ files end
with .C or .cpp.
Although the gcc command can compile a C++ file, that command doesn’t
automatically link with various class libraries that C++ programs typically
require. Compiling and linking a C++ program by using the g++ command is
easy because it runs gcc with appropriate options.
Suppose that you want to compile the following simple C++ program stored
in a file named hello.C. (Using an uppercase C extension for C++ source files
is customary.)
#include <iostream>
int main()
{
using namespace std;
cout << “Hello from Linux!” << endl;
}
To compile and link this program into an executable program named hello,
use this command:
g++ -o hello hello.C
The command creates the hello executable, which you can run as follows:
./hello
The program displays the following output:
Hello from Linux!
42_770191-bk08ch01.indd 53442_770191-bk08ch01.indd 534 8/6/10 9:51 AM8/6/10 9:51 AM