6
Chapter 1 • GETTING READY 13 On some systems, you must run the compile and link programs separately. On other systems, the compiler starts the linker automatically, so you have to give only the compile command. Now lets look at some specific systems. Unix System Because Cs popularity began on Unix systems, we will start there. Editing on a Unix System Unix C does not have its own editor. Instead, you use one of the general-purpose Unix editors, such as emacs, jove, vi, or an X Window System text editor. Your two main responsibilities are typing the program correctly and choosing a name for the file that will store the program. As 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. Using the vi editor, we prepared the following program and stored it in a file called inform. c. tfinclude <stdio.h> int main(void) printf("A .c is used to end a C program filename.\n"); return 0; This text 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 such as #include and 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 these 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 the fol- lowing: 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 delete the word void from the example.) If you use the Is command to list your files, you will

Unix System - eecs.yorku.ca

  • Upload
    others

  • View
    8

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Unix System - eecs.yorku.ca

Chapter 1 • GETTING READY 13

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

Now lets look at some specific systems.

Unix SystemBecause Cs popularity began on Unix systems, we will start there.

Editing on a Unix SystemUnix C does not have its own editor. Instead, you use one of the general-purpose Unix editors,such as emacs, jove, vi, or an X Window System text editor.

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

Using the vi editor, we prepared the following program and stored it in a file called in fo rm. c.

tfinclude <stdio.h>int main(void)

printf("A .c is used to end a C program f i lename.\n");

return 0;

This text is the source code, and i n f o r m . c is the source file. The important point here is thatthe source file is the beginning of a process, not the end.

Compiling on a Unix SystemOur program, although undeniably brilliant, is still gibberish to a computer. A computerdoesn't understand things such as #include and printf . (At this point, you probably don'teither, but you will soon learn, whereas the computer won't.) As we discussed earlier, we needthe help of a compiler to translate our code (source code) to the computer's code (machinecode). The result of these efforts will be the executable file, which contains all the machinecode that the computer needs to get the job done.

The Unix C compiler is called cc. To compile the i n fo rm. c program, you need to type the fol-lowing:

cc inform.c

After a few seconds, the Unix prompt will return, telling you that the deed is done. You mightget warnings and error messages if you failed to write the program properly, but let's assumeyou did everything right. (If the compiler complains about the word void, your system has notyet updated to an ANSI C compiler. We'll talk more about standards soon. Meanwhile, justdelete the word void from the example.) If you use the Is command to list your files, you will

Page 2: Unix System - eecs.yorku.ca

14 C PRIMER PLUS

o12

3

4

5

6

7

8

9

1C

11

12

13

14

1617

18

19

20

21

22

23_

24

25̂

26

27

28

29

30

31

32

33

34

35

36

37

38

39

*41

42 _

43

44

find that there is a new file called a. out (see Figure 1.5). This is the executable file containingthe translation (or compilation) of the program. To run it, just type

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 isreplaced by a new a. out the next time you compile a program.

FIGURE 1.5

Preparing a C programusing Unix.

What about the object code? The cc compiler creates an object code file having the same base-name as the source code, but with an . o extension. In our example, the object code file iscalled i n f o r m . o, but you won't find it, because the linker removes it once the executable pro-gram has been completed. However, if the original program used more than one source codefile, the object code files would be saved. When we discuss multiple-file programs later in thetext, you will see that this is a fine idea.

Linux SystemLinux is a popular open-source, Unix-like operating system that runs on a variety of platforms,including IBM compatibles and Macintoshes. Preparing C programs on Linux is much the

Page 3: Unix System - eecs.yorku.ca

Chapter 1 • GETTING READY 15

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 may be optional when installing Linux, so you (or someone) mighthave to install gcc if it wasn't installed earlier. Typically, the installation makes cc an alias forgcc, so you can use cc in the command line instead of gcc if you like.

You can obtain further information about gcc, including information about new releases, athttp ://www.gnu. org/software/gcc/gcc. html.

