Datasheet
Book VIII
Chapter 1
Programming
in Linux
533
Exploring the Software-Development Tools in Linux
accomplish this use the following program source; the task that is stored in
the file area.c computes the area of a circle whose radius is specified at the
command line:
#include <stdio.h>
#include <stdlib.h>
/* Function prototype */
double area_of_circle(double r);
int main(int argc, char **argv)
{
if(argc < 2)
{
printf(“Usage: %s radius\n”, argv[0]);
exit(1);
}
else
{
double radius = atof(argv[1]);
double area = area_of_circle(radius);
printf(“Area of circle with radius %f = %f\n”,
radius, area);
}
return 0;
}
You need another file that actually computes the area of a circle. Here’s the
listing for the circle.c file, which defines a function that computes the
area of a circle:
#include <math.h>
#define SQUARE(x) ((x)*(x))
double area_of_circle(double r)
{
return 4.0 * M_PI * SQUARE(r);
}
For such a simple program, of course, we could place everything in a single
file, but this example was contrived a bit to show you how to handle mul-
tiple files.
To compile these two files and to create an executable file named area, use
this command:
gcc -o area area.c circle.c
This invocation of GCC uses the -o option to specify the name of the execut-
able file. (If you don’t specify the name of an output file with the -o option,
GCC saves the executable code in a file named a.out.)
42_770191-bk08ch01.indd 53342_770191-bk08ch01.indd 533 8/6/10 9:51 AM8/6/10 9:51 AM