Programming Mechanics

I l @ ve RuBoard

Programming Mechanics

The exact steps you must follow to produce a program depend on your computer environment. Because C is portable, it's available in many environments, including UNIX, MS-DOS, Windows 95, and Macintosh. We'll look at some typical examples.

First, however, let's look at some aspects shared by many C environments, including the four we just mentioned. You don't really need to know what follows to run a C program, but it is good background. It can also help you understand why you have to go through some particular steps to get a C program.

When you write a program in the C language, you store what you write in a text file called a source code file. Most C systems, including the ones we mentioned, require that the name of the file end in .c : for example, wordcount.c and budget.c . The part of the name before the period is called the basename and the part after the period is called the extension. Therefore, budget is a basename and c is an extension. The combination budget.c is the filename. The name should also satisfy the requirements of the particular computer operating system. For example, MS-DOS is an operating systems for IBM PCs and clones . It requires that the basename be no more than 8 characters long, so the wordcount.c name mentioned earlier would not be a valid DOS filename. Some UNIX systems place a 14-character limit on the whole name, including the extension; other UNIX systems allow longer names, up to 255 characters. Windows 95 and Macintosh also allow long names .

So that we'll have something concrete to refer to, let's assume we have a source file called concrete.c containing the C source code in Listing 1.2.

Listing 1.2 The concrete.c program.
 #include <stdio.h> int main(void) {   printf("Concrete contains gravel and cement.\n");   return 0; } 

Don't worry about the details of the source code file shown in Listing 1.2; you'll learn about them in Chapter 2.

Object Code Files, Executable Files, and Libraries

The basic strategy in C programming is to use programs that convert your source code file to an executable file , which is a file containing ready-to-run machine language code. C implementations do this in two steps: compiling and linking. The compiler converts your source code to an intermediate code, and the linker combines this with other code to produce the executable file. C uses this two-part approach to facilitate the modularization of programs. You can compile individual modules separately and then use the linker to combine the compiled modules later. That way, if you need to change one module, you don't have to recompile the other ones.

There are several choices for the form of the intermediate files. The most prevalent choice, and the one taken by the implementations we describe, is to convert the source code to machine language code, placing the result in an object code file , or object file for short. (We are assuming that your source code consists of a single file.) Although the object file contains machine language code, it is not ready to run. The object file contains the translation of your source code, but it is not yet a complete program.

The first element missing from the object code file is something called start-up code , which is code that acts as an interface between your program and the operating system. For example, you can run, say, an IBM PC compatible under DOS or under Linux, a UNIX variety. The hardware is the same in either case, so the same object code would work with both, but you would need different start-up code for DOS than you would for Linux because these systems handle programs differently from one another.

The second missing element is the code for library routines. Nearly all C programs make use of routines (called functions ) that are part of the standard C library. For example, concrete.c uses the function printf() . The object code file does not contain the code for this function; it merely contains instructions saying to use the printf() function. The actual code is stored in another file, called a library. A library file contains object code for many functions.

The role of the linker is to bring together these three elements ”your object code, the standard start-up code for your system, and the library code ”and put them together into a single file, the executable file. For library code, the linker extracts only the code needed for the functions you use from the library (see Figure 1.4).

Figure 1.4. Compiler and linker.
graphics/01fig04.jpg

In short, an object file and an executable file both consist of machine language instructions. The object file, however, contains the machine language translation only for the code you used, but the executable file also has machine code for the library routines you use and for the start-up code.

On some systems, you must run the compile and link programs separately. On other systems, the compiler starts the linker automatically, so that you have to give only the compile command.

Now let's look at some specific systems.

UNIX System

Because C's popularity began on UNIX systems, we will start there.

Editing on a UNIX System

Unlike BASIC, UNIX C does not have its own editor. Instead, you use one of the general-purpose UNIX editors, such as ed , ex , edit , emacs , jove or vi .

Your two main responsibilities are typing the program correctly and choosing a name for the file that will store the program. As we discussed, the name should end with .c . Note that UNIX distinguishes between uppercase and lowercase. Therefore, budget.c , BUDGET.c , and Budget.c are three distinct and valid names for C source files, but BUDGET.C is not a valid name because it uses an uppercase C instead of a lowercase c .

Here is an example. Using the vi editors, we prepared the following program and stored it in a file called inform .c .

 #include <stdio.h> int main(void) {    printf("A .c is used to end a C program filename.\n");    return 0; } 

The text we just typed is the source code, and inform.c is the source file. The important point here is that the source file is the beginning of a process, not the end.

Compiling on a UNIX System