Integrated Development Environments (Windows)C compilers are not part of the standard Windows package, so you may need to obtain andinstall a C compiler. Quite a few vendors, including Microsoft, Borland, Metrowerks, andDigital Mars, offer Windows-based integrated development environments, or IDEs. (Thesedays, most are combined C and C++ compilers.) All have fast, integrated environments forputting together C programs. The key point is that each of these programs has a built-in editoryou can use to write a C program. Each provides menus that enable you to name and saveyour source code file, as well as menus that allow you to compile and run your program with-out leaving the IDE. Each dumps you back into the editor if the compiler finds any errors, andeach identifies the offending lines and matches them to the appropriate error messages.

The Windows IDEs can be a little intimidating at first because they offer a variety of targets—that is, a variety of environments in which the program will be used. For example, they mightgive you a choice of 16-bit Windows programs, 32-bit Windows programs, dynamic linklibrary files (DLLs), and so on. Many of the targets involve bringing in support for theWindows graphical interface. To manage these (and other) choices, you typically create a pro-ject to which you then add the names of the source code files you'll be using. The precise stepsdepend on the product you use. Typically, you first use the File menu or Project menu to cre-ate a project. What's important is choosing the correct form of project. The examples in thisbook are generic examples designed to run in a simple command-line environment. The vari-ous Windows IDEs provide one or more choices to match this undemanding assumption.Microsoft Visual C 7.1, for example, offers the Win32 Console Application option. ForMetrowerks CodeWarrior 9.0, choose Win32 C Stationery and then select C Console App orthe WinSIOUX C App (the latter has a nicer user interface). For other systems, look for anoption using terms such as DOS EXE, Console, or Character Mode executable. These modeswill run your executable program in a console-like window After you have the correct projecttype, use the IDE menu to open a new source code file. For most products, you can do this byusing the File menu. You may have to take additional steps to add the source file to theproject.

Because the Windows IDEs typically handle both C and C++, you need to indicate that youwant a C program. With some products, such as Metrowerks CodeWarrior, you use the projecttype to indicate that you want to use C. With other products, such as Microsoft Visual C++,you use the . c file extension to indicate that you want to use C rather than C++. However,

Page 4: Unix System - eecs.yorku.ca

THECompumonly isuch as' \ 0 1 2 '

When;:

16 C PRIMER PLUS

Decimal

37

most C programs also work as C++ programs. Reference Section IX, "Differences Between Cand C++," compares C and C++.

One problem you might encounter is that the window showing the program execution van-ishes when the program terminates. If that is the case for you, you can make the programpause until you press the Enter key. To do that, add the following line to the end of the pro-gram, 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 keystrokewaiting. 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 wouldhave typed your weight and then pressed the Enter key to enter the data. The program wouldread the weight, the first getchar ( ) would read the Enter key, and the second getchar ()would cause the program to pause until you press Enter again. If this doesn't make a lot ofsense to you now, it will after you learn more about C input.

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

DOS Compilers for the IBM PCFor many, running DOS on a PC is out of fashion these days, but it is still an option for thosewith limited computer resources and a modest budget and for those who prefer a simpleroperating system without the bells, whistles, and distractions of a windowing environment.Many Windows IDEs additionally provide command-line tools, allowing you to program inthe DOS command-line environment. The Comeau C/C++ compiler that is available on manysystems, including several Unix and Linux variants, has a command-line DOS version. Also,there are freeware and shareware C compilers that work under DOS. For example, there is aDOS-based version of the GNU gcc compiler.

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

C compilers for the PC typically, but not always, produce intermediate object code files havingan . ob j extension. Unlike Unix compilers, C compilers typically don't remove these files whendone. Some compilers produce assembly language files with . asm extensions or use some spe-cial format of their own.

Page 5: Unix System - eecs.yorku.ca

Chapter 1 • GETTING READY 17

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

Oconcrete

C on the MacintoshThe best known Macintosh C/C++ compiler is the Metrowerks CodeWarrior compiler. (TheWindows and Macintosh versions of CodeWarrior have very similar interfaces.) It provides aproject-based IDE similar to what you would find in a Windows compiler. Start by choosingNew Project from the File menu. You'll be given a choice of project types. For recentCodeWarrior versions, use the Std C Console choice. (Different releases of Code Warrior takedifferent navigation routes to this choice.) You might also have to choose between a 68KB ver-sion (for the Motorola 680x0 series of processors), a PPC version (for the PowerPC proces-sors), or a Carbon version (for OS X).

The new project has a small source code file as part of the initial project. You can try compilingand running that program to see whether you have your system set up properly.

