Jump to content United States-English
HP.com Home Products and Services Support and Drivers Solutions How to Buy
» Contact HP
More options
HP.com home
HP-UX Linker and Libraries User's Guide: HP 9000 Computers > Chapter 2 What Happens When You Compile and Link a Program

Compiling Programs on HP-UX: An Example

» 

Technical documentation

Complete book in PDF
» Feedback
Content starts here

 » Table of Contents

 » Glossary

 » Index

To create an executable program, you compile a source file containing a main program. For example, to compile an ANSI C program named sumnum.c, shown below, use this command (-Aa says to compile in ANSI mode):

$ cc -Aa sumnum.c 

The compiler displays status, warning, and error messages to standard error output (stderr). If no errors occur, the compiler creates an executable file named a.out in the current working directory. If your PATH environment variable includes the current working directory, you can run a.out as follows:

$ a.out
Enter a number: 4
Sum 1 to 4: 10

The process is essentially the same for all HP-UX compilers. For instance, to compile and run a similar FORTRAN program named sumnum.f:

$ f77 sumnum.f       Compile and link sumnum.f. 
... The compiler displays any messages here. $ a.out Run the program.
... Output from the program is displayed here.

Program source can also be divided among separate files. For example, sumnum.c could be divided into two files: main.c, containing the main program, and func.c, containing the function sum_n. The command for compiling the two together is:

$ cc -Aa main.c func.c
main.c:
func.c:

Notice that cc displays the name of each source file it compiles. This way, if errors occur, you know where they occur.

#include <stdio.h>              /* contains standard I/O defs */
int sum_n( int n ) /* sum numbers from n to 1 */
{
int sum = 0; /* running total; initially 0 */
for (; n >= 1; n--) /* sum from n to 1 */
sum += n; /* add n to sum */
return sum; /* return the value of sum */
}

main() /* begin main program */
{
int n; /* number to input from user */
printf("Enter a number: "); /* prompt for number */
scanf("%d", &n); /* read the number into n */
printf("Sum 1 to %d: %d\\n", n, sum_n(n)); /* display the sum */
}

Generally speaking, the compiler reads one or more source files, one of which contains a main program, and outputs an executable a.out file, as shown in Figure 2-1 “High-Level View of the Compiler ”.

Figure 2-1 High-Level View of the Compiler

High-Level View of the Compiler
Printable version
Privacy statement Using this site means you accept its terms Feedback to webmaster
© 1997 Hewlett-Packard Development Company, L.P.