Our program, although undeniably brilliant , is still gibberish to a computer. A computer doesn't understand things like #include or printf . (At this point, you probably don't either, but you will soon learn, whereas the computer won't.) As we discussed earlier, we need the help of a compiler to translate our code (source code) to the computer's code (machine code). The result of our efforts will be the executable file, which contains all the machine code that the computer needs to get the job done.

The UNIX C compiler is called cc . To compile the inform.c program, you need to type just this:

 cc inform.c 

After a few seconds, the UNIX prompt will return, telling you that the deed is done. You might get warnings and error messages if you failed to write the program properly, but let's assume you did everything right. (If the compiler complains about the word void , your system has not yet updated to an ANSI C compiler. We'll talk more about standards soon. Meanwhile, just omit the word void from the example.) If you use 1s to list your files, you will find that there is a new file called a.out (see Figure 1.5). This is the executable file containing the translation (or compilation) of the program. To run it, just type

Figure 1.5. Preparing a C program using UNIX.
graphics/01fig05.jpg
 a.out 

and wisdom pours forth:

 A .c is used to end a C program filename. 

If you want to keep the executable file ( a.out ), you should rename it. Otherwise, the file is replaced by a new a.out the next time you compile a program.

What about the object code? The cc compiler creates an object code file having the same basename as the source code, but with an o extension. In our example, the object code file is called inform.o , but you won't find it, for the linker removes it after the executable program has been completed. However,if the original program used more than one source code file, the object code files would be saved. When we discuss multiple-file programs later in the text, you will see that this is a fine idea.

Linux System

Linux is a popular public domain version of UNIX that runs on a variety of platforms, including IBM compatibles and Macintoshes. Preparing C programs on Linux is much the same as for UNIX systems, except that you would use the public domain C compiler, called gcc , that's provided by GNU. The compile command would look like this:

 gcc inform.c 

Note that installing gcc is optional when installing Linux, so you (or someone) might have to install gcc if it wasn't installed earlier. Typically, the installation makes cc an alias for gcc , so that you can use cc in the command line instead of gcc if you like.

Command-Line Compilers for the IBM PC

C compilers are not part of the PC operating system. They are add-ons, programs that have to be installed on the computer before you can create C programs.

The first C compilers for IBM PC compatibles were command-line compilers, which means you use them by typing commands at the DOS prompt. The usual cycle is first to run an editor program to create the source code, then exit the editor, and then run the compiler from the DOS command line. In short, the approach is much like that for UNIX. More recently, the trend has been toward integrated development environments ( IDEs ), which enable you to control the editing and compiling from one integrated program. In view of that, we'll make just a few general comments about using command-line compilers.

Source code files should be text files, not word processor files. (Word processor files contain a lot of additional information about fonts and formatting.) So you should use a text editor, such as the EDIT program that comes with some versions of DOS, or you can use a word processor, if you use the Save As feature to save the file in text mode. The file should have a .c extension. Some word processors automatically add a .txt extension to text files. If this happens to you, then you need to change the filename afterward, replacing txt with c .

Command-line C compilers typically, but not always, produce intermediate object code files having an .obj extension. Unlike UNIX compilers, C compilers don't remove these files when done. Some compilers produce assembly language files with .asm extensions or use some special format of their own.

Some compilers run the linker automatically after compiling; others might require that you run the linker manually. Linking results in the executable file, which appends the .exe extension to the original source code basename. For example, compiling and linking a source code file called concrete.c produces a file called concrete.exe . Some compilers provide an option to create an executable named concrete.com instead. In either case, you can run the program by typing the basename at the command line:

 C>concrete 

Integrated Development Environments (DOS)

The Inprise (formerly Borland) Turbo C/C++ 3.0 compiler is the most common IDE for DOS. It can run under DOS or in a DOS window under Windows. (The Borland C/C++ 3.1 compiler is similar.) After starting the program, choose File, New from the menu to create a new source code file. After entering your source code, choose File, Save from the menu to save the file. These products handle both C and C++ programs. When you save the file, use a .c extension to indicate that it is a C program; a .cpp extension indicates a C++ program.

There are a couple of paths to creating an executable file. One is to proceed step-by-step. First, choose Compile from the Compile menu. If that is successful, choose Link from the Compile menu. If that is successful, choose Run from the Run menu. Or you can just select Run as your first choice, and the Compile and Link stages are then executed first automatically.

The program runs in a DOS window, which disappears when the program finishes. However, choosing Output from the Window menu shows the results.

The IDE can have several windows open at once; for example, the editing window, the Output window, and a Message window. To compile, link, or run, make sure the editing window is the active window; you can do so by positioning the mouse cursor over the window and clicking.

Integrated Development Environments (Windows)