Language StandardsCurrently, many C implementations are available. Ideally, when you write a C program, itshould work the same on any implementation, providing it doesn't use machine-specific pro-gramming. For this to be true in practice, different implementations need to conform to a rec-ognized standard.

At first, there was no official standard for C. Instead, the first edition of The C ProgrammingLanguage by Brian Kernighan and Dennis Ritchie (1978) became the accepted standard, usu-ally referred to as K&R C or classic C. In particular, the "C Reference Manual" in that book'sappendix acted as the guide to C implementations. Compilers, for example, would claim tooffer a full K&R implementation. However, although this appendix defined the C language, itdid not define the C library. More than most languages, C depends on its library, so there isneed for a library standard, too. In the absence of any official standard, the library suppliedwith the Unix implementation became a de facto standard.

The First ANSVISO C StandardAs C evolved and became more widely used on a greater variety of systems, the C communityrealized it needed a more comprehensive, up-to-date, and rigorous standard. To meet thisneed, the American National Standards Institute (ANSI) established a committee (X3J11) in1983 to develop a new standard, which was adopted formally in 1989. This new standard(ANSI C) defines both the language and a standard C library. The International Organization

Page 6: Unix System - eecs.yorku.ca

18 C PRIMER PLUS

THE ASCIIComputers store clmonly used code iisuch as 'A ' for the'\012' and ' \0xa'When used as a pr

Decimal

0

Octal

0

Hex

0

2

3

4

5

6

7

8

9

10

11

12

02

03

04

05

06

07

010

011

012

013

014

13 _ | 01 5

0x2

0x3

0x4

0x5

0x6

0x7

0x8

0x9

Oxa

Oxb

Oxc

Oxd,

14 1016 JQxe

15

16

17

18

017

020

021

022

19 1 023

20

21

22

23

24

25

26

27

28

024

025

026

027

030

031

032

Dxf

Oxll

0x1

0x1

0x1

0x1

0x1

Ox'

Ox

Ox

Ox

Ox

033 j Ox

034 0>

29 035 JO)

036 |0:

037 ]0

j040 [C

1042

[043

I 044

I 046

for Standardization adopted a C standard (ISO C) in 1990. ISO C and ANSI C are essentiathe same standard. The final version of the ANSI/ISO standard is often referred to as C89(because that's when ANSI approval came) or C90 (because that's when ISO approval cameAlso, because the ANSI version came out first, people often used the term AN5I C.

The committee had several guiding principles. Perhaps the most interesting was this: Keepspirit of C. The committee listed the following ideas as expressing part of that spirit:

• Trust the programmer.

• Don't prevent the programmer from doing what needs to be done.

• Keep the language small and simple.

• Provide only one way to do an operation.

• Make it fast, even if it is not guaranteed to be portable.

By the last point, the committee meant that an implementation should define a particularoperation in terms of what works best for the target computer instead of trying to impose iabstract, uniform definition. You'll encounter examples of this philosophy as you learn theguage.

The C99 StandardIn 1994, work began on revising the standard, an effort that resulted in the C99 standard.joint ANSI/ISO committee, known then as the C9X committee, endorsed the original prindpies of the C90 standard, including keeping the language small and simple. The committeesintent was not to add new features to the language except as needed to meet the new goals.One of these main goals was to support international programming by, for example, providjways to deal with international character sets. A second goal was to "codify existing practiceaddress evident deficiencies." Thus, when meeting the need of moving C to 64-bit processoithe committee based the additions to the standard on the experiences of those who dealt witthis problem in real life. A third goal was to improve the suitability of C for doing criticalnumeric calculations for scientific and engineering projects.

These three points—internationalization, correction of deficiencies, and improvement of conputational usefulness—were the main change-oriented goals. The remaining plans for changwere more conservative in nature—for example, minimizing incompatibilities with C90 andlwith C++ and keeping the language conceptually simple. In the committee's words, ".. .thecommittee is content to let C++ be the big and ambitious language."

The upshot is that C99 changes preserve the essential nature of C, and C remains a lean, cleanefficient language. This book points out many of the C99 changes. Because most compilers aithis time don't fully implement all the C99 changes, you may find that some of them are notavailable on your system. Or you may find that some C99 features are available only if youalter the compiler settings.

I 051