Quite a few vendors , including Microsoft, Inprise (formerly named Borland), Symantec, Watcom, and Metrowerks offer Windows-based IDEs. All have fast, integrated environments for putting together C programs. The key point is that each of these programs has a built-in editor you can use to write a C program. Each provides menus that enable you to name and save your source code file, as well as menus that allow you to compile and run your program without leaving the IDE. Each dumps you back into the editor if the compiler finds any errors, and each identifies the offending lines and matches them to the appropriate error messages.

The Windows IDEs are more complex than the DOS IDEs because they support a variety of targets , that is, a variety of environments in which the program will be used. For example, they might give you a choice of 16-bit Windows programs, 32-bit Windows programs, dynamic-link library files (DLLs), and so on. Many of the targets involve bringing in support for the Windows graphical interface. To manage these (and other) choices, you typically create a project to which you then add the names of the source code files you'll be using. The precise steps depend on the product you use. Typically, you first use the File menu or Project menu to create a project. What's important is choosing the correct form of project. The examples in this book are generic examples designed to run in a simple command-line environment. The various Windows IDEs provide one or more choices to match this undemanding assumption. Some earlier Microsoft compilers offered a QuickWin option, and some Borland compilers offered an EasyWin option; both are suitable. Otherwise, look for an option using terms such as DOS e XE or Console or Character Mode executable . These modes will run your executable program in a console-like window. When you have the correct project type, use the IDE menu to open a new source code file. For most products, you can do this by using the File menu. You may have to take additional steps to add the source file to the project.

Because the Windows IDEs typically handle both C and C++, you need to indicate that you want a C program. With some products, such as Metrowerks CodeWarrior, you use the project type to indicate that you want to use C. With other products, such as Microsoft Visual C++ 5.0, you use the .c file extension to indicate that you want to use C rather than C++. Some products, such as Inprise's C++Builder, do only C++. However, most C programs also work as C++ programs. Appendix G, "Differences Between C and C++," compares C and C++.

One problem you might encounter is that the window showing the program execution vanishes when the program terminates. If that is the case for you, you can make the program pause until you press the Enter key. To do that, add the following line to the end of the program, just before the return statement:

 getchar(); 

This line reads a keystroke, so the program will pause until you press the Enter key. Sometimes, depending on how the program functions, there might already be a keystroke waiting. In that case, you'll have to use getchar() twice:

 getchar(); getchar(); 

For example, if the last thing the program did was ask you to enter your weight, you would have typed your weight, and then pressed the Enter key to enter the data. The program would read the weight, the first getchar() would read the Enter key, and the second getchar() would cause the program to pause until you pressed Enter again. If this doesn't make a lot of sense to you now, it will after you learn more about C input.

Although the various IDEs share many broad principles in common, the details vary from product to product and, within a product line, from version to version. You'll have to do some experimenting to learn how your compiler works. You might even have to read the manual or try an online tutorial.

C on the Macintosh

The two best-known Macintosh C++ compilers are Metrowerks CodeWarrior and Symantec C++ compiler (formerly Think C) for the Macintosh. Both provide project-based IDEs similar, in basic concepts, to what you would find in a Windows compiler. (Indeed, both companies offer Windows-based versions of their compilers.) With either product, start by choosing New Project from the File menu. You'll be given a choice of project types. For CodeWarrior, select MacOS:C/C++:ANSI C Console in older versions, or MacOS:C/C++:Standard Console:Std C Console in more recent versions; for Symantec, select ANSII C. You might also have to choose between a 68KB version (for the Motorola 680X0 series of processors) or a PPC version (for the PowerPC processors).

Both products include a small source code file as part of the initial project. You can try compiling and running that program to see if you have your system set up properly. However, after you provide your own code, you should delete this file from the project by highlighting the file in the project window and then choosing Remove from the Project menu.

Next, you need to add your source code to the project. You can choose New from the File menu to create a new file or Open from the File menu to open an existing file. Use a proper suffix, such as .cp or .cpp . Use the Project menu to add this file to the project list. Some programs in this book require that you add more than one source code file. When you are ready, choose Run from the Project menu.

Why Compile?

Those of you used to BASIC might wonder about going through these steps to run a program. It might seem time-consuming, and it may even be time-consuming . After a program is compiled, however, it runs much faster than a standard BASIC program. You trade some inconvenience in getting a program running for a swifter final product. Also, if you use an integrated package, the inconvenience is much reduced.

I l @ ve RuBoard


C++ Primer Plus
C Primer Plus (5th Edition)
ISBN: 0672326965
EAN: 2147483647
Year: 2000
Pages: 314
Authors: Stephen Prata

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net