home *** CD-ROM | disk | FTP | other *** search
Wrap
Text File | 1991-03-01 | 1013.0 KB | 20,727 lines
%@1@%%@AB@%Microsoft C - Advanced Programming Techniques%@AE@%%@EH@%%@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% %@AB@%Microsoft (R) C - Advanced Programming Techniques%@AE@%%@NL@% %@NL@% %@AB@%FOR MS (R) OS/2 AND MS-DOS (R) %@AB@%OPERATING SYSTEMS%@AE@%%@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% %@NL@% %@NL@% MICROSOFT CORPORATION%@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@%%@NL@% %@NL@% Information in this document is subject to change without notice and does not represent a commitment on the part of Microsoft Corporation. The software described in this document is furnished under a license agreement or nondisclosure agreement. The software may be used or copied only in accordance with the terms of the agreement. It is against the law to copy the software on any medium except as specifically allowed in the license or nondisclosure agreement. No part of this manual may be reproduced or trans- mitted in any form or by any means, electronic or mechanical, including photocopying and recording, for any purpose without the express written permission of Microsoft. (C) Copyright Microsoft Corporation, 1990. All rights reserved.%@NL@% %@NL@% Printed and bound in the United States of America.%@NL@% %@NL@% Microsoft, MS, MS-DOS, CodeView, InPort, and XENIX are registered trademarks and Windows is a trademark of Microsoft Corporation.%@NL@% %@NL@% Apple and Macintosh are registered trademarks and Finder is a trademark of Apple Computer, Inc.%@NL@% %@NL@% AT&T is a registered trademark of American Telephone and Telegraph Company.%@NL@% %@NL@% Hercules is a registered trademark and InColor is a trademark of Hercules Computer Technology.%@NL@% %@NL@% IBM is a registered trademark of International Business Machines Corporation.%@NL@% %@NL@% Intel is a registered trademark of Intel Corporation.%@NL@% %@NL@% Olivetti is a registered trademark of Ing. C. Olivetti.%@NL@% %@NL@% PDP-11 and VAX-11 are registered trademarks of Digital Equipment Corporation.%@NL@% %@NL@% WANG is a registered trademark of Wang Laboratories.%@NL@% %@NL@% Z8000 is a registered trademark of Zilog, Inc.%@NL@% %@NL@% Document No. LN06514-1189 OEMO711-6Z 10 9 8 7 6 5 4 3 2 1 %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@1@%%@AB@%Table of Contents%@AE@%%@EH@%%@NL@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@NL@% %@NL@% %@NL@% %@AB@%Introduction%@AE@%%@BO: 9686@%%@NL@% Scope of This Book%@BO: bdfd@%%@NL@% Document Conventions%@BO: a897@%%@NL@% %@NL@% %@NL@% %@AB@%PART I%@AE@%%@BO: b991@% %@AB@%Improving Program Performance%@AE@%%@NL@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@NL@% %@NL@% %@NL@% %@AB@%Chapter 1%@AE@%%@BO: bdfd@% %@AB@%Optimizing C Programs%@AE@%%@NL@% %@NL@% 1.1%@BO: a897@% Controlling Optimization from the Programmer's WorkBench%@NL@% 1.2%@BO: c938@% Controlling Optimization from the Command Line%@NL@% 1.3%@BO: ccf7@% Controlling Optimization with Pragmas%@NL@% 1.4%@BO: d6d0@% Default Optimization%@NL@% 1.4.1%@BO: d898@% Common Subexpression Elimination%@NL@% 1.4.2%@BO: db9a@% Dead-Store Elimination%@NL@% 1.4.3%@BO: de12@% Constant Propagation%@NL@% 1.5%@BO: e451@% Customizing Your Optimizations%@NL@% 1.5.1%@BO: e5c6@% Choosing Speed or Size (/Ot and /Os)%@NL@% 1.5.2%@BO: ea01@% Generating Intrinsic Functions (/Oi)%@NL@% 1.5.3%@BO: 107f9@% Assuming No Aliasing (/Oa and /Ow)%@NL@% 1.5.4%@BO: 1212b@% Performing Loop Optimizations (/Ol)%@NL@% 1.5.5%@BO: 12e46@% Disabling Unsafe Loop Optimizations (/On)%@NL@% 1.5.6%@BO: 12ff7@% Enabling Aggressive Optimizations (/Oz)%@NL@% 1.5.7%@BO: 13a0d@% Removing Stack Probes (/Gs)%@NL@% 1.5.8%@BO: 13daa@% Enabling Global Register Allocation (/Oe)%@NL@% 1.5.9%@BO: 14925@% Enabling Common Subexpression Optimization (/Oc and /Og)%@NL@% 1.5.10%@BO: 14e06@% Achieving Consistent Floating-Point Results (/Op)%@NL@% 1.5.11%@BO: 15770@% Using the 80186, 80188, or 80286 Processor (/G0, /G1, /G2)%@NL@% 1.5.12%@BO: 15f38@% Optimizing for Maximum Efficiency (/Ox)%@NL@% 1.6%@BO: 1651b@% Linker (LINK) Options that Control Optimization%@NL@% 1.6.1%@BO: 1666f@% Enabling Far Call Optimization (/FARCALLTRANSLATION)%@NL@% 1.6.2%@BO: 17905@% Packing Code (/PACKCODE)%@NL@% 1.6.3%@BO: 17f5b@% Packing Data (/PACKDATA)%@NL@% 1.6.4%@BO: 183a0@% Packing the Executable File (/EXEPACK)%@NL@% 1.7%@BO: 18674@% Optimizing in Different Environments%@NL@% 1.7.1%@BO: 18764@% Optimizing in DOS%@NL@% 1.7.2%@BO: 188d6@% Optimizing in OS/2%@NL@% 1.7.3%@BO: 189dc@% Optimizing in Microsoft Windows(tm)%@NL@% 1.8%@BO: 18c3f@% Choosing Function-Calling Conventions%@NL@% 1.8.1%@BO: 18f7f@% The C Calling Convention (/Gd)%@NL@% 1.8.2%@BO: 1932b@% The FORTRAN/Pascal Calling Convention (/Gc)%@NL@% 1.8.3%@BO: 19971@% The Register Calling Convention (/Gr)%@NL@% 1.8.4%@BO: 19f58@% The _fastcall Calling Convention%@NL@% %@NL@% %@AB@%Chapter 2%@AE@%%@BO: 1b75b@% %@AB@%Managing Memory%@AE@%%@NL@% %@NL@% 2.1%@BO: 1bb95@% Pointer Sizes%@NL@% 2.1.1%@BO: 1bdf8@% Pointers and 64K Segments%@NL@% 2.1.2%@BO: 1c3da@% Near Pointers%@NL@% 2.1.3%@BO: 1c68e@% Far Pointers%@NL@% 2.1.4%@BO: 1ca77@% Huge Pointers%@NL@% 2.1.5%@BO: 1d06e@% Based Addressing%@NL@% 2.2%@BO: 1d327@% Selecting a Standard Memory Model%@NL@% 2.2.1%@BO: 1d70e@% The Six Standard Memory Models%@NL@% 2.2.2%@BO: 1dc36@% Limitations on Code Size and Data Size%@NL@% 2.2.3%@BO: 1de9f@% The Tiny Memory Model%@NL@% 2.2.4%@BO: 1e27d@% The Huge Memory Model%@NL@% 2.2.5%@BO: 1ed27@% Null Pointers%@NL@% 2.2.6%@BO: 1f5f0@% Specifying a Memory Model%@NL@% 2.3%@BO: 1fcb2@% Mixing Memory Models%@NL@% 2.3.1%@BO: 2101e@% Pointer Problems%@NL@% 2.3.2%@BO: 21b7c@% Declaring Near, Far, Huge, and Based Variables%@NL@% 2.3.3%@BO: 2249a@% Declaring Near and Far Functions%@NL@% 2.3.4%@BO: 23064@% Pointer Conversions%@NL@% 2.4%@BO: 24124@% Customizing Memory Models%@NL@% 2.4.1%@BO: 249f8@% Setting a Size for Code Pointers%@NL@% 2.4.2%@BO: 24d6d@% Setting a Size for Data Pointers%@NL@% 2.4.3%@BO: 2530c@% Setting Up Segments%@NL@% 2.4.4%@BO: 26cc4@% Library Support for Customized Memory Models%@NL@% 2.4.5%@BO: 272c9@% Setting the Data Threshold%@NL@% 2.4.6%@BO: 27753@% Naming Modules and Segments%@NL@% %@NL@% %@AB@%Chapter 3%@AE@%%@BO: 283e2@% %@AB@%Using the In-Line Assembler%@AE@%%@NL@% %@NL@% 3.1%@BO: 28684@% Advantages of In-Line Assembly%@NL@% 3.2%@BO: 28b7b@% The _asm Keyword%@NL@% 3.3%@BO: 29386@% Using Assembly Language in _asm Blocks%@NL@% 3.4%@BO: 2aeac@% Using C in _asm Blocks%@NL@% 3.4.1%@BO: 2b3b3@% Using Operators%@NL@% 3.4.2%@BO: 2b8db@% Using C Symbols%@NL@% 3.4.3%@BO: 2bd9d@% Accessing C Data%@NL@% 3.4.4%@BO: 2c544@% Writing Functions%@NL@% 3.5%@BO: 2d276@% Using and Preserving Registers%@NL@% 3.6%@BO: 2dfda@% Jumping to Labels%@NL@% 3.7%@BO: 2e897@% Calling C Functions%@NL@% 3.8%@BO: 2ed4b@% Defining _asm Blocks as C Macros%@NL@% 3.9%@BO: 2fc28@% Optimizing%@NL@% %@NL@% %@AB@%Chapter 4%@AE@%%@BO: 306b8@% %@AB@%Controlling Floating-Point Math Operations%@AE@%%@NL@% %@NL@% 4.1%@BO: 30a74@% Declaring Floating-Point Types%@NL@% 4.1.1%@BO: 30d03@% Declaring Variables as Floating-Point Types%@NL@% 4.1.2%@BO: 32643@% Declaring Functions that Return Floating-Point Types%@NL@% 4.2%@BO: 32d2a@% C Run-Time Library Support of Type long double%@NL@% 4.3%@BO: 3307c@% Summary of Math Packages%@NL@% 4.3.1%@BO: 3376a@% Emulator Package%@NL@% 4.3.2%@BO: 33f87@% Math Coprocessor Package%@NL@% 4.3.3%@BO: 341c5@% Alternate Math Package%@NL@% 4.4%@BO: 34641@% Selecting Floating-Point Options (/FP)%@NL@% 4.4.1%@BO: 366b7@% In-Line Emulator Option (/FPi)%@NL@% 4.4.2%@BO: 36f6a@% In-Line Math Coprocessor Instructions Option (/FPi87)%@NL@% 4.4.3%@BO: 3737c@% Calls to Emulator Option (/FPc)%@NL@% 4.4.4%@BO: 37927@% Calls to Math Coprocessor Option (/FPc87)%@NL@% 4.4.5%@BO: 3826d@% Use Alternate Math Option (/FPa)%@NL@% 4.5%@BO: 386a4@% Library Considerations for Floating-Point Options%@NL@% 4.5.1%@BO: 3899b@% Using One Standard Library for Linking%@NL@% 4.5.2%@BO: 38cfd@% In-Line Instructions or Calls%@NL@% 4.6%@BO: 3913f@% Compatibility between Floating-Point Options%@NL@% 4.7%@BO: 39a6a@% Using the NO87 Environment Variable%@NL@% 4.8%@BO: 3a2a8@% Incompatibility Issues%@NL@% %@NL@% %@NL@% %@AB@%PART II%@AE@%%@BO: 3a90c@% %@AB@%Improving Programmer Productivity%@AE@%%@NL@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@NL@% %@NL@% %@NL@% %@AB@%Chapter 5%@AE@%%@BO: 3ada9@% %@AB@%Compiling and Linking Quickly%@AE@%%@NL@% %@NL@% 5.1%@BO: 3afdd@% Compiling Quickly%@NL@% 5.1.1%@BO: 3b0c7@% Quick Compiler%@NL@% 5.1.2%@BO: 3b47a@% Incremental Compile Option%@NL@% 5.2%@BO: 3b7b3@% Linking Quickly with ILINK%@NL@% 5.2.1%@BO: 3bf41@% Preparing for Incremental Linking%@NL@% 5.2.2%@BO: 3cae1@% Incremental Violations%@NL@% %@NL@% %@AB@%Chapter 6%@AE@%%@BO: 3d5e2@% %@AB@%Managing Development Projects with NMAKE%@AE@%%@NL@% %@NL@% 6.1%@BO: 3da36@% Overview of NMAKE%@NL@% 6.2%@BO: 3de62@% The NMAKE Command%@NL@% 6.3%@BO: 3e70a@% NMAKE Description Files%@NL@% 6.3.1%@BO: 3e89a@% Description Blocks%@NL@% 6.3.2%@BO: 4157f@% Comments%@NL@% 6.3.3%@BO: 4174e@% Macros%@NL@% 6.3.4%@BO: 45bdb@% Inference Rules%@NL@% 6.3.5%@BO: 473c7@% Directives%@NL@% 6.3.6%@BO: 48e0c@% Pseudotargets%@NL@% 6.3.7%@BO: 49ebe@% PWB's extmake Syntax%@NL@% 6.4%@BO: 4a5bf@% Command-Line Options%@NL@% 6.5%@BO: 4b91e@% NMAKE Command Files%@NL@% 6.6%@BO: 4bef2@% The TOOLS.INI File%@NL@% 6.7%@BO: 4c2bc@% In-Line Files%@NL@% 6.8%@BO: 4cb4d@% NMAKE Operations Sequence%@NL@% 6.9%@BO: 4de57@% Differences between NMAKE and MAKE%@NL@% %@NL@% %@AB@%Chapter 7%@AE@%%@BO: 4ed59@% %@AB@%Creating Help Files with HELPMAKE%@AE@%%@NL@% %@NL@% 7.1%@BO: 4f180@% Structure and Contents of a Help Database%@NL@% 7.1.1%@BO: 4f2e4@% Contents of a Help File%@NL@% 7.1.2%@BO: 5028d@% Help File Formats%@NL@% 7.2%@BO: 50e99@% Invoking HELPMAKE%@NL@% 7.3%@BO: 51889@% HELPMAKE Options%@NL@% 7.3.1%@BO: 51a53@% Options for Encoding%@NL@% 7.3.2%@BO: 543d4@% Options for Decoding%@NL@% 7.4%@BO: 558a5@% Creating a Help Database%@NL@% 7.5%@BO: 55ed3@% Help Text Conventions%@NL@% 7.5.1%@BO: 55fed@% Structure of the Help Text File%@NL@% 7.5.2%@BO: 56806@% Local Contexts%@NL@% 7.5.3%@BO: 56dec@% Context Prefixes%@NL@% 7.5.4%@BO: 582a4@% Hyperlinks%@NL@% 7.6%@BO: 5932f@% Using Help Database Formats%@NL@% 7.6.1%@BO: 59b21@% QuickHelp Format%@NL@% 7.6.2%@BO: 5db23@% Minimally Formatted ASCII Format%@NL@% 7.6.3%@BO: 5e410@% Rich Text Format (RTF)%@NL@% %@NL@% %@AB@%Chapter 8%@AE@%%@BO: 5f750@% %@AB@%Customizing the Microsoft Programmer's WorkBench%@AE@%%@NL@% %@NL@% 8.1%@BO: 5fc26@% Setting Switches%@NL@% 8.1.1%@BO: 5fe49@% Editing the <assign> Pseudofile%@NL@% 8.1.2%@BO: 604db@% Editing the TOOLS.INI Initialization File%@NL@% 8.2%@BO: 610f5@% Assigning Keystrokes%@NL@% 8.3%@BO: 619e7@% Writing Macros%@NL@% 8.3.1%@BO: 61b24@% Macro Syntax%@NL@% 8.3.2%@BO: 6270b@% Macro Responses%@NL@% 8.3.3%@BO: 62dd1@% Macro Arguments%@NL@% 8.3.4%@BO: 63473@% Macro Conditionals%@NL@% 8.3.5%@BO: 63da5@% Temporary Macros%@NL@% 8.3.6%@BO: 640d2@% Macro Recordings%@NL@% 8.4%@BO: 64b33@% Writing and Building C Extensions%@NL@% 8.4.1%@BO: 65cb5@% Building Real-Mode Extensions%@NL@% 8.4.2%@BO: 667cc@% Building Protected-Mode Extensions%@NL@% 8.4.3%@BO: 67183@% Describing Functions and Switches%@NL@% 8.4.4%@BO: 689a6@% Initializing Functions%@NL@% 8.4.5%@BO: 68d27@% Prototyping Functions%@NL@% 8.4.6%@BO: 69122@% Receiving Parameters%@NL@% 8.4.7%@BO: 6a36d@% Calling PWB Functions%@NL@% 8.4.8%@BO: 6c45b@% Calling C Library Functions%@NL@% %@NL@% %@AB@%Chapter 9%@AE@%%@BO: 6cc79@% %@AB@%Debugging C Programs with CodeView%@AE@%%@NL@% %@NL@% 9.1%@BO: 6d0c1@% Understanding CodeView Windows%@NL@% 9.2%@BO: 6e652@% Overview of Debugging Techniques%@NL@% 9.3%@BO: 6ec41@% Viewing and Modifying Program Data%@NL@% 9.3.1%@BO: 6edbe@% Displaying Variables in the Watch Window%@NL@% 9.3.2%@BO: 6f66e@% Displaying Expressions in the Watch Window%@NL@% 9.3.3%@BO: 6fd74@% Displaying Arrays and Structures%@NL@% 9.3.4%@BO: 70e92@% Displaying Array Elements Dynamically%@NL@% 9.3.5%@BO: 711f8@% Using Quick Watch%@NL@% 9.3.6%@BO: 717dc@% Displaying Memory%@NL@% 9.3.7%@BO: 72653@% Displaying the Processor Registers%@NL@% 9.3.8%@BO: 72b9c@% Modifying the Values of Variables, Registers, and Memory%@NL@% 9.4%@BO: 733af@% Controlling Execution%@NL@% 9.4.1%@BO: 735dc@% Continuous Execution%@NL@% 9.4.2%@BO: 75665@% Single-Stepping%@NL@% 9.5%@BO: 75bf1@% Replaying a Debug Session%@NL@% 9.6%@BO: 769d2@% Advanced CodeView Techniques%@NL@% 9.7%@BO: 78caf@% Controlling CodeView with Command-Line Options%@NL@% 9.8%@BO: 79ca7@% Customizing CodeView with the TOOLS.INI FILE%@NL@% %@NL@% %@NL@% %@AB@%PART III%@AE@%%@BO: 7a0b5@% %@AB@%Special Environments%@AE@%%@NL@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@NL@% %@NL@% %@NL@% %@AB@%Chapter 10%@AE@%%@BO: 7a411@% %@AB@%Communicating with Graphics%@AE@%%@NL@% %@NL@% 10.1%@BO: 7a96d@% Video Modes%@NL@% 10.1.1%@BO: 7aed0@% Sample Low-Level Graphics Program%@NL@% 10.1.2%@BO: 7b97c@% Setting a Video Mode%@NL@% 10.1.3%@BO: 7c764@% Reading the videoconfig Structure%@NL@% 10.1.4%@BO: 7d113@% Maximizing Resolution or Color%@NL@% 10.1.5%@BO: 7d740@% Selecting Your Own Video Modes%@NL@% 10.2%@BO: 7dc0f@% Mixing Colors and Changing Palettes%@NL@% 10.2.1%@BO: 7e2a7@% CGA Palettes%@NL@% 10.2.2%@BO: 7ec93@% Olivetti(R) Palettes%@NL@% 10.2.3%@BO: 7ef5d@% VGA Palettes%@NL@% 10.2.4%@BO: 7fb3a@% MCGA Palettes%@NL@% 10.2.5%@BO: 7fcaa@% EGA Palettes%@NL@% 10.2.6%@BO: 801b2@% Symbolic Constants%@NL@% 10.3%@BO: 80592@% Specifying Points within Coordinate Systems%@NL@% 10.3.1%@BO: 8099d@% Physical Coordinates%@NL@% 10.3.2%@BO: 812e6@% Viewport Coordinates%@NL@% 10.3.3%@BO: 81890@% Window Coordinates%@NL@% 10.3.4%@BO: 81ee4@% Screen Locations%@NL@% 10.3.5%@BO: 823fa@% Bounding Rectangles%@NL@% 10.3.6%@BO: 82781@% The Pixel Cursor%@NL@% 10.4%@BO: 82a7b@% Graphics Functions%@NL@% 10.4.1%@BO: 82cc4@% Controlling Video Modes%@NL@% 10.4.2%@BO: 83c39@% Changing Colors%@NL@% 10.4.3%@BO: 844c2@% Drawing Points, Lines, and Shapes%@NL@% 10.4.4%@BO: 859c2@% Defining Patterns%@NL@% 10.4.5%@BO: 86184@% Manipulating Images%@NL@% 10.5%@BO: 86bee@% Using Graphic Fonts%@NL@% 10.5.1%@BO: 877ab@% Using the C Font Library%@NL@% 10.5.2%@BO: 87c1d@% Registering the Fonts%@NL@% 10.5.3%@BO: 88036@% Setting the Current Font%@NL@% 10.5.4%@BO: 896c0@% Displaying Text%@NL@% 10.5.5%@BO: 898aa@% A Sample Program%@NL@% 10.5.6%@BO: 8a3d5@% Using Fonts Effectively%@NL@% %@NL@% %@AB@%Chapter 11%@AE@%%@BO: 8aaf4@% %@AB@%Creating Charts and Graphs%@AE@%%@NL@% %@NL@% 11.1%@BO: 8ae04@% Overview of Presentation Graphics%@NL@% 11.2%@BO: 8b7df@% Parts of a Graph%@NL@% 11.3%@BO: 8d6ab@% Writing a Presentation Graphics Program%@NL@% 11.3.1%@BO: 8ddc9@% Pie Chart%@NL@% 11.3.2%@BO: 8e7dc@% Bar, Column, and Line Charts%@NL@% 11.3.3%@BO: 8f968@% Scatter Diagram%@NL@% 11.4%@BO: 90562@% Manipulating Colors and Patterns%@NL@% 11.4.1%@BO: 90ad9@% Color Pool%@NL@% 11.4.2%@BO: 91535@% Style Pool%@NL@% 11.4.3%@BO: 91a9b@% Pattern Pool%@NL@% 11.4.4%@BO: 92c2b@% Character Pool%@NL@% 11.5%@BO: 92dd5@% Customizing the Chart Environment%@NL@% 11.5.1%@BO: 93be0@% titletype Structures%@NL@% 11.5.2%@BO: 9459e@% axistype Structures%@NL@% 11.5.3%@BO: 976d0@% windowtype Structures%@NL@% 11.5.4%@BO: 98696@% legendtype Structures%@NL@% 11.5.5%@BO: 9967d@% chartenv Structures%@NL@% %@NL@% %@AB@%Chapter 12%@AE@%%@BO: 9aa24@% %@AB@%Programming with Mixed Languages%@AE@%%@NL@% %@NL@% 12.1%@BO: 9ad4c@% Making Mixed-Language Calls%@NL@% 12.2%@BO: 9ba76@% Language Convention Requirements%@NL@% 12.2.1%@BO: 9bca6@% Naming Convention Requirement%@NL@% 12.2.2%@BO: 9cfc0@% Calling Convention Requirement%@NL@% 12.2.3%@BO: 9e1fd@% Parameter-Passing Requirement%@NL@% 12.3%@BO: 9f253@% Compiling and Linking%@NL@% 12.3.1%@BO: 9f3b2@% Compiling with Correct Memory Models%@NL@% 12.3.2%@BO: 9f9ac@% Linking with Language Libraries%@NL@% 12.4%@BO: a0128@% C Calls to High-Level Languages%@NL@% 12.5%@BO: a1883@% C Calls to BASIC%@NL@% 12.6%@BO: a2cd2@% C Calls to FORTRAN%@NL@% 12.6.1%@BO: a2e7e@% Calling a FORTRAN Subroutine from C%@NL@% 12.6.2%@BO: a3920@% Calling a FORTRAN Function from C%@NL@% 12.7%@BO: a4226@% C Calls to Pascal%@NL@% 12.7.1%@BO: a43cc@% Calling a Pascal Procedure from C%@NL@% 12.7.2%@BO: a4d77@% Calling a Pascal Function from C%@NL@% 12.8%@BO: a5596@% C Calls to Assembly Language%@NL@% 12.8.1%@BO: a5da1@% Writing the Assembly-Language Procedure%@NL@% 12.8.2%@BO: a6312@% Setting Up the Procedure%@NL@% 12.8.3%@BO: a6aae@% Entering the Procedure%@NL@% 12.8.4%@BO: a6f57@% Allocating Local Data%@NL@% 12.8.5%@BO: a7510@% Preserving Register Values%@NL@% 12.8.6%@BO: a802c@% Accessing Parameters%@NL@% 12.8.7%@BO: a8e40@% Returning a Value%@NL@% 12.8.8%@BO: a9a4d@% Exiting the Procedure%@NL@% 12.9%@BO: aa24b@% Handling Data in Mixed-Language Programming%@NL@% 12.9.1%@BO: aa39c@% Default Naming and Calling Conventions%@NL@% 12.9.2%@BO: aacde@% Numeric Data Representation%@NL@% 12.9.3%@BO: ab885@% Strings%@NL@% 12.9.4%@BO: ad1db@% Arrays%@NL@% 12.9.5%@BO: ad98d@% Array Declaration and Indexing%@NL@% 12.9.6%@BO: ae795@% Structures, Records, and User-Defined Types%@NL@% 12.9.7%@BO: aeec0@% External Data%@NL@% 12.9.8%@BO: af676@% Pointers and Address Variables%@NL@% 12.9.9%@BO: afe32@% Common Blocks%@NL@% 12.9.10%@BO: b08e9@% Using a Varying Number of Parameters%@NL@% %@NL@% %@AB@%Chapter 13%@AE@%%@BO: b0c3c@% %@AB@%Writing Portable Programs%@AE@%%@NL@% %@NL@% 13.1%@BO: b1007@% Assumptions about Hardware%@NL@% 13.1.1%@BO: b1169@% Size of Basic Types%@NL@% 13.1.2%@BO: b3a6e@% Storage Order and Alignment%@NL@% 13.1.3%@BO: b4c9f@% Byte Order in a Word%@NL@% 13.1.4%@BO: b58da@% Reading and Writing Structures%@NL@% 13.1.5%@BO: b5c84@% Bit Fields in Structures%@NL@% 13.1.6%@BO: b6909@% Processor Arithmetic Mode%@NL@% 13.1.7%@BO: b6f0a@% Pointers%@NL@% 13.1.8%@BO: b83ac@% Address Space%@NL@% 13.1.9%@BO: b8a46@% Character Set%@NL@% 13.2%@BO: b962b@% Assumptions about the Compiler%@NL@% 13.2.1%@BO: b9892@% Sign Extension%@NL@% 13.2.2%@BO: bab57@% Length and Case of Identifiers%@NL@% 13.2.3%@BO: bb247@% Register Variables%@NL@% 13.2.4%@BO: bb8b1@% Functions with a Variable Number of Arguments%@NL@% 13.2.5%@BO: bbbc6@% Evaluation Order%@NL@% 13.2.6%@BO: bc416@% Function and Macro Arguments with Side Effects%@NL@% 13.2.7%@BO: bcd8f@% Environment Differences%@NL@% 13.3%@BO: bd133@% Portability of Data Files%@NL@% 13.4%@BO: bd422@% Portability Concerns Specific to Microsoft C%@NL@% 13.5%@BO: bd7f3@% Microsoft C Byte Ordering%@NL@% %@NL@% %@NL@% %@AB@%PART IV%@AE@%%@BO: bde61@% %@AB@%OS/2 Support%@AE@%%@NL@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@NL@% %@NL@% %@NL@% %@AB@%Chapter 14%@AE@%%@BO: be208@% %@AB@%Building OS/2 Applications%@AE@%%@NL@% %@NL@% 14.1%@BO: be7b1@% The OS/2 Applications Program Interface%@NL@% 14.1.1%@BO: bec33@% Calling the OS/2 API%@NL@% 14.1.2%@BO: bf231@% Including the OS/2 Header Files%@NL@% 14.1.3%@BO: c006c@% Creating Dual-Mode Programs as Family Applications%@NL@% 14.2%@BO: c1470@% Compile Options for the CL Command%@NL@% 14.2.1%@BO: c1726@% The Link Mode Options (/Lp, /Lr, and /Lc)%@NL@% 14.2.2%@BO: c2381@% Creating Bound Programs Option (/Fb)%@NL@% 14.2.3%@BO: c2dcb@% Library Selection Options (/MT, /ML, /MD, /Zl)%@NL@% 14.2.4%@BO: c3cbe@% Memory-Model Options (/Ax)%@NL@% 14.3%@BO: c4599@% Module-Definition Files and Import Libraries%@NL@% 14.3.1%@BO: c53a4@% Adding a Module-Definition File to the LINK Command%@NL@% 14.3.2%@BO: c5818@% Creating Dynamic-Link Libraries (DLLs)%@NL@% 14.3.3%@BO: c5fe4@% Creating Programs with I/O Privileges%@NL@% 14.3.4%@BO: c670a@% Creating Presentation Manager Applications%@NL@% 14.3.5%@BO: c702b@% Creating Import Libraries with the IMPLIB Utility%@NL@% 14.4%@BO: c772b@% Link Command-Line Options%@NL@% 14.5%@BO: c87b2@% The BIND Utility%@NL@% %@NL@% %@AB@%Chapter 15%@AE@%%@BO: c9373@% %@AB@%Creating Multithread OS/2 Applications%@AE@%%@NL@% %@NL@% 15.1%@BO: c9735@% Multithread Programs%@NL@% 15.1.1%@BO: c9dc6@% Library Support%@NL@% 15.1.2%@BO: cb9f3@% Include Files%@NL@% 15.1.3%@BO: cbed0@% C Run-Time Library Functions for Thread Control%@NL@% 15.2%@BO: cd17f@% Sample Multithread C Program%@NL@% 15.3%@BO: cf4e2@% Writing a Multithread Program%@NL@% 15.4%@BO: d1b51@% Compiling and Linking%@NL@% 15.5%@BO: d282f@% Avoiding Problem Areas%@NL@% 15.6%@BO: d37c9@% Using the Protected-Mode CodeView Debugger%@NL@% 15.6.1%@BO: d3c94@% Compiling with the /Zi Option%@NL@% 15.6.2%@BO: d3f28@% Prompt for Thread Number%@NL@% 15.6.3%@BO: d4099@% Thread Commands%@NL@% 15.6.4%@BO: d5b8c@% Screen Groups Used by CodeView%@NL@% %@NL@% %@AB@%Chapter 16%@AE@%%@BO: d5e3d@% %@AB@%Dynamic Linking with OS/2%@AE@%%@NL@% %@NL@% 16.1%@BO: d61d4@% Overview of Dynamic Linking%@NL@% 16.1.1%@BO: d6650@% Load-Time and Run-Time Linking%@NL@% 16.1.2%@BO: d6b99@% Application Programs and DLLs%@NL@% 16.1.3%@BO: d6f69@% DLLs and Microsoft C Run-Time Libraries%@NL@% 16.2%@BO: d825b@% Designing and Writing DLLs%@NL@% 16.2.1%@BO: d853e@% Floating-Point Math Requirements%@NL@% 16.2.2%@BO: d8f0f@% Initialization and Termination Requirements%@NL@% 16.2.3%@BO: daf4b@% Making the DLL Re-Entrant%@NL@% 16.2.4%@BO: dc9ad@% Signal Handling%@NL@% 16.2.5%@BO: dcb62@% Using Microsoft C Keywords%@NL@% 16.2.6%@BO: dd57b@% Compile Options for Dynamic-Link Libraries%@NL@% 16.3%@BO: de27b@% Building DLLs with Microsoft C%@NL@% 16.3.1%@BO: de508@% DLLs with Static C Run-Time Library Functions%@NL@% 16.3.2%@BO: e0bb2@% DLLs without C Run-Time Library Functions%@NL@% 16.3.3%@BO: e1318@% Programs and DLLs with a C Run-Time DLL%@NL@% 16.3.4%@BO: e3bfc@% Using CodeView to Debug Dynamic-Link Libraries%@NL@% %@NL@% %@AB@%Appendix A%@AE@%%@BO: e416c@% %@AB@%Using Exit Codes%@AE@%%@NL@% %@NL@% A.1%@BO: e4487@% The exit Function%@NL@% A.2%@BO: e4c25@% Testing Exit Codes from Command and Batch Files%@NL@% A.3%@BO: e516f@% Accessing Exit Codes from Other Programs%@NL@% %@NL@% %@AB@%Appendix B%@AE@%%@BO: e5c07@% %@AB@%Differences between C Versions 5.1 and 6.0%@AE@%%@NL@% %@NL@% B.1%@BO: e5f2b@% Modifications for ANSI Compatibility%@NL@% B.1.1%@BO: e604a@% ANSI-Mandated New Features%@NL@% B.1.2%@BO: e6582@% Integer Promotion Rules%@NL@% B.1.3%@BO: e69a6@% Defining NULL as a Pointer%@NL@% B.1.4%@BO: e6aeb@% Shift Operators%@NL@% B.1.5%@BO: e6e1a@% Pointers to Typedefs%@NL@% B.1.6%@BO: e7281@% Identifying Nonstandard Keywords%@NL@% B.1.7%@BO: e76c3@% Trigraphs%@NL@% B.1.8%@BO: e7a5c@% ANSI Nonconformance%@NL@% B.2%@BO: e7d0b@% New Keywords and Functions%@NL@% B.2.1%@BO: e7e33@% In-Line Assembler%@NL@% B.2.2%@BO: e7fa5@% Based Pointers and Objects%@NL@% B.2.3%@BO: e8ba2@% Based Heap Allocation Support%@NL@% B.2.4%@BO: e8ee2@% Releasing Unused Heap Memory%@NL@% B.2.5%@BO: e9138@% Making Static Data Available to the Heap%@NL@% B.2.6%@BO: e9224@% Long Doubles%@NL@% B.2.7%@BO: e9612@% Long Double Functions%@NL@% B.2.8%@BO: e99c4@% Model-Independent String and Memory Functions%@NL@% B.2.9%@BO: ea290@% Mixed-Model Memory Allocation Support%@NL@% B.2.10%@BO: ea4f7@% The _fastcall Attribute (/Gr Option)%@NL@% B.2.11%@BO: eaef3@% Drive and Directory Functions%@NL@% B.2.12%@BO: eb1d9@% Text Output Functions for OS/2%@NL@% B.3%@BO: eb630@% New Features%@NL@% B.3.1%@BO: eb6d7@% Strings and Macros%@NL@% B.3.2%@BO: eb7a0@% CL Options%@NL@% B.3.3%@BO: ec428@% Tiny Memory Model (.COM Files)%@NL@% B.3.4%@BO: ec60e@% The Optimize Pragma%@NL@% B.3.5%@BO: ec8b7@% Nameless Structures and Unions%@NL@% B.3.6%@BO: ecc74@% Unsized Arrays as the Last Member of a Structure%@NL@% B.3.7%@BO: ecfbb@% Improved Warnings%@NL@% B.3.8%@BO: ed1ac@% Macros%@NL@% B.3.9%@BO: ed252@% Improved Multithread Support in OS/2%@NL@% B.3.10%@BO: ed5ec@% Pipe Support in OS/2%@NL@% B.4%@BO: ed84a@% Differences in Code Generation%@NL@% B.4.1%@BO: ed956@% Speed and Space Improvements%@NL@% B.4.2%@BO: ed9f0@% Code Quality%@NL@% B.4.3%@BO: edb8b@% Floating-Point Code Generation%@NL@% B.4.4%@BO: ede82@% Intrinsic Functions%@NL@% B.5%@BO: ee528@% Changes and Deletions%@NL@% B.5.1%@BO: ee5f9@% Deleted Features%@NL@% B.5.2%@BO: ee77b@% Evaluation of Real Expressions%@NL@% B.5.3%@BO: ee929@% Default Optimizations%@NL@% B.5.4%@BO: eeadf@% Sign Extension of char Arguments%@NL@% B.5.5%@BO: eec98@% Conditional Compilation and Signed Values%@NL@% B.5.6%@BO: eee9b@% The const and volatile Qualifiers%@NL@% B.5.7%@BO: ef152@% Memory Allocation%@NL@% B.5.8%@BO: ef2a5@% Memory Used by Command-Line Arguments%@NL@% B.5.9%@BO: ef40f@% Format Specifiers in printf%@NL@% B.5.10%@BO: ef859@% Functions that Return Float Values%@NL@% %@NL@% %@AB@%Appendix C%@AE@%%@BO: efa07@% %@AB@%Implementation-Defined Behavior%@AE@%%@NL@% %@NL@% C.1%@BO: efe6d@% Translation%@NL@% C.1.1%@BO: efebc@% Diagnostics%@NL@% C.2%@BO: f017d@% Environment%@NL@% C.2.1%@BO: f01cc@% Arguments to main%@NL@% C.2.2%@BO: f0890@% Interactive Devices%@NL@% C.3%@BO: f098e@% Identifiers%@NL@% C.3.1%@BO: f09dd@% Significant Characters without External Linkage%@NL@% C.3.2%@BO: f0b7a@% Significant Characters with External Linkage%@NL@% C.3.3%@BO: f0d79@% Upper- and Lowercase%@NL@% C.4%@BO: f11dd@% Characters%@NL@% C.4.1%@BO: f122b@% The ASCII Character Set%@NL@% C.4.2%@BO: f151c@% Multibyte Characters%@NL@% C.4.3%@BO: f168f@% Bits per Character%@NL@% C.4.4%@BO: f17cf@% Character Sets%@NL@% C.4.5%@BO: f1bf4@% Unrepresented Character Constants%@NL@% C.4.6%@BO: f1d93@% Wide Characters%@NL@% C.4.7%@BO: f1f0d@% Converting Multibyte Characters%@NL@% C.4.8%@BO: f2060@% Range of char Values%@NL@% C.5%@BO: f227f@% Integers%@NL@% C.5.1%@BO: f22cb@% Range of Integer Values%@NL@% C.5.2%@BO: f2659@% Demotion of Integers%@NL@% C.5.3%@BO: f2a1d@% Signed Bitwise Operations%@NL@% C.5.4%@BO: f2c39@% Remainders%@NL@% C.5.5%@BO: f2da8@% Right Shifts%@NL@% C.6%@BO: f3130@% Floating-Point Math%@NL@% C.6.1%@BO: f3187@% Values%@NL@% C.6.2%@BO: f34ae@% Casting Integers to Floating-Point Values%@NL@% C.6.3%@BO: f37ce@% Truncation of Floating-Point Values%@NL@% C.7%@BO: f396c@% Arrays and Pointers%@NL@% C.7.1%@BO: f39c3@% Largest Array Size%@NL@% C.7.2%@BO: f3c0e@% Casting Pointers%@NL@% C.7.3%@BO: f4018@% Pointer Subtraction%@NL@% C.8%@BO: f42d8@% Registers%@NL@% C.8.1%@BO: f4325@% Availability of Registers%@NL@% C.9%@BO: f44b9@% Structures, Unions, Enumerations, and Bit Fields%@NL@% C.9.1%@BO: f452d@% Improper Access to a Union%@NL@% C.9.2%@BO: f47e3@% Sign of Bit Fields%@NL@% C.9.3%@BO: f4925@% Storage of Bit Fields%@NL@% C.9.4%@BO: f4cba@% Alignment of Bit Fields%@NL@% C.9.5%@BO: f4f59@% The enum Type%@NL@% C.10%@BO: f5071@% Qualifiers%@NL@% C.10.1%@BO: f50c0@% Access to Volatile Objects%@NL@% C.11%@BO: f51dc@% Declarators%@NL@% C.11.1%@BO: f522c@% Maximum Number%@NL@% C.12%@BO: f537a@% Statements%@NL@% C.12.1%@BO: f53c9@% Limits on Switch Statements%@NL@% C.13%@BO: f552c@% Preprocessing Directives%@NL@% C.13.1%@BO: f5589@% Character Constants and Conditional Inclusion%@NL@% C.13.2%@BO: f57dc@% Including Bracketed File Names%@NL@% C.13.3%@BO: f5bc9@% Including Quoted File Names%@NL@% C.13.4%@BO: f5eb7@% Character Sequences%@NL@% C.13.5%@BO: f6113@% Pragmas%@NL@% C.13.6%@BO: f648b@% Default Date and Time%@NL@% C.14%@BO: f6604@% Library Functions%@NL@% C.14.1%@BO: f665a@% NULL Macro%@NL@% C.14.2%@BO: f6761@% Diagnostic Printed by the assert Function%@NL@% C.14.3%@BO: f6a50@% Character Testing%@NL@% C.14.4%@BO: f6ea9@% Domain Errors%@NL@% C.14.5%@BO: f6fb1@% Underflow of Floating-Point Values%@NL@% C.14.6%@BO: f7176@% The fmod Function%@NL@% C.14.7%@BO: f72cd@% The signal Function%@NL@% C.14.8%@BO: f7c08@% Default Signals%@NL@% C.14.9%@BO: f7d6e@% The SIGILL Signal%@NL@% C.14.10%@BO: f7efd@% Terminating Newline Characters%@NL@% C.14.11%@BO: f804e@% Blank Lines%@NL@% C.14.12%@BO: f8174@% Null Characters%@NL@% C.14.13%@BO: f829c@% File Position in Append Mode%@NL@% C.14.14%@BO: f841d@% Truncation of Text Files%@NL@% C.14.15%@BO: f855b@% File Buffering%@NL@% C.14.16%@BO: f86d2@% Zero-Length Files%@NL@% C.14.17%@BO: f87b4@% File Names%@NL@% C.14.18%@BO: f89f5@% File Access Limits%@NL@% C.14.19%@BO: f8ae9@% Deleting Open Files%@NL@% C.14.20%@BO: f8bf5@% Renaming with a Name that Exists%@NL@% C.14.21%@BO: f8d68@% Printing Pointer Values%@NL@% C.14.22%@BO: f9000@% Reading Pointer Values%@NL@% C.14.23%@BO: f9167@% Reading Ranges%@NL@% C.14.24%@BO: f9361@% File Position Errors%@NL@% C.14.25%@BO: f9542@% Messages Generated by the perror Function%@NL@% C.14.26%@BO: f991d@% Allocating Zero Memory%@NL@% C.14.27%@BO: f9ad6@% The abort Function%@NL@% C.14.28%@BO: f9c2a@% The atexit Function%@NL@% C.14.29%@BO: f9d9c@% Environment Names%@NL@% C.14.30%@BO: fa192@% The system Function%@NL@% C.14.31%@BO: fa403@% The strerror Function%@NL@% C.14.32%@BO: fa814@% The Time Zone%@NL@% C.14.33%@BO: fa923@% The clock Function%@NL@% %@AB@%Index%@AE@%%@BO: faa6e@% %@NL@% %@NL@% %@CR:C6A-Intro @%%@1@%%@AB@%Introduction%@AE@%%@EH@%%@NL@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@NL@% %@AI@%Advanced Programming Techniques%@AE@% describes how to get the most out of the Microsoft(R) C Professional Development System with its new integrated development environment─the Microsoft Programmer's WorkBench─and source-level debugging tool─the CodeView(R) debugger. %@NL@% %@NL@% In this manual, you will see how all the components of the Microsoft C Professional Development System work together to provide you with the most powerful development environment available. A key element in the power of the Professional Development System is your ability to customize it to suit your individual needs as a programmer. %@NL@% %@NL@% Because this book is arranged by topic, it answers questions about using Microsoft C version 6.0, rather than providing lists of options. If you have specific questions about menu items in the CodeView debugger, the Programmer's WorkBench, or any of the command-line utilities included in the Professional Development System, you can use the Microsoft C Advisor (on-line help) or the %@AI@%C Reference%@AE@% manual. %@AI@% %@AE@%%@NL@% %@NL@% %@AI@%Advanced Programming Techniques%@AE@% shows you how tools and utilities all fit together. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00010001 @%%@AB@%Scope of This Book%@AE@%%@EH@%%@NL@% %@NL@% %@AI@%Advanced Programming Techniques%@AE@% is divided into four parts. Part 1, "Improving Program Performance," helps you write more efficient programs. It provides specific information about optimizing─when and why to use various optimizing options. It also explains new memory management options and when to use them. For example, Chapter 3 describes the in-line assembler, a new feature that lets you mix assembly language with your C source code. %@NL@% %@NL@% Part 2, "Improving Programmer Productivity," will help you perform programming tasks more quickly and efficiently. Chapter 8 explains the different ways you can customize the new Programmer's WorkBench (PWB)─an editor and integrated development environment that allows you to %@NL@% %@NL@% %@NL@% ■ Create new programs%@NL@% %@NL@% ■ Modify existing programs%@NL@% %@NL@% ■ Browse source files%@NL@% %@NL@% ■ Obtain help about PWB, the C language, and the C run-time libraries%@NL@% %@NL@% ■ Set program build lists%@NL@% %@NL@% ■ Build programs%@NL@% %@NL@% ■ Debug programs with the CodeView debugger%@NL@% %@NL@% %@NL@% Chapter 8 also describes how to change PWB behavior to suit your programming style by making keyboard assignments, recording or writing macros, and writing C extensions. %@NL@% %@NL@% Also in Part 2 is a chapter about the Microsoft Program Maintenance Utility, NMAKE. NMAKE is a new program maintenance facility that allows you to use program lists as input, which provides extra flexibility in your program build process. It is a superset of the Microsoft XENIX(R) MAKE utility and is substantially more powerful than previous versions of MAKE. %@NL@% %@NL@% Chapter 9 in Part 2 describes the CodeView debugger, which is even more powerful than in previous releases. With CodeView version 3.0, you get many new features, including the ability to record a debugging session, then play it back (history and dynamic replay). %@NL@% %@NL@% Part 3, "Special Environments," describes new graphics capabilities. It also shows how to program in mixed languages and offers tips to make your programs more portable. Microsoft C helps you create graphics applications easily. The Microsoft C run-time libraries contain graphics functions for low-level graphics operations, such as drawing lines, rectangles, and circles. The libraries also contain functions for creating presentation graphics, such as pie charts and bar charts. %@NL@% %@NL@% Part 4, "OS/2 Support," describes how the Professional Development System helps you build OS/2 applications. The three chapters in Part 4 provide information about dual-mode applications, creating multithread applications, and creating dynamic-link libraries. %@NL@% %@NL@% A postage-paid documentation feedback card is at the end of this manual. After you have had a chance to become familiar with Microsoft C 6.0 and its documentation, please give us your opinion. Your ideas will help us as we develop future documentation. Also at the end of this book is a Product Assistance Request form. If you need to call Microsoft for assistance, use this form first to compile and organize pertinent information. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00010002 @%%@AB@%Document Conventions%@AE@%%@EH@%%@NL@% %@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% NOTE %@AI@%The pages that follow use the term "OS/2" to refer to the OS/2 %@AI@%systems─Microsoft Operating System/2 (MS%@AI@%(R)%@AE@%%@AI@% OS/2) and IBM%@AE@%%@AI@%(R) %@AE@%%@AI@%OS/2. %@AI@%Similarly, the term "DOS" refers to both the MS-DOS%@AE@%%@AI@%(R)%@AE@%%@AI@% and IBM Personal %@AI@%Computer DOS operating systems. The name of a specific operating system is %@AI@%used when it is necessary to note features that are unique to the system.%@AE@%%@AE@%%@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@%%@NL@% %@NL@% %@AB@%Example%@AE@% %@AB@%Description%@AE@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% STDIO.H Uppercase letters indicate file names, segment names, registers, and terms used at the DOS- or OS/2-command level. %@AB@%_cdecl%@AE@% Boldface letters indicate C keywords, operators, language-specific characters, and library functions, as well as OS/2 functions. Within discussions of syntax, bold type indicates that the text must be entered exactly as shown. %@AI@%expression%@AE@% Words in italics indicate placeholders for information you must supply, such as a file name. Italics are also occasionally used for emphasis in the text. «%@AI@%option%@AE@%» Items inside double square brackets are optional. %@AB@%#pragma pack%@AE@% {%@AB@%1%@AE@%|%@AB@%2%@AE@%} Braces and a vertical bar indicate a choice among two or more items. You must choose one of these items unless double square brackets surround the braces. %@AS@%CL A.C B.C C.OBJ%@AE@% This font is used for examples, user input, program output, and error messages in text. %@AB@%CL%@AE@% %@AI@%options%@AE@% «%@AI@% files%@AE@%...» A horizontal ellipsis following an item indicates that more items having the same form may follow. %@AS@%while%@AE@%( ) A vertical ellipsis tells you that part { of the example program has been . intentionally omitted. . . } CTRL+ENTER Small capital letters are used for the names of keys on the keyboard. When you see a plus sign (+) between two key names, you should hold down the first key while pressing the second. The carriage-return key (sometimes appearing as a bent arrow on the keyboard) is called ENTER. The cursor-movement keys (sometimes called direction keys) are called the ARROW keys. Individual keys are referred to by their direction (LEFT, UP) or by the name on the key (PGUP). "argument" Quotation marks enclose a new term the first time it is defined in text. Enhanced Graphics Adapter (EGA) The first time an acronym is used, it is often spelled out. %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@CR:C6A-Part 01 @%%@1@%%@AB@%PART I Improving Program Performance%@AE@%%@EH@%%@NL@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@NL@% The Microsoft C Professional Development System helps you create the fastest, smallest applications using its sophisticated optimizer and enhanced memory management capabilities. %@NL@% %@NL@% Chapter 1 tells when to use certain optimizations and describes how Microsoft C generates code that is efficient in execution speed and size. Chapter 2 explains the sophisticated tools Microsoft C gives you to allocate and manage program memory, including the new %@AB@%_based%@AE@% type. For cases where your program requires localized optimization, you can use the in-line assembler, described in Chapter 3, to introduce the tightest possible code. If your application requires floating-point math computations, you will find Chapter 4 helpful in explaining the options in the Microsoft C math packages; it explains which floating-point options yield the fastest, smallest, and most flexible code. %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@CR:C6A00010001 @%%@1@%%@AB@%Chapter 1 Optimizing C Programs%@AE@%%@EH@%%@NL@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@NL@% The Microsoft C compiler translates C source statements into machineexecutable instructions. In addition, the compiler rewrites or "optimizes" parts of your program to make it more efficient in ways that are not apparent at the source level. %@NL@% %@NL@% The compiler performs three general types of optimization: %@NL@% %@NL@% %@NL@% 1. It modifies or moves sections of code so that fewer instructions are used, or so that the instructions used make more efficient use of the processor.%@NL@% %@NL@% 2. It moves code and combines operations to maximize use of registers because operations on data stored in processor registers are far faster than the same operations on data stored in memory.%@NL@% %@NL@% 3. It eliminates sections of code that are redundant or unused.%@NL@% %@NL@% %@NL@% This chapter explains the various ways you can control how the Microsoft C compiler optimizes your code. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00010002 @%%@AB@%1.1 Controlling Optimization from the Programmer's WorkBench%@AE@%%@EH@%%@NL@% %@NL@% The Programmer's WorkBench (PWB) is an integrated development environment for editing, building, and debugging applications written in Microsoft C. For more information on the PWB, see %@AI@%Installing and Using the Microsoft C %@AI@%Professional Development System%@AE@%. %@NL@% %@NL@% There are two ways to compile from inside the Programmer's WorkBench: %@NL@% %@NL@% %@NL@% 1. Debug compile. In a default debug compile, the compiler performs no optimizations at all.%@NL@% %@NL@% 2. Release compile. In a default release compile, the compiler performs most optimizations.%@NL@% %@NL@% %@NL@% By modifying the settings in C Global Build Options, C Debug Build Options, and C Release Build Options (on the Options menu), you can fine-tune optimization by individually enabling or disabling any of the optimizations the compiler performs. %@NL@% %@NL@% The optimizations in each of the Build Options dialog boxes correspond to a command-line option to CL. (In fact, the PWB constructs a command line from your input and passes it to CL.) %@NL@% %@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% NOTE %@AI@%In this chapter, optimization options are discussed in terms of the effect %@AI@%of the optimization, the command-line option to invoke the optimization, and %@AI@%pragmas that control the optimization. All of these optimizations can be %@AI@%controlled at the compilation-unit (file) level using the Build Options %@AI@%dialog boxes.%@AE@%%@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@%%@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00010003 @%%@AB@%1.2 Controlling Optimization from the Command Line%@AE@%%@EH@%%@NL@% %@NL@% Controlling optimization from the command line requires that you determine which optimizations you need for your application. You then specify those optimizations using command-line options that begin with /O (and in some cases /G). %@NL@% %@NL@% If there is any conflict between options, the compiler uses the last option specified on the command line. The command line %@NL@% %@NL@% %@AS@% CL /Oa /Ol /Ot TEST.C%@AE@%%@NL@% %@NL@% compiles the program TEST.C. It specifies that the compiler can %@NL@% %@NL@% %@NL@% ■ Optimize on the assumption that you are doing no aliasing (/Oa)%@NL@% %@NL@% ■ Perform loop optimization (/Ol)%@NL@% %@NL@% ■ Perform other general speed-enhancing optimizations (/Ot)%@NL@% %@NL@% %@NL@% The preceding command line can also be written %@NL@% %@NL@% %@AS@% CL /Oalt TEST.C%@AE@%%@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00010004 @%%@AB@%1.3 Controlling Optimization with Pragmas%@AE@%%@EH@%%@NL@% %@NL@% Occasionally you will need to exercise a fine level of control over compiler optimizations. Command-line options allow you to control optimization over an entire compilation unit (file). In addition, Microsoft C supports several pragmas that allow you to exercise such control on a per-function basis. %@NL@% %@NL@% The pragmas that control optimization are described in this chapter under the type of optimization they affect. %@NL@% %@NL@% %@AU@% The optimize pragma is new to version 6.0.%@AE@% %@NL@% %@NL@% In version 6.0, you can control each of the following optimization parameters on a function-by-function basis using the %@AB@%optimize%@AE@% pragma: %@NL@% %@NL@% %@NL@% ■ Behavior of code with respect to aliasing (%@AB@%a%@AE@% and %@AB@%w%@AE@%)%@NL@% %@NL@% ■ Reduction of local common subexpressions (%@AB@%c%@AE@%)%@NL@% %@NL@% ■ Reduction of global common subexpressions (%@AB@%g%@AE@%)%@NL@% %@NL@% ■ Global register allocation (%@AB@%e%@AE@%)%@NL@% %@NL@% ■ Loop optimization (%@AB@%l%@AE@%)%@NL@% %@NL@% ■ Aggressiveness of optimizations (%@AB@%z%@AE@%)%@NL@% %@NL@% ■ Disabling of unsafe optimizations (%@AB@%n%@AE@%)%@NL@% %@NL@% ■ Achieving consistent floating-point results (%@AB@%p%@AE@%)%@NL@% %@NL@% ■ Optimizing for smaller code size or for faster execution speed (%@AB@%t%@AE@%)%@NL@% %@NL@% %@NL@% Any optimization or combination of options can be enabled or disabled using the %@AB@%optimize%@AE@% pragma. For example, if you have one function that uses aliases heavily, you need to inhibit optimizations that could cause problems with aliases. You do not, however, want to inhibit these optimizations for code that does not do aliasing. To do this, use the %@AB@%optimize %@AE@%pragma as follows: %@NL@% %@NL@% %@AS@% /* Function(s) that do not do aliasing. */ %@AS@% . %@AS@% . %@AS@% . %@AS@% #pragma optimize( "a", off ) %@AS@% /* Function(s) that do aliasing. */ %@AS@% . %@AS@% . %@AS@% . %@AS@% #pragma optimize( "a", on ) %@AS@% /* More function(s) that do not do aliasing. */%@AE@%%@NL@% %@NL@% The parameters to the %@AB@%optimize %@AE@%pragma can be combined in a string to enable or disable multiple options at once. For example, %@NL@% %@NL@% %@AS@% #pragma optimize( "lge", off )%@AE@%%@NL@% %@NL@% disables loop optimization, global common subexpression optimization, and global register allocation. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00010005 @%%@AB@%1.4 Default Optimization%@AE@%%@EH@%%@NL@% %@NL@% Many optimizations are not explicitly disabled by any command-line option except /Od (disable optimizations). These optimizations are small in scope and are almost always helpful. They include %@NL@% %@NL@% %@NL@% ■ Short range common subexpression elimination%@NL@% %@NL@% ■ Dead-store elimination%@NL@% %@NL@% ■ Constant propagation%@NL@% %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00010006 @%%@AB@%1.4.1 Common Subexpression Elimination%@AE@%%@EH@%%@NL@% %@NL@% In common subexpression elimination, the compiler finds code containing repeated subexpressions and produces modified code in which the subexpressions are evaluated only once. Subexpression elimination is usually done with temporary variables as shown in the following example: %@NL@% %@NL@% %@AS@% a = b + c * d; %@AS@% x = c * d / y;%@AE@%%@NL@% %@NL@% The preceding two lines contain the common subexpression %@AS@% c * d%@AE@%. This code can be modified to evaluate %@AS@% c * d %@AE@% only once; the result is placed in a temporary variable (usually a register): %@NL@% %@NL@% %@AS@% tmp = c * d; %@AS@% a = b + tmp; %@AS@% x = tmp / y;%@AE@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00010007 @%%@AB@%1.4.2 Dead-Store Elimination%@AE@%%@EH@%%@NL@% %@NL@% Dead-store elimination is an extension of common subexpression elimination. Variables that contain the same value in a short piece of code can be combined into a single temporary variable. %@NL@% %@NL@% In the following code fragment, the compiler detects that the expression %@AS@% %@AS@%func( x ) %@AE@% is equivalent to %@AS@% func( a + b )%@AE@%: %@NL@% %@NL@% %@AS@% x = a + b; %@AS@% x = func( x );%@AE@%%@NL@% %@NL@% Thus, the compiler can rewrite the code as follows: %@NL@% %@NL@% %@AS@% x = func( a + b);%@AE@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00010008 @%%@AB@%1.4.3 Constant Propagation%@AE@%%@EH@%%@NL@% %@NL@% When doing constant propagation, the compiler analyzes variable assignments and determines if they can be changed to constant assignments. In the following example, the variable %@AS@% i %@AE@% must have a value of %@AS@% 7 %@AE@% when it is assigned to %@AS@% j%@AE@%: %@NL@% %@NL@% %@AS@% i = 7; %@AS@% j = i;%@AE@%%@NL@% %@NL@% Instead of assigning %@AS@% i %@AE@% to %@AS@% j%@AE@%, the constant %@AS@% 7 %@AE@% can be assigned to %@AS@% j%@AE@%: %@NL@% %@NL@% %@AS@% i = 7; %@AS@% j = 7;%@AE@%%@NL@% %@NL@% While you could make any of these changes in the source file, doing so might reduce the readability of the program. In many cases, optimizations not only increase the efficiency of the program but allow you to write more readable code without any actual efficiency loss. %@NL@% %@NL@% %@AU@% Remove optimization before using a symbolic debugger.%@AE@% %@NL@% %@NL@% In some cases, you might want to disable even the default optimizations. Because optimizations may rearrange code in the object file, it can become difficult to recognize parts of your code during debugging. It is usually best to remove all optimization before using a symbolic debugger. You can remove all optimization with the /Od (disable optimizations) option. %@NL@% %@NL@% You can disable all optimizations for a function by including the statement %@AS@% %@AS@%#pragma optimize( "", off )%@AE@%. To restore optimization to its former state, use the statement %@AS@% #pragma optimize( "", on )%@AE@%. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00010009 @%%@AB@%1.5 Customizing Your Optimizations%@AE@%%@EH@%%@NL@% %@NL@% The default optimizations are sufficient for many applications, but you may want to tune your programs according to criteria not known to the compiler. The optimization options offer you a way of providing the compiler specific goals for optimizing your code. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00010010 @%%@AB@%1.5.1 Choosing Speed or Size (/Ot and /Os)%@AE@%%@EH@%%@NL@% %@NL@% In addition to the default optimizations, the Microsoft C compiler also automatically uses the /Ot option, which optimizes for speed. The /Ot option enables optimizations that increase speed but may also increase size. If you would rather optimize for program size, use the /Os option. The /Os option enables optimizations that decrease program size but may also decrease program speed. %@NL@% %@NL@% To optimize for speed or size on a per-function basis, use the %@AB@%optimize %@AB@%%@AE@%pragma with the %@AB@%t %@AE@%option. The on setting instructs the compiler to optimize for speed; the off setting instructs the compiler to optimize for compactness of code. For example, %@NL@% %@NL@% %@AS@% #pragma optimize( "t", off ) /* Optimize for smallest %@AS@% code. */ %@AS@% . %@AS@% . %@AS@% . %@AS@% #pragma optimize( "t", on ) /* Optimize for fastest %@AS@% code. */%@AE@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00010011 @%%@AB@%1.5.2 Generating Intrinsic Functions (/Oi)%@AE@%%@EH@%%@NL@% %@NL@% In place of some normal function calls, the C compiler can insert "intrinsic functions," which operate more quickly. Every time a function is called, a set of instructions must be executed to store parameters and to create space for local variables. When the function returns, more code must be executed to release space used by local variables and parameters and to return values to the calling routine. These instructions take time to execute. In the context of an average-sized function, the additional code is minimal, but if the function is only a line or two, the additional code can comprise almost half of the function's compiled code. %@NL@% %@NL@% One way to avoid this type of code expansion is to avoid such short functions, especially in often-used sections of code where speed is critical. But many library functions contain only a line or two of code. The compiler provides two forms of certain library functions. One form is a standard C function, which requires the overhead of a function call. The other form is a set of instructions that %@NL@% %@NL@% performs the same action as the function without issuing a function call. This second form is called an intrinsic function. Intrinsic functions are always faster than their function-call equivalents and can provide significant optimizations at the object-code level. %@NL@% %@NL@% For example, the function %@AB@%strcpy%@AE@% might be written as follows: %@NL@% %@NL@% %@AS@% int strcpy(char * dest, char * source) %@AS@% { %@AS@% while( *dest++ = *source++ ); %@AS@% }%@AE@%%@NL@% %@NL@% The compiler contains an intrinsic form of %@AB@%strcpy%@AE@%. If you instruct the compiler to generate intrinsic functions, any call to %@AB@%strcpy%@AE@% will be replaced with this intrin-sic form. %@NL@% %@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% NOTE %@AI@%While the example above is written in C for clarity, most of the library %@AI@%functions use assembly language to take full advantage of the 80x86 %@AI@%instruction set. Intrinsic functions are not simply library functions %@AI@%defined as macros. %@AE@%%@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@%%@NL@% %@NL@% Compiling with the /Oi option causes the compiler to use the intrinsic forms of the following functions: %@NL@% %@NL@% %@AB@%abs labs memset strcat%@AE@% %@AB@%_disable lrotl outp strcmp%@AE@% %@AB@%_enable lrotr outpw strcpy%@AE@% %@AB@%fabs memcmp rotl strlen%@AE@% %@AB@%inp memcpy rotr strset%@AE@% %@AB@%inpw While the following floating-point functions do not have true intrinsic forms, they do have versions that pass arguments directly to the floating-point chip instead of pushing them on the normal argument stack: %@NL@% %@NL@% %@AB@%acos fmod acosl fmodl%@AE@% %@AB@%asin log asinl logl%@AE@% %@AB@%atan log10 atanl log10l%@AE@% %@AB@%atan2 pow atan2l powl%@AE@% %@AB@%ceil sin ceill sinl%@AE@% %@AB@%cos sinh cosl sinhl%@AE@% %@AB@%cosh sqrt coshl sqrtl%@AE@% %@AB@%exp tan expl tanl%@AE@% %@AB@%floor tanh floorl tanhl%@AE@% ────────────────────────────────────────────────────────────────────────────%@NL@% %@AU@%WARNING%@AE@%%@NL@% %@NL@% The compiler performs optimizations assuming math intrinsics have no side effects. This assumption is true except if you have written your own %@AB@%matherr %@AB@%%@AE@%function and that function alters global variables. If you have written a %@AB@%matherr %@AE@%function to handle floating-point errors, and your function has side effects, use the%@AB@% function %@AE@%pragma to instruct the compiler not to generate intrinsic code for math functions.%@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% %@NL@% If you want the compiler to generate intrinsic functions for only a subset of the functions listed above, use the %@AB@%intrinsic %@AE@%pragma rather than the /Oi option. The %@AB@%intrinsic%@AE@% pragma has the following format: %@NL@% %@NL@% %@AS@% #pragma intrinsic( function1, ... )%@AE@%%@NL@% %@NL@% If you want to have intrinsic functions generated for most of the functions above and function calls for only a few, compile with the /Oi option and force function use with the %@AB@%function %@AE@%pragma. The %@AB@%function%@AE@% pragma has the following format: %@NL@% %@NL@% %@AS@% #pragma function( function1, ... )%@AE@%%@NL@% %@NL@% The following code illustrates the use of the %@AB@%intrinsic%@AE@% pragma: %@NL@% %@NL@% %@AS@% #pragma intrinsic(abs) %@AS@% %@AS@% void main( void ) %@AS@% { %@AS@% int i, j; %@AS@% %@AS@% i = big_routine_1(); %@AS@% j = abs( i ); %@AS@% big_routine_2( j ); %@AS@% }%@AE@%%@NL@% %@NL@% Generating intrinsic functions for this program causes the call to %@AB@%abs %@AE@%to be replaced with assembly-language code that takes the absolute value of a number. The program will execute more quickly because the function-calling overhead is no longer required when %@AB@%abs %@AE@%is called. %@NL@% %@NL@% In the previous example, the overall speed increase is small because there is only a single call to %@AB@%abs%@AE@%. In the following example, where the call to %@AB@%abs %@AE@%is in a loop and there are many calls, you can save a significant amount of execution time by generating intrinsic functions. %@NL@% %@NL@% %@AS@% #pragma intrinsic( abs ) %@AS@% void main( void ) %@AS@% { %@AS@% int i, j, x;%@AE@%%@NL@% %@NL@% %@AS@% for( j = 0; j < 1000; j++ ) %@AS@% { %@AS@% for( i = 0; i < 1000; i++) %@AS@% { %@AS@% x += abs( i - j ); %@AS@% } %@AS@% } %@AS@% printf( "The value of x is %d\n", x ); %@AS@% }%@AE@%%@NL@% %@NL@% The following is a list of restrictions on using the intrinsic forms of function calls: %@NL@% %@NL@% %@NL@% ■ Do not use the intrinsic forms of the floating-point math functions with the alternate math libraries (%@AI@%m%@AE@%LIBCA%@AI@%y%@AE@%.LIB).%@NL@% %@NL@% ■ Do not use the intrinsic forms of the floating-point math functions in OS/2 dynamic-link libraries (DLLs) because you must use the alternate math library with LLIBCDLL.LIB.%@NL@% %@NL@% ■ If you use the /Ox (maximum optimization) option, you are enabling the /Oi (generate intrinsic functions) option. Be careful that your use of /Ox does not conflict with the points listed previously.%@NL@% %@NL@% %@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% NOTE %@AI@%Intrinsic versions of %@AB@%_enable%@AE@%%@AI@%, %@AE@%%@AI@%%@AB@%_disable%@AE@%%@AE@%%@AI@%, %@AE@%%@AI@%%@AB@%inp%@AE@%%@AE@%%@AI@%, %@AE@%%@AI@%%@AB@%outp%@AE@%%@AE@%%@AI@%, %@AE@%%@AI@%%@AB@%inpw%@AE@%%@AE@%%@AI@%, and %@AE@%%@AI@%%@AB@%outpw %@AB@%%@AE@%%@AE@%%@AI@%do not work under OS/2. You must use the library versions. You can use the %@AI@%%@AE@%%@AI@%%@AB@%function %@AE@%%@AE@%%@AI@%pragm%@AE@%%@AI@%a to force these functions to become library calls.%@AE@%%@AE@%%@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00010012 @%%@AB@%1.5.3 Assuming No Aliasing (/Oa and /Ow)%@AE@%%@EH@%%@NL@% %@NL@% An "alias" is a name used to refer to a memory location already referred to by a different name. Because a memory access takes more time than it takes to access the CPU's registers, the compiler tries to store frequently used variables in registers. However, the aliasing reduces the extent to which a compiler can keep variables in registers. %@NL@% %@NL@% A pointer is a reference to a memory location. Because the value of a pointer is not determined until the program is run, the compiler has no way of knowing which memory location will be modified when the program executes; it could be a reference to a variable. Therefore, the compiler must assume that any time the value pointed to by any pointer changes, the value of any variable might also change. This limits the extent to which the compiler can move values from memory to registers. %@NL@% %@NL@% The /Oa option tells the compiler to ignore the possibility of multiple aliases for a memory location. In the list that follows, the term "reference" means read or write; that is, whether a variable is on the left-hand side of an assignment statement or the right-hand side, you are still referring to it. In addition, any function calls that use a variable as a parameter are references to that variable. When you tell the compiler to assume that you are not doing aliasing, it expects that the following rules are being followed for any variable not declared as %@AB@%volatile%@AE@%: %@NL@% %@NL@% %@NL@% ■ If a variable is used directly, no pointers are used to reference that variable.%@NL@% %@NL@% ■ If a pointer is used to refer to a variable, that variable is not referred to directly.%@NL@% %@NL@% ■ If a pointer is used to modify a memory location, no other pointers are used to access the same memory location.%@NL@% %@NL@% %@NL@% To clarify how these rules affect your code, consider the following example: %@NL@% %@NL@% %@AS@% char p; %@AS@% char *ptr_p; %@AS@% %@AS@% ptr_p = &p; /* Take the address of p. */%@AE@%%@NL@% %@NL@% You can now refer either to %@AS@% *ptr_p %@AE@% or to %@AS@% p%@AE@%, but not to both within the same function. If you must refer to the variable by both names, you are using aliases. %@NL@% %@NL@% Code referring to the same location with two pointers uses aliases. For example, %@NL@% %@NL@% %@AS@% char *p_buf; %@AS@% char *p_alias; %@AS@% %@AS@% if( (p_alias = p_buf = malloc( 5000 )) == NULL ) %@AS@% return; %@AS@% else %@AS@% { %@AS@% . %@AS@% . %@AS@% . %@AS@% }%@AE@%%@NL@% %@NL@% The code in the example above is common. It demonstrates dynamically allocating a block of memory from the heap, and preserving the original address in %@AS@% p_buf%@AE@%. The program then performs all pointer arithmetic on the alias %@AS@% p_alias%@AE@%. When the function finishes with the block of memory, %@AS@% p_buf %@AE@% is a valid argument for the %@AB@%free %@AE@%function because it still contains the original address. %@NL@% %@NL@% %@AU@% The /Oa and /Ow options tell the compiler that you have not used aliases in %@AU@%your code.%@AE@% %@NL@% %@NL@% The difference between the /Oa and the /Ow option is that when you use /Oa you specify that you will not be doing aliasing (which allows the compiler to perform significant optimizations that might not otherwise have been possible), and that function calls are safe. The /Ow option is similar to the /Oa option, except that after a function call, pointer variables must be reloaded from memory. %@NL@% %@NL@% Here is an example of a program that would be a poor candidate for the /Oa or /Ow optimization option: %@NL@% %@NL@% %@AS@% int g; %@AS@% %@AS@% void main( void ) %@AS@% { %@AS@% add_em( &g ); %@AS@% } %@AS@% %@AS@% int add_em( int *p ) %@AS@% { %@AS@% *p = 2; /* Assign a value to an alias for g. */ %@AS@% g = 3; /* Assign a value directly to g. */ %@AS@% return( *p + g ); %@AS@% }%@AE@%%@NL@% %@NL@% In the function %@AS@% add_em%@AE@%, both %@AS@% g %@AE@% and %@AS@% *p %@AE@% refer to the same memory location. This location is first assigned %@AS@% 2%@AE@%, then %@AS@% 3%@AE@%. The value pointed to by %@AS@% *p %@AE@% (the alias for %@AS@% g%@AE@%) is then added to %@AS@% g%@AE@%, and the result is returned to the main program. If you do not use the /Oa command-line option, the compiler assumes that the reference to %@AS@% *p %@AE@% could refer to the same memory location as does %@AS@% g %@AE@% and makes no attempt to use a register to store the value of either. If, however, you do specify the /Oa option, the compiler assumes that %@AS@% g %@AE@% and %@AS@% *p %@AE@% refer to different memory locations and stores each in a different register. At the return statement, %@AS@% g %@AE@% will have a different value than %@AS@% *p%@AE@%, even though both aliases should actually contain the same value. %@NL@% %@NL@% Note that the compiler keeps values in registers for only a limited time. If different aliases to a memory location occur in different functions, for example, they will not cause unexpected results. When in doubt, avoid aliasing. %@NL@% %@NL@% %@AU@% Bugs involving aliasing are difficult to spot.%@AE@% %@NL@% %@NL@% Aliasing bugs most frequently show up as corruption of data. If you find that global or local variables are being assigned seemingly random values, take the following steps to determine if you have a problem with optimization and aliasing: %@NL@% %@NL@% %@NL@% ■ Compile the program with /Od (disable optimizations).%@NL@% %@NL@% ■ If the program works when compiled with the /Od option, check your normal compile options for the /Oa option (assume no aliasing).%@NL@% %@NL@% ■ If you were using the /Oa option, fix your compile options so that /Oa is not specified.%@NL@% %@NL@% %@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% NOTE %@AI@%You can instruct the compiler to disable optimizations that are unsafe with %@AI@%code that does aliasing by using the %@AB@%optimize%@AE@%%@AI@% pragma with the %@AE@%%@AI@%%@AB@%a%@AE@%%@AE@%%@AI@% or %@AE@%%@AI@%%@AB@%w%@AE@%%@AE@%%@AI@% option.%@CR:C6A00010013 @%%@AE@%%@AE@%%@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00010014 @%%@AB@%1.5.4 Performing Loop Optimizations (/Ol)%@AE@%%@EH@%%@NL@% %@NL@% The /Ol option enables a set of optimizations involving loops. Because loops involve sections of code that are executed repeatedly, they are targets for optimization. These optimizations all involve moving code or rewriting code so that it executes faster. %@NL@% %@NL@% Loop optimization can be turned on with the /Ol option or with the %@AB@%loop_opt %@AE@% pragma. The following line enables loop optimization for all subsequent functions: %@NL@% %@NL@% %@AS@% #pragma loop_opt( on )%@AE@%%@NL@% %@NL@% The following line turns it off: %@NL@% %@NL@% %@AS@% #pragma loop_opt( off )%@AE@%%@NL@% %@NL@% %@AU@% The /Ol option removes invariant code.%@AE@% %@NL@% %@NL@% An optimal loop contains only expressions whose values change through each execution of the loop. Any subexpression whose value is constant should be evaluated before the body of the loop is executed. Unfortunately, these subexpressions are not always readily apparent. The optimizer can remove many of these expressions from the body of a loop at compile time. This example illustrates invariant code in a loop: %@NL@% %@NL@% %@AS@% i = -100; %@AS@% while( i < 0 ) %@AS@% { %@AS@% i += x + y; %@AS@% }%@AE@%%@NL@% %@NL@% In the preceding example, the expression %@AS@% x + y %@AE@% does not change in the loop body. Loop optimization removes this subexpression from the body of the loop so that it is only executed once, not every time the loop body is executed. The optimizer will change the code to the following fragment: %@NL@% %@NL@% %@AS@% i = -100; %@AS@% t = x + y; %@AS@% while( i < 0 ) %@AS@% { %@AS@% i += t; %@AS@% }%@AE@%%@NL@% %@NL@% Loop optimization is much more effective when the compiler can assume no aliasing. While you can use loop optimization without the /Oa or /Ow option, use /Oa to ensure that the most options possible are used. %@NL@% %@NL@% Here is a code fragment that could have an aliasing problem: %@NL@% %@NL@% %@AS@% i = -100; %@AS@% while( i < 0 ) %@AS@% { %@AS@% i += x + y; %@AS@% *p = i; %@AS@% }%@AE@%%@NL@% %@NL@% If you do not specify the /Oa option, the compiler must assume that either %@AS@% %@AS@%x %@AE@% or %@AS@% y %@AE@% could be modified by the assignment to %@AS@% *p%@AE@%. Therefore, the compiler cannot assume the subexpression %@AS@% x + y %@AE@% is constant for each loop iteration. If you specify that you are not doing any aliasing (with the /Oa option), the compiler assumes that modifying %@AS@% *p %@AE@% cannot affect either %@AS@% x %@AE@% or %@AS@% y%@AE@%, and that the subexpression is indeed constant and can be removed from the loop, as in the previous example. %@NL@% %@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% NOTE %@AI@%All loop optimizations specified by the /Ol option or the %@AB@%loop_opt%@AE@%%@AI@% pragma %@AI@%are safe optimizations. To enable aggressive loop optimizations, you must %@AI@%use the enable aggressive optimizations (/Oz) option. While the %@AI@%optimizations enabled by the combination of /Ol and /Oz are not safe for all %@AI@%cases, they will work properly for most programs.%@AE@%%@AE@%%@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00010015 @%%@AB@%1.5.5 Disabling Unsafe Loop Optimizations (/On)%@AE@%%@EH@%%@NL@% %@NL@% The disable unsafe loop optimizations (/On) option is an obsolescent option and is only retained for compatibility with existing makefiles. Loop optimizations are, by default, safe optimizations. The /On option is the default and has the opposite effect of the /Oz (enable aggressive optimizations) option. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00010016 @%%@AB@%1.5.6 Enabling Aggressive Optimizations (/Oz)%@AE@%%@EH@%%@NL@% %@NL@% The compiler can perform extremely aggressive optimizations. These optimizations produce high code quality both in terms of speed and size. Certain programs, however, cannot be optimized with the technologies enabled by the /Oz option. For these programs, you should not specify this option; you can still use all other optimization options. %@NL@% %@NL@% Because the optimization strategies enabled by the /Oz option are so aggressive, they are not part of the maximum optimization (/Ox) option. %@NL@% %@NL@% Examples of the effects of the /Oz option are %@NL@% %@NL@% %@NL@% ■ Loop optimization (/Ol). Loop optimization enables a technology that anticipates program flow and tries to remove invariant expressions from loops. When you specify the enable aggressive optimizations option (/Oz), the compiler removes invariant expressions even when it might cause an error. Errors with the enable aggressive optimizations option occur most often when an invariant expression that can cause an exception is protected by an %@AB@%if%@AE@% statement. The invariant expression is hoisted out of the loop body, causing it to be evaluated prior to the evaluation of the %@AB@%if%@AE@% statement that was designed to protect it. Here are two examples that illustrate this problem: %@NL@% %@AS@% for( i = 0; i 100; ++i ) %@AS@% if( float_val != 0.0F ) %@AS@% /* Protect against divide-by-zero. */ %@AS@% float_result = pi / float_val;%@AE@%%@NL@% %@NL@% %@AS@% while( condition ) %@AS@% if( ptr_val != NULL ) %@AS@% /* Protect pointer dereference. */ %@AS@% char_var = *ptr_val;%@AE@%%@NL@% %@NL@% %@NL@% ■ Global register allocation (/Oe). The enable aggressive optimizations option enables some register allocation strategies that can cause invalid segment selectors to be placed in registers. Although this problem is benign in DOS, it causes protection faults in OS/2.%@NL@% %@NL@% %@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% NOTE %@AI@%You can instruct the compiler to enable aggressive optimizations on a %@AI@%function-by-function basis by using the %@AB@%optimize%@AE@%%@AI@% pragma with the %@AE@%%@AI@%%@AB@%z %@AE@%%@AE@%%@AI@%option.%@AE@%%@AE@%%@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00010017 @%%@AB@%1.5.7 Removing Stack Probes (/Gs)%@AE@%%@EH@%%@NL@% %@NL@% Every time a function is called, the stack provides space for all parameters and local variables declared in that function. A short assembly function that checks for a stack overflow condition is then called. Stack overflows are usually caused either by infinite loops or by runaway recursive routines. Such errors can also be caused by extremely large parameters or local variables. %@NL@% %@NL@% Stack probes can be important during program development. Stack-overflow errors alert you to problems in your code. When the program has been tested, however, stack checking often becomes unnecessary. The compiler allows you to remove stack-checking code with either the /Gs option or the %@AB@%check_stack %@AB@%%@AE@%pragma. Eliminating stack probes produces programs that are smaller and that run more quickly. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00010018 @%%@AB@%1.5.8 Enabling Global Register Allocation (/Oe)%@AE@%%@EH@%%@NL@% %@NL@% The global register allocation option (/Oe) instructs the compiler to analyze your program and allocate CPU registers as efficiently as possible. Without the global register allocation option, the compiler uses the CPU's registers for several purposes: %@NL@% %@NL@% %@NL@% ■ Holding temporary copies of variables%@NL@% %@NL@% ■ Holding variables declared with the %@AB@%register%@AE@% keyword%@NL@% %@NL@% ■ Passing parameters to functions declared with the %@AB@%_fastcall%@AE@% keyword (or functions in programs compiled with the /Gr command-line option)%@NL@% %@NL@% %@NL@% When you enable global register allocation, the compiler ignores the %@AB@%register%@AE@% keyword and allocates register storage to variables (and possibly to common subexpressions). The compiler allocates register storage to variables or subexpressions according to frequency of use. Because of the limited number of physical registers, variables held in registers are sometimes placed back in memory to free the register for another use. Here is a C program example that demonstrates how the compiler might rewrite your code to accomplish this: %@NL@% %@NL@% %@AS@% /* Original program */ %@AS@% %@AS@% func() %@AS@% { %@AS@% int i, j; %@AS@% char *pc; %@AS@% %@AS@% for( i = 0; i < 1000; ++i ) %@AS@% { %@AS@% j = i / 3; %@AS@% *pc++ = (char)i; %@AS@% } %@AS@% %@AS@% for( j = 0, --pc; j < 1000; %@AS@% ++j, --pc ) %@AS@% *pc--; %@AS@% }%@AE@%%@NL@% %@NL@% %@AS@% /* Example of how the compiler might optimize the %@AS@% * code to move i and j in and out of registers */ %@AS@% %@AS@% func() %@AS@% { %@AS@% int i, j; %@AS@% char *pc; %@AS@% %@AS@% { %@AS@% register int i; /* i is in a register for this block. */ %@AS@% for( i = 0; i < 1000; ++i ) %@AS@% { %@AS@% j = i / 3; %@AS@% *pc++ = (char)i; %@AS@% } %@AS@% } %@AS@% %@AS@% { %@AS@% register int j; /* j is in a register for this block. */ %@AS@% for( j = 0, --pc; j < 1000; %@AS@% ++j, --pc ) %@AS@% *pc--; %@AS@% } %@AS@% }%@AE@%%@NL@% %@NL@% In the preceding example, there are blocks (enclosed in curly braces) whose only purpose is to delimit the span of code across which variables should remain in registers. %@NL@% %@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% NOTE %@AI@%You can enable or disable global register allocation on a %@AI@%function-by-function basis using the %@AB@%optimize%@AE@%%@AI@% pragma with the %@AE@%%@AI@%%@AB@%e%@AE@%%@AE@%%@AI@% option.%@CR:C6A00010019 @%%@AE@%%@AE@%%@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00010020 @%%@AB@%1.5.9 Enabling Common Subexpression Optimization (/Oc and /Og)%@AE@%%@EH@%%@NL@% %@NL@% When you use option /Og (enable global common subexpression optimizations), the compiler searches entire functions for common subexpressions. Option /Oc (default common subexpression optimization) examines only short sections of code for common subexpressions. You can disable default common subexpression optimization with the /Od option. For more information about common subexpression optimization, see Section 1.4, "Default Optimization." %@NL@% %@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% NOTE %@AI@%You can enable or disable block-scope common subexpression optimization on a %@AI@%function-by-function basis using the %@AB@%optimize%@AE@%%@AI@% pragma with the %@AE@%%@AI@%%@AB@%c %@AE@%%@AE@%%@AI@%option. You %@AI@%can enable or disable global common subexpression optimization on a %@AI@%function-by-function basis using the %@AE@%%@AI@%%@AB@%optimize%@AE@%%@AE@%%@AI@% pragma with the %@AE@%%@AI@%%@AB@%g %@AE@%%@AE@%%@AI@%option.%@CR:C6A00010021 @%%@AE@%%@AE@%%@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00010022 @%%@AB@%1.5.10 Achieving Consistent Floating-Point Results (/Op)%@AE@%%@EH@%%@NL@% %@NL@% Floating-point numbers stored in memory use either 32, 64, or 80 bits, depending on whether they are of type %@AB@%float%@AE@%, type %@AB@%double%@AE@%, or type %@AB@%long %@AB@%double%@AE@%. The 80%@AI@%x%@AE@%87 family of coprocessors uses 80-bit registers for all operations. If a value of type %@AB@%float%@AE@% or type %@AB@%double%@AE@% is kept in these registers through a number of operations, it will be more accurate than if that value is moved to and from memory between operations. %@NL@% %@NL@% Because of the difference in precision between memory and register representation of a floating-point number, a value stored in memory is not always equal to the same value in the 80%@AI@%x%@AE@%87 register. %@NL@% %@NL@% The difference in precision primarily affects strict equality or strict inequality tests (%@AB@%==%@AE@% and %@AB@%!=%@AE@%); however, relational tests of magnitude (%@AB@%>%@AE@%, %@AB@%>=%@AE@%, %@AB@%%@AE@%, and %@AB@%%@AE@%) can behave erroneously if the coprocessor is able to maintain significant digits that memory variables cannot. %@NL@% %@NL@% You can avoid the difference in precision by using the /Op option. This option forces floating-point values to be written to memory between floating-point operations. While storing these values to memory reduces the precision of floating-point expressions, it also ensures that these expressions will produce consistent results regardless of the rest of the code. %@NL@% %@NL@% You can change the handling of floating-point results on a function-by-function basis using the %@AB@%optimize %@AE@%pragma with the %@AB@%p %@AE@%option.%@CR:C6A00010023 @% %@NL@% %@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% NOTE %@AI@%Using the /Op option suppresses other optimizations because the %@AI@%floating-point registers are not available for storage of intermediate %@AI@%results. Because you suppress these optimizations, code compiled with the %@AI@%/Op option executes more slowly than code compiled without this option. %@AI@%Careful coding practices, especially in tests of strict equality and %@AI@%inequality, can alleviate the need for this option.%@AE@%%@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00010024 @%%@AB@%1.5.11 Using the 80186, 80188, or 80286 Processor (/G0, /G1, /G2)%@AE@%%@EH@%%@NL@% %@NL@% The compiler generates 8086 object code (/G0) unless you take special steps. Because the newer processors (the 80186, 80188, and 80286) are backwardcompatible with the 8086 instruction set, using this instruction set ensures compatibility with all 80%@AI@%x%@AE@%86-based computers. While you gain compatibility across the entire family of 80%@AI@%x%@AE@%86 processors, you lose the advantage of some of the more powerful instructions in the newer processors. %@NL@% %@NL@% If you know your program will only be running on an 80186, 80188, or 80286 processor, you can cause the compiler to generate instructions specific to these processors. These instructions increase the speed of your program, but you lose compatibility with machines that use older processors in the 80%@AI@%x%@AE@%86 family. Table 1.1 lists the options for processor-specific code generation: %@NL@% %@NL@% %@AB@%Table 1.1 %@AB@%Processor Compatibility%@AE@%%@AE@% %@TH: 6 432 02 23 53 @%Command-Line Option Compatible Processors%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%/G0 8088, 8086, 80188, 80186, 80286, 80388, 80486/G1 80188, 80186, 80286, 80386, 80486/G2 80286, 80386, 80486%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@TE: 6 432 02 23 53 @% ────────────────────────────────────────────────────────────────────────────%@NL@% NOTE %@AI@%When developing only for OS/2, always use the /G2 option, because OS/2 does %@AI@%not run on the 8086, 8088, 80186, or 80188. Do not use /G2 for Family %@AI@%Applications because they might be run on machines with 8088, 8086, 80188, %@AI@%or 80186 processors.%@AE@%%@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00010025 @%%@AB@%1.5.12 Optimizing for Maximum Efficiency (/Ox)%@AE@%%@EH@%%@NL@% %@NL@% The /Ox option combines a number of different optimizations: %@NL@% %@NL@% %@NL@% ■ Enable global register allocation (/Oe)%@NL@% %@NL@% ■ Enable global common subexpression optimization (/Og)%@NL@% %@NL@% ■ Enable block-scoped common subexpression optimization (/Oc)%@NL@% %@NL@% ■ Generate intrinsic functions (/Oi)%@NL@% %@NL@% ■ Perform loop optimizations (/Ol)%@NL@% %@NL@% ■ Optimize for speed (/Ot)%@NL@% %@NL@% ■ Remove stack probes (/Gs)%@NL@% %@NL@% %@NL@% %@AU@% Use /Ozax /Gr to get the fastest program.%@AE@% %@NL@% %@NL@% The /Ox option does not include several optimizations that can improve code efficiency: /Oa (assume no aliasing), /Oz (enable aggressive optimizations), and /Gr (use fastcall calling convention). Before enabling these optimizations, you should read the sections that describe the /Oa and /Oz options and the fastcall calling convention to determine if they are appropriate for your application. %@NL@% %@NL@% %@AU@% Use the optimize pragma to reduce code size.%@AE@% %@NL@% %@NL@% If you are more concerned with executable file size than execution time, use the /Ox and /Gs options, then issue the %@AB@%optimize %@AE@%pragma as follows: %@NL@% %@NL@% %@AS@% #pragma optimize( "t", off )%@AE@%%@NL@% %@NL@% This set of options produces the smallest possible code, while also performing some speed optimizations. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00010026 @%%@AB@%1.6 Linker (LINK) Options that Control Optimization%@AE@%%@EH@%%@NL@% %@NL@% Most code optimization is performed before the object file is produced. There are four optimizations that the linker can perform to speed program execution and reduce the disk space used by an executable file. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00010027 @%%@AB@%1.6.1 Enabling Far Call Optimization (/FARCALLTRANSLATION)%@AE@%%@EH@%%@NL@% %@NL@% You can call a function two ways. In a far call, the function is called using both the segment and the offset of the function. This allows a program to call a routine outside a 64K segment. In a near call, both the calling statement and the function must be located in the same segment. Only the offset is used to access the function; the segment address is implicit. You can only use near calls to routines located in the same segment.%@CR:C6A00010028 @%%@CR:C6A00010029 @% %@NL@% %@NL@% Because of the architecture of the processor, near function calls execute faster than far calls. The decision to declare functions as near or far is often made when selecting a memory model. As it is difficult to determine where the linker will place a given function in memory, it is impractical for the programmer to choose the way a function is called. %@NL@% %@NL@% %@AU@% Use /FARCALLTRANSLATION with medium, large, and huge model programs.%@AE@% %@NL@% %@NL@% The /FARCALLTRANSLATION option enables far call optimization. When you use this option, any function calls within the same segment as the function being called are converted to near calls. This optimization has no effect if you have selected the tiny, small, or compact model, because all calls are already near calls. %@NL@% %@NL@% The abbreviation for the /FARCALLTRANSLATION option is /F. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%How /FARCALLTRANSLATION Affects Your Code%@AE@%%@EH@%%@NL@% %@NL@% The linker can perform a form of post-optimization (an optimization that occurs after most of the actual code generation is complete) that translates far calls into near calls when possible. This optimization allows a given function to be called with both near and far calls in the same program. To perform this translation, the linker takes a section of object code such as %@NL@% %@NL@% %@AS@% CALL FAR _func%@AE@%%@NL@% %@NL@% where %@AS@% func %@AE@% is defined in the current segment, and replaces it with the following code: %@NL@% %@NL@% %@AS@% PUSH CS %@AS@% CALL NEAR _func %@AS@% NOP%@AE@%%@NL@% %@NL@% This substitution works because the linker has inserted %@AS@% PUSH CS %@AE@% to place a far return address on the stack. %@NL@% %@NL@% %@AU@% Use /FARCALLTRANSLATION with /PACKCODE.%@AE@% %@NL@% %@NL@% The /FARCALLTRANSLATION option is most effective when used in conjunction with the /PACKCODE option discussed in Section 1.6.2. Using the /PACKCODE option causes far calls that were intersegment to become intrasegment calls. The /FARCALLTRANSLATION feature can then take advantage of the new grouping to translate all intrasegment far calls into near calls.%@CR:C6A00010030 @% %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Benefits of /FARCALLTRANSLATION%@AE@%%@EH@%%@NL@% %@NL@% The /FARCALLTRANSLATION option is of significant benefit to protected-mode programs. Table 1.2 illustrates why. %@NL@% %@NL@% %@AB@%Table 1.2 %@AB@%Processor Clock Cycles for Calling Sequence%@AE@%%@AE@% %@TH: 34 1635 03 20 15 11 15 15 @% %@AB@%Cycles (Real%@AE@% %@AB@%Cycles %@AE@% %@AB@%Mode)%@AE@% %@AB@%(Protected %@AE@% %@AB@%Mode)%@AE@%%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%%@AE@% %@AB@%%@AE@% %@AB@%%@AE@% %@AB@%%@AE@%%@AB@%Instructions%@AE@% 286 %@AB@%386%@AE@% %@AB@%286%@AE@% %@AB@%386%@AE@%%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%Far Function Call %@AS@%CALL FAR PTR _func%@AE@% 13 17 26 34Total 13 17 26 34%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%Near Function Call %@AS@%PUSH CS%@AE@% 3 2 3 2%@AS@%CALL NEAR PTR %@AE@% 7 7 7 7%@AS@%_func%@AE@% %@AS@%NOP%@AE@% 3 3 3 3Total 13 12 13 12%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%Savings 0 5 13 22%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@TE: 34 1635 03 20 15 11 15 15 @% %@NL@% %@3@%%@CR:C6A00010031 @%%@AB@%1.6.2 Packing Code (/PACKCODE)%@AE@%%@EH@%%@NL@% %@NL@% The /PACKCODE linker option groups neighboring code segments together. When used with the /F option, the /PACKCODE option greatly increases the number of near calls that can be made to a function. This option can be followed with a limit (expressed in bytes) at which to stop packing and to begin a new group. Here is the syntax for the /PACKCODE option: ;/PACKCODE option %@NL@% %@NL@% %@AS@% /PACKCODE:number%@AE@%%@NL@% %@NL@% where %@AI@%number%@AE@% is an optional hexadecimal, octal, or decimal number that specifies the limit for packing. The radix (octal, decimal, or hexadecimal) is specified just as you would specify it to a C program.%@CR:C6A00010032 @% %@NL@% %@NL@% %@AB@%Radix%@AE@% %@AB@%Rules for Specification%@AE@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% Octal Specify the octal number with a leading 0. You can only use the digits 0 through 7 in an octal number. For example, 07777. Decimal Specify the decimal number without a leading 0. For example, 65530. Hexadecimal Specify the hexadecimal number with a leading 0x. For example, 0x3FFF. If you omit the packing limit, the linker supplies a default value of 65, 530. %@NL@% %@NL@% The abbreviation for the /PACKCODE option is /PACKC. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00010033 @%%@AB@%1.6.3 Packing Data (/PACKDATA)%@AE@%%@EH@%%@NL@% %@NL@% The /PACKDATA option is analogous to the /PACKCODE option, except that it groups together neighboring data segments instead of code segments. This option is most useful when you have a large-model program that exceeds the OS/2 limitation of 255 segments. By using /PACKDATA, you can group segments, thereby reducing the total number OS/2 has to manage. Here is the syntax for the /PACKDATA option:%@CR:C6A00010034 @% %@NL@% %@NL@% %@AS@% /PACKDATA:number%@AE@%%@NL@% %@NL@% where %@AI@%number%@AE@% is an optional hexadecimal, octal, or decimal number that specifies the limit for packing. The radix (hexadecimal, octal, or decimal) is specified just as you would specify it to a C program. For more information on specifying hexadecimal, octal, or decimal numbers, see Section 1.6.2 above. %@NL@% %@NL@% If the packing limit is omitted, the linker supplies a default value of 65,535 (0xFFFF).%@CR:C6A00010035 @% %@NL@% %@NL@% The abbreviation for the /PACKDATA option is /PACKD. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00010036 @%%@AB@%1.6.4 Packing the Executable File (/EXEPACK)%@AE@%%@EH@%%@NL@% %@NL@% The executable file created by the compiler often contains sequences of repeated bytes. You can remove these repeated sequences with the /EXEPACK option. This decreases the size of the resulting executable file as well as program load time.%@CR:C6A00010037 @% %@NL@% %@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% %@AU@%WARNING%@AE@%%@NL@% %@NL@% Because the /EXEPACK option removes debug information from the executable file, you should not use it with the /CODEVIEW option.%@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00010038 @%%@AB@%1.7 Optimizing in Different Environments%@AE@%%@EH@%%@NL@% %@NL@% The environment in which you plan to use a program can have a bearing on the types of optimizations that you should use. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00010039 @%%@AB@%1.7.1 Optimizing in DOS%@AE@%%@EH@%%@NL@% %@NL@% You need not take special precautions for programs written under DOS unless you are writing a terminate-and-stay-resident (TSR) program. If an interrupt-driven routine could modify a memory location in a program, you should declare that variable %@AB@%volatile%@AE@%. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00010040 @%%@AB@%1.7.2 Optimizing in OS/2%@AE@%%@EH@%%@NL@% %@NL@% Many of the rules for interrupt routines apply to OS/2. If one thread can modify variables in another thread, declare these variables as %@AB@%volatile%@AE@%. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00010041 @%%@AB@%1.7.3 Optimizing in Microsoft Windows(tm)%@AE@%%@EH@%%@NL@% %@NL@% Microsoft Windows(tm) can move segments dynamically. As a result of dynamic heap compaction, pointers maintained in registers can be invalidated. The /Ow option instructs the compiler that you will not be using aliases, but that Windows might cause certain optimizations to be unsafe across function calls. %@NL@% %@NL@% If you are not using any aliases you must still use the /Ow option with Windows programs. See Section 1.5.3, "Assuming No Aliasing (/Oa and /Ow)," for more information. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00010042 @%%@AB@%1.8 Choosing Function-Calling Conventions%@AE@%%@EH@%%@NL@% %@NL@% In Microsoft C, version 6.0, functions can call other functions using three different conventions. Note that, while no calling convention has been defined as "standard," most C compilers use conventions similar to those described here. The C calling convention requires the most object code to set up, but it is the only calling convention that supports functions with variable-length argument lists. The FORTRAN/Pascal calling convention is more compact, but does not allow for variable-length argument lists. The %@AB@%_fastcall%@AE@%, or register calling convention is the fastest of the three calling conventions, but it does not support variable-length argument lists or mixed-language program interfaces. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00010043 @%%@AB@%1.8.1 The C Calling Convention (/Gd)%@AE@%%@EH@%%@NL@% %@NL@% Because C allows functions to have a variable number of parameters, parameters must be pushed onto the stack from right to left. (If parameters were pushed from left to right, it would be difficult for the compiler to determine which parameter was first.) If you do not specify command-line options that modify the function-calling convention, the C calling convention is used; otherwise, the %@AB@%_cdecl%@AE@% keyword must be used before any function using the C calling convention.%@CR:C6A00010044 @%%@CR:C6A00010045 @%%@CR:C6A00010046 @% %@NL@% %@NL@% If, for example, you use the /Gr (register calling convention) option when you compile, and the function %@AS@% add_two %@AE@% must have the C calling convention, declare %@AS@% add_two %@AE@% as follows: %@NL@% %@NL@% %@AS@% int _cdecl add_two( int x, int y );%@AE@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00010047 @%%@AB@%1.8.2 The FORTRAN/Pascal Calling Convention (/Gc)%@AE@%%@EH@%%@NL@% %@NL@% Use the FORTRAN/Pascal calling convention for any functions declared with either the %@AB@%_fortran%@AE@% or %@AB@%_pascal%@AE@% keywords. (The two keywords currently produce identical results.) Parameters to these functions are always pushed on the stack from left to right. While any function can be declared with the FORTRAN/ Pascal convention, it is used primarily for prototypes to Pascal or FORTRAN routines called from within C programs. This calling convention can also produce smaller, faster programs. %@NL@% %@NL@% The /Gc option (generate Pascal-style function calls) can be used to make all functions in a file observe the FORTRAN/Pascal calling convention. %@NL@% %@NL@% Note that C run-time library routines must still be called using C calling conventions. Because these routines are declared using the %@AB@%_cdecl%@AE@% keyword header files, you must include the appropriate header files in any program using run-time library routines. %@NL@% %@NL@% Functions with variable-length parameter lists (such as %@AB@%printf%@AE@%) cannot use the FORTRAN/Pascal calling convention. %@NL@% %@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% NOTE %@AI@%The /ML, /MD, and /MT options cause all floating-point functions to be %@AI@%declared as FORTRAN/Pascal. See Chapter 16, "Dynamic Linking with OS/2," for %@AI@%more information.%@AE@%%@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00010048 @%%@AB@%1.8.3 The Register Calling Convention (/Gr)%@AE@%%@EH@%%@NL@% %@NL@% You can decrease execution time if parameters to functions are passed in registers rather than on the stack. Compiling with the /Gr command-line option enables the register calling convention for an entire file. The %@AB@%_fastcall%@AE@% keyword enables the register calling convention on a function-by-function basis. %@NL@% %@NL@% Because the 80%@AI@%x%@AE@%86 processor has a limited number of registers, only the first three parameters are allocated to registers; the rest are passed using the FORTRAN/Pascal calling convention. The register calling convention can increase the speed of a program.%@CR:C6A00010049 @%%@CR:C6A00010050 @%%@CR:C6A00010051 @% %@NL@% %@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% NOTE %@AI@%The compiler allocates different registers for variables declared as %@AB@%register %@AE@%%@AI@%and for passing arguments using the register calling convention. %@AI@%This calling convention will not conflict with any register variables that %@AI@%you may have declared.%@AE@%%@AE@%%@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@%%@NL@% %@NL@% Exercise caution when using the register calling convention for any function written in in-line assembly language. Your use of registers in assembly-language could conflict with the compiler's use of registers for storing parameters. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00010052 @%%@AB@%1.8.4 The _fastcall Calling Convention%@AE@%%@EH@%%@NL@% %@NL@% This section describes the details of the %@AB@%_fastcall%@AE@% calling convention. The information is for the use of assembly-language programmers who are interested in using either the in-line assembler or the Microsoft Macro Assembler (MASM) to write functions declared as %@AB@%_fastcall%@AE@%. Functions declared as %@AB@%_fastcall%@AE@% accept arguments in registers rather than on the stack; functions declared as %@AB@%_cdecl%@AE@% or %@AB@%_pascal%@AE@% accept parameters only on the stack. %@NL@% %@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% %@AU@%WARNING%@AE@%%@NL@% %@NL@% The register usage documented here applies only to Microsoft C, version 6.0. It may change in future releases of the compiler.%@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% %@NL@% %@NL@% %@4@%%@AB@%Argument-Passing Convention%@AE@%%@EH@%%@NL@% %@NL@% The %@AB@%_fastcall%@AE@% calling convention is a "strongly typed" register calling convention. This typing allows the compiler to generate better code by passing arguments in registers that correspond to the data type you are passing. Because the compiler chooses registers depending on the type of the argument and not in a strict linear order, the calling program and called function must agree on the types of the arguments in order to communicate data correctly. %@NL@% %@NL@% For each type of argument there is a list of register candidates. The arguments are allocated to registers or, if no suitable register remains unused, are pushed onto the stack left-to-right. Each argument is put in the first register candidate that does not already contain an argument. Table 1.3 shows the basic types and the register candidate list for each. %@NL@% %@NL@% %@AB@%Table %@AB@%1.3 Register Candidates%@AE@%%@AE@% %@TH: 11 634 02 33 43 @%%@AB@%Type%@AE@% Register Candidates%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%character AL, DL, BLunsigned character AL, DL, BLinteger AX, DX, BXunsigned integer AX, DX, BXlong integer DX:AXunsigned long integer DX:AXnear pointer BX, AX, DXfar or huge pointer passed on the stack%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@TE: 11 634 02 33 43 @% All far and huge pointers are pushed on the stack, as are all structures, unions, and floating-point types.%@CR:C6A00010053 @% %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Return Value Convention%@AE@%%@EH@%%@NL@% %@NL@% The %@AB@%_fastcall%@AE@% return value convention is based on the size of the return value, except with floating-point types. All floating point types are returned on the top of the NDP stack. For more information about the NDP stack and returning floating-point values, see Chapter 4, "Controlling Floating-Point Math Operations." The following list shows how values 4 bytes or smaller, including unions and structures, are returned from a %@AB@%_fastcall %@AB@%%@AE@%function. %@NL@% %@NL@% %@AB@%Size%@AE@% %@AB@%Return Convention%@AE@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% 1 Byte AL Register 2 Bytes AX Register 4 Bytes DX, AX Registers (for pointers, the segment is returned in DX, the offset in AX; for long integers, the most-significant byte is returned in DX, leastsignificant byte in AX) Note that the protocol for returning values 4 bytes or smaller is the same as for functions declared as %@AB@%_cdecl%@AE@%. To return structures and unions larger than 4 bytes, the calling program passes a hidden parameter as the last item pushed. This parameter is a near pointer, implicitly SS-relative, to a buffer in which the value is to be returned. A far pointer to SS:%@AI@%hidden-param%@AE@% must be returned in DX:AX. This is the same convention for returning structures as %@AB@%_pascal.%@AE@%%@CR:C6A00010054 @% %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Stack Adjustment Convention%@AE@%%@EH@%%@NL@% %@NL@% Unlike functions declared as %@AB@%_cdecl%@AE@%, functions declared as %@AB@%_fastcall%@AE@% must pop the arguments off the stack. The calling program does not adjust the stack after function return. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Register Preservation Requirement%@AE@%%@EH@%%@NL@% %@NL@% All functions must preserve the DS, BP, SI, and DI registers. Your %@AB@%_fastcall%@AE@% function can modify the values in AX, BX, CX, DX, and ES. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Function-Naming Convention%@AE@%%@EH@%%@NL@% %@NL@% The public name put into the object file for a function declared as %@AB@%_fastcall%@AE@% is the name given by the user with a leading "at sign" (@). No case translation is performed on the function name. The function declaration %@NL@% %@NL@% %@AS@% int _fastcall FCFunc( void );%@AE@%%@NL@% %@NL@% causes the compiler to place the public symbol %@AS@% @FCFunc %@AE@% in your object file at every location %@AS@% FCFunc %@AE@% is referenced in your program. %@NL@% %@NL@% If you do not declare the function as %@AB@%_fastcall%@AE@% in your C program, the compiler assumes the default calling convention. The default is usually the C calling convention but can be changed by the /Gc (Pascal Calling Convention), /Gr (Register Calling Convention), or /Gd (C Calling Convention) options. If the linker gives you an unresolved external reference, you may have failed to declare an external %@AB@%_fastcall%@AE@% function properly. For more information about calling conventions, see Chapter 12, "Programming with Mixed Languages."%@CR:C6A00010055 @% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@CR:C6A00020001 @%%@1@%%@AB@%Chapter 2 Managing Memory%@AE@%%@EH@%%@NL@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@NL@% When you develop advanced applications in Microsoft C, you must pay attention to memory management─that is, how data and code are stored and accessed in memory. A well-thought-out memory strategy will make your programs run faster and occupy less memory. %@NL@% %@NL@% You can follow one or more of these memory management strategies: %@NL@% %@NL@% %@NL@% ■ Choose a standard memory model.%@NL@% %@NL@% ■ Create a mixed-model program with the %@AB@%_near%@AE@%, %@AB@%_far%@AE@%, %@AB@%_huge%@AE@%, and %@AB@%_based%@AE@% keywords.%@NL@% %@NL@% ■ Create your own customized memory model.%@NL@% %@NL@% ■ Allocate memory as you need it with the %@AB@%malloc%@AE@% family of functions.%@NL@% %@NL@% %@NL@% This chapter explains pointers, memory models (including the new tiny model), variations such as custom memory models and mixed models, and based pointers. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00020002 @%%@AB@%2.1 Pointer Sizes%@AE@%%@EH@%%@NL@% %@NL@% One of the strengths of the C language is that it allows you to use pointers to directly access memory locations. %@NL@% %@NL@% Every Microsoft C program has at least two parts: the code (function definitions) and the data (variables and constants). As a program runs, it refers to elements of the code or the data by their addresses. These addresses can be stored in pointer variables. %@NL@% %@NL@% Pointer variables can fit into 16 bits or 32 bits, depending on the distance of the object to which they refer. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00020003 @%%@AB@%2.1.1 Pointers and 64K Segments%@AE@%%@EH@%%@NL@% %@NL@% IBM personal computers and compatibles use the Intel(R) 8086, 80186, 80286, or 80386 processors (collectively called the 80%@AI@%x%@AE@%86 family). These processors have a "segmented" architecture, which means they all have a mode that treats memory as a series of segments, each of which occupies up to 64K of memory. An offset from the base of the segment allows you to access information within a given segment. Moving to a new segment requires additional machine code. %@NL@% %@NL@% %@AU@% A 16-bit pointer can address up to 65,536 locations.%@AE@% %@NL@% %@NL@% The 64K limit is necessary because the 80%@AI@%x%@AE@%86 registers are 16 bits (2 bytes) wide. A single register can address only 65,536 (64K) unique memory locations. %@NL@% %@NL@% A pointer variable that fully specifies a memory address needs 16 bits for the segment location and another 16 bits for the offset within the segment, a total of 32 bits. However, if you have several variables in the same general area, your program can set the segment register once and treat the pointers as smaller 16-bit quantities. %@NL@% %@NL@% The 80%@AI@%x%@AE@%86 register CS holds the base for the code segment; the register DS holds the base for the data segment. Two other segment registers are available: the stack segment register (SS) and the extra segment register (ES). (The 80386 has additional segment registers: FS and GS.) %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00020004 @%%@AB@%2.1.2 Near Pointers%@AE@%%@EH@%%@NL@% %@NL@% If you don't explicitly specify a memory model, Microsoft C defaults to the small model, which allots up to 64K for the code and another 64K for the data (see Figure 2.1). %@NL@% %@NL@% %@AU@%(This figure may be found in the printed book.)%@AE@%%@NL@% %@NL@% When a small-model program runs, the CS and DS segment registers never change. All code pointers and all data pointers contain 16 bits because they remain within the 64K range. %@NL@% %@NL@% These 16-bit pointers to objects within a single 64K segment are called "near pointers." Accessing a near object is called "near addressing." %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00020005 @%%@AB@%2.1.3 Far Pointers%@AE@%%@EH@%%@NL@% %@NL@% If your program needs more than 64K for code or data, at least some of the pointers must specify the memory segment, which means these pointers occupy 32 bits instead of 16 bits. %@NL@% %@NL@% These larger 32-bit pointers that can point anywhere in memory are called "far pointers." Accessing a far object is called "far addressing." %@NL@% %@NL@% %@AU@% Far pointers can address any location, but they are bigger and slower.%@AE@% %@NL@% %@NL@% Far addressing has the advantage that your program can address any available memory location─up to 640K in DOS or several megabytes in OS/2. The disadvantages of the larger far pointers is that they take up more memory (four bytes instead of two) and that any use of the pointers (assigning, modifying, or otherwise accessing values) takes more time. %@NL@% %@NL@% Allowing either code or data to expand beyond 64K makes your programs larger and slower. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00020006 @%%@AB@%2.1.4 Huge Pointers%@AE@%%@EH@%%@NL@% %@NL@% A third type of pointer in Microsoft C is the "huge" pointer, which applies only to data pointers. Code pointers cannot be declared as huge. %@NL@% %@NL@% A huge address is similar to a far address in that both contain 32 bits, made up of a segment value and an offset value. They differ only in the way pointer arithmetic is performed. %@NL@% %@NL@% For far pointers, Microsoft C assumes that code and data objects lie completely within the segment in which they start, so pointer arithmetic operates only on the offset portion of the address. Limiting the size of any single item to 64K makes pointer arithmetic faster. %@NL@% %@NL@% Huge pointers overcome this size limitation; pointer arithmetic is performed on all 32 bits of the data item's address, thus allowing data items referenced by huge pointers to span more than one segment. In this code fragment, %@NL@% %@NL@% %@AS@% int _huge *hp; %@AS@% int _far *fp; %@AS@% . %@AS@% . %@AS@% . %@AS@% hp++; %@AS@% fp++;%@AE@%%@NL@% %@NL@% both %@AS@% hp %@AE@% and %@AS@% fp %@AE@% are incremented. The huge pointer is incremented as a 32-bit value that represents the combined segment and offset. Only the offset part of the far pointer (a 16-bit value) is incremented. %@NL@% %@NL@% Extending the size of pointer arithmetic from 16 to 32 bits causes such arithmetic to execute more slowly. You gain the use of larger arrays by paying a price in execution speed. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00020007 @%%@AB@%2.1.5 Based Addressing%@AE@%%@EH@%%@NL@% %@NL@% When you declare near, far, and huge variables, the Microsoft C compiler and linker automatically manage details such as allocating memory and keeping track of segments. %@NL@% %@NL@% A "based pointer" is a fourth kind of pointer that operates as a 16-bit offset from a base that you specify. In this respect, based addressing differs from near, far, or huge addressing; you're responsible for naming the base, instead of letting the compiler decide. %@NL@% %@NL@% Based pointers are new to version 6.0 of Microsoft C. They are explained in more detail in Section 2.5, "Using Based Variables." %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00020008 @%%@AB@%2.2 Selecting a Standard Memory Model%@AE@%%@EH@%%@NL@% %@NL@% If you want to choose one size for all pointers, there's no need to declare each variable as near or far. Instead, you select a standard memory model and your choice applies to all variables in the program. %@NL@% %@NL@% One advantage of using standard memory models is simplicity. You specify the way the compiler allocates storage for code and data only once. %@NL@% %@NL@% %@AU@% A standard memory model assumes all pointers are the same size.%@AE@% %@NL@% %@NL@% Another advantage is that the standard memory models do not require the use of Microsoft-specific keywords such as %@AB@%_near%@AE@% and %@AB@%_far%@AE@%, so they are best for writing code that is portable to other (non-DOS) systems. %@NL@% %@NL@% The disadvantage of standard memory models is that, because they make global assumptions about the environment, they do not always produce the most efficient code. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00020009 @%%@AB@%2.2.1 The Six Standard Memory Models%@AE@%%@EH@%%@NL@% %@NL@% The six Microsoft C memory models are shown in Table 2.1. %@NL@% %@NL@% %@AB@%Table 2.1 %@AB@%Memory Models %@AE@%%@AE@% %@TH: 10 600 03 10 22 11 33 @% Maximum Total Memory Model Code Data Data Arrays%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%Tiny <64K <64K <64KSmall 64K 64K 64KMedium No limit 64K 64KCompact 64K No limit 64KLarge No limit No limit 64KHuge No limit No limit No limit%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@TE: 10 600 03 10 22 11 33 @% The SETUP program creates the libraries that support the six standard memory models. %@NL@% %@NL@% When you choose one of the standard memory models, the compiler inserts the name of the corresponding C run-time library in the object file so the linker chooses it automatically. Each memory model has its own library, except for the huge memory model (which uses the large-model library) and the tiny model (which uses the small-model library). %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00020010 @%%@AB@%2.2.2 Limitations on Code Size and Data Size%@AE@%%@EH@%%@NL@% %@NL@% When writing a program in Microsoft C, keep in mind two limitations that apply to all six memory models:%@CR:C6A00020011 @% %@NL@% %@NL@% %@NL@% ■ No single source module can generate 64K or more of code. You must break large programs into modules and link their individual .OBJ files to create the .EXE file.%@NL@% %@NL@% ■ No single data item can exceed 64K unless it appears in a huge-model program or it has been declared with the %@AB@%_huge%@AE@% keyword.%@NL@% %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00020012 @%%@AB@%2.2.3 The Tiny Memory Model%@AE@%%@EH@%%@NL@% %@NL@% The tiny memory model is new to Microsoft C. It resembles the small model with three exceptions:%@CR:C6A00020013 @%%@CR:C6A00020014 @% %@NL@% %@NL@% %@NL@% ■ The tiny model cannot exceed 64K per program (including both code and data). A small-model program, on the other hand, can occupy up to 128K: 64K for code and 64K for data.%@NL@% %@NL@% ■ The tiny model produces .COM, rather than .EXE, files. To produce .COM files, compile with the /AT option. Then link with the / TINY option and link in CRTCOM.OBJ.%@NL@% %@NL@% ■ The tiny model applies to DOS only; it is not available in OS/2.%@NL@% %@NL@% %@NL@% Although the tiny model imposes the most severe limits on code and data size, it produces the smallest programs. The tiny memory model only offers a load-time speed advantage over the small model; they both produce the fastest programs. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00020015 @%%@AB@%2.2.4 The Huge Memory Model%@AE@%%@EH@%%@NL@% %@NL@% The huge memory model is nearly identical to the large model. The only difference is that the huge model permits individual arrays to exceed 64K in size. For example, an %@AB@%int%@AE@% uses two bytes, so an array of 40,000 integers, occupying 80,000 bytes of memory, would be permitted in the huge model. All other models limit each array, structure, or other data object to no more than 64K. %@NL@% %@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% NOTE %@AI@%Automatic arrays cannot be declared huge. Only static arrays and arrays %@AI@%occupying memory allocated by the %@AB@%halloc%@AE@%%@AI@% function can be huge.%@AE@%%@AE@%%@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@%%@NL@% %@NL@% %@AU@% The huge model lifts the limits on arrays.%@AE@% %@NL@% %@NL@% Although the huge model lifts the limits on arrays, some size restrictions do apply. To maintain efficient addressing, no individual array element is allowed to cross a segment boundary. This has the following implications: %@NL@% %@NL@% %@NL@% ■ No single element of an array can be larger than 64K. An array can be larger than 64K, but its individual elements cannot.%@NL@% %@NL@% ■ For any array larger than 128K, all elements must have a size in bytes equal to a power of 2: 2 bytes, 4 bytes, 8 bytes, 16 bytes, and so on. If the array is 128K or smaller, its elements can be any size, up to and including 64K.%@NL@% %@NL@% %@NL@% Pointer arithmetic changes within the huge model, as well. In particular, the %@AB@%sizeof%@AE@% operator may return an incorrect value. The ANSI draft standard for C defines the value returned by %@AB@%sizeof%@AE@% to be of type %@AB@%size_t%@AE@% (which, in Microsoft C, is %@NL@% %@NL@% an %@AB@%unsigned int%@AE@%). The size in bytes of a huge array is an %@AB@%unsigned long%@AE@% value, however. To find the correct value, you must use a type cast: %@NL@% %@NL@% %@AS@% (unsigned long)sizeof(monster_array)%@AE@%%@NL@% %@NL@% Similarly, the C language defines the result of subtracting two pointers as %@AB@%ptrdiff_t%@AE@% (a %@AB@%signed int%@AE@% in Microsoft C). Subtracting two huge pointers will yield a %@AB@%long%@AE@% value. Microsoft C gives the correct result with the following type cast: %@NL@% %@NL@% %@AS@% (long)(ptr1_huge - ptr2_huge)%@AE@%%@NL@% %@NL@% When you select huge model, all %@AB@%extern%@AE@% arrays are treated as %@AB@%_huge%@AE@%. Operations on data declared as %@AB@%_huge%@AE@% can be less efficient than the same operations on data declared as %@AB@%_far%@AE@%. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00020016 @%%@AB@%2.2.5 Null Pointers%@AE@%%@EH@%%@NL@% %@NL@% Within the medium and compact models, code pointers and data pointers differ in size: one is 16 bits wide and the other is 32 bits wide. When using these memory models, you should be careful in your use of the manifest constant %@AB@%NULL%@AE@%. %@NL@% %@NL@% %@AB@%%@AE@%NULL represents a null data pointer. The C include files define it as %@NL@% %@NL@% %@AS@% #define NULL ((void *) 0)%@AE@%%@NL@% %@NL@% %@AU@% There can be problems in models with different sizes of code and data %@AU@%pointers.%@AE@% %@NL@% %@NL@% In memory models where data pointers have the same size as code pointers, the actual size of a null pointer doesn't matter. In memory models where code and data pointers are different sizes, problems can occur. Consider this example: %@NL@% %@NL@% %@AS@% void main() %@AS@% { %@AS@% func1( NULL ); %@AS@% func2( NULL ); %@AS@% } %@AS@% %@AS@% func1( char *dp ) %@AS@% { %@AS@% . %@AS@% . %@AS@% . %@AS@% } %@AS@% %@AS@% func2( char (*fp)( void ) ) %@AS@% { %@AS@% . %@AS@% . %@AS@% . %@AS@% }%@AE@%%@NL@% %@NL@% In the absence of function prototypes for %@AS@% func1 %@AE@% and %@AS@% func2%@AE@%, the compiler always assumes that %@AB@%NULL%@AE@% refers to data and not code. %@NL@% %@NL@% The example above works correctly in tiny, small, large, and huge models because, in those models, a data pointer is the same size as a code pointer. Under medium or compact model, however, %@AS@% main %@AE@% passes %@AB@% NULL%@AE@% to %@AS@% func2 %@AE@% as a null data pointer rather than as a null code pointer (a pointer to a function), which means the pointer is the wrong size. %@NL@% %@NL@% To ensure that your code works properly in all models, declare each function with a prototype. For example, before %@AS@% main%@AE@%, include these two lines: %@NL@% %@NL@% %@AS@% int func1( char *dp ); %@AS@% int func2( char (*fp)( void ));%@AE@%%@NL@% %@NL@% If you add these prototypes to the example, the code works properly in all memory models. Prototypes force the compiler to coerce code pointers to the correct size. Prototypes also enable strong type-checking of parameters. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00020017 @%%@AB@%2.2.6 Specifying a Memory Model%@AE@%%@EH@%%@NL@% %@NL@% If you do not specify a memory model, Microsoft C defaults to the small model, which is adequate for many small to mid-sized programs. %@NL@% %@NL@% You can select a memory model from the Programmer's WorkBench or from the command line. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Selecting from within PWB%@AE@%%@EH@%%@NL@% %@NL@% If you're compiling from the Programmer's WorkBench, open the Options menu and choose C Global Build Options. The available memory models appear in the upper left corner. Choose one of the six standard models or choose Customized and type in the options for a customized model. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Selecting from the Command Line%@AE@%%@EH@%%@NL@% %@NL@% You can choose a memory model by including an option on the command line. For example, to compile CLICK.C as a compact-model program, type this: %@NL@% %@NL@% %@AS@% CL /AC CLICK.C%@AE@%%@NL@% %@NL@% The /AC option selects the compact memory model. The six options and four libraries are listed below: %@NL@% %@NL@% %@AB@%Option%@AE@% %@AB@%Memory Model: Library%@AE@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% /AT Tiny Model: SLIBC%@AI@%xx%@AE@%.LIB (plus CRTCOM.OBJ) /AS Small Model: SLIBC%@AI@%xx%@AE@%.LIB /AM Medium Model: MLIBC%@AI@%xx%@AE@%.LIB /AC Compact Model: CLIBC%@AI@%xx%@AE@%.LIB /AL Large Model: LLIBC%@AI@%xx%@AE@%.LIB /AH Huge Model: LLIBC%@AI@%xx%@AE@%.LIB %@NL@% %@2@%%@CR:C6A00020018 @%%@AB@%2.3 Mixing Memory Models%@AE@%%@EH@%%@NL@% %@NL@% In standard memory models, explained above, all data pointers are the same size and all code pointers are the same size. %@NL@% %@NL@% A mixed memory model selectively combines different types of pointers within the same program. A mixed model extends the limits of a given memory model while retaining its benefits.%@CR:C6A00020019 @%%@CR:C6A00020020 @%%@CR:C6A00020021 @%%@CR:C6A00020022 @% %@NL@% %@NL@% %@AU@% A mixed memory model lets you mix near and far pointers.%@AE@% %@NL@% %@NL@% For example, imagine a programming situation where you add an array to a small-model program, pushing the data segment past the 64K limit. %@NL@% %@NL@% You could solve the problem by moving up from the small to the compact memory model. Doing so would bump all data pointers from two to four bytes. The .EXE file would grow accordingly. Execution time would slow. %@NL@% %@NL@% A second and perhaps better solution is to stay within the standard small memory model, which uses near pointers, but to declare the new array as far. You mix near pointers and far pointers, creating a mixed model. %@NL@% %@NL@% Microsoft C lets you override the standard addressing convention for a given memory model by specifying that certain items are %@AB@%_near%@AE@%, %@AB@%_far%@AE@%, %@AB@%_huge%@AE@%, or %@AB@%_based%@AE@%. These keywords are not a standard part of the C language; they are Microsoft extensions, meaningful only on systems that use 80%@AI@%x%@AE@%86 microprocessors. Using these keywords may affect the portability of your code. %@NL@% %@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% NOTE %@AI@%Previous versions of the Microsoft C Compiler accepted the keywords %@AB@%near%@AE@%%@AI@%, %@AI@%%@AE@%%@AI@%%@AB@%far%@AE@%%@AE@%%@AI@%, and %@AE@%%@AI@%%@AB@%huge %@AE@%%@AE@%%@AI@%without an initial underscore. Since the ANSI draft standard %@AI@%for C permits compiler implementors to reserve identifiers that begin with %@AI@%underscores, an underscore was added to these keywords to mark them as %@AI@%Microsoft-specific. To maintain compatibility with existing source code, the %@AI@%compiler still recognizes the obsolescent versions of these keywords.%@AE@%%@AE@%%@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@%%@NL@% %@NL@% You can compile a program in the small model, for example, but declare a certain array to be %@AB@%_far%@AE@%. At run time, the address of that array occupies four bytes. The program may slow slightly when accessing items in that particular far array, but throughout the rest of the program, all addressing would be near. Note that all pointers to elements of an array declared as %@AB@%_far%@AE@% must also be declared as %@AB@%_far%@AE@%. %@NL@% %@NL@% Table 2.2 lists the effects of these keywords on data pointers, code pointers, and pointer arithmetic. %@NL@% %@NL@% %@AB@%Table 2.2 %@AB@%Addressing Declared with Microsoft Keywords%@AE@%%@AE@% %@TH: 35 1876 02 09 22 22 23 @%Keyword Data Code Arithmetic%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%_near%@AE@% Data reside in Functions reside in 16 bits default data current code segment; 16-bit segment; 16-bit addresses addresses %@AB@%_far%@AE@% Data can be anywhere Functions can be 16 bits in memory, not called from anywhere necessarily in the in memory; 32-bit default data addresses segment; 32-bit addresses %@AB@%_huge%@AE@% Data can be anywhere Not applicable; 32 bits in memory, not code cannot be (data only) necessarily in the declared %@AB@%_huge%@AE@% default data segment. Individual data items (arrays) can exceed 64K in size; 32-bit addresses %@AB@%_based%@AE@% Data can be anywhere Not applicable; 16 bits in memory, not code cannot be (data only) necessarily in the declared %@AB@%_based%@AE@% default data segment; 16-bit addresses plus a known base provide the range of 32-bit addresses %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@TE: 35 1876 02 09 22 22 23 @% %@NL@% %@3@%%@CR:C6A00020023 @%%@AB@%2.3.1 Pointer Problems%@AE@%%@EH@%%@NL@% %@NL@% When you declare items to be %@AB@%_near%@AE@%, %@AB@%_far%@AE@%, %@AB@%_huge%@AE@%, or %@AB@%_based%@AE@%, you can link with a standard run-time library. Be aware, however, that in some cases, the modified pointers will be incompatible with standard library functions. Watch for these problems that affect pointers:%@CR:C6A00020024 @%%@CR:C6A00020025 @%%@CR:C6A00020026 @%%@CR:C6A00020027 @% %@NL@% %@NL@% %@NL@% ■ A library function that expects a 16-bit pointer as an argument will not function properly with modified variables that occupy 32 bits. In other words, you can cast a near pointer to a far pointer, because it adds the segment value and maintains the integrity of the address. If you cast a far pointer to near, however, the compiler generates a warning message because the offset may not lie within the default data segment, in which case the original far address is irretrievably lost.%@NL@% %@NL@% ■ A library function that returns a pointer will return a pointer of the default size for the memory model. This is only a problem if you are assigning the return value to a pointer of a smaller size. For example, there may be difficulties if you compile with a model that selects far data pointers, but you have explicitly declared the variable to receive the return value %@AB@%_near%@AE@%.%@NL@% %@NL@% %@STUB@% This warning does not apply to all functions. See Section B.2.8 in Appendix B for a list of model-independent string and memory functions such as %@AB@%_fstrcat%@AE@%, the far version of %@AB@%strcat%@AE@%.%@NL@% %@NL@% ■ Based pointers pose a special problem. Based pointers are passed to other functions as is (without normalization). Certain functions expect to receive based pointers, but most do not. Therefore, in most cases, you must either explicitly cast a based pointer to a far pointer or make sure that all functions that receive based pointers are prototyped.%@NL@% %@NL@% %@NL@% Some run-time library functions support near, far, huge, and based variables. For example, %@AB@%halloc%@AE@% allocates memory for a huge data array. %@NL@% %@NL@% You can always pass the value (but not the address) of a far item to a small-model library routine. For example, %@NL@% %@NL@% %@AS@% /* Compile in small model */ %@AS@% #include <stdio.h> %@AS@% long _far time_val; %@AS@% %@AS@% void main() %@AS@% { %@AS@% time( &time_val ); /* Illegal far address */ %@AS@% printf( "%ld\n", time_val ); /* Legal value */ %@AS@% }%@AE@%%@NL@% %@NL@% When you use a mixed memory model, you should include function prototypes with argument-type lists to ensure that all pointer arguments are passed to functions correctly. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00020028 @%%@AB@%2.3.2 Declaring Near, Far, Huge, and Based Variables%@AE@%%@EH@%%@NL@% %@NL@% The %@AB@%_near%@AE@%, %@AB@%_far%@AE@%, %@AB@%_huge%@AE@%, and %@AB@%_based%@AE@% keywords modify either objects or pointers to objects. When using them to declare variables, keep these rules in mind:%@CR:C6A00020029 @%%@CR:C6A00020030 @%%@CR:C6A00020031 @%%@CR:C6A00020032 @% %@NL@% %@NL@% %@NL@% ■ The keyword always modifies the object or pointer immediately to its right. In complex declarations, think of the %@AB@%_far%@AE@% keyword and the item to its right as being a single unit. For example, in the case of the declaration%@NL@% %@NL@% %@STUB@% %@AS@%char _far * _near *p;%@AE@%%@NL@% %@NL@% %@STUB@% %@AS@%p %@AE@% is a near pointer to a far pointer to %@AB@%char%@AE@%, which resides in the default data segment for the memory model being used.%@NL@% %@NL@% %@STUB@% By contrast, the declaration%@NL@% %@NL@% %@STUB@% %@AS@%char _far * _near p;%@AE@%%@NL@% %@NL@% %@STUB@% is a far pointer to %@AB@%char%@AE@% that will always be stored in DGROUP, regardless of the memory model being used.%@NL@% %@NL@% ■ If the item immediately to the right of the keyword is an identifier, the keyword determines whether the item will be allocated in the default data segment (%@AB@% _near%@AE@%) or a separate data segment (%@AB@% _far%@AE@%, %@AB@%_huge%@AE@%, or %@AB@%_based%@AE@%). For example,%@NL@% %@NL@% %@STUB@% %@AS@%char _far a;%@AE@%%@NL@% %@NL@% %@STUB@% allocates %@AS@% a %@AE@% as an item of type %@AB@%char%@AE@% with a %@AB@%_far%@AE@% address.%@NL@% %@NL@% ■ If the item immediately to the right of the keyword is a pointer, the keyword determines whether the pointer will hold a near address (16 bits), a based address (16 bits), a far address (32 bits), or a huge address (also 32 bits). For example,%@NL@% %@NL@% %@STUB@% %@AS@%char _huge *p;%@AE@%%@NL@% %@NL@% %@STUB@% allocates %@AS@% p %@AE@% as a huge pointer (32 bits) to an item of type %@AB@%char%@AE@%. Any arithmetic performed on the huge pointer %@AS@% p %@AE@% will affect all 32 bits. That is, the instruction %@AS@% p++ %@AE@% increments the pointer as a 32-bit entity.%@NL@% %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00020033 @%%@AB@%2.3.3 Declaring Near and Far Functions%@AE@%%@EH@%%@NL@% %@NL@% You cannot declare functions as %@AB@%_huge%@AE@% or %@AB@%_based%@AE@%. The rules for using the %@AB@%_near%@AE@% and %@AB@%_far%@AE@% keywords for functions are similar to those for using them with data: %@NL@% %@NL@% %@NL@% ■ The keyword always modifies the function or pointer immediately to its right.%@NL@% %@NL@% ■ If the item immediately to the right of the keyword is a function, the keyword determines whether the function will be allocated as near or far. For example,%@NL@% %@NL@% %@STUB@% %@AS@%char _far fun();%@AE@%%@NL@% %@NL@% %@STUB@% defines %@AS@% fun %@AE@% as a function with a 32-bit address that returns a %@AB@%char%@AE@%. The function may be located in near memory or far memory, but it is called with the full 32-bit address. The %@AB@%_far%@AE@% keyword applies to the function, not to the return type.%@NL@% %@NL@% ■ If the item immediately to the right of the keyword is a pointer to a function, the keyword determines whether the function will be called using a near (16-bit) or far (32-bit) address. For example,%@NL@% %@NL@% %@STUB@% %@AS@%char (_far *pfun)( );%@AE@%%@NL@% %@NL@% %@STUB@% defines %@AS@% pfun %@AE@% as a far pointer (32 bits) to a function returning type %@AB@%char%@AE@%.%@NL@% %@NL@% ■ Function declarations must match function definitions.%@NL@% %@NL@% ■ The %@AB@%_huge%@AE@% and %@AB@%_based%@AE@% keywords do not apply to functions. That is, a function cannot be huge (larger than 64K) or based. A function can return a huge data pointer to the calling function. A function can return a based pointer unless it is a pointer based on %@AB@%_self%@AE@% (see Section 2.5.2, "Declaring Based Variables").%@NL@% %@NL@% %@NL@% The example below declares %@AS@% fun1 %@AE@% as a far function returning type %@AB@%char%@AE@%: %@NL@% %@NL@% %@AS@% char _far fun1(void); /* small model */ %@AS@% char _far fun(void) %@AS@% { %@AS@% . %@AS@% . %@AS@% . %@AS@% }%@AE@%%@NL@% %@NL@% Here, the %@AS@% fun2 %@AE@% function is a near function that returns a far pointer to type %@AB@%char%@AE@%: %@NL@% %@NL@% %@AS@% char _far * _near fun2( ); /* large model */ %@AS@% char _far * _near fun( ) %@AS@% { %@AS@% . %@AS@% . %@AS@% . %@AS@% }%@AE@%%@NL@% %@NL@% The example below declares %@AS@% pfun %@AE@% as a far pointer to a function that has an %@AB@%int%@AE@% return type, assigns the address of %@AB@%printf%@AE@% to %@AS@% pfun%@AE@%, and prints "Hello world." twice. %@NL@% %@NL@% %@AS@% /* Compile in medium, large, or huge model */ %@AS@% %@AS@% #include <stdio.h> %@AS@% int (_far *pfun)( char *, ... ); %@AS@% %@AS@% void main() %@AS@% { %@AS@% pfun = printf; %@AS@% pfun( "Hello world.\n" ); %@AS@% (*pfun)( "Hello world.\n" ); %@AS@% }%@AE@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00020034 @%%@AB@%2.3.4 Pointer Conversions%@AE@%%@EH@%%@NL@% %@NL@% Passing near or far pointers as arguments to functions can cause automatic conversions in the size of the pointer argument. Passing a pointer to an unprototyped function forces the pointer size to the larger of the following two sizes: %@NL@% %@NL@% %@NL@% ■ The default pointer size for that type, as defined by the memory model selected during compilation.%@NL@% %@NL@% %@STUB@% For example, in medium-model programs, data pointer arguments are near by default, and code pointer arguments are far by default.%@NL@% %@NL@% ■ The size of the type of the argument.%@NL@% %@NL@% %@NL@% Note that if you supply a based pointer as an argument to a function and do not specifically cast it to a far pointer type, a 16-bit offset from the base segment is passed. %@NL@% %@NL@% %@AU@% Function prototypes prevent problems that may occur in mixed memory models.%@AE@% %@NL@% %@NL@% If you provide a function prototype with complete argument types, the compiler performs type-checking and enforces the conversion of actual arguments to the declared type of the corresponding formal argument. However, if no declaration is present or the argument-type list is empty, the compiler will convert nonbased pointer arguments automatically to the default type or the type of the argument, whichever is larger. To avoid mismatched arguments, always use a prototype with the argument types. %@NL@% %@NL@% For example, the following program produces unexpected results in compact-model, large-model, or huge-model programs. %@NL@% %@NL@% %@AS@% void main( ) %@AS@% { %@AS@% int _near *x; %@AS@% char _far *y; %@AS@% int z = 1; %@AS@% %@AS@% test_fun( x, y, z ); /* x is coerced to far %@AS@% pointer in compact, %@AS@% large, or huge model */ %@AS@% } %@AS@% %@AS@% int test_fun( int _near *ptr1, char _far *ptr2, int a) %@AS@% { %@AS@% printf("Value of a = %d\n", a); %@AS@% }%@AE@%%@NL@% %@NL@% If the preceding example is compiled as a tiny, small, or medium program, the size of %@AS@% x %@AE@% is 16 bits, the size of %@AS@% y %@AE@% is 32 bits, and the value printed for %@AS@% a %@AE@% is 1. %@NL@% %@NL@% However, if the example is compiled in compact, large, or huge model, both %@AS@% %@AS@%x %@AE@% and %@AS@% y %@AE@% are automatically converted to far pointers when they are passed to %@AS@% test_fun%@AE@%. Since %@AS@% ptr1%@AE@%, the first parameter of %@AS@% test_fun%@AE@%, is defined as a near pointer argument, it takes only 16 bits of the 32 bits passed to it. The next parameter, %@AS@% ptr2%@AE@%, takes the remaining 16 bits passed to %@AS@% ptr1%@AE@%, plus 16 bits of the 32 bits passed to it. Finally, the third parameter, %@AS@% a%@AE@%, takes the leftover 16 bits from %@AS@% ptr2%@AE@%, instead of the value of %@AS@% z %@AE@% in the %@AB@%main%@AE@% function. %@NL@% %@NL@% This shifting process does not generate an error message, because both the function call and the function definition are legal. In this case the program does not work as intended, however, since the value assigned to %@AS@% a %@AE@% is not the value intended. %@NL@% %@NL@% To pass %@AS@% ptr1 %@AE@% as a near pointer, you should include a function prototype that specifically declares this argument for %@AS@% test_fun %@AE@% as a near pointer, as shown below: %@NL@% %@NL@% %@AS@% /* First, prototype test_fun so the compiler %@AS@% * knows in advance about the near pointer argument: %@AS@% */ %@AS@% int test_fun (int _near*, char _far *, int); %@AS@% %@AS@% main ( ) %@AS@% { %@AS@% int _near *x; %@AS@% char _far *y; %@AS@% int z = 1; %@AS@% %@AS@% test_fun ( x, y, z ); /* now, x is not coerced %@AS@% * to a far pointer; it is %@AS@% * passed as a near pointer, %@AS@% * no matter which memory %@AS@% * model is used %@AS@% */ %@AS@% } %@AS@% %@AS@% int test_fun ( int _near *ptr1, char _far *ptr2, int a) %@AS@% { %@AS@% printf ( "Value of a = %d\n", a ); %@AS@% }%@AE@%%@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00020035 @%%@AB@%2.4 Customizing Memory Models%@AE@%%@EH@%%@NL@% %@NL@% A third way to manage memory is to combine different features from standard memory models to create your own customized memory model. You should have a thorough understanding of C memory models and the architecture of 80%@AI@%x%@AE@%86 processors before creating your own nonstandard memory models. %@NL@% %@NL@% %@AU@% In a customized model, you select the size of code pointers and data %@AU@%pointers.%@AE@% %@NL@% %@NL@% The /A%@AI@%string%@AE@% option lets you change the attributes of the standard memory models to create your own memory models. The three letters in %@AI@%string%@AE@% correspond to the code pointer size, the data pointer size, and the stack and data segment setup, respectively. Because the letter allowed in each field is unique to that field, you can give the letters in any order after /A. All three letters must be present. %@NL@% %@NL@% The standard memory-model options (/AT, /AS, /AM, /AC, /AL, and /AH) can be specified in the /A%@AI@%string%@AE@% form. As an example of how to construct memory models, the standard memory-model options are listed below with their /A%@AI@%string%@AE@% equivalents: %@NL@% %@NL@% %@AB@%Standard%@AE@% %@AB@%Custom Equivalent%@AE@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% /AT /Asnd /AS /Asnd /AM /Alnd /AC /Asfd /AL /Alfd /AH /Alhd For example, you might want to create a huge-compact model. This model would allow huge data items but only one code segment. The option for specifying this model would be /Ashd. %@NL@% %@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% NOTE %@AI@%Tiny model is identical to small model except that it causes the linker to %@AI@%search for CRTCOM.LIB. The executable file generated when you specify tiny %@AI@%model is a .COM file rather than a .EXE.%@AE@%%@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00020036 @%%@AB@%2.4.1 Setting a Size for Code Pointers%@AE@%%@EH@%%@NL@% %@NL@% Within a custom memory model, you choose whether code pointers are short or long: %@NL@% %@NL@% %@AB@%Option%@AE@% %@AB@%Size%@AE@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% /As%@AI@%xx%@AE@% Short (near) code pointers /Al%@AI@%xx%@AE@% Long (far) code pointers The /As (short) option tells the compiler to generate near 16-bit pointers and addresses for all functions. This is the default for tiny-, small-, and compact-model programs. %@NL@% %@NL@% The /Al (long) option means that far 32-bit pointers and addresses are used to address all functions. Far pointers are the default for medium-, large-, and huge-model programs. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00020037 @%%@AB@%2.4.2 Setting a Size for Data Pointers%@AE@%%@EH@%%@NL@% %@NL@% Data pointers can be near, far, or huge: %@NL@% %@NL@% %@AB@%Option%@AE@% %@AB@%Size%@AE@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% /A%@AI@%x%@AE@%n%@AI@%x%@AE@% Near data pointers /A%@AI@%x%@AE@%f%@AI@%x%@AE@% Far data pointers /A%@AI@%x%@AE@%h%@AI@%x%@AE@% Huge data pointers The /An (near) option tells the compiler to use 16-bit pointers and addresses for all data. This is the default for tiny-, small-, and medium-model programs. %@NL@% %@NL@% The /Af (far) option specifies that all data pointers and addresses are 32 bits. This is the default for compact- and large-model programs. %@NL@% %@NL@% The /Ah (huge) option specifies that all data pointers and addresses are far (32-bit) and that arrays are permitted to extend beyond a 64K segment. This is the default for huge-model programs. %@NL@% %@NL@% With far data pointers, no single data item can be larger than a segment (64K) because address arithmetic is performed only on 16 bits (the offset portion) of the address. When huge data pointers are used, individual data items can be larger than a segment (64K) because address arithmetic is performed on both the segment and the offset. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00020038 @%%@AB@%2.4.3 Setting Up Segments%@AE@%%@EH@%%@NL@% %@NL@% Within a customized model, you can choose to make the stack segment (SS) equal the data segment (DS), in which case they overlap:%@CR:C6A00020039 @% %@NL@% %@NL@% %@AB@%Option%@AE@% %@AB@%Effect%@AE@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% /A%@AI@%xx%@AE@%d SS == DS /A«%@AI@%xx%@AE@%»u SS != DS; DS reloaded on function entry /A«%@AI@%xx%@AE@%»w SS != DS; DS not reloaded on function entry %@NL@% %@4@%%@AB@%Segment Setup Option /Ad%@AE@%%@EH@%%@NL@% %@NL@% The option /Ad tells the compiler that the segment addresses stored in the SS and DS registers are equal. The stack segment and the default data segment are combined into a single segment. This is the default for all standard-model programs. In small- and medium-model programs, the stack plus all data must occupy less than 64K; thus, any data item is accessed with only a 16-bit offset from the segment address in the SS and DS registers. %@NL@% %@NL@% In compact-, large-, and huge-model programs, initialized global and static data are placed in the default data segment up to a certain threshold. The address of this segment is stored in the DS and SS registers. All pointers to data, including pointers to local data (the stack), are full 32-bit addresses. This is important to remember when passing pointers as arguments in multiple-segment programs. Although you may have more than 64K of total data in these models, no more than 64K of data can occupy the default segment. The /Gt and /ND options control allocation of items in the default data segment if a program exceeds this limit. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Segment Setup Option /Au%@AE@%%@EH@%%@NL@% %@NL@% The option /Au tells the compiler that the stack segment does not necessarily coincide with the data segment. In addition, it adds the %@AB@%_loadds%@AE@% attribute to all functions within a module, forcing the compiler to generate code to load the DS register with the correct value prior to entering the function body. Combine the /ND option with /Au to name data segments other than the default. When /Au is combined with /ND, the address in the DS register is saved upon entry to each function, and the new DS value for the module in which the function was defined is loaded into the register. The previous DS value is restored on exit from the function. Therefore, only one data segment is accessible at any given time. The /ND option lets you combine these segments into a single segment. %@NL@% %@NL@% If a standard memory-model option precedes it on the command line, the /Au option can be specified without any letters indicating data pointer or code pointer sizes. The program uses a standard memory model, but different segments are set up for the stack and data segments. %@NL@% %@NL@% The /Au option is useful for OS/2 or Microsoft Windows dynamic-link libraries (DLLs), since it forces DS to be loaded on entry to each function. It is also useful for writing extensions to the Programmer's WorkBench. This is a costly operation, however, so consider using the /Aw option. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Segment Setup Option /Aw%@AE@%%@EH@%%@NL@% %@NL@% The option /Aw, like /Au, causes the compiler to assume that the stack segment is separate from the data segment. The compiler does not automatically load the DS register at each function entry point. The /Aw option is useful in creating applications that interface with an operating system or with a program running at the operating-system level. The operating system or the program running under the operating system actually receives the data intended for the application program and places that data in a segment; then the operating system or program must load the DS register with the segment address for the application program. %@NL@% %@NL@% As with the /Au option, the /Aw option can be specified without data pointer and code pointer letters if a standard memory-model option precedes it on the command line. In such a case, the program uses the specified memory model just as with /Au, but the DS register is not reloaded at each function entry point. %@NL@% %@NL@% Even though /Au and /Aw indicate that the stack may be in a separate segment, the stack's size is still fixed at the default size unless this is overridden with the /F compiler option or the /STACK linker option. %@NL@% %@NL@% The /Aw option is useful for writing OS/2 and Microsoft Windows dynamic-link libraries (DLLs), but care must be taken when it is used. Declare all entry points to the dynamic-link library as %@AB@%_loadds%@AE@% to force DS to be loaded on entry to the function (exactly like the /Au option). The other functions will then be more efficient, though, because they will not have to perform redundant loads of the DS register. For example, %@NL@% %@NL@% %@AS@% _export _loadds _far pascal LibFunc( void ) %@AS@% { %@AS@% . %@AS@% . %@AS@% . %@AS@% HelperFunc(); } %@AS@% %@AS@% HelperFunc( void ) %@AS@% { %@AS@% . %@AS@% . %@AS@% . %@AS@% }%@AE@%%@NL@% %@NL@% The library entry point, %@AS@% LibFunc%@AE@%, is declared as %@AB@%_loadds%@AE@% to force the DS register to be loaded on entry. The function %@AS@% HelperFunc%@AE@%, which is private to the dynamic-link library, is declared as a normal C function. Since it cannot be called from outside of the module, %@AS@% HelperFunc %@AE@% does not need to reload DS. %@NL@% %@NL@% If you choose one of the options that specifies that the stack segment is not equal to the data segment (SS != DS), you cannot pass the address of frame variables as arguments to functions that take near pointers. That is, in tiny, small, and medium models, you cannot pass the address of a local variable (which is allocated on the stack) as an argument, because the receiving function will assume the pointer is relative to the data segment. However, the receiving function could solve this problem by declaring the pointer to be the following: %@NL@% %@NL@% %@AS@% based(_segname("_STACK"))%@AE@%%@NL@% %@NL@% Another solution would be to cast the pointer to a far pointer in both locations as follows: %@NL@% %@NL@% %@AS@% /* Call func with an explicit cast to far */ %@AS@% func( (char far *)frame_var ); %@AS@% . %@AS@% . %@AS@% . %@AS@% void func( char far *formal_var )%@AE@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00020040 @%%@AB@%2.4.4 Library Support for Customized Memory Models%@AE@%%@EH@%%@NL@% %@NL@% Most C programs make function calls to the routines in the C run-time library. When you write mixed-model programs, you are responsible for determining which library (if any) is suitable for your program and for ensuring that the appropriate library is linked. Table 2.3 shows the libraries from which to extract the start-up routine for each customized memory model. %@NL@% %@NL@% %@AB@%Table 2.3 %@AB@%Start-Up Routines for Customized Memory Models%@AE@%%@AE@% %@TH: 7 736 02 49 27 @%%@AB@%Memory-Model%@AE@% %@AB@%Option%@AE@% %@AB@%From Library%@AE@%%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%/Asn%@AI@%x%@AE@%; /AS plus /A%@AI@%x %@AE@% SLIBC%@AI@%f%@AE@%.LIB/Asf%@AI@%x%@AE@%; /Ash%@AI@%x%@AE@%; /AC plus /A%@AI@%x%@AE@% CLIBC%@AI@%f%@AE@%.LIB/Aln%@AI@%x%@AE@%; /AM plus /A%@AI@%x%@AE@% MLIBC%@AI@%f%@AE@%.LIB/Alf%@AI@%x%@AE@%; /Alh%@AI@%x%@AE@%; /AL plus /A%@AI@%x%@AE@%; /AH plus /A%@AI@%x %@AE@% LLIBC%@AI@%f%@AE@%.LIB%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@TE: 7 736 02 49 27 @% The /A%@AI@%x%@AE@% option represents either /Au or /Aw. In the library names, %@AI@% f%@AE@% is either E (emulator library), 7 (8087/80287 library), or A (alternate math library). %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00020041 @%%@AB@%2.4.5 Setting the Data Threshold%@AE@%%@EH@%%@NL@% %@NL@% %@AB@%Option%@AE@% %@AB@%Effect%@AE@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% /Gt«%@AI@%number%@AE@%» Sets the threshold The /Gt option causes all data items whose size is greater than to %@AI@%number%@AE@% bytes to be allocated to a new data segment. When %@AI@%number%@AE@% is specified, it must follow the /Gt option immediately, with no intervening spaces. When %@AI@%number%@AE@% is omitted, the default threshold value is 256. When the /Gt option is omitted, the default threshold value is 32,767. %@NL@% %@NL@% The /Gt option applies only to compact-, large-, and huge-model programs, since small- and medium-model programs have only one data segment. The option is particularly useful with programs that have more than 64K of initialized static and global data in small data items, because otherwise you run out of memory in the default data segment and can't link the program. The /Gt option has no effect on uninitialized global data. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00020042 @%%@AB@%2.4.6 Naming Modules and Segments%@AE@%%@EH@%%@NL@% %@NL@% %@AB@%Option%@AE@% %@AB@%Effect%@AE@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% /NM %@AI@%modulename%@AE@% Names the module /NT %@AI@%textsegment%@AE@% Names the code segment /ND %@AI@%datasegment%@AE@% Names the data segment "Module" is another name for an object file created by the C compiler from a single source file. Every module has a name. The compiler uses this name in error messages if problems are encountered during processing. The module name is usually the same as the source-file name. You can change this name using the /NM (name module) option. The new %@AI@%modulename%@AE@% can include any combination of letters and digits. The space between /NM and %@AI@%modulename%@AE@% is optional. %@NL@% %@NL@% Every module has at least two segments: a code segment (sometimes called the text segment) containing the program instructions, and a data segment containing the program data. %@NL@% %@NL@% The compiler normally creates the code and data segment names. The default names depend on the memory model chosen for the program. For example, in small-model programs the code segment is named %@AB@%_TEXT%@AE@% and the data segment is named %@AB@%_DATA%@AE@%. %@NL@% %@NL@% Table 2.4 summarizes the naming conventions for code and data segments. %@NL@% %@NL@% %@AB@%Table 2.4 %@AB@%Segment-Naming Conventions%@AE@%%@AE@% %@TH: 9 727 02 10 14 08 44 @%Model Code Data Module%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%Tiny %@AB@%_TEXT%@AE@% %@AB@%_DATA%@AE@% ---Small %@AB@%_TEXT%@AE@% %@AB@%_DATA%@AE@% ---Medium %@AI@%module%@AE@%%@AB@%_TEXT%@AE@% %@AB@%_DATA%@AE@% %@AI@%filename%@AE@%Compact %@AB@%_TEXT%@AE@% %@AB@%_DATA%@AE@% %@AI@%filename%@AE@%Large %@AI@%module%@AE@%%@AB@%_TEXT%@AE@% %@AB@%_DATA%@AE@% %@AI@%filename%@AE@%Huge %@AI@%module%@AE@%%@AB@%_TEXT%@AE@% %@AB@%_DATA%@AE@% %@AI@%filename%@AE@%%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@TE: 9 727 02 10 14 08 44 @% In memory models that contain multiple data segments (compact, large, and huge), %@AB@%_DATA%@AE@% is the name of the default data segment. Other data segments have unique private names. You can override the default names with the options /NT (name text) and /ND (name data). %@NL@% %@NL@% The /ND option is commonly used to create and compile modules that contain data only. Such modules can be accessed from other parts of the program by declaring their variables as external. %@NL@% %@NL@% If you change the name of the default data segment with /ND, your program must load the DS register with the segment selector of your named data segment before it accesses it. You must therefore compile your program either with the /A%@AI@%string%@AE@%form of the memory-model option and the /Au option for the segment setup, or with the /A option for a s%@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@CR:C6A00030001 @%%@1@%%@AB@%Chapter 3 Using the In-Line Assembler%@AE@%%@EH@%%@NL@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@NL@% This chapter explains how to use the Microsoft C in-line assembler. Assembly language serves many purposes, such as improving program speed, reducing memory needs, and controlling hardware. The in-line assembler lets you embed assembly-language instructions directly in your C source programs without extra assembly and link steps. The in-line assembler is built into the compiler─you don't need a separate assembler such as the Microsoft Macro Assembler (MASM). %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00030002 @%%@AB@%3.1 Advantages of In-Line Assembly%@AE@%%@EH@%%@NL@% %@NL@% Because the in-line assembler doesn't require separate assembly and link steps, it is more convenient than a separate assembler. In-line assembly code can use any C variable or function name that is in scope, so it is easy to integrate it with your program's C code. And because the assembly code can be mixed in-line with C statements, it can do tasks that are cumbersome or impossible in C alone.%@CR:C6A00030003 @% %@NL@% %@NL@% The uses of in-line assembly include %@NL@% %@NL@% %@NL@% ■ Writing functions in assembly language%@NL@% %@NL@% ■ Spot-optimizing speed-critical sections of code%@NL@% %@NL@% ■ Calling DOS and BIOS routines with the %@AB@%INT%@AE@% instruction%@NL@% %@NL@% ■ Creating TSR (terminate-and-stay-resident) code or handler routines that require knowledge of processor states%@NL@% %@NL@% %@NL@% In-line assembly is a special-purpose tool. If you plan to transport an application, you'll probably want to place machine-specific code in a separate module. And because the in-line assembler doesn't support all of MASM's macro and data directives, you may find it more convenient to use MASM for such modules. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00030004 @%%@AB@%3.2 The _asm Keyword%@AE@%%@EH@%%@NL@% %@NL@% The %@AB@%_asm%@AE@% keyword invokes the in-line assembler and can appear wherever a C statement is legal. It cannot appear by itself. It must be followed by an assembly instruction, a group of instructions enclosed in braces, or, at the very least, an empty pair of braces. The term "%@AB@%_asm%@AE@% block" here refers to any instruction or group of instructions, whether or not in braces. %@NL@% %@NL@% Below is a simple %@AB@%_asm%@AE@% block enclosed in braces. (The code prints the "beep" character, ASCII 7.) %@NL@% %@NL@% %@AS@% _asm %@AS@% { %@AS@% mov ah, 2 %@AS@% mov dl, 7 %@AS@% int 21h %@AS@% }%@AE@%%@NL@% %@NL@% Alternatively, you can put %@AB@%_asm%@AE@% in front of each assembly instruction: %@NL@% %@NL@% %@AS@% _asm mov ah, 2 %@AS@% _asm mov dl, 7 %@AS@% _asm int 21h%@AE@%%@NL@% %@NL@% Since the %@AB@%_asm%@AE@% keyword is a statement separator, you can also put assembly instructions on the same line: %@NL@% %@NL@% %@AS@% _asm mov ah, 2 _asm mov dl, 7 _asm int 21h%@AE@%%@NL@% %@NL@% %@AU@% Braces can prevent ambiguity and needless repetition.%@AE@% %@NL@% %@NL@% All three examples generate the same code, but the first style─enclosing the %@AB@%_asm%@AE@% block in braces─has some advantages. The braces clearly separate assembly code from C code and avoid needless repetition of the %@AB@%_asm%@AE@% keyword. Braces can also prevent ambiguities. If you want to put a C statement on the same line as an %@AB@%_asm%@AE@% block, you must enclose the block in braces. Without the braces, the compiler cannot tell where assembly code stops and C statements begin. Finally, since the text in braces has the same format as ordinary MASM text, you can easily cut and paste text from existing MASM source files. %@NL@% %@NL@% The braces enclosing an %@AB@%_asm%@AE@% block don't affect variable scope, as do braces in C. You can also nest %@AB@%_asm%@AE@% blocks, but the nesting doesn't affect variable scope. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00030005 @%%@AB@%3.3 Using Assembly Language in _asm Blocks%@AE@%%@EH@%%@NL@% %@NL@% The in-line assembler has much in common with other assemblers. For example, it accepts any expression that is legal in MASM, and it supports all 80286 and 80287 instructions. This section describes the use of assembly-language features in %@AB@%_asm%@AE@% blocks. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Instruction Set%@AE@%%@EH@%%@NL@% %@NL@% The in-line assembler supports the full instruction set of the Intel 80286 and 80287 processors. It does not recognize 80386- and 80387-specific instructions. To use 80286 or 80287 instructions, compile with the /G2 option. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Expressions%@AE@%%@EH@%%@NL@% %@NL@% In-line assembly code can use any MASM expression, that is, any combination of operands and operators that evaluates to a single value or address. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Data Directives and Operators%@AE@%%@EH@%%@NL@% %@NL@% Although an %@AB@%_asm%@AE@% block can reference C data types and objects, it cannot define data objects with MASM directives or operators. Specifically, you cannot use the definition directives %@AB@%DB%@AE@%, %@AB@%DW%@AE@%, %@AB@%DD%@AE@%, %@AB@%DQ%@AE@%, %@AB@%DT%@AE@%, and %@AB@%DF%@AE@%, or the operators %@AB@%DUP%@AE@% or %@AB@%THIS%@AE@%. Nor are MASM structures and records available. The in-line assembler doesn't accept the directives %@AB@%STRUC%@AE@%, %@AB@%RECORD%@AE@%, %@AB@%WIDTH%@AE@%, or %@AB@%MASK%@AE@%. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%EVEN and ALIGN Directives%@AE@%%@EH@%%@NL@% %@NL@% While the in-line assembler doesn't support most MASM directives, it does support %@AB@%EVEN%@AE@% and %@AB@%ALIGN%@AE@%. These directives put %@AB@%NOP%@AE@% (no operation) instructions in the assembly code as needed to align labels to specific boundaries. This makes instruction-fetch operations more efficient for some processors (not including eight-bit processors such as the Intel 8088). %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Macros%@AE@%%@EH@%%@NL@% %@NL@% The in-line assembler is not a macro assembler. You cannot use MASM macro directives (%@AB@%MACRO%@AE@%, %@AB@%REPT%@AE@%, %@AB@%IRC%@AE@%, %@AB@%IRP%@AE@%, and %@AB@%ENDM%@AE@%) or macro operators ( %@AB@%<>%@AE@%, %@AB@%!%@AE@%, %@AB@%&%@AE@%, %@AB@%%%@AE@%, and %@AB@%.TYPE%@AE@%). An %@AB@%_asm%@AE@% block can use C preprocessor directives, however. See Section 3.4, "Using C in %@AB@%_asm%@AE@% Blocks" for more information. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Segment References%@AE@%%@EH@%%@NL@% %@NL@% You must refer to segments by register rather than by name (the segment name %@AB@%_TEXT%@AE@% is invalid, for instance). Segment overrides must use the register explicitly, as in ES:[BX]. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Type and Variable Sizes%@AE@%%@EH@%%@NL@% %@NL@% The %@AB@%LENGTH%@AE@%, %@AB@%SIZE%@AE@%, and %@AB@%TYPE%@AE@% operators have a limited meaning in in-line assembly. They cannot be used at all with the %@AB@%DUP%@AE@% operator (because you cannot define data with MASM directives or operators). But you can use them to find the size of C variables or types: %@NL@% %@NL@% %@NL@% ■ The %@AB@%LENGTH%@AE@% operator can return the number of elements in an array. It returns the value 1 for nonarray variables.%@NL@% %@NL@% ■ The %@AB@%SIZE%@AE@% operator can return the size of a C variable. A variable's size is the product of its %@AB@%LENGTH%@AE@% and %@AB@%TYPE%@AE@%.%@NL@% %@NL@% ■ The %@AB@%TYPE%@AE@% operator can return the size of a C type or variable. If the variable is an array, %@AB@%TYPE%@AE@% returns the size of a single element of the array.%@NL@% %@NL@% %@NL@% For instance, if your program has an eight-element %@AB@%int%@AE@% array, %@NL@% %@NL@% %@AS@% int arr[8];%@AE@%%@NL@% %@NL@% the following C and assembly expressions yield the size of %@AS@% arr %@AE@% and its elements: %@NL@% %@NL@% %@TH: 6 425 02 12 27 37 @%_asm C Size%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AS@%LENGTH arr%@AE@% sizeof(ar)/sizeof(arr[0]) 8%@AS@%SIZE arr%@AE@% sizeof (arr) 16%@AS@%TYPE arr%@AE@% size14(arr[0]) 2%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@TE: 6 425 02 12 27 37 @% %@NL@% %@4@%%@AB@%Comments%@AE@%%@EH@%%@NL@% %@NL@% Instructions in an %@AB@%_asm%@AE@% block can use assembly-language comments: %@NL@% %@NL@% %@AS@% _asm mov ax, offset buff ; Load address of buff%@AE@%%@NL@% %@NL@% Because C macros expand into a single logical line, avoid using assemblylanguage comments in macros (see Section 3.8, "Defining %@AB@%_asm%@AE@% Blocks as C Macros"). An %@AB@%_asm%@AE@% block can also contain C-style comments, as noted below. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%The _emit Pseudoinstruction%@AE@%%@EH@%%@NL@% %@NL@% The %@AB@%_emit%@AE@% pseudoinstruction is similar to the %@AB@%DB%@AE@% directive of MASM. It allows you to define a single immediate byte at the current location in the current text segment. However, %@AB@%_emit%@AE@% can define only one byte at a time, and it can only define bytes in the text segment. It uses the same syntax as the %@AB@%INT%@AE@% instruction. %@NL@% %@NL@% One use for %@AB@%_emit%@AE@% is to define 80386-specific instructions, which the in-line assembler does not support. The following fragment, for instance, defines the 80386 %@AB@%CWDE%@AE@% instruction: %@NL@% %@NL@% %@AS@% /* Assumes 16-bit mode */ %@AS@% #define cwde _asm _emit 0x66 _asm _emit 0x98 %@AS@% . %@AS@% . %@AS@% . %@AS@% _asm { %@AS@% cwde %@AS@% }%@AE@%%@NL@% %@NL@% %@NL@% %@4@%%@AB@%Debugging and Listings%@AE@%%@EH@%%@NL@% %@NL@% %@AU@% In-line assembly code can be debugged with CodeView.%@AE@% %@NL@% %@NL@% Programs containing in-line assembly code can be debugged with the CodeView debugger, assuming you compile with the /Zi option. %@NL@% %@NL@% Within CodeView, you can set breakpoints on both C and assembly-language lines. If you enable mixed assembly and C mode, you can display both the source and disassembled form of the assembly code. %@NL@% %@NL@% Note that putting multiple assembly instructions or C statements on one line can hamper debugging with CodeView. In source mode, the CodeView debugger lets you set breakpoints on a single line but not on individual statements on the same line. The same principle applies to an %@AB@%_asm%@AE@% block defined as a C macro, which expands to a single logical line. %@NL@% %@NL@% If you create a mixed source and assembly listing with the /Fc compiler option, the listing contains both the source and assembly forms of each assemblylanguage line. Macros are not expanded in listings, but they are expanded during compilation. %@NL@% %@NL@% See Chapter 9, "Debugging C Programs with CodeView," for more information. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00030006 @%%@AB@%3.4 Using C in _asm Blocks%@AE@%%@EH@%%@NL@% %@NL@% Because in-line assembly instructions can be mixed with C statements, they can refer to C variables by name and use many other elements of C. An %@AB@%_asm%@AE@% block can use the following C language elements: %@NL@% %@NL@% %@NL@% ■ Symbols, including labels and variable and function names%@NL@% %@NL@% ■ Constants, including symbolic constants and %@AB@%enum%@AE@% members%@NL@% %@NL@% ■ Macros and preprocessor directives%@NL@% %@NL@% ■ Comments (both %@AS@% /* */ %@AE@% and %@AS@% // %@AE@%)%@NL@% %@NL@% ■ Type names (wherever a MASM type would be legal)%@NL@% %@NL@% ■ %@AB@%typedef%@AE@% names, generally used with operators such as %@AB@%PTR%@AE@% and %@AB@%TYPE%@AE@% or to specify structure or union members%@NL@% %@NL@% %@NL@% Within an %@AB@%_asm%@AE@% block, you can specify integer constants with either C notation or assembler radix notation (0x100 and 100h are equivalent, for instance). This allows you to define (using %@AB@%#define%@AE@%) a constant in C, and use it in both C and assembly portions of the program. You can also specify constants in octal by preceding them with a 0. For example, 0777 specifies an octal constant. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00030007 @%%@AB@%3.4.1 Using Operators%@AE@%%@EH@%%@NL@% %@NL@% An %@AB@%_asm%@AE@% block cannot use C-specific operators, such as the %@AB@%%@AE@% operator. However, operators shared by C and MASM, such as the %@AB@%*%@AE@% operator, are interpreted as assembly-language operators. For instance, outside an %@AB@%_asm%@AE@% block, square brackets (%@AB@% [] %@AE@%) are interpreted as enclosing array subscripts, which C automatically scales to the size of an element in the array. Inside an %@AB@%_asm%@AE@% block, they are seen as the MASM index operator, which yields an unscaled byte offset from any data object or label (not just an array). The following code illustrates the difference: %@NL@% %@NL@% %@AS@% int array[10]; %@AS@% %@AS@% _asm mov array[6], bx ; Store BX at array+6 (not scaled) %@AS@% %@AS@% array[6] = 0; /* Store 0 at array+12 (scaled) */%@AE@%%@NL@% %@NL@% The first reference to %@AS@% array %@AE@% is not scaled, but the second is. Note that you can use the %@AB@%TYPE%@AE@% operator to achieve scaling based on a constant. For instance, the following statements are equivalent: %@NL@% %@NL@% %@AS@% _asm mov array[6 * TYPE int], 0 ; Store 0 at array + 12 %@AS@% %@AS@% array[6] = 0; /* Store 0 at array + 12 */%@AE@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00030008 @%%@AB@%3.4.2 Using C Symbols%@AE@%%@EH@%%@NL@% %@NL@% An %@AB@%_asm%@AE@% block can refer to any C symbol in scope where the block appears. (C symbols are variable names, function names, and labels─in other words, names that aren't symbolic constants or %@AB@%enum%@AE@% members.) %@NL@% %@NL@% A few restrictions apply to the use of C symbols: %@NL@% %@NL@% %@NL@% ■ Each assembly-language statement can contain only one C symbol. Multiple symbols can appear in the same assembly instruction only with %@AB@%LENGTH, TYPE%@AE@%, and %@AB@%SIZE%@AE@% expressions.%@NL@% %@NL@% ■ Functions referenced in an %@AB@%_asm%@AE@% block must be declared (prototyped) earlier in the program. Otherwise, the compiler cannot distinguish between function names and labels in the %@AB@%_asm%@AE@% block.%@NL@% %@NL@% ■ An %@AB@%_asm%@AE@% block cannot use any C symbols with the same spelling as MASM reserved words (regardless of case). MASM reserved words include instruction names such as %@AB@%PUSH%@AE@% and register names such as SI.%@NL@% %@NL@% ■ Structure and union tags are not recognized in %@AB@%_asm%@AE@% blocks.%@NL@% %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00030009 @%%@AB@%3.4.3 Accessing C Data%@AE@%%@EH@%%@NL@% %@NL@% A great convenience of in-line assembly is the ability to refer to C variables by name. An %@AB@%_asm%@AE@% block can refer to any symbols─including variable names─that are in scope where the block appears. For instance, if the C variable %@AS@% var %@AE@% is in scope, the instruction %@NL@% %@NL@% %@AS@% _asm mov ax, var%@AE@%%@NL@% %@NL@% stores the value of %@AS@% var %@AE@% in AX. %@NL@% %@NL@% If a structure or union member has a unique name, an %@AB@%_asm%@AE@% block can refer to it using only the member name, without specifying the C variable or %@AB@%typedef%@AE@% name before the period (%@AB@%.%@AE@%) operator. If the member name is not unique, however, you must place a variable or %@AB@%typedef%@AE@% name immediately before the period (%@AB@%.%@AE@%) operator. For instance, the following structure types share %@AS@% %@AS@%same_name %@AE@% as their member name: %@AS@% %@AE@%%@NL@% %@NL@% %@AS@% struct first_type %@AS@% { %@AS@% char *weasel; %@AS@% int same_name; %@AS@% }; %@AS@% %@AS@% struct second_type %@AS@% { %@AS@% int wonton; %@AS@% long same_name; %@AS@% };%@AE@%%@NL@% %@NL@% If you declare variables with the types %@NL@% %@NL@% %@AS@% struct first_type hal; %@AS@% struct second_type oat;%@AE@%%@NL@% %@NL@% all references to the member %@AS@% same_name %@AE@% must use the variable name, because %@AS@% same_name %@AE@% is not unique. But the member %@AS@% weasel %@AE@% has a unique name, so you can refer to it using only its member name: %@NL@% %@NL@% %@AS@% _asm %@AS@% { %@AS@% mov bx, OFFSET hal %@AS@% mov cx, [bx]hal.same_name ; Must use 'hal' %@AS@% mov si, [bx].weasel ; Can omit 'hal' %@AS@% }%@AE@%%@NL@% %@NL@% Note that omitting the variable name is merely a coding convenience. The same assembly instructions are generated whether or not it is present. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00030010 @%%@AB@%3.4.4 Writing Functions%@AE@%%@EH@%%@NL@% %@NL@% If you write a function with in-line assembly code, it's a simple matter to pass arguments to the function and return a value from it. The following examples compare a function first written for a separate assembler and then rewritten for the in-line assembler. The function, called %@AS@% power2%@AE@%, receives two parameters, multiplying the first parameter by 2 to the power of the second parameter. Written for a separate assembler, the function might look like this: %@NL@% %@NL@% %@AS@% ; POWER.ASM %@AS@% ; Compute the power of an integer %@AS@% ; %@AS@% PUBLIC _power2 %@AS@% _TEXT SEGMENT WORD PUBLIC 'CODE' %@AS@% _power2 PROC %@AS@% %@AS@% push bp ; Save BP %@AS@% mov bp, sp ; Move SP into BP so we can refer %@AS@% ; to arguments on the stack %@AS@% mov ax, [bp+4] ; Get first argument %@AS@% mov cx, [bp+6] ; Get second argument %@AS@% shl ax, cl ; AX = AX * ( 2 ^ CL ) %@AS@% pop bp ; Restore BP %@AS@% ret ; Return with sum in AX %@AS@% %@AS@% _power2 ENDP %@AS@% _TEXT ENDS %@AS@% END%@AE@%%@NL@% %@NL@% %@AU@% Function arguments are usually passed on the stack.%@AE@% %@NL@% %@NL@% Since it's written for a separate assembler, the function requires a separate source file and assembly and link steps. C function arguments usually are passed on the stack, so this version of the %@AS@% power2 %@AE@% function accesses its arguments by their positions on the stack. (Note that the %@AB@%MODEL%@AE@% directive, available in MASM and some other assemblers, also allows you to access stack arguments and local stack variables by name.) %@NL@% %@NL@% The POWER2.C program below writes the %@AS@% power2 %@AE@% function with in-line assembly code: %@NL@% %@NL@% %@AS@% /* POWER2.C */ %@AS@% #include <stdio.h> %@AS@% %@AS@% int power2( int num, int power ); %@AS@% %@AS@% void main( void ) %@AS@% { %@AS@% printf( "3 times 2 to the power of 5 is %d\n", \ %@AS@% power2( 3, 5) ); %@AS@% } %@AS@% %@AS@% int power2( int num, int power ) %@AS@% { %@AS@% _asm %@AS@% { %@AS@% mov ax, num ; Get first argument %@AS@% mov cx, power ; Get second argument %@AS@% shl ax, cl ; AX = AX * ( 2 to the power of CL ) %@AS@% } %@AS@% /* Return with result in AX */ %@AS@% }%@AE@%%@NL@% %@NL@% The in-line version of the %@AS@% power2 %@AE@% function refers to its arguments by name and appears in the same source file as the rest of the program. This version also requires fewer assembly instructions. Since C automatically preserves BP, the %@AB@%_asm%@AE@% block doesn't need to do so. It can also dispense with the %@AB@%RET%@AE@% instruction, since the C part of the function performs the return. %@NL@% %@NL@% Because the in-line version of %@AS@% power2 %@AE@% doesn't execute a C %@AB@%return%@AE@% statement, it causes a harmless warning if you compile at warning levels 2 or higher: %@NL@% %@NL@% %@AS@% warning C4035: 'power2' : no return value%@AE@%%@NL@% %@NL@% The function does return a value, but the compiler cannot tell that in the absence of a %@AB@%return%@AE@% statement. Simply ignore the warning in this context. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00030011 @%%@AB@%3.5 Using and Preserving Registers%@AE@%%@EH@%%@NL@% %@NL@% In general, you should not assume that a register will have a given value when an %@AB@%_asm%@AE@% block begins. An %@AB@%_asm%@AE@% block inherits whatever register values happen to result from the normal flow of control. %@NL@% %@NL@% If you use the %@AB@%_fastcall%@AE@% calling convention, the compiler passes function arguments in registers instead of the stack. This can create problems in functions with %@AB@%_asm%@AE@% blocks, since a function has no way to tell which parameter is in which register. If the function happens to receive a parameter in AX and immediately stores something else in AX, the parameter is lost. In addition, you must preserve the CX and ES registers in any function declared with %@AB@%_fastcall%@AE@%. %@NL@% %@NL@% %@AU@% Don't use the _fastcall calling convention for functions with _asm blocks.%@AE@% %@NL@% %@NL@% To avoid such register conflicts, don't use the %@AB@%_fastcall%@AE@% convention for functions that contain an %@AB@%_asm%@AE@% block. If you specify the %@AB@%_fastcall%@AE@% convention globally with the /Gr compiler option, declare every function containing an %@AB@%_asm%@AE@% block with %@AB@%_cdecl%@AE@%. (The %@AB@%_cdecl%@AE@% attribute tells the compiler to use the normal C calling convention for that function.) If you are not compiling with /Gr, avoid declaring the function with the %@AB@%_fastcall%@AE@% attribute. %@NL@% %@NL@% As you may have noticed in the POWER2.C example in Section 3.4.4, the %@AS@% %@AS@%power2 %@AE@% function doesn't preserve the value in the AX register. When you write a function in assembly language, you don't need to preserve the AX, BX, CX, DX, ES, and flags registers. However, you should preserve any other registers you use (DI, SI, DS, SS, SP, and BP). %@NL@% %@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% %@AU@%WARNING%@AE@%%@NL@% %@NL@% If your in-line assembly code changes the direction flag using the STD or CLD instructions, you must restore the flag to its original value.%@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% %@NL@% %@AU@% Functions return values in the AX and DX registers.%@AE@% %@NL@% %@NL@% The POWER2.C example in Section 3.4.4 also shows that functions return values in registers. This is true whether the function is written in assembly language or in C. %@NL@% %@NL@% If the return value is short (a %@AB@%char%@AE@%, %@AB@%int%@AE@%, or %@AB@%near%@AE@% pointer), it is stored in AX. The POWER2.C example returned a value by terminating with the desired value in AX. %@NL@% %@NL@% If the return value is long, store the high word in DX and the low word in AX. To return a longer value (such as a floating-point value), store the value in memory and return a pointer to the value (in AX if %@AB@%near%@AE@% or in DX:AX if %@AB@%far%@AE@%). %@NL@% %@NL@% Assembly instructions that appear in-line with C statements are free to alter the AX, BX, CX, and DX registers. C doesn't expect these registers to be maintained between statements, so you don't need to preserve them. The same is true of the SI and DI registers, with some exceptions (see Section 3.9, "Optimizing"). You should preserve the SP and BP registers unless you have some reason to change them─to switch stacks, for instance. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00030012 @%%@AB@%3.6 Jumping to Labels%@AE@%%@EH@%%@NL@% %@NL@% Like an ordinary C label, a label in an %@AB@%_asm%@AE@% block has scope throughout the function in which it is defined (not only in the block). Both assembly instructions and C %@AB@%goto%@AE@% statements can jump to labels inside or outside the %@AB@%_asm%@AE@% block. %@NL@% %@NL@% %@AU@% Labels in _asm blocks have function scope and are not case sensitive.%@AE@% %@NL@% %@NL@% Unlike C labels, labels defined in %@AB@%_asm%@AE@% blocks are not case sensitive, even when used in C statements. C labels are not case sensitive in an %@AB@%_asm%@AE@% block, either. (Outside an %@AB@%_asm%@AE@% block, a C label is case sensitive as usual.) The following do-nothing code shows all the permutations: %@NL@% %@NL@% %@AS@% void func( void ) %@AS@% { %@AS@% goto C_Dest; /* legal */ %@AS@% goto c_dest; /* error */ %@AS@% %@AS@% goto A_Dest; /* legal */ %@AS@% goto a_dest; /* legal */ %@AS@% %@AS@% _asm %@AS@% { %@AS@% jmp C_Dest ; legal %@AS@% jmp c_dest ; legal %@AS@% %@AS@% jmp A_Dest ; legal %@AS@% jmp a_dest ; legal %@AS@% %@AS@% a_dest: ; _asm label %@AS@% } %@AS@% %@AS@% C_Dest: /* C label */ %@AS@% return; %@AS@% }%@AE@%%@NL@% %@NL@% Don't use C library function names as labels in %@AB@%_asm%@AE@% blocks. For instance, you might be tempted to use %@AS@% exit %@AE@% as a label, %@NL@% %@NL@% %@AS@% jne exit %@AS@% . %@AS@% . %@AS@% . %@AS@% exit: %@AS@% ; More _asm code follows%@AE@%%@NL@% %@NL@% forgetting that %@AB@%exit%@AE@% is the name of a C library function. The code doesn't cause a compiler error, but it might cause a jump to the %@AB@%exit%@AE@% function instead of the desired location. %@NL@% %@NL@% As in MASM programs, the dollar symbol (%@AB@%$%@AE@%) serves as the current location counter─a label for the instruction currently being assembled. In %@AB@%_asm%@AE@% blocks, its main use is to make long conditional jumps: %@NL@% %@NL@% %@AS@% jne $+5 ; next instruction is 5 bytes long %@AS@% jmp farlabel %@AS@% ; $+5 %@AS@% . %@AS@% . %@AS@% . %@AS@% farlabel:%@AE@%%@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00030013 @%%@AB@%3.7 Calling C Functions%@AE@%%@EH@%%@NL@% %@NL@% An %@AB@%_asm%@AE@% block can call C functions, including C library routines. The following example calls the %@AB@%printf%@AE@% library routine: %@NL@% %@NL@% %@AS@% #include <stdio.h> %@AS@% %@AS@% char format[] = "%s %s\n"; %@AS@% char hello[] = "Hello"; %@AS@% char world[] = "world"; %@AS@% %@AS@% void main( void ) %@AS@% { %@AS@% _asm %@AS@% { %@AS@% mov ax, offset world %@AS@% push ax %@AS@% mov ax, offset hello %@AS@% push ax %@AS@% mov ax, offset format %@AS@% push ax %@AS@% call printf %@AS@% } %@AS@% }%@AE@%%@NL@% %@NL@% Since function arguments are passed on the stack, you simply push the needed arguments─string pointers, in the example above─before calling the function. The arguments are pushed in reverse order, so they come off the stack in the desired order. To emulate the C statement %@NL@% %@NL@% %@AS@% printf( format, hello, world );%@AE@%%@NL@% %@NL@% the example pushes pointers to %@AS@% world%@AE@%, %@AS@% hello%@AE@%, and %@AS@% format%@AE@%, in that order, then calls %@AB@%printf%@AE@%. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00030014 @%%@AB@%3.8 Defining _asm Blocks as C Macros%@AE@%%@EH@%%@NL@% %@NL@% C macros offer a convenient way to insert assembly code into C code, but they demand extra care because a macro expands into a single logical line. To create trouble-free macros, follow these rules: %@NL@% %@NL@% %@NL@% ■ Enclose the %@AB@%_asm%@AE@% block in braces.%@NL@% %@NL@% ■ Put the %@AB@%_asm%@AE@% keyword in front of each assembly instruction.%@NL@% %@NL@% ■ Use old-style C comments (%@AS@% /* comment */ %@AE@%) instead of assembly-style comments (%@AS@% ; comment %@AE@%) or single-line C comments (%@AS@% // comment %@AE@%).%@NL@% %@NL@% %@NL@% To illustrate, the following example defines a simple macro: %@NL@% %@NL@% %@AS@% #define BEEP _asm \ %@AS@% /* Beep sound */ \ %@AS@% { \ %@AS@% _asm mov ah, 2 \ %@AS@% _asm mov dl, 7 \ %@AS@% _asm int 21h \ %@AS@% }%@AE@%%@NL@% %@NL@% At first glance, the last three %@AB@%_asm%@AE@% keywords seem superfluous. They are needed, however, because the macro expands into a single line: %@NL@% %@NL@% %@AS@% _asm /* Beep sound */ { _asm mov ah, 2 _asm mov dl, 7 _asm int 21h }%@AE@%%@NL@% %@NL@% The third and fourth %@AB@%_asm%@AE@% keywords are needed as statement separators. The only statement separators recognized in %@AB@%_asm%@AE@% blocks are the newline character and %@AB@%_asm%@AE@% keyword. And since a block defined as a macro is one logical line, you must separate each instruction with %@AB@%_asm%@AE@%. %@NL@% %@NL@% The braces are essential as well. If you omit them, the compiler can be confused by C statements on the same line to the right of the macro invocation. Without the closing brace, the compiler cannot tell where assembly code stops, and it sees C statements after the %@AB@%_asm%@AE@% block as assembly instructions. %@NL@% %@NL@% %@AU@% Use C comments in _asm blocks written as macros.%@AE@% %@NL@% %@NL@% Assembly-style comments that start with a semicolon (;) continue to the end of the line. This causes problems in macros because the compiler ignores everything after the comment, all the way to the end of the logical line. The same is true of single-line C comments (%@AS@% // comment %@AE@%). To prevent errors, use old-style C comments (%@AS@% /* comment */ %@AE@%) in %@AB@%_asm%@AE@% blocks defined as macros. %@NL@% %@NL@% %@AU@% An _asm block written as a C macro can take arguments but cannot return a %@AU@%value.%@AE@% %@NL@% %@NL@% An %@AB@%_asm%@AE@% block written as a C macro can take arguments. Unlike an ordinary C macro, however, an %@AB@%_asm%@AE@% macro cannot return a value. So you cannot use such macros in C expressions. %@NL@% %@NL@% Be careful not to invoke macros of this type indiscriminately. For instance, invoking an assembly-language macro in a function declared with the %@AB@%_fastcall%@AE@% con-vention may cause unexpected results. (See Section 3.5, "Using and Preserving Registers.") %@NL@% %@NL@% %@AU@% You can convert MASM macros to C macros.%@AE@% %@NL@% %@NL@% Note that some MASM-style macros can be written as C macros. Below is a MASM macro that sets the video page to the value specified in the %@AS@% page %@AE@% argument: %@NL@% %@NL@% %@AS@% setpage MACRO page %@AS@% mov ah, 5 %@AS@% mov al, page %@AS@% int 10h %@AS@% ENDM%@AE@%%@NL@% %@NL@% The following code defines %@AS@% setpage %@AE@% as a C macro: %@NL@% %@NL@% %@AS@% #define setpage( page ) _asm \ %@AS@% { \ %@AS@% _asm mov ah, 5 \ %@AS@% _asm mov al, page \ %@AS@% _asm int 10h \ %@AS@% }%@AE@%%@NL@% %@NL@% Both macros do the same job. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00030015 @%%@AB@%3.9 Optimizing%@AE@%%@EH@%%@NL@% %@NL@% The presence of an %@AB@%_asm%@AE@% block in a function affects optimization in a few different ways. First, as you might expect, the compiler doesn't try to optimize the %@AB@%_asm%@AE@% block itself. What you write in assembly language is exactly what you get. %@NL@% %@NL@% Second, the presence of an %@AB@%_asm%@AE@% block affects register variable storage. Under normal circumstances (unless you suppress optimization with the /Od option) the compiler automatically stores variables in registers. This is not done, however, in any function that contains an %@AB@%_asm%@AE@% block. To get register variable storage in such a function, you must request it with the %@AB@%register%@AE@% keyword. %@NL@% %@NL@% Since the compiler stores register variables in the SI and DI registers, these registers represent variables in functions that request register storage. The first eligible variable is stored in SI and the second in DI. Preserve SI and DI in such functions unless you want to change the register variables. %@NL@% %@NL@% Keep in mind that the name of a variable declared with %@AB@%register%@AE@% translates directly into a register reference (assuming a register is available for such use). For instance, if you declare %@NL@% %@NL@% %@AS@% register int sample;%@AE@%%@NL@% %@NL@% and the variable %@AS@% sample %@AE@% happens to be stored in SI, then the %@AB@%_asm%@AE@% instruction %@NL@% %@NL@% %@AS@% _asm mov ax, sample%@AE@%%@NL@% %@NL@% is equivalent to %@NL@% %@NL@% %@AS@% _asm mov ax, si%@AE@%%@NL@% %@NL@% If you declare a variable with %@AB@%register%@AE@% and the compiler cannot store the variable in a register, the compiler issues a warning to that effect at compile time. The solution is to remove the %@AB@%register%@AE@% declaration from that variable. %@NL@% %@NL@% Register variables form a slight exception to the general rule that an assembly-language statement can contain no more than one C symbol. If one of the symbols is a register variable, for example, %@NL@% %@NL@% %@AS@% register int v1; %@AS@% int v2;%@AE@%%@NL@% %@NL@% then an instruction can use two C symbols, as in %@NL@% %@NL@% %@AS@% mov v1, v2%@AE@%%@NL@% %@NL@% Finally, the presence of in-line assembly code inhibits the following optimizations for the entire function in which the code appears: %@NL@% %@NL@% %@NL@% ■ Loop ( /Ol )%@NL@% %@NL@% ■ Global register allocation ( /Oe )%@NL@% %@NL@% ■ Global optimizations and common subexpressions ( /Og )%@NL@% %@NL@% %@NL@% These optimizations are suppressed no matter which compiler options you use. %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@CR:C6A00040001 @%%@1@%%@AB@%Chapter 4 Controlling Floating-Point Math Operations%@AE@%%@EH@%%@NL@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@NL@% This chapter describes how to control the way your Microsoft C programs perform floating-point math operations. It describes the math packages that you can include in C libraries when you run the SETUP program, then discusses the options you can specify in the Programmer's WorkBench (PWB) or on the CL command line to choose the appropriate library for linking and controlling floating-point instructions.%@CR:C6A00040002 @% %@NL@% %@NL@% This chapter also explains how to override floating-point options by changing libraries at link time, and how to control use of the Intel math coprocessor (80%@AI@%x%@AE@%87) using the NO87 environment variable.%@CR:C6A00040003 @%%@CR:C6A00040004 @%%@CR:C6A00040005 @%%@CR:C6A00040006 @% %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00040007 @%%@AB@%4.1 Declaring Floating-Point Types%@AE@%%@EH@%%@NL@% %@NL@% Microsoft C supports three floating-point types that conform to the Institute of Electrical and Electronics Engineers (IEEE) standard 754 format:%@CR:C6A00040008 @% %@NL@% %@NL@% %@NL@% 1. Type %@AB@%float%@AE@%, a 32-bit floating-point quantity%@NL@% %@NL@% 2. Type %@AB@%double%@AE@%, a 64-bit floating-point quantity%@NL@% %@NL@% 3. Type %@AB@%long double%@AE@%, an 80-bit floating-point quantity%@NL@% %@NL@% %@NL@% You can declare variables as any of these types. You can also declare functions that return any of these types. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00040009 @%%@AB@%4.1.1 Declaring Variables as Floating-Point Types%@CR:C6A00040010 @%%@AE@%%@EH@%%@NL@% %@NL@% You can declare variables as %@AB@%float%@AE@%, %@AB@%double%@AE@%, or %@AB@%long double%@AE@%, depending on the needs of your application. The principal differences between the three types are the significance they can represent, the storage they require, and their range. Table 4.1 shows the relationship between significance and storage requirements.%@CR:C6A00040011 @%%@CR:C6A00040012 @%%@CR:C6A00040013 @%%@CR:C6A00040014 @%%@CR:C6A00040015 @%%@CR:C6A00040016 @%%@CR:C6A00040017 @%%@CR:C6A00040018 @%%@CR:C6A00040019 @%%@CR:C6A00040020 @% %@NL@% %@NL@% %@AB@%Table 4.1 %@AB@%Floating-Point Types%@AE@%%@AE@% %@TH: 6 416 02 14 20 42 @%Type Significant Digits Number of Bytes%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%float%@AE@% 6-7 4%@AB@%double%@AE@% 15-16 8%@AB@%long double%@AE@% 19 10%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@TE: 6 416 02 14 20 42 @% Floating-point variables are represented by a mantissa, which contains the value of the number, and an exponent, which contains the order of magnitude of the number.%@CR:C6A00040021 @%%@CR:C6A00040022 @% %@NL@% %@NL@% Table 4.2 shows the number of bits allocated to the mantissa and the exponent for each floating-point type. The most-significant bit of any %@AB@%float%@AE@%, %@AB@%double%@AE@%, or %@AB@%long double %@AE@%is always the sign bit. If it is 1, the number is considered negative; otherwise, it is considered a positive number.%@CR:C6A00040023 @% %@NL@% %@NL@% %@AB@%Table 4.2 %@AB@%Lengths of Exponents and Mantissas%@AE@%%@AE@% %@TH: 6 421 02 14 17 45 @%Type Exponent Length Mantissa Length%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%float%@AE@% 8 bits 23 bits%@AB@%double%@AE@% 11 bits 52 bits%@AB@%long double%@AE@% 15 bits 64 bits%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@TE: 6 421 02 14 17 45 @% Because exponents are stored in an unsigned form, the exponent is biased by half its possible value. For type %@AB@%float%@AE@%, the bias is 127; for type %@AB@%double%@AE@%, it is 1,023; for type %@AB@%long double%@AE@%, it is 16,383. You can compute the actual exponent value by subtracting the bias value from the exponent value.%@CR:C6A00040024 @% %@NL@% %@NL@% The mantissa is stored as a binary fraction greater than or equal to 1 and less than 2. For types %@AB@%float %@AE@%and %@AB@%double%@AE@%, there is an implied leading 1 in the mantissa in the most-significant bit position, so the mantissas are actually 24 and 53 bits long, respectively, even though the most-significant bit is never stored in memory. %@NL@% %@NL@% Instead of the storage method just described, the floating-point package can store binary floating-point numbers as denormalized numbers. Denormalized numbers are nonzero floating-point numbers with reserved exponent values in which the most-significant bit of the mantissa is zero. By using denormalized format, the range of a floating-point number can be extended at the cost of precision. You cannot control whether a floating-point number is represented in normalized or denormalized form; the floating-point package determines the representation. The floating-point packages never use denormalized form unless the exponent becomes less than the minimum that can be represented in a normalized form.%@CR:C6A00040025 @%%@CR:C6A00040026 @% %@NL@% %@NL@% Table 4.3 shows the minimum and maximum value you can store in variables of each floating-point type. The values listed in this table apply only to normalized floating-point numbers; denormalized floating-point numbers have a smaller minimum value. Note that numbers retained in 80%@AI@%x%@AE@%87 registers are always represented in 80-bit normal form; numbers can only be represented in denormal form when stored in 32- or 64-bit floating-point variables (type %@AB@%float%@AE@% and type %@AB@%long%@AE@%).%@CR:C6A00040027 @%%@CR:C6A00040028 @% %@NL@% %@NL@% %@AB@%Table 4.3 %@AB@%Range of Floating-Point Types%@AE@%%@AE@% %@TH: 6 527 02 14 31 31 @%Type Minimum Value Maximum Value%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%float%@AE@% 1.175494351 E - 38 3.402823466 E + 38%@AB@%double%@AE@% 2.2250738585072014 E - 308 1.7976931348623158 E + 308%@AB@%long double%@AE@% 3.362103143112093503 E - 4932 1.189731495357231765 E + 4932%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@TE: 6 527 02 14 31 31 @% If precision is less of a concern than storage, consider using type %@AB@%float%@AE@% for floating-point variables. Conversely, if precision is the most important criterion, use type %@AB@%long double%@AE@%.%@CR:C6A00040029 @%%@CR:C6A00040030 @% %@NL@% %@NL@% %@AU@% Microsoft C observes type-widening rules.%@CR:C6A00040031 @%%@AE@% %@NL@% %@NL@% Floating-point variables can be promoted to a type of greater significance (for example, from type %@AB@%float%@AE@% to type %@AB@%double%@AE@%). Promotion often occurs when you perform arithmetic on floating-point variables. This arithmetic is always done in as high a degree of precision as the variable with the highest degree of precision. For example, consider the following type declarations:%@CR:C6A00040032 @%%@CR:C6A00040033 @% %@NL@% %@NL@% %@AS@% float f_short; %@AS@% double f_long; %@AS@% long double f_longer; %@AS@% %@AS@% f_short = f_short * f_long;%@AE@%%@NL@% %@NL@% In the preceding example, the variable %@AS@% f_short %@AE@% is promoted to type %@AB@%double%@AE@% and multiplied by %@AS@% f_long%@AE@%; then the result is rounded to type %@AB@%float %@AE@%before being assigned to %@AS@% f_short%@AE@%. %@NL@% %@NL@% In the example below (which uses the declarations from the preceding example), the arithmetic is done in %@AB@%float%@AE@% (32-bit) precision on the variables; the result is then promoted to type %@AB@%long double%@AE@%. %@NL@% %@NL@% %@AS@% f_longer = f_short * f_short;%@AE@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00040034 @%%@AB@%4.1.2 Declaring Functions that Return Floating-Point Types%@CR:C6A00040035 @%%@AE@%%@EH@%%@NL@% %@NL@% You can declare functions that return the floating-point types %@AB@%float%@AE@%, %@AB@%double%@AE@%, and %@AB@%long double%@AE@%. Functions that return types %@AB@%float%@AE@% or %@AB@%double%@AE@% do not place their return values in registers; they place their return values in a global location called the floating-point accumulator ( fac). %@NL@% %@NL@% When declaring a function as a floating-point type in a multithreaded program for OS/2, you should use the %@AB@%_pascal%@AE@% keyword to specify the FORTRAN/Pascal calling convention. Declaring the function as %@AB@%_pascal%@AE@% causes the return value to be placed on the stack, rather than in the floating-point accumulator, %@AB@% fac%@AE@%. %@NL@% %@NL@% %@AU@% You can write re-entrant functions that return floating-point types.%@AE@% %@NL@% %@NL@% Using the current thread's private stack to return values allows you to write re-entrant functions by eliminating possible contention between threads for the floating-point accumulator.%@CR:C6A00040036 @%%@CR:C6A00040037 @%%@CR:C6A00040038 @%%@CR:C6A00040039 @%%@CR:C6A00040040 @%%@CR:C6A00040041 @%%@CR:C6A00040042 @% %@NL@% %@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% NOTE %@AI@%Functions that return type %@AB@%long double%@AE@%%@AI@% always place their return values on %@AI@%the stack. You need not use the %@AE@%%@AI@%%@AB@%_pascal%@AE@%%@AE@%%@AI@% keyword with functions declared as %@AI@%%@AE@%%@AI@%%@AB@%long double%@AE@%%@AE@%%@AI@%.%@AE@%%@AE@%%@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@%%@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00040043 @%%@AB@%4.2 C Run-Time Library Support of Type long double%@CR:C6A00040044 @%%@CR:C6A00040045 @%%@CR:C6A00040046 @%%@AE@%%@EH@%%@NL@% %@NL@% All of the Microsoft C run-time libraries support type %@AB@%long double%@AE@%. Each of the normal floating-point math functions has a special version that supports type %@AB@%long double%@AE@%. These functions have the same name as the functions that support type %@AB@%float %@AE@%and type %@AB@%double%@AE@%, except that they end with %@AB@%l%@AE@%. For example, the function that returns the absolute value of a variable of type %@AB@%float %@AE@%or type %@AB@%double %@AE@%is %@AB@%fabs%@AE@%. The %@AB@%long double %@AE@%equivalent function is %@AB@%fabsl%@AE@%. The two exceptions to this rule are the %@AB@%_atold%@AE@% and %@AB@%_strtodl%@AE@% functions. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00040047 @%%@AB@%4.3 Summary of Math Packages%@AE@%%@EH@%%@NL@% %@NL@% The Microsoft C compiler offers a choice of the following three math packages for handling floating-point operations:%@CR:C6A00040048 @% %@NL@% %@NL@% %@NL@% 1. Emulator (default)%@CR:C6A00040049 @%%@CR:C6A00040050 @%%@NL@% %@NL@% 2. Math coprocessor (a library that supports the Intel 80%@AI@%x%@AE@%87 family of math coprocessors)%@CR:C6A00040051 @%%@CR:C6A00040052 @%%@NL@% %@NL@% 3. Alternate math %@NL@% %@NL@% %@NL@% When you install Microsoft C, the SETUP program allows you to build combined libraries. These libraries include the floating-point math library that you choose. Any programs linked with that library use the math package included in the library; you must use the appropriate PWB or CL option to make sure that the library you want is used at link time.%@CR:C6A00040053 @% %@NL@% %@NL@% The following descriptions of these math packages are designed to help you choose the appropriate math option for your needs when you build a library using SETUP. For more information about SETUP and about building combined libraries, see %@AI@%Installing and Using the Microsoft C Professional Development %@AI@%System%@AE@%.%@CR:C6A00040054 @% %@NL@% %@NL@% Note that this chapter does not describe mode-specific libraries. For simplicity, the base names of libraries are noted in their default form; that is %@AI@%m%@AE@%LIBC%@AI@%f%@AE@%.LIB, where %@AI@%m%@AE@% is the model designator and %@AI@%f%@AE@% is the floating-point math package designator. For information about mode-specific libraries, see Chapter 14, "Building OS/2 Applications," or %@AI@%Installing and %@AI@%Using the Microsoft C Professional Development System%@AE@%. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00040055 @%%@AB@%4.3.1 Emulator Package%@CR:C6A00040056 @%%@CR:C6A00040057 @%%@AE@%%@EH@%%@NL@% %@NL@% Programs created using the emulator math package automatically detect and use an 80%@AI@%x%@AE@%87 numeric coprocessor if one is installed. If no coprocessor is installed, these 80%@AI@%x%@AE@%87 instructions are carried out in software. The emulator package is the default math package; SETUP uses it if you do not explicitly choose another package. Also, the emulator math option is the option selected by default by the compiler if no other floating-point math option is specified.%@CR:C6A00040058 @%%@CR:C6A00040059 @%%@CR:C6A00040060 @% %@NL@% %@NL@% Use the emulator math package to maximize accuracy on systems without math coprocessors or if your program will be run on some systems with coprocessors and some systems without coprocessors.%@CR:C6A00040061 @% %@NL@% %@NL@% The emulator package performs basic operations to the same degree of accuracy as a math coprocessor. However, the emulator routines used for transcendental math functions (such as %@AB@%sin%@AE@%, %@AB@%cos%@AE@%, %@AB@%tan%@AE@%) differ slightly from the corresponding functions performed on a coprocessor. This difference can cause a slight discrepancy (usually within two bits) between the results of these operations when performed with the software emulation instead of with a math coprocessor.%@CR:C6A00040062 @% %@NL@% %@NL@% %@AU@% When you use the emulator package, some floating-point exceptions are %@AU@%masked.%@CR:C6A00040063 @%%@AE@% %@NL@% %@NL@% When you use a math coprocessor or the emulator floating-point math package, interrupt-enable, precision, underflow, and denormalized-operand exceptions are masked by default. The remaining floating-point exceptions are unmasked. See the discussion of the %@AB@%_control87%@AE@% function in on-line help for more information about 80%@AI@%x%@AE@%87 floating-point exceptions.%@CR:C6A00040064 @%%@CR:C6A00040065 @%%@CR:C6A00040066 @%%@CR:C6A00040067 @%%@CR:C6A00040068 @%%@CR:C6A00040069 @% %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00040070 @%%@AB@%4.3.2 Math Coprocessor Package%@CR:C6A00040071 @%%@CR:C6A00040072 @%%@AE@%%@EH@%%@NL@% %@NL@% The math coprocessor package utilizes the 80%@AI@%x%@AE@%87 math coprocessor exclusively for floating-point calculations. If you use the math coprocessor package, the machine on which your application is to run must have an 80%@AI@%x%@AE@%87 coprocessor to perform floating-point operations. This package gives you the fastest, smallest programs possible for handling floating-point math.%@CR:C6A00040073 @%%@CR:C6A00040074 @% %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00040075 @%%@AB@%4.3.3 Alternate Math Package%@CR:C6A00040076 @%%@CR:C6A00040077 @%%@CR:C6A00040078 @%%@CR:C6A00040079 @%%@AE@%%@EH@%%@NL@% %@NL@% The alternate math package gives you the smallest and fastest programs possible without a coprocessor. However, the program results are not as accurate as results given by the emulator package. %@NL@% %@NL@% The alternate math package uses the same format as the IEEE standard-format numbers with less precision and weaker error checking. The alternate math package does not support infinities, NANs ("not a number"), and denormal numbers.%@CR:C6A00040080 @%%@CR:C6A00040081 @%%@CR:C6A00040082 @%%@CR:C6A00040083 @%%@CR:C6A00040084 @% %@NL@% %@NL@% You must always use the alternate math package when developing routines that are to be placed in an OS/2 dynamic-link library (DLL) using LLIBCDLL.LIB. Do not, however, use the alternate math package for building the C run-time DLL using CDLLOBJS.LIB; instead, use the emulator math package. For more information about creating dynamic-link libraries for OS/2, see Chapter 16.%@CR:C6A00040085 @%%@CR:C6A00040086 @% %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00040087 @%%@AB@%4.4 Selecting Floating-Point Options (/FP)%@AE@%%@EH@%%@NL@% %@NL@% You can select a floating-point library and the method of accessing floatingpoint routines by setting options in PWB or by specifying command-line options to CL. You can choose between the emulator, alternate, or math coprocessor library. You can also access the floating-point routines by issuing a function call (or calls) or by generating in-line 80%@AI@%x%@AE@%87 instructions to execute the floating-point operation. The smallest and the fastest floating-point math option is the in-line math coprocessor package because the compiler generates true 80%@AI@%x%@AE@%87 coprocessor instructions. If, however, you cannot depend on the target computer having a coprocessor, you must use either the emulator or alternate math options.%@CR:C6A00040088 @%%@CR:C6A00040089 @%%@CR:C6A00040090 @% %@NL@% %@NL@% To specify floating-point options on the CL command line, you must specify an option from the list in Table 4.4. You specify these options to CL starting with the floating-point option string /FP. %@NL@% %@NL@% Based on the floating-point option and the memory-model option you choose, the compiler embeds a library name in the object file that it creates. This library is then considered the default library; that is, the linker searches in the standard places for a library with that name. If it finds a library with that name, the linker uses the library to resolve external references in the object file being linked. Otherwise, it displays a message indicating that it could not find the library. %@NL@% %@NL@% This mechanism allows the linker to automatically link object files with the appropriate library. However, you can link with a different library in some cases. See Table 4.4 and Section 4.5, "Library Considerations for Floating-Point Options," for more information about linking with different libraries. %@NL@% %@NL@% Table 4.4 summarizes the floating-point options and their effects. These options are described in detail in the following sections. %@NL@% %@NL@% %@AB@%Table 4.4 %@AB@%Summary of Floating-Point Options%@AE@%%@AE@% %@TH: 51 3718 03 23 15 15 21 17 @%Option for CL for PWB Combined Use Libraries of Method Effect Coprocessor Selected%@AB@%───────────────────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%/FPi In-line Default; Uses coprocessor if %@AI@%m%@AE@%LIBCE.LIB%@AU@%(2)%@AE@%In-Line larger than present%@AU@%(1)%@AE@% Emulation /FPi87, but can work without a coprocessor; most efficient way to get maximum precision without a coprocessor /FPi87 In-line Smallest and Requires %@AI@%m%@AE@%LIBC7.LIBIn-Line Math fastest coprocessor Coprocessor option available with a coprocessor /FPc Calls Slower than Uses coprocessor if %@AI@%m%@AE@%LIBCE.LIB%@AU@%(2,3)%@AE@%Calls to /FPi, but present%@AU@%(1)%@AE@% Emulator allows use of alternate math library at link time /FPc87 Calls Slower than Requires %@AI@%m%@AE@%LIBC7.LIB%@AU@%(3,4)%@AE@%Calls to Math /FPi87, but coprocessor unless Coprocessor allows use of library changed at alternate link time%@AU@%(5)%@AE@% math library at link time /FPa Calls Fastest and Ignores %@AI@%m%@AE@%LIBCA.LIB%@AU@%(2,4)%@AE@%Alternate Math smallest coprocessor option available without a coprocessor, but sacrifices some accuracy for speed %@AB@%───────────────────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@TE: 51 3718 03 23 15 15 21 17 @% %@AU@%(1) %@AE@% Use of the coprocessor can be suppressed by setting NO87. %@AU@%(2) %@AE@% Can be linked explicitly with %@AI@%m%@AE@%LIBC7.LIB at link time. %@AU@%(3) %@AE@% Can be linked explicitly with %@AI@%m%@AE@%LIBCA.LIB at link time. %@AU@%(4) %@AE@% Can be linked explicitly with %@AI@%m%@AE@%LIBCE.LIB at link time. %@AU@%(5) %@AE@% Use of the coprocessor can be suppressed by setting NO87 if you change to the emulator library at link time. %@NL@% %@NL@% %@NL@% Optimizations such as constant propagation and constant subexpression elimination can cause some expressions to be evaluated at compile time. Such evaluations always use IEEE format and are unaffected by the floating-point option you choose. For more information about optimizing, see Chapter 1, "Optimizing C Programs."%@CR:C6A00040091 @%%@CR:C6A00040092 @%%@CR:C6A00040093 @% %@NL@% %@NL@% %@AU@% You can specify floatingpoint options in the Programmer's WorkBench.%@AE@% %@NL@% %@NL@% To specify floating-point options when using the Programmer's WorkBench, you must modify the C Global Build Options (available on the Options menu). In the C Global Build Options dialog box, select one of the following floating-point math options:%@CR:C6A00040094 @%%@CR:C6A00040095 @%%@CR:C6A00040096 @% %@NL@% %@NL@% %@AB@%Option%@AE@% %@AB@%Effect%@AE@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% Emulation Calls %@CR:C6A00040097 @% Generates calls; makes emulator math library the default (/FPc) 80%@AI@%x%@AE@%87 Calls %@CR:C6A00040098 @% Generates calls; makes math coprocessor library the default (/FPc87) Fast Alternate Math %@CR:C6A00040099 @% Generates calls; makes alternate math library the default (/FPa) Inline Emulation %@CR:C6A00040100 @% Generates in-line instructions; makes emulator math library the default (/FPi); this is the default option Inline 80x87 Generates in-line instructions; selects Instructions %@CR:C6A00040101 @% math coprocessor library (/FPi87) %@NL@% %@3@%%@CR:C6A00040102 @%%@AB@%4.4.1 In-Line Emulator Option (/FPi)%@CR:C6A00040103 @%%@CR:C6A00040104 @%%@CR:C6A00040105 @%%@AE@%%@EH@%%@NL@% %@NL@% The in-line emulator option (/FPi) generates in-line instructions for an 80%@AI@%x%@AE@%87 coprocessor and places the name of the emulator library (%@AI@%m%@AE@%LIBCE.LIB) in the object file. At link time, you can specify the math coprocessor library (%@AI@%m%@AE@%LIBC7.LIB) instead. If you do not choose a floating-point option, the compiler uses the in-line emulator option by default.%@CR:C6A00040106 @% %@NL@% %@NL@% The in-line emulator option is useful if you cannot be sure that an 80%@AI@%x%@AE@%87 coprocessor will be available on the target computer. Programs compiled using the in-line emulator option work as described below: %@NL@% %@NL@% %@NL@% ■ If a coprocessor is present at run time, the program uses the coprocessor.%@NL@% %@NL@% ■ If no coprocessor is present, the program uses the emulator. In this case, the in-line emulator option offers the most efficient way to get maximum precision in floating-point results.%@NL@% %@NL@% %@NL@% When you use the in-line emulator option, the compiler does not generate in-line 80%@AI@%x%@AE@%87 instructions. For real-mode code, the compiler generates software interrupts to library code, which then fixes up the interrupts to use either the emulator or the coprocessor, depending on whether a coprocessor is present. For protected-mode code, the compiler generates no such interrupts; it generates 80%@AI@%x%@AE@%87 instructions. If the target computer does not have a coprocessor, an "unsupported extension" exception occurs, which is vectored to library code. If you want true in-line 80%@AI@%x%@AE@%87 instructions, use the in-line math coprocessor option (/FPi87). %@NL@% %@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% NOTE %@AI@%In an OS/2 dynamic-link library built with LLIBCDLL.LIB, you cannot use code %@AI@%that requires the emulator library. You must use the alternate math library %@AI@%instead.%@CR:C6A00040107 @%%@AE@%%@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00040108 @%%@AB@%4.4.2 In-Line Math Coprocessor Instructions Option (/FPi87)%@CR:C6A00040109 @%%@CR:C6A00040110 @%%@CR:C6A00040111 @%%@AE@%%@EH@%%@NL@% %@NL@% The in-line math coprocessor instructions option (/FPi87) instructs the compiler to place 80%@AI@%x%@AE@%87 coprocessor instructions in your code for many math operations. It also causes the name of a math coprocessor library (%@AI@%m%@AE@%LIBC7.LIB) to be embedded in the object file.%@CR:C6A00040112 @% %@NL@% %@NL@% If you use the in-line math coprocessor instructions option and link with the library %@AI@%m%@AE@%LIBC7.LIB, an 80%@AI@%x%@AE@%87 coprocessor must be present at run time, or the program fails and the following error message is displayed: %@NL@% %@NL@% %@AS@% run-time error R6002 %@AS@% - floating point not loaded%@AE@%%@NL@% %@NL@% Compiling with the in-line math coprocessor instructions option results in the smallest, fastest programs possible for handling floating-point results.%@CR:C6A00040113 @%%@CR:C6A00040114 @% %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00040115 @%%@AB@%4.4.3 Calls to Emulator Option (/FPc)%@CR:C6A00040116 @%%@CR:C6A00040117 @%%@AE@%%@EH@%%@NL@% %@NL@% The calls to emulator option (/FPc) generates floating-point calls to the emulator library and places the names of an emulator library (%@AI@%m%@AE@%LIBCE.LIB) in the object file. At link time, you can specify a math coprocessor library (%@AI@%m%@AE@%LIBC7.LIB) or an alternate math library (%@AI@%m%@AE@%LIBCA.LIB) instead. Thus, the calls to emulator option gives you more flexibility in the libraries you can use for linking than the in-line emulator option. %@NL@% %@NL@% Using the calls to emulator option is also recommended in the following cases: %@NL@% %@NL@% %@NL@% ■ If you compile modules that perform floating-point operations and plan to include these modules in a library%@CR:C6A00040118 @%%@NL@% %@NL@% ■ If you compile modules that you want to link with libraries other than the libraries provided with Microsoft C%@CR:C6A00040119 @%%@NL@% %@NL@% %@NL@% You cannot link with an alternate math library if your program uses the intrinsic forms of floating-point library routines (that is, if you have compiled the program with the /Oi or /Ox option, selected the Generate Intrinsic Functions option from the Debug Build Options or Release Build Options dialog box in the Programmer's WorkBench, or specified math functions in an %@AB@%intrinsic%@AE@% pragma). %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00040120 @%%@AB@%4.4.4 Calls to Math Coprocessor Option (/FPc87)%@CR:C6A00040121 @%%@CR:C6A00040122 @%%@AE@%%@EH@%%@NL@% %@NL@% The calls to math coprocessor option (/FPc87) generates function calls to routines in the math coprocessor library (%@AI@%m%@AE@%LIBC7.LIB) that issue the corresponding 80%@AI@%x%@AE@%87 instructions. As with the in-line math coprocessor instructions option (/FPi87), at link time you can choose to link with an emulator library (%@AI@%m%@AE@%LIBCE.LIB). However, /FPc offers more flexibility in choosing libraries, since you can change your mind and link with the appropriate alternate math library as well (%@AI@%m%@AE@%LIBCA.LIB). %@NL@% %@NL@% The disadvantages of using the calls to math coprocessor option as opposed to the in-line coprocessor option are the following: %@NL@% %@NL@% %@NL@% ■ Your executable size is larger because a call requires more instructions than a true coprocessor instruction.%@CR:C6A00040123 @%%@NL@% %@NL@% ■ Your program does not execute as fast because you must issue a function call for each floating-point operation.%@CR:C6A00040124 @%%@NL@% %@NL@% %@NL@% You cannot link with an alternate math library if your program uses the intrinsic forms of floating-point library routines (that is, if you have compiled the program with the /Oi or /Ox option, selected the Generate Intrinsic Functions option from the Debug Build Options or Release Build Options dialog box in the Programmer's WorkBench, or specified math functions in an %@AB@%intrinsic%@AE@% pragma). %@NL@% %@NL@% You must have a math coprocessor installed to run programs compiled with the /FPc option and linked with a math coprocessor library. Otherwise, the program fails and the following error message is displayed: %@NL@% %@NL@% %@AS@% run-time error R6002 %@AS@% - floating point not loaded%@AE@%%@NL@% %@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% NOTE %@AI@%Certain optimizations are not performed when you use the calls to math %@AI@%coprocessor option. This can reduce the efficiency of your code; also, since %@AI@%arithmetic of different precision can result, there may be slight %@AI@%differences in your results.%@CR:C6A00040125 @%%@AE@%%@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00040126 @%%@AB@%4.4.5 Use Alternate Math Option (/FPa)%@CR:C6A00040127 @%%@CR:C6A00040128 @%%@CR:C6A00040129 @%%@AE@%%@EH@%%@NL@% %@NL@% The use alternate math option (/FPa) generates floating-point calls and selects the alternate math library for the appropriate memory model (%@AI@%m%@AE@%LIBCA.LIB). Calls to this library provide the fastest and smallest option for code intended to run on a machine without an 80%@AI@%x%@AE@%87 coprocessor. With this option, you can choose an emulator library (%@AI@%m%@AE@%LIBCE.LIB) or a math coprocessor library (%@AI@%m%@AE@%LIBC7.LIB) at link time.%@CR:C6A00040130 @%%@CR:C6A00040131 @% %@NL@% %@NL@% You cannot link with an alternate math library if your program uses the intrinsic forms of floating-point library routines (that is, if you have compiled the program with the /Oi or /Ox option, selected the Generate Intrinsic Functions from the Debug Build Options or Release Build Options dialog box in the Programmer's WorkBench, or specified math functions in an %@AB@%intrinsic%@AE@% pragma). %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00040132 @%%@AB@%4.5 Library Considerations for Floating-Point Options%@CR:C6A00040133 @%%@AE@%%@EH@%%@NL@% %@NL@% You may want to use libraries in addition to the default library for the floating-point option you have chosen in your compile options. For example, you may want to create your own libraries (or other collections of subprograms in object-file form), then link these libraries at a later time with object files that you have compiled using different options. %@NL@% %@NL@% The following sections describe these cases and ways to handle them. Although the discussion assumes that you are putting your object files into libraries, the same considerations apply if you are simply using individual object files. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00040134 @%%@AB@%4.5.1 Using One Standard Library for Linking%@AE@%%@EH@%%@NL@% %@NL@% You must use only one standard C run-time library when you link. You can control which library is used in one of two ways: %@NL@% %@NL@% %@NL@% 1. In the Programmer's WorkBench, add the name of the C run-time library file you want to the program list using the Edit Program List option from the Make menu. You must also modify the Linker Options (from the Make menu) by specifying No Default Library Search.%@NL@% %@NL@% 2. From the LINK command line, give the /NODEFAULTLIBRARYSEARCH (/NOD) option and then specify the name of the combined library file you want to use in the %@AI@%link-libinfo%@AE@% field of the CL command line. This overrides the library names embedded in the object files.%@NL@% %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00040135 @%%@AB@%4.5.2 In-Line Instructions or Calls%@CR:C6A00040136 @%%@CR:C6A00040137 @%%@AE@%%@EH@%%@NL@% %@NL@% When deciding on a floating-point option, you should decide whether you want to use in-line instructions. If you do, compile with the in-line math coprocessor instructions (/FPi87) or in-line emulator (/FPi) option. Otherwise, compile for floating-point function calls using the calls to math coprocessor (/FPc87), calls to emulator (/FPc), or alternate math (/FPa) option. %@NL@% %@NL@% If you choose to use in-line instructions for your precompiled object files, you cannot link with an alternate math library (%@AI@%m%@AE@%LIBCA.LIB). However, in-line instructions achieve the best performance from your programs on machines that have an 80%@AI@%x%@AE@%87 coprocessor installed.%@CR:C6A00040138 @% %@NL@% %@NL@% If you choose to use calls, your programs are slower, but at link time you can switch to any standard C run-time library (that is, any library created by the SETUP program) that supports the memory model you have chosen. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00040139 @%%@AB@%4.6 Compatibility between Floating-Point Options%@CR:C6A00040140 @%%@AE@%%@EH@%%@NL@% %@NL@% Each time you compile a source file, you can specify a floating-point option. When you link two or more source files to produce an executable program file, you must ensure that floating-point operations are handled consistently and that the environment is set up properly to allow the linker to find the required library. %@NL@% %@NL@% If you are building libraries of C routines that contain floating-point operations, the calls to emulator option (/FPc) provides the most flexibility.%@CR:C6A00040141 @%%@CR:C6A00040142 @% %@NL@% %@NL@% The examples that follow illustrate how you can link your program with a library other than the default. The floating-point option and the substitute library are compatible. %@NL@% %@NL@% The example below compiles the program %@AS@% CALC.C %@AE@% with the medium-model option (/AM). Because no floating-point option is specified, the default in-line emulator option (/FPi) is used. The in-line emulator option generates 80%@AI@%x%@AE@%87 instructions and specifies the emulator library MLIBCE.LIB in the object file. The /LINK field specifies the /NODEFAULTLIBRARYSEARCH (/NOD) option and the names of the medium-model math coprocessor library. Specifying the math coprocessor library forces the program to use an 80%@AI@%x%@AE@%87 coprocessor; the program fails if a coprocessor is not present. %@NL@% %@NL@% %@AS@% CL /AM CALC.C /link MLIBC7 /NOD%@AE@%%@NL@% %@NL@% The example below compiles %@AS@% CALC.C %@AE@% using the small (default) memory model and the alternate math option (/FPa). The /LINK field specifies the /NOD option and the library SLIBCE.LIB. Specifying the emulator library causes all floating-point calls to refer to the emulator library instead of the alternate math library. %@NL@% %@NL@% %@AS@% CL /FPa CALC.C /link SLIBCE /NOD%@AE@%%@NL@% %@NL@% The example below compiles %@AS@% CALC.C %@AE@% with the calls to math coprocessor option (/FPc87), which places the library name SLIBC7.LIB in the object file. The /LINK field overrides this default-library specification by giving the /NOD option and the name of the small-model alternate math library (SLIBCA.LIB). %@NL@% %@NL@% %@AS@% CL /FPc87 CALC.C /link SLIBCA.LIB/NOD%@AE@%%@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00040143 @%%@AB@%4.7 Using the NO87 Environment Variable%@CR:C6A00040144 @%%@CR:C6A00040145 @%%@AE@%%@EH@%%@NL@% %@NL@% Programs compiled using either the calls to emulator (/FPc) or the in-line emulator (/FPi) option automatically use an 80%@AI@%x%@AE@%87 coprocessor at run time if one is installed. You can override this and force the use of the software emulator by setting an environment variable named NO87.%@CR:C6A00040146 @%%@CR:C6A00040147 @%%@CR:C6A00040148 @%%@CR:C6A00040149 @%%@CR:C6A00040150 @%%@CR:C6A00040151 @% %@NL@% %@NL@% %@AU@% Use the NO87 environment variable to suppress use of the 80x87 coprocessor %@AU@%at run time.%@AE@% %@NL@% %@NL@% If NO87 is set to any value when the program is executed, use of the coprocessor is suppressed. The value of the NO87 setting is printed on the standard output as a message. The message is printed only if a coprocessor is present and suppressed; if no coprocessor is present, no message appears. If you don't want a message to be printed, set NO87 equal to one or more spaces. A blank string for NO87 causes a blank line to be printed. %@NL@% %@NL@% Note that only the presence or absence of the NO87 definition is important in suppressing use of the coprocessor. The actual value of the NO87 setting is used only for printing the message. %@NL@% %@NL@% The NO87 variable takes effect with any program linked with an emulator library (%@AI@%m%@AE@%LIBCE.LIB). It has no effect on programs linked with math coprocessor libraries (%@AI@%m%@AE@%LIBC7.LIB) or programs linked with alternate math libraries (%@AI@%m%@AE@%LIBCA.LIB). %@NL@% %@NL@% When a program that uses an emulator library is executed and an 80%@AI@%x%@AE@%87 coprocessor is present, the example below causes the message %@AS@% Use of %@AS@%coprocessor suppressed %@AE@% to appear. %@NL@% %@NL@% %@AS@% SET NO87=Use of coprocessor suppressed%@AE@%%@NL@% %@NL@% The syntax below sets the NO87 variable to the space character. Use of the coprocessor is still suppressed, but no message is displayed. %@NL@% %@NL@% %@AS@% SET NO87=space%@AE@%%@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00040152 @%%@AB@%4.8 Incompatibility Issues%@CR:C6A00040153 @%%@AE@%%@EH@%%@NL@% %@NL@% The exception handler in the libraries for 80%@AI@%x%@AE@%87 floating-point calculations (%@AI@%m%@AE@%LIBCE.LIB and %@AI@%m%@AE@%LIBC7.LIB) is designed to work without modification on the IBM PC family of computers and on closely compatible computers, including the WANG(R) PC, the AT&T(R) 6300, and the Olivetti(R) personal computers. Also, the libraries need not be modified for the Texas Instruments(R) Professional Computer, even though it is not compatible. Any machine that uses nonmaskable interrupts (NMI) for 80%@AI@%x%@AE@%87 exceptions will run with the unmodified libraries. If your computer is not one of these, and if you are not sure whether it is completely compatible, you may need to modify the math coprocessor libraries.%@CR:C6A00040154 @% %@NL@% %@NL@% All Microsoft languages that support 80%@AI@%x%@AE@%87 coprocessors intercept 80%@AI@%x%@AE@%87 exceptions in order to produce accurate results and properly detect error conditions. To make the libraries work correctly on incompatible machines, you can modify the libraries. To make this easier, an assembly-language source file, EMOEM.ASM, is included on the C 6.0 distribution disk. Any machine that sends the 80%@AI@%x%@AE@%87 exception to an 8259 Priority Interrupt Controller (master or master/slave) can be supported by a simple table change to the EMOEM.ASM module. The source file contains further instructions about how to modify EMOEM.ASM, patch libraries, and executable files.%@CR:C6A00040155 @% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@CR:C6A-Part 02 @%%@1@%%@AB@%PART II Improving Programmer Productivity%@AE@%%@EH@%%@NL@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@NL@% The Microsoft C Professional Development System helps you write and debug software rapidly. %@NL@% %@NL@% Chapter 5 describes the quick compile and incremental compile options, both of which can save you time when compiling programs. Chapter 5 also describes the incremental linker, ILINK, which can save you time when you link your application. Chapter 6 describes NMAKE, a powerful new program maintenance utility that automates your program build process. Chapter 7 describes how to build help files with HELPMAKE, the help-file maintenance utility. When you need to share documentation in a readily accessible form, you can add it to the Microsoft Advisor on-line help system using the information in Chapter 7. Chapter 8 explains how to customize the Programmer's WorkBench to make it a personalized development platform. Chapter 9 offers procedures (and some tips) for using the CodeView debugger to find errors in your programs. %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@CR:C6A00050001 @%%@1@%%@AB@%Chapter 5 Compiling and Linking Quickly%@AE@%%@EH@%%@NL@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@NL@% The fundamental processes of compiling and linking take time to perform. The larger your application grows, the longer it takes to compile and link. %@NL@% %@NL@% This chapter describes how you can speed up compiling by using the quick compiler and incremental compile option, and how you can speed up linking by using ILINK, the Incremental Linker. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00050002 @%%@AB@%5.1 Compiling Quickly%@AE@%%@EH@%%@NL@% %@NL@% This section describes two ways to speed up the compiling process: using the quick compiler and using the incremental compile option. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00050003 @%%@AB@%5.1.1 Quick Compiler%@AE@%%@EH@%%@NL@% %@NL@% The Microsoft C Professional Development System includes two separate C compilers: the full compiler and the quick compiler. If you don't specify otherwise, your program is compiled by the full compiler. %@NL@% %@NL@% You access the quick compiler by specifying the /qc command-line option for CL or by selecting the Quick Compile option from the C Release Build or C Debug Build Options dialogs in the PWB Options menu. %@NL@% %@NL@% The quick compiler cannot perform as many optimizations as the full compiler, but it is much faster. You can use it to save time during development, whenever optimizations are not critical. When your application is finished, you can compile with the full compiler, using all the desired optimizations. %@NL@% %@NL@% On-line help for the /qc option describes which optimizations the quick compiler can perform. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00050004 @%%@AB@%5.1.2 Incremental Compile Option%@AE@%%@EH@%%@NL@% %@NL@% You can speed up compiling even more by compiling incrementally. Incremental compilation means that the compiler compiles only those functions that have changed since you last compiled. %@NL@% %@NL@% The incremental compile option is available only with the quick compiler (see the previous section). You can access it from within PWB or from the DOS command line. Within PWB, select the Incremental Compile option in the C Release Build dialog box or in the C Debug Build Options dialog box. From the DOS command line, specify the /Gi option for CL. %@NL@% %@NL@% The incremental compile option automatically triggers another time-saving feature: the Incremental Linker, which is described in the next section. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00050005 @%%@AB@%5.2 Linking Quickly with ILINK%@AE@%%@EH@%%@NL@% %@NL@% %@AU@% ILINK links only those modules that have changed since the last link.%@AE@% %@NL@% %@NL@% The Incremental Linker (ILINK) offers the same advantage in linking that the incremental compile option offers in compiling. Rather than link every module in an application, as LINK does, ILINK links only those modules that have changed since the last link. The more modules your application contains, the more time ILINK can potentially save. %@NL@% %@NL@% In a normal development scenario, you use LINK at the beginning and end of the process, and use ILINK in the middle. In the early stages of development, when your application contains only a few modules, ILINK offers no speed advantage over LINK. Once your application contains several modules, you can save time by using ILINK. %@NL@% %@NL@% %@AU@% You must link once with LINK to prepare for incremental linking.%@AE@% %@NL@% %@NL@% To prepare for incremental linking, you must run LINK using /INCREMENTAL, as described in Section 5.2.1. At the same time, you have the option of adding padding bytes to code or data segments by specifying the /PADCODE and /PADDATA options. Padding allows ILINK to expand a segment without relinking the entire module in which it is contained. %@NL@% %@NL@% Now you can link with ILINK during the rest of development. If changes in your code require a full link, ILINK invokes LINK automatically. When the application is finished, you link a last time with LINK to produce the final executable file. %@NL@% %@NL@% You can use ILINK with programs compiled for any memory model except tiny model. (Memory models are described in Chapter 2, "Managing Memory.") Typically, ILINK is not efficient for small- or compact-model programs unless they were compiled with the incremental compile option, which is described in Section 5.1.2. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00050006 @%%@AB@%5.2.1 Preparing for Incremental Linking%@AE@%%@EH@%%@NL@% %@NL@% There are three LINK options that relate to the use of ILINK. One of them (/INCREMENTAL) is mandatory; the other two (/PADCODE and /PADDATA) are optional. This section explains the LINK options that prepare for ILINK. See on-line help for a complete list of LINK options. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%The /INCREMENTAL Option%@AE@%%@EH@%%@NL@% %@NL@% The /INCREMENTAL (/INC) option prepares an object file for incremental linking. You must always run LINK using this option before using ILINK. When you specify /INC, the linker produces two extra files: a symbol file (.SYM) and an ILINK support file (.ILK). The .SYM and .ILK files tell ILINK which parts of the executable file need to be updated. %@NL@% %@NL@% You must use /INCREMENTAL whenever you use the /PADCODE and /PADDATA options, which are described below. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%The /PADCODE Option%@AE@%%@EH@%%@NL@% %@NL@% The /PADCODE option causes LINK to add padding bytes at the end of a module's code segment. The padding bytes leave room for the code segment to grow in subsequent links, allowing ILINK to update only that module. You can use the /PADCODE option only when /INC is also specified. %@NL@% %@NL@% Code padding is usually necessary for programs using the small memory model. It is also recommended for compact- or mixed-model programs. You do not need to specify /PADCODE for other memory models (medium, large, or huge).%@CR:C6A00050007 @%%@CR:C6A00050008 @% %@NL@% %@NL@% If you don't specify /PADCODE, LINK doesn't pad the code segment at all. To add padding, specify the desired number of bytes. The optimum amount of padding depends on how much your code changes from one link to the next. If you expect to add only a little code, choose a relatively%@CR:C6A00050009 @% small amount of padding, say 32 to 64 bytes. If ILINK issues the message %@NL@% %@NL@% %@AS@% padding exceeded%@AE@%%@NL@% %@NL@% and performs a full link more often than desired, increase the padding by a small amount, say 32 bytes. In any case, remember that the total size of a code segment, including padding bytes, cannot exceed 64K (65,535) bytes. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%The /PADDATA Option%@AE@%%@EH@%%@NL@% %@NL@% Like /PADCODE, the /PADDATA option causes LINK to add padding bytes that leave room for the segment to grow in subsequent links. However, the /PADDATA option pads the end of the data segment rather than the code segment. You can use /PADDATA only when /INC is also specified. %@NL@% %@NL@% If you don't specify /PADDATA, LINK adds 16 bytes of padding by default. The default padding amount should suffice in many cases, since public variables are added less frequently than code. If you need more padding, specify the desired number of bytes. Remember that the total size of a data segment, including padding bytes, cannot exceed 64K (65,535) bytes. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00050010 @%%@AB@%5.2.2 Incremental Violations%@AE@%%@EH@%%@NL@% %@NL@% ILINK can generate two kinds of errors: real errors and incremental violations. Real errors are errors such as undefined symbols that cannot be resolved by a full link. If ILINK detects a real error, it displays an error message (real errors are documented in on-line help). %@NL@% %@NL@% Incremental violations are caused by code changes you have made that go beyond the scope of incremental linking. When an incremental violation occurs, ILINK invokes LINK automatically. The following sections describe the incremental violations. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Changing Libraries%@AE@%%@EH@%%@NL@% %@NL@% An incremental violation occurs when a library changes. Furthermore, if an altered module shares a code segment with a library, ILINK needs access to the library as well as to the altered module. %@NL@% %@NL@% If you add a function, procedure, or subroutine call to a library that has never been called before, ILINK invokes LINK automatically. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Exceeding Code/Data Padding%@AE@%%@EH@%%@NL@% %@NL@% An incremental violation occurs if two or more modules contribute to the same physical segment and either module exceeds its padding. The padding allows the module to increase the specified number of bytes before another full link is required. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Moving or Deleting Data Symbols%@AE@%%@EH@%%@NL@% %@NL@% An incremental violation occurs if a data symbol is moved or deleted. To add new data symbols without requiring a full link, add the new symbols at the end of all other data symbols in the module. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Deleting Code Symbols%@AE@%%@EH@%%@NL@% %@NL@% You can move or add code symbols, but an incremental violation occurs if you delete any code symbols from a module. Code symbols can be moved within a module but cannot be moved between modules. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Changing Segment Definitions%@AE@%%@EH@%%@NL@% %@NL@% An incremental violation results if you add, delete, or change the order of segment definitions. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Adding CodeView(R) Debugger Information%@AE@%%@EH@%%@NL@% %@NL@% If you include CodeView debugger information for a module when you fully link (by compiling and linking with CodeView debugger support), ILINK supports CodeView debugger information for the module. ILINK maintains symbolic information for current symbols, and it adds information for any new symbols. However, if you try to add CodeView debugger information for a module that did not previously have CodeView debugger support, an incremental violation occurs. See Chapter 9, "Debugging C Programs with CodeView," for more information about CodeView. %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@CR:C6A00060001 @%%@1@%%@AB@%Chapter 6 Managing Development Projects with NMAKE%@AE@%%@EH@%%@NL@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@NL@% The Microsoft Program-Maintenance Utility (NMAKE) is a sophisticated command processor that can save time and simplify project management. By determining which project files depend on others, NMAKE can automatically execute the commands needed to update your project when any project file has changed. %@NL@% %@NL@% The advantage of using NMAKE over simple batch files is that NMAKE does only what is needed. You don't waste time rebuilding files that are already up-to-date. NMAKE also has advanced features, such as macros, that help you manage complex projects. %@NL@% %@NL@% This chapter provides complete documentation for NMAKE. Information about NMAKE is also available in on-line help. If you are familiar with MAKE, the predecessor of NMAKE, be sure to read Section 6.9, "Differences Between NMAKE and MAKE." There are some important differences between the two utilities. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00060002 @%%@AB@%6.1 Overview of NMAKE%@AE@%%@EH@%%@NL@% %@NL@% NMAKE works by comparing the times and dates of two sets of files, which are called "targets" and "dependents." A target is normally a file that you want to create, such as an executable file. A dependent is a file used to create a target, such as a C source file. %@NL@% %@NL@% When you run NMAKE, it reads a "description file" that you supply. The description file consists of one or more blocks. Each block typically lists a target, the target's dependents, and the command that builds the target. NMAKE compares the date and time of the target to those of its dependents. If any dependent has changed more recently than the target, NMAKE updates the target by executing the command listed in the block. %@NL@% %@NL@% NMAKE's main purpose is to help you update applications quickly and simply. However, it can execute any command, so it is not limited to compiling and linking. NMAKE can also make backups, move files, and do many other project management tasks. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00060003 @%%@AB@%6.2 The NMAKE Command%@AE@%%@EH@%%@NL@% %@NL@% When you run NMAKE, you can supply the description-file name and other arguments using the following syntax: %@NL@% %@NL@% %@AB@%NMAKE%@AE@% «%@AI@%options%@AE@%» «%@AI@%macros%@AE@%» «%@AI@%targets%@AE@%» «%@AI@%descriptfile%@AE@%» %@NL@% %@NL@% All of the command-line fields are optional. If you don't supply any arguments, NMAKE looks for a default description file named MAKEFILE and follows various other defaults that are described in this chapter. %@NL@% %@NL@% The %@AI@%options%@AE@% field lists NMAKE options, which are described in Section 6.4, "Command-Line Options." %@NL@% %@NL@% The %@AI@%macros%@AE@% field lists macro definitions, which allow you to replace text in the description file. Macros are described in Section 6.3.3. %@NL@% %@NL@% The %@AI@%targets%@AE@% field lists targets to build. If you do not list any targets, NMAKE builds only the first target in the description file. (This is a significant departure from the behavior of MAKE, NMAKE's predecessor. See Section 6.9, "Differences between NMAKE and MAKE.") %@NL@% %@NL@% The %@AI@%descriptfile%@AE@% field specifies a description file. If this field is absent, NMAKE automatically looks for a file named MAKEFILE in the current directory. You can also specify the description file with the /F option (for information, see Section 6.4, "Command-Line Options"). %@NL@% %@NL@% Below is a typical NMAKE command: %@NL@% %@NL@% %@AS@% NMAKE /S "program = sample" sort.exe search.exe%@AE@%%@NL@% %@NL@% The command supplies four arguments: an option (/S), a macro definition (%@AS@%"program = sample"%@AE@%), and two target specifications (%@AS@%sort.exe search.exe%@AE@%). %@NL@% %@NL@% Because the command does not specify a description file, NMAKE looks for the default description file, MAKEFILE. The /S option tells NMAKE to suppress the display of commands as they are executed. The macro definition performs a text substitution throughout the description file, replacing every instance of %@AS@% program %@AE@% with %@AS@% sample%@AE@%. The target specifications tell NMAKE to update the targets SORT.EXE and SEARCH.EXE. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00060004 @%%@AB@%6.3 NMAKE Description Files%@AE@%%@EH@%%@NL@% %@NL@% You must always supply NMAKE with a description file. In addition to description blocks, which tell NMAKE how to build your project's target files, the description file can contain comments, macros, inference rules, and directives. This section describes all the elements of description files. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00060005 @%%@AB@%6.3.1 Description Blocks%@AE@%%@EH@%%@NL@% %@NL@% Description blocks form the heart of the description file. Figure 6.1 illustrates a typical NMAKE description block, including the three parts: targets, dependents, and commands. %@NL@% %@NL@% %@AU@%(This figure may be found in the printed book.)%@AE@%%@NL@% %@NL@% %@AU@% A target is a file that you want to build.%@AE@% %@NL@% %@NL@% The targets part of the description block lists one or more files to build. The line that lists targets and dependents is called the "dependency line." %@NL@% %@NL@% The example in Figure 6.1 tells NMAKE to build a single target, MYAPP.EXE. Although single targets are common, you can also list multiple targets; separate each target name with a space. If the rightmost target name is one character long, put a space between the name and the colon. %@NL@% %@NL@% The target is normally a file, but it can also be a "pseudotarget," a name that allows you to build groups of files or execute a group of commands. See Section 6.3.6, "Pseudotargets." %@NL@% %@NL@% %@AU@% A dependent is a file used to build a target.%@AE@% %@NL@% %@NL@% The dependents part of the description block lists one or more files from which the target is built. It is separated from the targets part by a colon. The example in Figure 6.1 lists three dependents: %@NL@% %@NL@% %@AS@% myapp.exe : myapp.obj another.obj myapp.def%@AE@%%@NL@% %@NL@% The example tells NMAKE to build the target MYAPP.EXE whenever MYAPP.OBJ, ANOTHER.OBJ, or MYAPP.DEF has changed more recently than MYAPP.EXE. %@NL@% %@NL@% If any dependents of a target are listed as targets in other description blocks, then NMAKE builds those files before it builds the original target. Essentially NMAKE evaluates a "dependency tree" for the entire description file. It builds files in the order needed to update the original target, never building a target until all files that depend on it are up-to-date. %@NL@% %@NL@% The dependent list can also include a list of directories in which NMAKE should search for dependents. The directory list is enclosed in curly braces ( {} ) and precedes the dependent list. NMAKE searches the current directory first, then the directories you list: %@NL@% %@NL@% %@AS@% forward.exe : {\src\alpha;d:\proj}pass.obj%@AE@%%@NL@% %@NL@% In the line above, the target, FORWARD.EXE, has one dependent: PASS.OBJ. The directory list specifies two directories: %@NL@% %@NL@% %@AS@% {\src\alpha;d:\proj}%@AE@%%@NL@% %@NL@% NMAKE begins searching for PASS.OBJ in the current directory. If it is not found, NMAKE searches the \ SRC \ ALPHA directory, then the D:\ PROJ directory. If NMAKE cannot find a dependent in the current directory or a listed directory, it looks for an inference rule that describes how to create the dependent (see Section 6.3.4, "Inference Rules"). %@NL@% %@NL@% %@AU@% The commands part of a description block can contain one or more %@AU@%commands.%@AE@% %@NL@% %@NL@% The commands part of the description block lists the command(s) NMAKE should use to build the target. This can be any command that you can execute from the command line. The example tells NMAKE to build MYAPP.EXE using the following LINK command: %@NL@% %@NL@% %@AS@% LINK myapp another.obj, /align:16, NUL, os2, myapp%@AE@%%@NL@% %@NL@% Notice that the line above is indented. NMAKE uses indentation to distinguish between the dependency line and command line. If the command appears on a separate line, as here, it must be indented at least one space or tab. The dependency line must not be indented (it cannot start with a space or tab). %@NL@% %@NL@% Many targets are built with a single command, but you can place more than one command after the dependency line. A long command can span several lines if each line ends with a backslash ( \ ). %@NL@% %@NL@% You can also place the command at the end of the dependency line. Separate the command from the rightmost dependent with a semicolon. %@NL@% %@NL@% In OS/2 description files, NMAKE imposes a slight restriction on the use of the CD, CHDIR, and SET commands. Do not place any of these commands on a command line that uses the ampersand (&) to execute multiple commands. For instance, the following command line is legal in an OS/2 description file, %@NL@% %@NL@% %@AS@% DIR & COPY sample.c backup.c%@AE@%%@NL@% %@NL@% but this line is not legal because it places a CD command after the ampersand: %@NL@% %@NL@% %@AS@% DIR & CD \mydir%@AE@%%@NL@% %@NL@% To use CD, CHDIR, or SET in a description block, place the command on a separate line: %@NL@% %@NL@% %@AS@% DIR %@AS@% CD \mydir%@AE@%%@NL@% %@NL@% Your OS/2 user's documentation contains more information about using the ampersand in command lines. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Wild Cards%@AE@%%@EH@%%@NL@% %@NL@% You can use DOS wild-card characters (* and ?) to specify target and dependent file names. NMAKE expands wild cards in target names when it reads the description file. It expands wild cards in the dependent names when it builds the target. For example, the following description block compiles all source files with the .C extension: %@NL@% %@NL@% %@AS@% bondo.exe : *.c %@AS@% CL *.c%@AE@%%@NL@% %@NL@% %@NL@% %@4@%%@AB@%Command Modifiers%@AE@%%@EH@%%@NL@% %@NL@% Command modifiers provide extra control over the command listed in a description block. They are special characters that appear in front of a command. You can use more than one modifier for a single command. Table 6.1 describes the three NMAKE command modifiers. %@NL@% %@NL@% %@AB@%Table %@AB@%6.1 Command Modifiers%@AE@%%@AE@% %@TH: 45 2536 02 34 42 @%Character Action%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%At sign (@) Prevents NMAKE from displaying the command as it executes. In the example below, NMAKE does not display the ECHO command line: %@AS@%sort.exe : sort.obj%@AE@% %@AS@% @ECHO sorting%@AE@% The output of the ECHO command appears as usual.Dash (-) Turns off error checking for the command. If the dash is followed by a number, NMAKE stops only if the error level returned by the command is greater than the number. In the following example, if the program %@AS@% sample %@AE@% returned an error code NMAKE does not stop but continues to execute commands: %@AS@%light.lst : light.txt%@AE@% %@AS@% -sample light.txt%@AE@%Exclamation point (!) Executes the command for each dependent file if the command uses the predefined macros %@AB@%$?%@AE@% or %@AB@%$**%@AE@%. The %@AB@%$?%@AE@% macro refers to all dependent files that are out-of-date with respect to the target. The %@AB@%$**%@AE@% macro refers to all dependent files in the description block (see Section 6.3.3, "Macros"). For example, %@AS@%print:hop.asm skip.bas jump.c%@AE@% %@AS@% !print $** lpt1:%@AE@% generates the following commands: %@AS@%print hop.asm lpt1:%@AE@% %@AS@%print skip.bas lpt1:%@AE@% %@AS@%print jump.c lpt1:%@AE@%%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@TE: 45 2536 02 34 42 @% %@NL@% %@4@%%@AB@%Using Control Characters as Literals%@AE@%%@EH@%%@NL@% %@NL@% Occasionally, you may need to list a file name that contains a character that NMAKE uses as a control character. These characters are %@NL@% %@NL@% # ( ) $ ^ \ { } ! @ - %@NL@% %@NL@% To use an NMAKE control character as a literal character, place a caret (^) in front of it. For example, say that you define a macro that ends with a backslash: %@NL@% %@NL@% %@AS@% exepath=c:\bin\%@AE@%%@NL@% %@NL@% The line above is intended to define a macro named %@AS@% exepath %@AE@% with the value %@AS@% %@AS@%c:\bin\%@AE@%. But the second backslash causes unexpected results. Since the back-slash is the NMAKE line-continuation character, the line actually defines the macro %@AS@% exepath %@AE@% as %@AS@% c:\bin %@AE@% followed by whatever appears on the next line of the description file. You can solve the problem by placing a caret in front of the second backslash: %@NL@% %@NL@% %@AS@% exepath=c:\bin^\%@AE@%%@NL@% %@NL@% You can also use a caret to place a literal newline character in a description file. This feature can be useful in macro definitions: %@NL@% %@NL@% %@AS@% XYZ=abc^ %@AS@% def%@AE@%%@NL@% %@NL@% NMAKE interprets the example as if you assigned the C-style string %@AS@% abc\ndef %@AS@%%@AE@%to the %@AS@% XYZ %@AE@% macro. This effect differs from using the backslash ( \s ) to continue a line. A newline character that follows a backslash is replaced with a space. %@NL@% %@NL@% Carets that precede noncontrol characters are ignored. The line %@NL@% %@NL@% %@AS@% ign^ore : these ca^rets%@AE@%%@NL@% %@NL@% is interpreted as %@NL@% %@NL@% %@AS@% ignore : these carets%@AE@%%@NL@% %@NL@% A caret that appears in quotation marks is treated as a literal caret character. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Listing a Target in Multiple Description Blocks%@AE@%%@EH@%%@NL@% %@NL@% You can specify more than one description block for the same target by placing two colons (::) after the target. This feature can be useful for building a complex target, such as a library, that contains components created with different commands. For example, %@NL@% %@NL@% %@AS@% target.lib :: a.asm b.asm c.asm %@AS@% CL a.asm b.asm c.asm %@AS@% LIB target -+a.obj -+b.obj -+c.obj; %@AS@% target.lib :: d.c e.c %@AS@% CL /c d.c e.c %@AS@% LIB target -+d.obj -+e.obj;%@AE@%%@NL@% %@NL@% Both description blocks update the library named TARGET.LIB. If any of the assembly-language files have changed more recently than the library, NMAKE executes the commands in the first block to assemble the source files and update %@NL@% %@NL@% the library. Similarly, if any of the C-language files have changed, NMAKE executes the second group of commands, which compile the C files and update the library. %@NL@% %@NL@% If you use a single colon in the example above, NMAKE issues an error message. It is legal, however, to use single colons if commands are listed in only one block. In this case, dependency lines are cumulative. For example, %@NL@% %@NL@% %@AS@% target: jump.bas %@AS@% target: up.c %@AS@% echo Building target...%@AE@%%@NL@% %@NL@% is equivalent to %@NL@% %@NL@% %@AS@% target: jump.bas up.c %@AS@% echo Building target...%@AE@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00060006 @%%@AB@%6.3.2 Comments%@AE@%%@EH@%%@NL@% %@NL@% You can place comments in a description file by preceding them with a number sign (#): %@NL@% %@NL@% %@AS@% # This comment appears on its own line %@AS@% huey.exe : huey.obj dewey.obj # Comment on the same line %@AS@% link huey.obj dewey.obj;%@AE@%%@NL@% %@NL@% A comment extends to the end of the line in which it appears. Command lines cannot contain comments. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00060007 @%%@AB@%6.3.3 Macros%@AE@%%@EH@%%@NL@% %@NL@% %@AU@% Macros allow you to do text replacements throughout the description file.%@AE@% %@NL@% %@NL@% Macros offer a convenient way to replace a string in the description file with another string. The text is automatically replaced each time you run NMAKE. Macros are useful in a variety of tasks, including the following: %@NL@% %@NL@% %@NL@% ■ To create a standard description file for several projects. The macro represents the file names used in commands. These file names are then defined when you run NMAKE. When you switch to a different project, you can change file names throughout the description file by changing a single macro.%@NL@% %@NL@% ■ To control the options that NMAKE passes to the compiler or linker. When you specify options in a macro, you can change options throughout the description file in one easy step.%@NL@% %@NL@% %@NL@% You can define your own macros or use predefined macros. This section begins by describing user-defined macros. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%User-Defined Macros%@AE@%%@EH@%%@NL@% %@NL@% You can define a macro with %@NL@% %@NL@% %@AS@% macroname = string%@AE@%%@NL@% %@NL@% The %@AI@%macroname%@AE@% can be any combination of letters, digits, and the underscore ( _ ) character. Macro names are case sensitive. NMAKE interprets %@AS@% MyMacro %@AE@% and %@AS@% MYMACRO %@AE@% as different macro names. %@NL@% %@NL@% The %@AI@%string%@AE@% can be any string, including a null string. For example, %@NL@% %@NL@% %@AS@% command = LINK%@AE@%%@NL@% %@NL@% defines a macro named %@AS@% command %@AE@% and assigns it the string %@AS@% LINK%@AE@%. %@NL@% %@NL@% You can define macros in the description file or on the command line. In the description file, you must define each macro on a separate line; the line cannot start with a space or tab. The %@AI@%string%@AE@% can contain embedded spaces, and NMAKE ignores spaces on either side of the equal sign. You do not need to enclose %@AI@%string%@AE@% in quotation marks (if you do, they become part of the string). %@NL@% %@NL@% Slightly different rules apply when you define a macro on the command line, because of the way that the command line handles spaces. You must enclose %@AI@%string%@AE@% in quotation marks if it contains embedded spaces. No spaces can surround the equal sign. You can also enclose the entire macro definition, %@AI@%macroname%@AE@% and %@AI@%string%@AE@%, in quotation marks. For example, %@NL@% %@NL@% %@AS@% NMAKE "program=sample"%@AE@%%@NL@% %@NL@% defines the macro %@AS@% program%@AE@%, assigning it the value %@AS@% sample%@AE@%. %@NL@% %@NL@% Once you have defined a macro, you can "undefine" it with the !UNDEF directive (see Section 6.3.5, "Directives"). %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Invoking Macros%@AE@%%@EH@%%@NL@% %@NL@% You invoke a macro by enclosing its name in parentheses preceded by a dollar sign ($). (The parentheses are optional if %@AI@%macroname%@AE@% is one character long.) For example, you can invoke the %@AS@% command %@AE@% macro defined above as %@NL@% %@NL@% %@AS@% $(command)%@AE@%%@NL@% %@NL@% When NMAKE runs, it replaces every occurrence of %@AS@% $(command) %@AE@% with %@AS@% LINK%@AE@%. The following description file defines and uses three macros: %@NL@% %@NL@% %@AS@% program = sample %@AS@% c = LINK %@AS@% options = %@AS@% %@AS@% $(program).exe : $(program).obj %@AS@% $c $(options) $(program).obj;%@AE@%%@NL@% %@NL@% NMAKE interprets the description block as %@NL@% %@NL@% %@AS@% sample.exe : sample.obj %@AS@% LINK sample.obj;%@AE@%%@NL@% %@NL@% NMAKE replaces every occurrence of %@AS@% $(program) %@AE@% with %@AS@% sample%@AE@%, every instance of %@AS@% $c %@AE@% with %@AS@% LINK%@AE@%, and every instance of %@AS@% $(options) %@AE@%with a null string. Because %@AS@% c %@AE@% is only one character long, you do not need to enclose it in parentheses. %@NL@% %@NL@% If you invoke a macro that is not defined, NMAKE treats the macro as a null string. %@NL@% %@NL@% Occasionally, you may need to use the dollar sign ($) as a literal character. Use two signs ($$), or precede it with a caret (^$). %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Predefined Macros%@AE@%%@EH@%%@NL@% %@NL@% NMAKE provides several predefined macros, which represent various file names and commands. Predefined macros are useful in their own right, and they are also employed in predefined inference rules, which are described later in this chapter. Table 6.2 lists NMAKE predefined macros. %@NL@% %@NL@% %@AB@%Table %@AB@%6.2 Predefined Macros%@AE@%%@AE@% %@TH: 29 1603 02 34 42 @%Macro Meaning%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%$@ %@AE@% The current target's full name.%@AB@%$* %@AE@% The current target's base name (full name minus the file extension).%@AB@%$** %@AE@% The dependents of the current target.%@AB@%$? %@AE@% The dependents that are out-of-date with respect to the current target.%@AB@%$$@ %@AE@% The target that NMAKE is currently evaluating. You can only use this macro to specify a dependent.%@AB@%$< %@AE@% The dependent file that is out-of-date with respect to the current target (evaluated only for inference rules).%@AB@%$(CC) %@AE@% The command to invoke the C compiler. By default,%@AB@% $(CC)%@AE@% is predefined as %@AS@% CC = cl%@AE@%, which invokes the optimizing compiler.%@AB@%$(AS) %@AE@% The command that invokes the Microsoft Macro Assembler. NMAKE predefines this macro as %@AS@% AS = masm%@AE@%. %@TE: 29 1603 02 34 42 @% %@AB@%Table %@AB@%6.2 (continued)%@AE@%%@AE@% %@TH: 53 3240 02 34 42 @%Macro Meaning%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%$(MAKE) %@AE@% The name with which the NMAKE utility is invoked. This macro is used to invoke NMAKE recursively. It causes the line on which it appears to be executed even if the /N option is on. You can redefine this macro if you want to execute another program. The %@AB@%$(MAKE)%@AE@% macro is useful for building different versions of a program. The following description file invokes NMAKE recursively to build targets in the VERS1 and VERS2 directories. %@AS@%all :vers1 vers2%@AE@% %@AS@%versl :%@AE@% %@AS@% cd versl%@AE@% %@AS@% $(MAKE)%@AE@% %@AS@% cd . .%@AE@% %@AS@%vers2 :%@AE@% %@AS@% cd vers2%@AE@% %@AS@% $(MAKE)%@AE@% %@AS@% cd . .%@AE@% The example changes to the VERS1 directory, then invokes NMAKE recursively, causing NMAKE to process the file MAKEFILE in that directory. Then it changes to the VERS2 directory and invokes NMAKE again, processing the file MAKEFILE in that directory. Deeply recursive build procedures can exhaust NMAKE's run-time stack, causing a run-time error. To eliminate the error, use the EXEHDR utility to increase NMAKE's run-time stack. The following command, for example, gives NMAKE.EXE a stack size of 16,384 (0x4000) bytes: %@AS@%exehdr /stack:0x4000 nmake.exe%@AE@%%@AB@%$(MAKEFLAGS) %@AE@% The NMAKE options currently in effect. If you invoke NMAKE recursively, you should use the command: %@AS@% $(MAKE)%@AE@% %@AS@% %@AE@% %@AS@%$(MAKEFLAGS)%@AE@%. You cannot redefine this macro.%@AB@%$(MAKEDIR) %@AE@% The directory from which NMAKE is invoked.%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@TE: 53 3240 02 34 42 @% Like user-defined macro names, predefined macro names are case sensitive. NMAKE interprets %@AS@% CC %@AE@% and %@AS@% cc %@AE@% as different macro names. %@NL@% %@NL@% %@AU@% Macro modifiers allow you to specify parts of predefined macros %@AU@%representing file names.%@AE@% %@NL@% %@NL@% You can append characters to any of the first six macros in Table 6.2 to modify its meaning. Appending a %@AB@%D%@AE@% specifies the directory part of the file name only, an %@AB@%F%@AE@% specifies the file name, a %@AB@%B%@AE@% specifies just the base name, and an %@AB@%R%@AE@% specifies the complete file name without the extension. If you add one of these characters, you must enclose the macro name in parentheses. (The predefined macros %@AB@%$$@%@AE@% and %@AB@%$**%@AE@% are the only exceptions to the rule that macro names more than one character long must be enclosed in parentheses.) %@NL@% %@NL@% For example, assume that %@AB@%$@%@AE@% has the value C:\ SOURCE \ PROG \ SORT.OBJ. The list below shows the effect of combining the special characters with %@AB@%$@%@AE@%: %@NL@% %@NL@% %@AB@%Macro%@AE@% %@AB@%Value%@AE@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@AB@%$(@D)%@AE@% C:\ SOURCE \ PROG %@AB@%$(@F)%@AE@% SORT.OBJ %@AB@%$(@B)%@AE@% SORT %@AB@%$(@R)%@AE@% C:\ SOURCE \ PROG \ SORT For example, in the code below, the macro %@AB@%$?%@AE@% represents the names of all dependents that are more recent than the target. The exclamation point causes NMAKE to execute the LIB command once for each dependent in the list. As a result, the LIB command is executed up to three times, each time replacing a module with a newer version. %@NL@% %@NL@% %@AS@% trig.lib : sin.obj cos.obj arctan.obj %@AS@% !LIB trig.lib -+$?;%@AE@%%@NL@% %@NL@% In the following example, NMAKE updates a group of include files: %@NL@% %@NL@% %@AS@% # Include files depend on versions in current directory %@AS@% DIR=c:\include %@AS@% $(DIR)\globals.h : globals.h %@AS@% COPY globals.h $@ %@AS@% $(DIR)\types.h : types.h %@AS@% COPY types.h $@ %@AS@% $(DIR)\macros.h : macros.h %@AS@% COPY macros.h $@%@AE@%%@NL@% %@NL@% Each of the files GLOBALS.H, TYPES.H, and MACROS.H in the directory C:\ INCLUDE depends on its counterpart in the current directory. If one of the include files is out-of-date, NMAKE replaces it with the file of the same name from the current directory. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Substitution within Macros%@AE@%%@EH@%%@NL@% %@NL@% Just as macros allow you to substitute text in a description file, you can also substitute text within a macro itself. Use the following form: %@NL@% %@NL@% %@AS@% $(macroname:string1 = string2)%@AE@%%@NL@% %@NL@% %@AU@% You can replace text in a macro, as well as in the description file.%@AE@% %@NL@% %@NL@% Every occurrence of %@AI@%string1%@AE@% is replaced by %@AI@%string2%@AE@% in the macro %@AI@%macroname%@AE@%. Do not put any spaces or tabs between %@AI@%macroname%@AE@% and the colon. Spaces between the colon and %@AI@%string1%@AE@% are made part of %@AI@%string1%@AE@%. If %@AI@%string2%@AE@% is a null string, all occurrences of %@AI@%string1%@AE@% are deleted from the %@AI@%macroname%@AE@% macro. %@NL@% %@NL@% The following description file illustrates macro substitution: %@NL@% %@NL@% %@AS@% SRCS = prog.c sub1.c sub2.c %@AS@% prog.exe : $(SRCS:.c=.obj) %@AS@% LINK $**; %@AS@% %@AS@% DUP : $(SRCS) %@AS@% !COPY $** c:\backup%@AE@%%@NL@% %@NL@% The predefined macro %@AB@%$**%@AE@% stands for the names of all the dependent files (see the previous section). If you invoke the example file with a command line that specifies both targets, NMAKE executes the following commands: %@NL@% %@NL@% %@AS@% LINK prog.obj sub1.obj sub2.obj;%@AE@%%@NL@% %@NL@% %@AS@% COPY prog.c c:\backup %@AS@% COPY sub1.c c:\backup %@AS@% COPY sub2.c c:\backup%@AE@%%@NL@% %@NL@% The macro substitution does not alter the definition of the %@AS@% SRCS %@AE@% macro, rather, it simply replaces the listed characters. When NMAKE builds the target PROG.EXE, it gets the definition for the predefined macro %@AB@%$**%@AE@% (the dependent list) from the dependency line, which specifies the macro substitution in %@AS@% SRCS%@AE@%. The same is true for the second target, %@AS@% DUP%@AE@%. In this case, however, no macro substitution is requested, so %@AS@% SRCS %@AE@% retains its original value, and %@AB@%$**%@AE@% represents the names of the C source files. (In the example above, the target %@AS@% DUP %@AE@% is a pseudotarget; Section 6.3.6 describes pseudotargets.) %@NL@% %@NL@% You can also perform substitution in the following predefined macros: %@AB@%$@%@AE@%, %@AB@%$*%@AE@%, %@AB@%$**%@AE@%, %@AB@%$?%@AE@%, and%@AB@% $%@AE@%. The principle is the same as for other macros. The command in the following description block substitutes within a predefined macro: %@NL@% %@NL@% %@AS@% target.abc : depend.xyz %@AS@% echo $(@:targ=blank)%@AE@%%@NL@% %@NL@% If dependent %@AS@% depend.xyz %@AE@% is out-of-date relative to target %@AS@% target.abc%@AE@%, then NMAKE executes the command %@NL@% %@NL@% %@AS@% echo blanket.abc%@AE@%%@NL@% %@NL@% The example uses the predefined macro %@AB@%$@%@AE@%, which equals the full name of the current target ( %@AS@%target.abc%@AE@%). It substitutes %@AS@% blank %@AE@% for %@AS@% targ %@AE@% in the target, resulting in %@AS@% blanket.abc%@AE@%. Note that you do not put the usual dollar sign in front of the predefined macro. The example uses %@NL@% %@NL@% %@AS@% $(@:targ=blank)%@AE@%%@NL@% %@NL@% instead of %@NL@% %@NL@% %@AS@% $($@:targ=blank)%@AE@%%@NL@% %@NL@% to substitute within the predefined macro %@AB@%$@%@AE@%. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Inherited Macros%@AE@%%@EH@%%@NL@% %@NL@% When NMAKE executes, it creates macros equivalent to every current environment variable. These are called "inherited" macros because they have the same names and values as the corresponding environment%@CR:C6A00060008 @% variables. (The inherited macro is all uppercase, however, even if the corresponding environment variable is not.) %@NL@% %@NL@% Inherited macros can be used like other macros. You can also redefine them. The following example redefines the inherited macro %@AS@% PATH%@AE@%: %@NL@% %@NL@% %@AS@% PATH = c:\tools\bin %@AS@% %@AS@% sample.obj : sample.c %@AS@% CL /c sample.c%@AE@%%@NL@% %@NL@% %@AU@% Inherited macros take their definitions from environment variables.%@AE@% %@NL@% %@NL@% No matter what value PATH had in the DOS environment, it has the value %@AS@% %@AS@%c:\tools\bin %@AE@% when NMAKE executes the CL command in this description block. Redefining the inherited macro does not affect the original environment variable; when NMAKE terminates, PATH has its original value. %@NL@% %@NL@% The /E option defeats macro inheritance. If you supply this option, NMAKE ignores any attempt to redefine a macro that derives from an environment variable. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Precedence among Macro Definitions%@AE@%%@EH@%%@NL@% %@NL@% If you define the same macro in more than one place, NMAKE uses the macro with the highest precedence. The precedence from highest to lowest is as follows: %@NL@% %@NL@% %@NL@% 1. Macros defined on the command line%@NL@% %@NL@% 2. Macros defined in a description file or include file%@NL@% %@NL@% 3. Inherited macros%@NL@% %@NL@% 4. Macros defined in the TOOLS.INI file%@NL@% %@NL@% 5. Predefined macros such as%@AB@% CC %@AE@%and%@AB@% AS%@AE@%%@NL@% %@NL@% %@NL@% The /E option defeats any attempt to redefine inherited macros. If you run NMAKE with this option, macros inherited from environment variables override any same-named macros in the description file. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00060009 @%%@AB@%6.3.4 Inference Rules%@AE@%%@EH@%%@NL@% %@NL@% Inference rules are templates that NMAKE uses to create files with a given extension. For instance, when NMAKE encounters a description block with no commands, it tries to apply an inference rule that tells how to create the target from the dependent files, given the two extensions. Similarly, if a dependent file does not exist, NMAKE tries to apply an inference rule that tells how to create the missing dependent from another file with the same base name. %@NL@% %@NL@% %@AU@% Inference rules tell NMAKE how to create files with a certain extension.%@AE@% %@NL@% %@NL@% Inference rules provide a convenient shorthand for common operations. For instance, you can use an inference rule to avoid repeating the same command in several description blocks. %@NL@% %@NL@% You can define your own inference rules or use predefined inference rules. This section begins by describing user-defined inference rules. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%User-Defined Inference Rules%@AE@%%@EH@%%@NL@% %@NL@% You can define inference rules in the description file or in the TOOLS.INI file. An inference-rule definition lists two file extensions and one or more commands. For instance, the following inference rule tells NMAKE how to build a .OBJ file using a .C file:%@CR:C6A00060010 @% %@NL@% %@NL@% %@AS@% .C.OBJ: %@AS@% CL /c $<;%@AE@%%@NL@% %@NL@% The first line lists two extensions. The second extension (.OBJ) specifies the type of the desired file and the first (.C) specifies the type of the desired file's dependent. The second line lists the command used to build the desired file. Here, the predefined macro %@AB@%$%@AE@% represents the name of a dependent that is out-of-date relative to the target. %@NL@% %@NL@% NMAKE could apply the above inference rule to the following description block: %@NL@% %@NL@% %@AS@% sample.obj :%@AE@%%@NL@% %@NL@% The description block lists only a target, SAMPLE.OBJ. Both the dependent and the command are missing. However, given the target's base name and extension, plus the above inference rule, NMAKE has enough information to build the target. NMAKE first looks for a .C file with the same base name as the target. If SAMPLE.C exists, NMAKE compares its date to that of SAMPLE.OBJ (the comparison is triggered by the predefined macro %@AB@%$%@AE@%). If SAMPLE.C has changed more recently, NMAKE compiles it using the CL command listed in the inference rule: %@NL@% %@NL@% %@AS@% CL/c sample.c%@AE@%%@NL@% %@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% NOTE %@AI@%NMAKE applies an inference rule only if the base name of the file it is %@AI@%trying to create matches the base name of a file that already exists. Thus, %@AI@%inference rules are useful only when there is a one-to-one correspondence %@AI@%between the desired file and its dependent. You cannot define an inference %@AI@%rule that replaces several modules in a library, for example.%@AE@%%@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@%%@NL@% %@NL@% %@NL@% %@4@%%@AB@%Extension Search Paths%@AE@%%@EH@%%@NL@% %@NL@% If an inference rule does not specify a search path, as in the example above, NMAKE looks for files in the current directory. You can specify a single path for each of the extensions, using the following form: %@NL@% %@NL@% %@AS@% {frompath}. fromext{topath}. toext: %@AS@% commands%@AE@%%@NL@% %@NL@% NMAKE searches in the %@AI@%frompath%@AE@% directory for files with the %@AI@%fromext%@AE@% extension. It uses %@AI@%commands%@AE@% to create files with the %@AI@%toext%@AE@% extension in the %@AI@%topath%@AE@% directory. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Predefined Inference Rules%@AE@%%@EH@%%@NL@% %@NL@% NMAKE provides predefined inference rules to perform these common development tasks: %@NL@% %@NL@% %@NL@% ■ Creating an .OBJ file by compiling a .C file%@NL@% %@NL@% ■ Creating an .OBJ file by assembling an .ASM file%@NL@% %@NL@% ■ Creating an .EXE file by compiling a .C file and linking the resulting .OBJ file%@NL@% %@NL@% %@NL@% Table 6.3 describes the predefined inference rules. %@NL@% %@NL@% %@AB@%Table %@AB@%6.3 Predefined Inference Rules%@AE@%%@AE@% %@TH: 6 432 02 16 26 34 @%Inference Rule Command Default Action%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%.c.obj $(CC) $(CFLAGS) /c $*.c cl /c $*.c.asm.obj $(AS) $(AFLAGS) $*; masm $*;.c.exe $(CC) $(CFLAGS) $*.c cl $*.c%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@TE: 6 432 02 16 26 34 @% For example, say that you have the following description file: %@NL@% %@NL@% %@AS@% sample.exe :%@AE@%%@NL@% %@NL@% Like the previous example, this description block lists a target without any dependents or commands. NMAKE looks at the target's extension (.EXE) and checks for an inference rule that describes how to create a .EXE file. The last rule in Table 6.3 provides this information: %@NL@% %@NL@% %@AS@% .c.exe: %@AS@% $(CC) $(CFLAGS) $*.c%@AE@%%@NL@% %@NL@% To apply this rule, NMAKE first looks for a file with the same base name as the target (SAMPLE) and the .C extension. If SAMPLE.C exists in the current directory, NMAKE executes the CL command given in the rule. The command compiles SAMPLE.C and links the resulting file SAMPLE.OBJ to create SAMPLE.EXE. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Precedence among Inference Rules%@AE@%%@EH@%%@NL@% %@NL@% If the same inference rule is defined in more than one place, NMAKE uses the rule with the highest precedence. The precedence from highest to lowest is %@NL@% %@NL@% %@NL@% 1. Inference rules defined in the description file%@NL@% %@NL@% 2. Inference rules defined in the TOOLS.INI file%@NL@% %@NL@% 3. Predefined inference rules%@NL@% %@NL@% %@NL@% NMAKE uses a predefined inference rule only if no user-defined inference rule exists for the desired operation. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00060011 @%%@AB@%6.3.5 Directives%@AE@%%@EH@%%@NL@% %@NL@% Directives allow you to write description files that are similar to batch files. Directives can execute commands conditionally, display error messages, include other files, and turn on or off certain options. %@NL@% %@NL@% %@AU@% NMAKE directives are similar to C preprocessor directives.%@AE@% %@NL@% %@NL@% A directive begins with an exclamation point (!), which must appear at the beginning of the line. You can place spaces between the exclamation point and the directive keyword. (See Table 6.4.) %@NL@% %@NL@% %@AB@%Table 6.4 %@AB@%Directives%@AE@%%@AE@% %@TH: 49 3078 02 25 51 @%Directive Description%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%!CMDSWITCHES Turns on or off one of four NMAKE options: /D, /I,{%@AB@%+%@AE@%| %@AB@%-%@AE@%}%@AI@%opt%@AE@%... /N, and /S. If no options are specified, the options are reset to the way they were when NMAKE started. Turn an option on by preceding it with a plus sign (+), or turn it off by preceding it with a minus sign (-). Using this keyword updates the %@AB@%MAKEFLAGS%@AE@% macro.!ELSE Executes the statements between the%@AB@% !ELSE%@AE@% and%@AB@% %@AE@% %@AB@%!ENDIF%@AE@% keywords if the statements preceding the %@AB@%%@AE@% %@AB@%!ELSE%@AE@% keyword were not executed.!ENDIF Marks the end of the%@AB@% !IF%@AE@%,%@AB@% !IFDEF%@AE@%, or%@AB@% !IFNDEF%@AE@% block of statements.!ERROR %@AI@%text%@AE@% Causes %@AI@%text%@AE@% to be printed and then stops execution.!IF %@AI@%constantexpression%@AE@% Executes the statements between the%@AB@% !IF %@AE@%keyword and the next %@AB@%!ELSE%@AE@% or %@AB@%!ENDIF%@AE@% keyword if %@AI@%constant%@AE@% %@AI@%expression%@AE@% evaluates to a nonzero value.!IFDEF %@AI@%macroname%@AE@% Executes the statements between the %@AB@%!IFDEF%@AE@% keyword and the next%@AB@% !ELSE%@AE@% or%@AB@% !ENDIF %@AE@%keyword if %@AI@%%@AE@% %@AI@%macroname%@AE@% is defined. NMAKE considers a macro with a null value to be defined.!IFNDEF %@AI@%macroname%@AE@% Executes the statements between the%@AB@% !IFNDEF%@AE@% keyword and the next%@AB@% !ELSE%@AE@% or %@AB@%!ENDIF%@AE@% keyword if %@AI@%%@AE@% %@AI@%macroname%@AE@% is not defined.!INCLUDE %@AI@%filename%@AE@% Reads and evaluates the file %@AI@%filename%@AE@% before continuing with the current description file. If %@AI@%%@AE@% %@AI@%filename%@AE@% is enclosed by angle brackets (< >), NMAKE searches for the file in the directories specified by the %@AB@%INCLUDE%@AE@% macro. Otherwise, it looks only in the current directory. The %@AB@%%@AE@% %@AB@%INCLUDE%@AE@% macro is initially set to the value of the INCLUDE environment variable.!UNDEF %@AI@%macroname%@AE@% Marks %@AI@%macroname%@AE@% as being undefined in NMAKE's symbol table.%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@TE: 49 3078 02 25 51 @% The %@AI@%constantexpression%@AE@% used with the %@AB@%!IF%@AE@% directive can consist of integer constants, string constants, or program invocations. Integer constants can use the C unary operators for numerical negation (%@AB@%-%@AE@%), one's complement (%@AB@%~%@AE@%), and logical negation (%@AB@%!%@AE@%). They can also use any of the C binary operators listed in Table 6.5. %@NL@% %@NL@% %@AB@%Table 6.5 %@AB@%Directive Operators%@AE@%%@AE@% %@TH: 21 1088 02 22 54 @%Operator Description%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%+%@AE@% Addition%@AB@%-%@AE@% Subtraction%@AB@%*%@AE@% Multiplication%@AB@%/%@AE@% Division%@AB@%%%@AE@% Modulus%@AB@%&%@AE@% Bitwise AND%@AB@%|%@AE@% Bitwise OR%@AB@%^^%@AE@% Bitwise XOR%@AB@%&&%@AE@% Logical AND%@AB@%||%@AE@% Logical OR%@AB@%<<%@AE@% Left shift%@AB@%>>%@AE@% Right shift%@AB@%==%@AE@% Equality%@AB@%!=%@AE@% Inequality%@AB@%<%@AE@% Less than%@AB@%>%@AE@% Greater than%@AB@%<=%@AE@% Less than or equal to%@AB@%>=%@AE@% Greater than or equal to%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@TE: 21 1088 02 22 54 @% You can group expressions using parentheses. NMAKE treats numbers as decimal unless they start with 0 (octal) or 0x (hexadecimal). Use the equality (%@AB@%==%@AE@%) operator to compare two strings for equality or the inequality (%@AB@%!=%@AE@%) operator to compare for inequality. Enclose strings with quotes. Program invocations must be in square brackets ([ ]). %@NL@% %@NL@% The following example illustrates directives: %@NL@% %@NL@% %@AS@% !INCLUDE <infrules.txt> %@AS@% !CMDSWITCHES +D %@AS@% winner.exe:winner.obj %@AS@% !IFDEF debug %@AS@% ! IF "$(debug)"=="y" %@AS@% LINK /CO winner.obj; %@AS@% ! ELSE %@AS@% LINK winner.obj; %@AS@% ! ENDIF %@AS@% !ELSE %@AS@% ! ERROR Macro named debug is not defined. %@AS@% !ENDIF%@AE@%%@NL@% %@NL@% The !INCLUDE directive causes NMAKE to insert the file INFRULES.TXT into the description file. The !CMDSWITCHES directive turns on the /D option, which displays the dates of the files as they are checked. If WINNER.EXE is out-of-date with respect to WINNER.OBJ, the !IFDEF directive checks to see if the macro %@AS@% debug %@AE@% is defined. If it is defined, the !IF directive checks to see if it is set to %@AS@% y%@AE@%. If it is, the linker is invoked with the /CO option; otherwise it is invoked without. If the %@AS@% debug %@AE@% macro is not defined, the !ERROR directive prints the message and NMAKE stops. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00060012 @%%@AB@%6.3.6 Pseudotargets%@AE@%%@EH@%%@NL@% %@NL@% Pseudotargets are useful for building a group of files or executing a group of commands.%@CR:C6A00060013 @% %@NL@% %@NL@% A "pseudotarget" is similar to a target, but it is not a file. It is a name that serves as a "handle" for building a group of files or executing a group of commands. In the following example, %@AS@% UPDATE %@AE@% is a pseudotarget. %@NL@% %@NL@% %@AS@% UPDATE: *.* %@AS@% !COPY $** a:\product%@AE@%%@NL@% %@NL@% When NMAKE evaluates a pseudotarget, it always considers the dependents to be out-of-date. In the example, NMAKE copies each of the dependent files to the specified drive and directory. %@NL@% %@NL@% Like macro names, pseudotarget names are case sensitive. Predefined pseudotarget names are all uppercase. %@NL@% %@NL@% The pseudotargets in Table 6.6 are predefined to provide special rules in a description file. You can use their names on the command line, in a description file, or in the TOOLS.INI file. You need not specify them as targets; NMAKE uses the rules they define no matter where they appear.%@CR:C6A00060014 @% %@NL@% %@NL@% %@AB@%Table %@AB@%6.6 Pseudotargets%@AE@%%@AE@% %@TH: 50 3027 02 34 42 @%Pseudotarget Action%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%.IGNORE: Ignores exit codes returned by programs called from the description file. Same effect as invoking NMAKE with the /I option..PRECIOUS: %@AI@%target(s)%@AE@% Tells NMAKE not to delete %@AI@%target(s)%@AE@% if the commands that build it are quit or interrupted. Using this pseudotarget overrides the NMAKE default. By default, NMAKE deletes the target if it cannot be sure the target is built successfully. The .PRECIOUS pseudotarget is rarely needed. Like most professional tools, Microsoft language tools clean up by themselves when errors occur..SILENT: Does not display lines as they are executed. Same effect as invoking NMAKE with the /S option..SUFFIXES:%@AI@%list%@AE@% Lists file suffixes for NMAKE to try when building a target file for which no dependents are specified. This list is used together with inference rules. See Section 6.3.4, "Inference Rules." When NMAKE finds a target without any dependents, it searches the current directory for a file with the same base name as the target and a suffix from the list. If NMAKE finds such a file, and if an inference rule applies to the file, then NMAKE treats the file as a depen- dent of the target. The order of the suffixes in the list defines the order in which NMAKE searches for the file. The list is predefined as follows: %@AS@%.SUFFIXES: .obj .exe .c .asm%@AE@% To add suffixes to the list, specify %@AS@% %@AE@% %@AS@%.SUFFIXES : %@AE@% followed by the new suffixes. To clear the list, specify %@AS@% .SUFFIXES:%@AE@%%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@TE: 50 3027 02 34 42 @% %@NL@% %@3@%%@CR:C6A00060015 @%%@AB@%6.3.7 PWB's extmake Syntax%@AE@%%@EH@%%@NL@% %@NL@% NMAKE description files can use the same syntax as the %@AB@%extmake%@AE@% switch of PWB (see Chapter 8, "Customizing the Microsoft Programmer's WorkBench"). This syntax allows you to determine the drive, path, base name, and extension of the first dependent, information that is not otherwise available. The file name, and parts of its name, are represented using the syntax %@NL@% %@NL@% %@AS@% %|partsF%@AE@%%@NL@% %@NL@% where %@AI@%parts%@AE@% is one or more of the following: %@NL@% %@NL@% %@AB@%Letter%@AE@% %@AB@%Description%@AE@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@AB@%d%@AE@% Drive %@AB@%e%@AE@% File extension %@AB@%f%@AE@% File base name %@AB@%p%@AE@% Path %@AB@%s%@AE@% Complete name The following example uses %@AB@%extmake%@AE@% syntax: %@NL@% %@NL@% %@AS@% sample.obj : sample.c %@AS@% CL /Fod:%|pfF %|dfeF%@AE@%%@NL@% %@NL@% In this example, the sequence %@AS@% %|pfF %@AE@% represents the path and base name of the first dependent file, while the sequence %@AS@% %|dfeF %@AE@% represents the drive, base name, and extension of the same file. The example, then, compiles the file and writes the output to a file on the same path but with the default .OBJ extension. %@NL@% %@NL@% The percent symbol (%) is a replacement character in DOS and OS/2 command lines in the description file. To use %@AB@%extmake%@AE@% syntax in command-line arguments, specify each percent symbol as a double percent symbol (%%). %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00060016 @%%@AB@%6.4 Command-Line Options%@AE@%%@EH@%%@NL@% %@NL@% NMAKE accepts a number of options, which are listed in Table 6.7. You can specify options in uppercase or lowercase and use either a slash or dash. For example, -A, /A, -a, and /a all represent the same option. %@NL@% %@NL@% %@AB@%Table %@AB@%6.7 NMAKE Options%@AE@%%@AE@% %@TH: 73 3813 02 34 42 @%Option Action%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%/A Builds all of the requested targets even if they are not out-of-date./C Suppresses nonfatal error or warning messages and the NMAKE logo display./D Displays the modification date of each file./E Causes environment variables to override macro definitions in description files. See Section 6.3.3, "Macros."/F %@AI@%filename%@AE@% Specifies %@AI@%filename%@AE@% as the name of the description file. If you supply a dash (-) instead of a file name, NMAKE gets input from the standard input device instead of the description file./HELP Calls the QuickHelp utility. If the QuickHelp program is not available, NMAKE displays the most commonly used NMAKE options./I Ignores return codes from commands listed in the description file. NMAKE processes the whole description file even if errors occur./N Displays but does not execute the description file's commands. This option is useful for debugging description files and checking which targets are out-of-date./NOLOGO Suppresses the NMAKE logo display./P Displays all macro definitions and target descriptions on the standard output device./Q Returns zero if the target is up-to-date and nonzero if it is not. This option is useful when running NMAKE from a batch file./R Ignores inference rules and macros that are predefined or defined in the TOOLS.INI file./S Suppresses the display of commands listed in the description file./T Changes the modification dates for out-of-date target files to the current date./X %@AI@%filename%@AE@% Sends all error output to %@AI@%filename%@AE@%, which can be a file or a device. If you supply a dash (-) instead of a file name, the error output is sent to the standard output device./Z Used for internal communication between NMAKE and PWB./? Displays a brief summary of NMAKE syntax and exits to the operating system.%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@TE: 73 3813 02 34 42 @% The following command specifies two NMAKE options: %@NL@% %@NL@% %@AS@% NMAKE /f sample.mak /c targ1 targ2%@AE@%%@NL@% %@NL@% The /f option tells NMAKE to read the description file SAMPLE.MAK. The /c option tells NMAKE not to display nonfatal error messages and warnings. The command lists two targets (%@AS@%targ1 %@AE@% and %@AS@% targ2%@AE@%) to update. %@NL@% %@NL@% %@AS@% NMAKE /D /N targ1 targ1.mak%@AE@%%@NL@% %@NL@% In the example above, NMAKE updates the target %@AS@% targ1%@AE@%. If the current directory does not contain a file named MAKEFILE, NMAKE reads the file TARG1.MAK as the description file. The /D option displays the modification date of each file; the /N option displays the commands without executing them. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00060017 @%%@AB@%6.5 NMAKE Command Files%@AE@%%@EH@%%@NL@% %@NL@% Occasionally, you may need to give NMAKE a long list of command-line arguments that exceeds the maximum length of a command line (128 characters in DOS, 256 in OS/2). To do this, place the command arguments in a file, then give the name of the file when you run NMAKE. %@NL@% %@NL@% For instance, say that you create a file named UPDATE, which consists of this line: %@NL@% %@NL@% %@AS@% /S "program = sample" sort.exe search.exe%@AE@%%@NL@% %@NL@% If you start NMAKE with the command %@NL@% %@NL@% %@AS@% NMAKE @update%@AE@%%@NL@% %@NL@% NMAKE reads its command-line arguments from UPDATE. The at sign (@) tells NMAKE to read arguments from the file. The effect is the same as if you typed the arguments directly on the command line: %@NL@% %@NL@% %@AS@% NMAKE /S "program = sample" sort.exe search.exe%@AE@%%@NL@% %@NL@% Within the file, line breaks between arguments are treated as spaces. Macro definitions that contain spaces must be enclosed in quotation marks, just as if you typed them on the command line. You can continue a macro definition across multiple lines by ending each line except the last with a backslash ( \ ): %@NL@% %@NL@% %@AS@% /S "program \ %@AS@% = sample" sort.exe search.exe%@AE@%%@NL@% %@NL@% This file is equivalent to the first example. The backslash in the example allows the macro definition (%@AS@%"program = sample" %@AE@%) to span two lines. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00060018 @%%@AB@%6.6 The TOOLS.INI File%@AE@%%@EH@%%@NL@% %@NL@% You can customize NMAKE by placing commonly used macros and inference rules in the TOOLS.INI initialization file. Settings for NMAKE must follow a line that begins with %@AS@% [NMAKE]%@AE@%. This part of the initialization file can contain macro definitions, .SUFFIXES lists, and inference rules. For example, %@NL@% %@NL@% %@AS@% [NMAKE] %@AS@% CC=cl %@AS@% CFLAGS=-Gc -Gs -W3 -Oat %@AS@% .c.obj: %@AS@% $(CC) -c $(CFLAGS) $*.c%@AE@%%@NL@% %@NL@% If TOOLS.INI contains the code above, NMAKE reads and applies the lines following %@AS@% [NMAKE]%@AE@%. The example defines the macros %@AB@%CC%@AE@% and %@AB@%CFLAGS%@AE@% and redefines the inference rule for making .OBJ files from .C sources. %@NL@% %@NL@% NMAKE looks for TOOLS.INI in the current directory. If it is not found there, NMAKE searches the directory specified by the INIT environment variable. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00060019 @%%@AB@%6.7 In-Line Files%@AE@%%@EH@%%@NL@% %@NL@% NMAKE can write "in-line files," which can contain any text you specify. One use for in-line files is to write a response file for another utility such as LIB. (Response files are useful when you need to supply a program with a long list of arguments that exceeds the maximum length of the command line.) %@NL@% %@NL@% Use this syntax to create an in-line file: %@NL@% %@NL@% %@AS@% target : dependents %@AS@% command << «filename» %@AS@% inlinetext %@AS@% <<«KEEP | NOKEEP»%@AE@%%@NL@% %@NL@% All of the text between the two sets of double angle brackets (%@AB@%%@AE@%) is placed in the in-line file. The %@AI@%filename%@AE@% is optional. If you don't supply %@AI@%filename%@AE@%, NMAKE gives the in-line file a unique name. NMAKE places the in-line file in the current directory or, if the TMP environment variable is defined, in the directory specified by TMP. %@NL@% %@NL@% The in-line file can be temporary or permanent. If you don't specify otherwise, or if you specify %@AB@%NOKEEP%@AE@%, it is temporary. Specify %@AB@%KEEP%@AE@% to retain the file. %@NL@% %@NL@% The following example creates a LIB response file named LIB.LRF: %@NL@% %@NL@% %@AS@% math.lib : add.obj sub.obj mul.obj div.obj %@AS@% LIB @<<lib.lrf %@AS@% math.lib %@AS@% -+add.obj-+sub.obj-+mul.obj-+div.obj %@AS@% listing %@AS@% <<KEEP%@AE@%%@NL@% %@NL@% The resulting response file tells LIB which library to use, the commands to execute, and the listing file to produce: %@NL@% %@NL@% %@AS@% math.lib %@AS@% -+add.obj-+sub.obj-+mul.obj-+div.obj %@AS@% listing%@AE@%%@NL@% %@NL@% The in-line file specification can create more than one in-line file. For instance, %@NL@% %@NL@% %@AS@% target.abc : depend.xyz %@AS@% cat <<file1 <<file2 %@AS@% I am the contents of file1. %@AS@% <<KEEP %@AS@% I am the contents of file2. %@AS@% <<KEEP%@AE@%%@NL@% %@NL@% The example creates two in-line files named FILE1 and FILE2; then NMAKE executes the command: %@NL@% %@NL@% %@AS@% CAT file1 file2%@AE@%%@NL@% %@NL@% The %@AB@%KEEP%@AE@% keywords tell NMAKE not to delete FILE1 and FILE2 when done. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00060020 @%%@AB@%6.8 NMAKE Operations Sequence%@AE@%%@EH@%%@NL@% %@NL@% If you are writing a complex description file, you may need to know the exact order of steps that NMAKE follows. This section describes those steps in order. %@NL@% %@NL@% When you run NMAKE from the command line, its first task is to find the description file, following these steps: %@NL@% %@NL@% %@NL@% 1. If NMAKE is invoked with the /F option, it uses the file name specified in the option.%@NL@% %@NL@% 2. If /F is not specified, NMAKE looks for a file named MAKEFILE in the current directory. If such a file exists, it is used as a description file.%@NL@% %@NL@% 3. If MAKEFILE is not in the current directory, NMAKE parses the command line for the first string that is not an option or a macro definition and treats this string as a file name. If the file-name extension does not appear in the .SUFFIXES list, NMAKE uses the file as the description file. If the extension appears in the .SUFFIXES list, NMAKE tries additional strings until it finds a suitable file. (See Section 6.3.6, "Pseudotargets," for a description of the .SUFFIXES list.)%@NL@% %@NL@% 4. If NMAKE still has not found a description file, it returns an error.%@NL@% %@NL@% %@NL@% NMAKE stops searching for a description file as soon as it finds one, even if other potential description files exist. If you specify /F, NMAKE uses the file specified by that option even if MAKEFILE exists in the current directory. Similarly, if NMAKE uses MAKEFILE, any description file listed in the command line is treated as a target. %@NL@% %@NL@% %@AU@% If you do not specify targets, NMAKE updates only the first target in the %@AU@%description file.%@AE@% %@NL@% %@NL@% Next, NMAKE updates every target listed on the command line. If none is listed, NMAKE updates only the first target in the description file. (This behavior differs from the older MAKE program's default; see Section 6.9, "Differences between NMAKE and MAKE.") %@NL@% %@NL@% NMAKE then applies macro definitions and inference rules in the following order, from highest to lowest priority: %@NL@% %@NL@% %@NL@% 1. Macros defined on the command line%@NL@% %@NL@% 2. Macros defined in a description file or include file%@NL@% %@NL@% 3. Inherited macros%@NL@% %@NL@% 4. Macros defined in the TOOLS.INI file%@NL@% %@NL@% 5. Predefined macros such as %@AB@%CC%@AE@% and %@AB@%AS%@AE@%%@NL@% %@NL@% %@NL@% Definitions in later steps take precedence over definitions in earlier steps. The /E option, however, causes inherited macros to override macros defined on the command line. The /R option causes NMAKE to ignore macros and inference rules that are predefined or defined in TOOLS.INI. %@NL@% %@NL@% Now NMAKE updates each target in the order in which it appears in the description file. It compares the date and time of each dependent with that of the target and performs the commands needed to update the target. If you specify the /A option or if the target is a pseudotarget, NMAKE updates the target even if its dependents are not out-of-date. %@NL@% %@NL@% If the target has no explicit dependents, NMAKE looks in the current directory for one or more files whose extensions are in the .SUFFIXES list. If it finds such files, NMAKE treats them as dependents and updates the target according to the commands. %@NL@% %@NL@% If no commands are given to update the target or if the dependents cannot be found, NMAKE applies inference rules to build the target. By default, it tries to build .EXE files from .OBJ files; and it tries to build .OBJ files from .C and .ASM sources. In practice, this means you should specify .OBJ files as dependents, because NMAKE compiles your source files when it can't find the .OBJ files. %@NL@% %@NL@% NMAKE normally quits processing the description file when a command returns an error. In addition, if it cannot tell that the target was built successfully, NMAKE deletes the partially created target. If you use the /I commandline option, NMAKE ignores exit codes and attempts to continue processing. The .IGNORE pseudotarget has the same effect. To prevent NMAKE from deleting the partially created target, specify the target name in the .PRECIOUS pseudotarget. %@NL@% %@NL@% Alternatively, you can use the dash (-) command modifier to ignore the error code for an individual command. An optional number after the dash tells NMAKE to continue if the command returns an error code that is less than or equal to the number, and to stop if the error code is greater than the number. %@NL@% %@NL@% You can help document errors by using the !ERROR directive to print descriptive text. The directive causes NMAKE to print some text, then stop, even if you use /I, .IGNORE, or the dash (-) modifier. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00060021 @%%@AB@%6.9 Differences between NMAKE and MAKE%@AE@%%@EH@%%@NL@% %@NL@% As its name implies, NMAKE is a new utility that replaces the older Microsoft MAKE program. NMAKE differs from MAKE in the following ways: %@NL@% %@NL@% %@NL@% ■ NMAKE does not evaluate targets sequentially. Instead, NMAKE updates the targets you specify when you invoke it, regardless of their positions in the description file. If no targets are specified, NMAKE updates only the first target in the file.%@NL@% %@NL@% ■ NMAKE accepts command-line arguments from a file.%@NL@% %@NL@% ■ NMAKE provides more command-line options.%@NL@% %@NL@% ■ NMAKE provides more predefined macros.%@NL@% %@NL@% ■ NMAKE permits substitutions within macros.%@NL@% %@NL@% ■ NMAKE supports directives placed in the description file.%@NL@% %@NL@% ■ NMAKE allows you to specify include files in the description file.%@NL@% %@NL@% %@NL@% The first item in the list deserves special emphasis. While MAKE normally builds every target, working from beginning to end of the description file, NMAKE expects you to specify targets on the command line. If you do not, NMAKE builds only the first target in the description file. %@NL@% %@NL@% The difference is clear if you run NMAKE using a typical MAKE description file, which lists a series of subordinate targets followed by a higher-level target that depends on the subordinates: %@NL@% %@NL@% %@AS@% pmapp.obj : pmapp.c %@AS@% CL /c /G2sw /W3 pmapp.c %@AS@% %@AS@% pmapp.exe : pmapp.obj pmapp.def %@AS@% LINK pmapp, /align:16, NUL, os2, pmapp%@AE@%%@NL@% %@NL@% MAKE builds both targets (PMAPP.OBJ and PMAPP.EXE), but NMAKE builds only the first target (PMAPP.OBJ). %@NL@% %@NL@% Because of these performance differences, you may want to convert MAKE files to NMAKE files. MAKE description files are easy to convert. A simple method is to create a new description block at the beginning of the file. Give this block a pseudotarget named %@AS@% ALL %@AE@% and list the top-level target as a dependent of %@AS@% ALL%@AE@%. To build %@AS@% ALL%@AE@%, NMAKE must update every target upon which the target of %@AS@% ALL %@AE@% depends: %@NL@% %@NL@% %@AS@% ALL : pmapp.exe %@AS@% %@AS@% pmapp.obj : pmapp.c %@AS@% CL /c /G2sw /W3 pmapp.c %@AS@% %@AS@% pmapp.exe : pmapp.obj pmapp.def %@AS@% LINK pmapp, /align:16, NUL, os2, pmapp%@AE@%%@NL@% %@NL@% If the above file is named MAKEFILE, you can update the target PMAPP.EXE with the command %@NL@% %@NL@% %@AS@% NMAKE%@AE@%%@NL@% %@NL@% or the command %@NL@% %@NL@% %@AS@% NMAKE ALL%@AE@%%@NL@% %@NL@% Note that it is not necessary to list PMAPP.OBJ as a dependent of %@AS@% ALL%@AE@%. NMAKE builds a dependency tree for the entire description file, and builds whatever files are needed to update PMAPP.EXE. So if PMAPP.C is out-ofdate with respect to PMAPP.OBJ, NMAKE compiles PMAPP.C to create PMAPP.OBJ, then links PMAPP.OBJ to create PMAPP.EXE. %@NL@% %@NL@% The same technique is suitable for description files with more than one top-level target. List all of the top-level targets as dependents of %@AS@% ALL%@AE@%: %@NL@% %@NL@% %@AS@% ALL : pmapp.exe second.exe another.exe%@AE@%%@NL@% %@NL@% The example updates the targets PMAPP.EXE, SECOND.EXE, and ANOTHER.EXE. %@NL@% %@NL@% If the description file lists a single, top-level target, you can use an even simpler technique. Move the top-level block to the beginning of the file: %@NL@% %@NL@% %@AS@% pmapp.exe : pmapp.obj pmapp.def %@AS@% LINK pmapp, /align:16, NUL, os2, pmapp %@AS@% %@AS@% pmapp.obj : pmapp.c %@AS@% CL /c /G2sw /W3 pmapp.c%@AE@%%@NL@% %@NL@% NMAKE updates the second target (PMAPP.OBJ) whenever needed to keep the first target (PMAPP.EXE) current. %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@CR:C6A00070001 @%%@1@%%@AB@%Chapter 7 Creating Help Files with HELPMAKE%@AE@%%@EH@%%@NL@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@NL@% If you have used PWB or other Microsoft language products such as QuickC, you are familiar with the many advantages of on-line help. The Microsoft Help-File-Creation Utility (HELPMAKE) allows you to create your own help files for use with Microsoft products. It also allows you to customize the help files supplied with Microsoft language products. %@NL@% %@NL@% HELPMAKE translates help text files into a help database accessible from within the following: %@NL@% %@NL@% %@NL@% ■ Microsoft C 6.0 Programmer's WorkBench (PWB)%@NL@% %@NL@% ■ QuickHelp Utility%@NL@% %@NL@% ■ Microsoft Editor 1.02%@NL@% %@NL@% ■ Microsoft QuickC 2.0%@NL@% %@NL@% ■ Microsoft QuickPascal 1.0%@NL@% %@NL@% ■ Microsoft QuickBASIC 4.5%@NL@% %@NL@% %@NL@% This chapter describes how to create and modify help files using the HELPMAKE utility. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00070002 @%%@AB@%7.1 Structure and Contents of a Help Database%@AE@%%@EH@%%@NL@% %@NL@% HELPMAKE creates a help database from one or more input files that contain information formatted for the help system. This section defines some of the terms involved in formatting and outlines the formats that HELPMAKE can process. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00070003 @%%@AB@%7.1.1 Contents of a Help File%@AE@%%@EH@%%@NL@% %@NL@% As you might expect, each help text file starts with a topic and some information about the topic, then lists another topic and some information about it, and so on. In HELPMAKE terminology, topics are called "contexts"; the information is called "topic text." %@NL@% %@NL@% The %@AB@%.context%@AE@% command introduces a context. In the source file for C 6.0 help, for example, this line introduces help for the %@AB@%open%@AE@% function: %@NL@% %@NL@% %@AS@% .context open%@AE@%%@NL@% %@NL@% The %@AB@%.context%@AE@% command and other formatting elements are described in Section 7.5, "Help Text Conventions." %@NL@% %@NL@% Whether a context is one or several words depends on the application. QuickBASIC, for example, considers spaces to be delimiters, so in QuickBASIC help files contexts are limited to a single word. Other applications, such as the Microsoft Editor, can handle contexts that span several words. Either way, the application simply hands the context to an internal "help engine," which searches the database for information. %@NL@% %@NL@% Often, especially with library routines, the same information applies to more than one subject. For example, the string-to-number functions %@AB@%strtod%@AE@%, %@AB@%strtol%@AE@%, and %@AB@%stroul%@AE@% share the same help text. The help file lists all three function names as contexts for one block of topic text. The converse, however, is not true. You cannot specify different blocks of topic text, in different places in the help file, to describe a single subject. %@NL@% %@NL@% %@AU@% Cross-references help you navigate through a help database.%@AE@% %@NL@% %@NL@% Cross-references make it possible to view information about related topics, including header files and code examples. The help for the %@AB@%open%@AE@% function, for example, references the %@AB@%access%@AE@% function and the ASCII header file FCNTL.H. Cross-references can point to other contexts in the same help database, to contexts in other help databases, or to ASCII files outside the database. %@NL@% %@NL@% Help files can have two kinds of cross-references: %@NL@% %@NL@% %@NL@% ■ Implicit%@NL@% %@NL@% ■ Explicit, or hyperlinks%@NL@% %@NL@% %@NL@% %@AU@% Implicit cross-references are coded with an ordinary .context command.%@AE@% %@NL@% %@NL@% The word "open" is an implicit cross-reference throughout C 6.0 help. If you select the word "open" anywhere in C 6.0 help, the help system displays information on the %@AB@%open%@AE@% function. As illustrated above, the context for %@AB@%open%@AE@% begins with an ordinary %@AB@%.context%@AE@% command. As a result, anywhere that you select "open," the help system references this context. %@NL@% %@NL@% %@AU@% Hyperlinks are explicit cross-references marked by invisible text.%@AE@% %@NL@% %@NL@% A "hyperlink" is an explicit cross-reference tied to a word or phrase at a specific location in the help file. You create hyperlinks when you write the help text. The hyperlink consists of a word or phrase followed by invisible text that gives the context to which the hyperlink refers. %@NL@% %@NL@% For example, to cause an instance of the word "formatting" to display help on the %@AB@%printf%@AE@% function, you would create an explicit cross-reference from the word "formatting" to the context "printf." Elsewhere in the file, "formatting" has no special significance but, at that one position, it references the help for %@AB@%printf%@AE@%. Section 7.5.4 describes how to create hyperlinks. %@NL@% %@NL@% %@AU@% Formatting flags let you change the appearance of text.%@AE@% %@NL@% %@NL@% Help text can also include formatting flags to control the appearance of the text on the screen. Using these flags, you can make certain words appear in various colors, inverse video, and so forth, depending on the application displaying help and the graphics capabilities of the host computer. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00070004 @%%@AB@%7.1.2 Help File Formats%@AE@%%@EH@%%@NL@% %@NL@% You can create help files using any of three formats: %@NL@% %@NL@% %@NL@% ■ QuickHelp format%@NL@% %@NL@% ■ Rich Text Format (RTF)%@NL@% %@NL@% ■ Minimally formatted ASCII%@NL@% %@NL@% %@NL@% In addition, you can reference unformatted ASCII files, such as include files, from within a help database. %@NL@% %@NL@% An entire help system (such as the one supplied with Microsoft C or QuickBASIC) can use any combination of files formatted with different format types. With C, for example, the README.DOC information file is encoded as minimally formatted ASCII; the help files for the PWB, C language, and run-time library are encoded in the QuickHelp format. The database also cross-references the header (include) files, which are unformatted ASCII files stored outside the database. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%QuickHelp%@AE@%%@EH@%%@NL@% %@NL@% QuickHelp format is the default and is the format into which HELPMAKE decodes help databases. Use any text editor to create a QuickHelp-format help text file. QuickHelp format also lends itself to a relatively easy automated translation from other document formats. %@NL@% %@NL@% QuickHelp files can contain any kind of cross-reference or formatting attribute. Typically, you use QuickHelp format for any changes to a database supplied by Microsoft. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%RTF%@AE@%%@EH@%%@NL@% %@NL@% Rich Text Format (RTF) is a Microsoft word-processing format that many other word processors also support. You can create RTF help text with any word processor that generates RTF output. You can also use any utility program that takes word-processor output and produces an RTF file. %@NL@% %@NL@% Use RTF when you want to transfer help files from one application to another while retaining formatting information. You can format RTF files directly with the word-processing program; you need not edit them to insert any special commands or tags. Like QuickHelp files, RTF files can contain formatting attributes and cross-references. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Minimally Formatted ASCII%@AE@%%@EH@%%@NL@% %@NL@% Minimally formatted ASCII files simply define contexts and their topic text. These files cannot contain screen-formatting commands or explicit crossreferences (implicit cross-references are allowed). They are often used to display text such as README.DOC and small help files that do not require compression. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Unformatted ASCII%@AE@%%@EH@%%@NL@% %@NL@% Unformatted ASCII files are exactly what their name implies: regular ASCII files with no special formatting commands, context definitions, or special information. An unformatted ASCII file does not become part of the help database. Only its name is used as the object of a cross-reference. The standard C header (include) files are unformatted ASCII files used for cross-references by the help system for the C run-time library. Unformatted ASCII files are also useful for storing program examples. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00070005 @%%@AB@%7.2 Invoking HELPMAKE%@AE@%%@EH@%%@NL@% %@NL@% The HELPMAKE program can encode or decode help files, allowing you to create new help files or modify existing ones. Encoding converts a text file to a compressed help database. HELPMAKE can encode text files written in QuickHelp, RTF, and minimally formatted ASCII format. Decoding converts a help database to a text file for editing. HELPMAKE always decodes a help database into a QuickHelp format text file. %@NL@% %@NL@% Invoke HELPMAKE with the following syntax: %@NL@% %@NL@% %@AS@% HELPMAKE «options» { /En | /D } { sourcefiles }%@AE@%%@NL@% %@NL@% The %@AI@%options%@AE@% modify the action of HELPMAKE; they are described in Section 7.3. %@NL@% %@NL@% %@AU@% Use the /E option to encode with HELPMAKE and use the /D option to decode.%@AE@% %@NL@% %@NL@% You must supply either the /E (encode) or the /D (decode) option. When encoding (/E) to create a help database, you must use the /O option to specify the file name of the database. %@NL@% %@NL@% The %@AI@%sourcefile%@AE@% field is required. It specifies the input file for HELPMAKE. If you use the /D (decode) option, %@AI@%sourcefile%@AE@% can be one or more help database files (such as QC.HLP). HELPMAKE decodes the database files into a single text file. If you use the /E (encode) option, %@AI@%sourcefile%@AE@% can be one or more help text files (such as QC.SRC). Separate file names with a space. Standard wild-card characters can also be used. %@NL@% %@NL@% The example below invokes HELPMAKE with the /V, /E, and /O options (see Section 7.3.1, "Options for Encoding"). HELPMAKE reads input from the text file %@AS@% my.txt %@AE@% and writes the compressed help database in the file %@AS@% my.hlp%@AE@%. The /E option causes maximum compression. Note that the DOS redirection symbol (>) sends a log of HELPMAKE activity to the file %@AS@% my.log%@AE@%. You may find it helpful to redirect the log file because, in its more verbose modes (given by /V), HELPMAKE may generate a lengthy log. %@NL@% %@NL@% %@AS@% HELPMAKE /V /E /Omy.hlp my.txt > my.log%@AE@%%@NL@% %@NL@% The example below invokes HELPMAKE to decode the help database %@AS@% my.hlp %@AE@% into the text file %@AS@% my.src%@AE@%, given with the /O option. Once again, the /V option results in verbose output, and the output is directed to the log file %@AS@% %@AS@%my.log%@AE@%. Section 7.3.2 describes additional options for decoding. %@NL@% %@NL@% %@AS@% HELPMAKE /V /D /Omy.src my.hlp > my.log%@AE@%%@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00070006 @%%@AB@%7.3 HELPMAKE Options%@AE@%%@EH@%%@NL@% %@NL@% HELPMAKE accepts a number of command-line options, which are described below. You can specify options in uppercase or lowercase letters, and precede them with either a forward slash ( / ) or a dash (-). For example, -L, /L, -l, and /l all represent the same option. Most options apply only to encoding; others apply only to decoding; and a few apply to both. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00070007 @%%@AB@%7.3.1 Options for Encoding%@AE@%%@EH@%%@NL@% %@NL@% When you encode a file─that is, when you build a help database─you must specify the /E option. In addition, you can supply various other options that control the way HELPMAKE works. All the options that apply when encoding are listed below: %@NL@% %@NL@% %@AB@%Option%@AE@% %@AB@%Action%@AE@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% /A%@AI@%c%@AE@% Specifies %@AI@%c%@AE@% as an application-specific control character for the help database file. The character marks a line that contains special information for internal use by the application. For example, QuickC uses the colon (%@AB@%:%@AE@%). /C Indicates that the context strings for this help file are case sensitive. At run time, all searches for help topics are case sensitive if the help database was built with the /C option in effect. /E«%@AI@%n%@AE@%» Creates (encodes) a help database from a specified text file. The optional %@AI@%n%@AE@% indicates the amount of compression to take place. If %@AI@%n%@AE@% is omitted, HELPMAKE compresses the file as much as possible, thereby reducing the size of the file by about 50%. The more compression requested, the longer HELPMAKE takes to create a database file. The value of %@AI@%n%@AE@% is a number in the range 0 - 15. It is the sum of successive powers of 2 representing various compression techniques, as listed below: %@AB@%Value%@AE@% %@AB@%Technique%@AE@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% 0 No compression 1 Run-length compression 2 Key word compression 4 Extended key word compression 8 Huffman compression Add values to combine compression techniques. For example, use /E3 to get run-length and key word compression. This is useful in the testing stages of creating a help database when you need to create the database quickly and are not too concerned with size. /H Displays a summary of HELPMAKE syntax and exits. /HELP Invokes QH.EXE, the QuickHelp utility, for help about HELPMAKE. If QuickHelp is not available, displays the same information as the /H option. /K %@AI@%filename%@AE@% Optimizes key word compression by supplying a list of characters that act as word separators. The %@AI@%filename%@AE@% is a file containing your list of separator characters. When you select key word compression, HELPMAKE scans the help file to identify "key words." A key word is any word that occurs often enough to justify replacing it with a shorter character sequence. HELPMAKE normally uses the following characters as word separators: ■ All characters from 0-32 (including the space) ■ !"#&'( )*+'-, /:;<=>?@[\]^_`{|}~ ■ 127 When performing key word compression, HELPMAKE treats as a word any series of characters not appearing in the separator list. Depending on the content of your help file, you may be able to improve key word compression by using the /K option to specify a different list of separator characters. For instance, the default separator list contains the number sign (#). If your help file contains %@AB@%#include%@AE@% directives, HELPMAKE normally treats %@AB@%%@AE@% %@AB@%#include%@AE@% as the word %@AB@%include%@AE@% without a number sign. To cause HELPMAKE to treat %@AB@%%@AE@% %@AB@%#include%@AE@% as a word, you could specify the following separator list: %@AS@% %@AE@% %@AS@%!"&'()*+'-,/:;<=>?@[\]^_`{|}~%@AE@% The list above does not include the number sign. HELPMAKE always treats characters in the range 0-32 as separators, so you do not need to include them. Your list must include all the other characters you want HELPMAKE to use as separators, including the space. /L Locks the generated file so that it cannot be decoded by HELPMAKE at a later time. /O%@AI@%destfile%@AE@% Specifies %@AI@%destfile%@AE@% as the name of the help database. /S%@AI@%n%@AE@% Specifies the type of input file, according to the following %@AI@%n%@AE@% values: %@AB@%Option%@AE@% %@AB@%File%@AE@% %@AB@%Type%@AE@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% /S1 Rich Text Format (RTF) /S2 QuickHelp (default) /S3 Minimally formatted ASCII /T Translates dot commands into internal format. If your help file contains dot commands other than %@AB@%.context%@AE@%, you should supply this option when encoding it. Dot commands are described in Section 7.6.1, "QuickHelp Format," and in later sections. /V«%@AI@%n%@AE@%» Indicates the verbosity of diagnostic and informational output, depending on the value of %@AI@%n%@AE@%. Increasing the value adds more information to the output. If you omit this option or specify only /V, HELPMAKE gives you its most verbose output. The possible values of %@AI@%n%@AE@% are listed below: %@AB@%Option%@AE@% %@AB@%Effect%@AE@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% /V Maximum diagnostic output /V0 No diagnostic output and no banner /V1 Prints only HELPMAKE banner (default) /V2 Prints pass names /V3 Prints contexts on first pass /V4 Prints contexts on each pass /V5 Prints any intermediate steps within each pass /V6 Prints statistics on help file and compression /W%@AI@%width%@AE@% Indicates the fixed width of the resulting help text in number of characters. The values of %@AI@%width%@AE@% can range from 11 to 255. If the /W option is omitted, the default is 76. When encoding RTF source (/S1), HELPMAKE automatically formats the text to %@AI@%width%@AE@%. When encoding QuickHelp (/S2) or minimally formatted ASCII (/S3) files, HELPMAKE truncates lines to this width. %@NL@% %@3@%%@CR:C6A00070008 @%%@AB@%7.3.2 Options for Decoding%@AE@%%@EH@%%@NL@% %@NL@% To decode a help database into QuickHelp files, you must use the /D option. In addition, HELPMAKE accepts other options to control the decoding process. The list below shows all the options that are valid when decoding: %@NL@% %@NL@% %@AB@%Option%@AE@% %@AB@%Action%@AE@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% /D«%@AI@%letter%@AE@%» Decodes the input file into its original text or component parts. If a destination file is not specified with the /O option, the help file is decoded to %@AB@%stdout%@AE@%. HELPMAKE decodes the file differently depending on the letter specified: %@AB@%Letter%@AE@% %@AB@%Effect%@AE@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% /D "Decode." Fully decodes the help database, leaving all cross-references and formatting information intact. /DS "Decode split." Splits the concatenated, compressed help database into its components using their original names. If the database was created without concatenation (the default), HELPMAKE simply copies it to a file with its original name. No decompression occurs. /DU "Decode unformatted." Decompresses the database and removes all screen formatting and cross-references. The output can still be used later for input and recompression, but all screen formatting and cross-references are lost. /H Displays a summary of HELPMAKE syntax and exits without encoding or decoding any files. /HELP Invokes QH.EXE, the QuickHelp utility, for information about HELPMAKE. If QuickHelp is not available, displays the same information as the /H option. /O%@AI@%destfile%@AE@% Specifies %@AI@%destfile%@AE@% for the decoded output from HELPMAKE. If %@AI@%destfile%@AE@% is omitted, the help database is decoded to %@AB@%stdout%@AE@%. HELPMAKE always decodes help database files into QuickHelp format. /T Translates dot commands from internal format into dot-command format. You should always supply this option when decoding a help database that contains dot commands other than %@AB@%.context%@AE@%. /V«%@AI@%n%@AE@%» Indicates the verbosity of diagnostic and informational output depending on the value of %@AI@%n%@AE@%. The possible values are listed below. If you omit this option or specify only /V, HELPMAKE gives you its most verbose output. %@AB@%Option%@AE@% %@AB@%Effect%@AE@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% /V Maximum diagnostic output /V0 No diagnostic output and no banner /V1 Prints only the HELPMAKE banner /V2 Prints pass names /V3 Prints contexts on first pass %@NL@% %@2@%%@CR:C6A00070009 @%%@AB@%7.4 Creating a Help Database%@AE@%%@EH@%%@NL@% %@NL@% You can create a Microsoft-compatible help database by either of two methods. %@NL@% %@NL@% The first method is to decompress an existing help database, modify the resulting help text file, and recompress the help text file to form a new database. %@NL@% %@NL@% The second and simpler method is to append a new help database to an existing help database. This method involves the following steps: %@NL@% %@NL@% %@NL@% 1. Create a help text file in QuickHelp format, RTF, or minimally formatted ASCII.%@NL@% %@NL@% 2. Use HELPMAKE to create a help database file. The example below invokes HELPMAKE, using SAMPLE.TXT as the input file and producing a help database file named %@AS@% sample.hlp%@AE@%: %@NL@% %@AS@% HELPMAKE /V /E /Osample.hlp sample.txt > sample.log%@AE@%%@NL@% %@NL@% %@NL@% 3. Make a backup copy of the existing database file (for safety's sake).%@NL@% %@NL@% 4. Append the new help database file to the existing help database. The example below concatenates the new database %@AS@% sample.hlp %@AE@% onto the end of the CLANG.HLP database: %@NL@% %@AS@% COPY clang.hlp /b + sample.hlp /b%@AE@%%@NL@% %@NL@% %@NL@% 5. Test the database. The %@AS@% sample.hlp %@AE@% database contains the context %@AS@% %@AS@% sample%@AE@%. If you type the word "sample" in the PWB and request help on it, the help window displays the text associated with the context %@AS@% %@AS@% sample%@AE@%.%@NL@% %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00070010 @%%@AB@%7.5 Help Text Conventions%@AE@%%@EH@%%@NL@% %@NL@% Microsoft help databases have a common structure and follow certain organizational conventions. You should follow the same conventions to create Microsoft-compatible help files. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00070011 @%%@AB@%7.5.1 Structure of the Help Text File%@AE@%%@EH@%%@NL@% %@NL@% The help-retrieval capability that is built into Microsoft products is simply a data-retrieval tool. It imposes no restrictions on the content and format of the help text. The HELPMAKE utility and the display routines built into Microsoft language environments, however, make certain assumptions about the format of help text. This section provides some guidelines for creating help text files compatible with those assumptions. %@NL@% %@NL@% In all three help text formats, the help text source file is a sequence of topics, each preceded by one or more unique context definitions. The following list specifies the various formats and the corresponding context definition statements: %@NL@% %@NL@% %@AB@%Format %@AE@% %@AB@%Context Definition%@AE@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% QuickHelp %@AB@%.context %@AE@%%@AI@%context%@AE@% RTF \ par %@AI@%>>context%@AE@% \ par Minimally formatted %@AI@%>>context%@AE@% ASCII (none) In QuickHelp format, each topic begins with one or more %@AB@%.context%@AE@% statements that define the context strings that map to the topic text. Subsequent lines up to the next %@AB@%.context%@AE@% statement constitute the topic text. %@NL@% %@NL@% In RTF format, each context definition must be in a paragraph of its own (denoted by \ par), beginning with the help delimiter (>>). Subsequent paragraphs up to the next context definition constitute the topic text. %@NL@% %@NL@% In minimally formatted ASCII, each context definition must be on a separate line, and each must begin with the help delimiter (>>). As in RTF and QuickHelp files, subsequent lines up to the next context definition constitute the topic text. %@NL@% %@NL@% See Section 7.6, "Using Help Database Formats," for detailed information about these three formats. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00070012 @%%@AB@%7.5.2 Local Contexts%@AE@%%@EH@%%@NL@% %@NL@% Context strings that begin with an "at" sign (@) are defined as "local" and have no implicit cross-references. They are used in cross-references instead of the context string that otherwise is generated.%@CR:C6A00070013 @% %@NL@% %@NL@% When you use a local context, HELPMAKE does not generate a global context string (a context string that is known throughout the help file). Instead, it embeds an encoded cross-reference that has meaning only within the current context. For example, %@NL@% %@NL@% %@AS@% .context normal %@AS@% This is a normal topic, accessible by the context string "normal." %@AS@% [button\v@local\v] is a cross-reference to the following topic. %@AS@% %@AS@% .context @local %@AS@% %@AS@% This topic can be reached only if the user browses %@AS@% sequentially through the file or uses the cross-reference %@AS@% in the previous topic.%@AE@%%@NL@% %@NL@% In the example above, the text %@AS@% [button\v@local\v] %@AE@% defines %@AS@% local %@AE@% as a local context. If the user selects the text %@AS@% [button] %@AE@% or scrolls through the file, the help system displays the topic text that follows the context definition for %@AS@% local%@AE@%. Because %@AS@% local %@AE@% is defined with the "at" sign (@), it can be accessed only by a hyperlink within the help file or by sequentially browsing through the file. Making a context local saves file space and speeds access. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00070014 @%%@AB@%7.5.3 Context Prefixes%@AE@%%@EH@%%@NL@% %@NL@% Microsoft help databases use several context prefixes. A "context prefix" is a single letter followed by a period. It appears before a context string that has a predefined meaning. If you decode a Microsoft help database, many of these contexts may appear in the resulting text file. %@NL@% %@NL@% %@AU@% Most context prefixes are internal. %@AE@% %@NL@% %@NL@% Except for the h. prefix, which is described below, context prefixes are internal. You do not need to add them in help files that you write. %@NL@% %@NL@% You can use the h. prefix to identify standard help-file contexts. For instance, h.default identifies the default help screen: the screen that normally appears when you select "top-level" help. Table 7.1 lists the standard h. contexts. %@NL@% %@NL@% %@AB@%Table 7.1 %@AB@%Standard h. Contexts%@AE@%%@AE@% %@TH: 43 2399 02 34 42 @%Context Description%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%h.contents The table of contents for the help file. You should also define the string "contents" for direct reference to this context.h.default The default help screen, typically displayed when the user presses SHIFT+F1 at the "top level" in most applications. The contents are generally devoted to information about using help.h.index The index for the help file. You can also define the string "index" for direct reference to this context.h.notfound The help text that is displayed when the help system cannot find information about the requested context. The text could be an index of contexts, a topical list, or general information about using help.h.pg# A specific page within the help file. This is used in response to a "go to page #" request.h.pg$ The help text that is logically last in the file. This is used by some applications in response to a "go to the end" request made within the help window.h.pg1 The help text that is logically first in the file. This is used by some applications in response to a "go to the beginning" request made within the help window.h.title The title of the help database.%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@TE: 43 2399 02 34 42 @% The context prefixes in Table 7.2 are internal to Microsoft products. They appear in decompressed databases, but you do not need to use them. %@NL@% %@NL@% %@AB@%Table 7.2 %@AB@%Microsoft Product Context Prefixes%@AE@%%@AE@% %@TH: 28 1705 02 34 42 @%Prefix Purpose%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%d. Dialog box. Each dialog box is assigned a number. Its help context string is d. followed by the number (for example, %@AS@% %@AE@% %@AS@%d.12%@AE@%).e. Error number. If a product supports the error-numbering scheme used by Microsoft languages, it displays help for each error using this prefix. For example, the context %@AS@% e.c1234 %@AE@% refers to the C compiler error message number C1234.m. Menu item. Contexts that relate to product menu items are defined by their accelerator keys. For example, the Exit selection on the FILE menu item is accessed by ALT+F X and is referenced in help by %@AS@% m.f.x%@AE@%.n. Message number. Each message box is assigned a number. Its help context string is n. plus the number (for example, %@AS@% n.5 %@AE@%).%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@TE: 28 1705 02 34 42 @% %@NL@% %@3@%%@CR:C6A00070015 @%%@AB@%7.5.4 Hyperlinks%@AE@%%@EH@%%@NL@% %@NL@% Explicit cross-references, or hyperlinks, in the help text file are marked with invisible text. A hyperlink comprises a word or phrase followed by invisible text that gives the context to which the hyperlink refers. %@NL@% %@NL@% The keystroke that activates the hyperlink depends on the application. Consult the documentation for each product to find the specific keystroke needed. %@NL@% %@NL@% When the user activates the hyperlink, the help system displays the topic named by the invisible text. The invisible cross-reference text is formatted as one of the following: %@NL@% %@NL@% %@AB@%Hyperlink Text%@AE@% %@AB@%Action%@AE@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@AI@%contextstring%@AE@% Causes the help topic associated with %@AI@%%@AE@% %@AI@%contextstring%@AE@% to be displayed. For example, %@AS@% exeformat %@AE@% results in the display of the help topic associated with the context %@AS@% exeformat%@AE@%. %@AI@%filename%@AE@%! Treats %@AI@%filename%@AE@% as a single topic to be displayed. For example, %@AS@% %@AE@% %@AS@%$INCLUDE:stdio.h! %@AE@% searches the INCLUDE environment variable for file STDIO.H and displays it as a single help topic. %@AI@%filename%@AE@%!%@AI@%contextstring%@AE@% Works the same way as %@AI@%contextstring%@AE@% above, except that only the help file %@AI@%%@AE@% %@AI@%filename%@AE@% is searched for the context. If the file is not already open, the help system finds it (by searching either the current path or an explicit environment variable) and opens it. For example, %@AS@% %@AE@% %@AS@%$BIN:readme.doc!patches %@AE@% searches for %@AS@% %@AE@% %@AS@%readme.doc %@AE@% in the BIN environment variable and displays the topic associated with %@AS@% patches%@AE@%. In the following example, the word %@AS@% Example %@AE@% is a hyperlink: %@NL@% %@NL@% %@AS@% \bSee also:\p \uExample\p\vopen.ex\v%@AE@%%@NL@% %@NL@% The hyperlink refers to %@AS@% open.ex%@AE@%. If you select any of the letters of %@AS@% %@AS@%Example%@AE@%, the help system displays the topic whose context is %@AS@% open.ex%@AE@%. On the screen, this line appears as follows: %@NL@% %@NL@% %@AS@% See also: Example%@AE@%%@NL@% %@NL@% An application might display %@AS@% See also: %@AE@% and %@AS@% Example %@AE@% in different colors or character types, depending on such factors as your default color selection and type of monitor. %@NL@% %@NL@% When a hyperlink needs to cross-reference more than one word, you must use an anchor, as in the following example: %@NL@% %@NL@% %@AS@% \bSee also:\p \uExample\p\vprintf.ex\v, fprintf, scanf, sprintf, %@AS@% vfprintf, vprintf, vsprintf %@AS@% \aformatting table\vprintf.table\v%@AE@%%@NL@% %@NL@% This part of the example is an anchored hyperlink: %@NL@% %@NL@% %@AS@% \aformatting table\vprintf.table\v%@AE@%%@NL@% %@NL@% %@AU@% Anchored hyperlinks must fit on a single line.%@AE@% %@NL@% %@NL@% The \ a flag creates an anchor for the cross-reference. In the example, the phrase following the \ a flag (%@AS@%formatting table%@AE@%) is the hyperlink. It refers to the context %@AS@% printf.table%@AE@%. The first \v flag marks both the end of the hyperlink and the beginning of the invisible text. The name %@AS@% printf.table %@AE@% is invisible; it does not appear on the screen when the help is displayed. The second \v flag ends the invisible text. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00070016 @%%@AB@%7.6 Using Help Database Formats%@AE@%%@EH@%%@NL@% %@NL@% The text format of the database can be any of three types. The list below briefly describes these types. Sections 7.6.1-7.6.3 describe the formatting types in detail. %@NL@% %@NL@% An entire help system (such as the one supplied with the Professional Development System or QuickC) can use any combination of files formatted with different format types. With C, for example, the README.DOC information file is encoded as minimally formatted ASCII; and the help files for the C language and run-time library are encoded in the QuickHelp format. The database also cross-references the header (include) files, which are unformatted ASCII files stored outside the database. %@NL@% %@NL@% %@AB@%Type%@AE@% %@AB@%Characteristics%@AE@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% QuickHelp Uses dot commands and embedded formatting characters (the default formatting type expected by HELPMAKE); supports highlighting, color, and cross-references. This format must be compressed before using. Minimally formatted ASCII Uses a help delimiter (>>) to define help contexts; does not support highlighting, color, or crossreferences. This format can be compressed, but compression is not required. RTF Uses a subset of standard RTF; supports highlighting, color, and cross-references; supports dot commands. This format must be compressed before using. %@NL@% %@3@%%@CR:C6A00070017 @%%@AB@%7.6.1 QuickHelp Format%@AE@%%@EH@%%@NL@% %@NL@% The QuickHelp format uses a dot command and embedded formatting flags to convey information to HELPMAKE.%@CR:C6A00070018 @% %@NL@% %@NL@% %@NL@% %@4@%%@AB@%QuickHelp Dot Commands%@AE@%%@EH@%%@NL@% %@NL@% QuickHelp supports a number of dot commands, which identify topics and convey other topic-related information to the help system. If your help file contains dot commands other than %@AB@%.context%@AE@%, you must supply the /T option when encoding and decoding with HELPMAKE. %@NL@% %@NL@% %@AU@% You can define more than one context for a single topic.%@AE@% %@NL@% %@NL@% The most important dot command is the %@AB@%.context%@AE@% command. Every topic in a QuickHelp file begins with one or more %@AB@%.context%@AE@% commands. Each %@AB@%.context%@AE@% command defines a context string for the topic text. You can define more than one context for a single topic, as long as you do not place any topic text between them.%@CR:C6A00070019 @% %@NL@% %@NL@% Typical dot commands are shown below. The first defines a context for the %@AB@% %@AB@%#include%@AE@% C preprocessor directive. The second set illustrates multiple contexts for one block of topic text. In this case, the same topic text explains all of the string-to-number conversion routines in C. %@NL@% %@NL@% %@AS@% .context #include %@AS@% . %@AS@% .description of #include goes here %@AS@% . %@AS@% .context strtod %@AS@% .context strtol %@AS@% .context strtoul %@AS@% . %@AS@% . description of string-to-number functions goes here %@AS@% .%@AE@%%@NL@% %@NL@% The QuickHelp format supports several other dot commands. Table 7.3 lists all of the dot commands available in QuickHelp format. %@NL@% %@NL@% %@AB@%Table 7.3 %@AB@%QuickHelp Dot Commands%@AE@%%@AE@% %@TH: 100 6368 02 34 42 @%%@AB@%Command%@AE@% %@AB@%Action%@AE@%%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%.category%@AE@% %@AI@%string%@AE@% Lists the category in which the current topic appears and its position in the list of topics. The category name is used by the QuickHelp Topic command, which brings up the list of topics to which the current topic belongs. Some applications, such as the PWB, use this name as a pointer to the applicable table of contents.%@AB@%.command%@AE@% Indicates that the topic text is not a displayable help topic. Use this command to hide hyperlink topics and other internal information. Hyperlink topics are described in Section 7.5.5, "Hyperlink Commands."%@AB@%.comment%@AE@% %@AI@%string%@AE@% The %@AI@%string%@AE@% is a comment that appears only in the help source file. Comments are especially useful for documenting the purpose of cross-references. Because comments are not inserted in the help database, they are not restored when you decompress a help file.%@AB@%.context%@AE@% %@AI@%string%@AE@% The %@AI@%string%@AE@% introduces a topic.%@AB@%.end%@AE@% Ends a paste section. See the %@AB@%.paste%@AE@% command below.%@AB@%.freeze%@AE@% %@AI@%numlines%@AE@% Indicates that the first %@AI@%numlines%@AE@% lines should be frozen as the top line of the help screen. This is normally used to freeze a row of cross-reference buttons at the top of a help topic that might be scrolled.%@CR:C6A00070020 @%%@AB@%.length%@AE@% %@AI@%topiclength%@AE@% Indicates the default window size, in %@AI@%%@AE@% %@AI@%topiclength%@AE@% lines, of the topic about to be displayed. This command is always the first line in the topic if present.%@AB@%.list%@AE@% Indicates that the current topic contains a list of topics. QuickHelp displays a highlighted line; you can choose a topic by moving the highlighted line over the desired topic and pressing %@AB@%%@AE@% %@AB@%ENTER%@AE@%. Help searches for the first word of the line.%@AB@%.mark%@AE@% %@AI@%name%@AE@% «%@AI@%column%@AE@%» Defines a mark immediately preceding the following line of text. This command can be used in help script commands to indicate that the display of a particular topic begins at the marked line. The %@AI@%name%@AE@% identifies the mark. The optional %@AI@%column%@AE@% value is an integer that indicates a column location within the specified line.%@AB@%.next%@AE@% %@AI@%context%@AE@% Tells the help system to look up the next topic using %@AI@%%@AE@% %@AI@%context%@AE@% instead of the next topic's name. You can use this command to skip large blocks of %@AB@%.command%@AE@% or %@AB@%.popup%@AE@% topics.%@AB@%.previous%@AE@% %@AI@%context%@AE@% Tells the help system to look up the previous topic using %@AI@%context%@AE@% instead of the previous topic's name. You can use this command to skip large blocks of %@AB@%%@AE@% %@AB@%.command%@AE@% or %@AB@%.popup%@AE@% topics.%@AB@%.paste%@AE@% %@AI@%pastename%@AE@% Begins a paste section. The %@AI@%pastename%@AE@% appears in the QuickHelp Paste menu.%@AB@%.popup%@AE@% Tells the help system to display the current topic as a popup instead of a normal, scrollable topic.%@AB@%.ref%@AE@% %@AI@%string(s)%@AE@% Tells the help system to display the list of %@AI@%string%@AE@% topics in the Reference menu. You can list as many topics as needed; separate each additional %@AI@%string%@AE@% with a comma.%@AB@%.topic%@AE@% %@AI@%text%@AE@% Defines %@AI@%text%@AE@% as the name or title to be displayed in place of the context string if the application help displays a title. This command is always the first line in the context unless you also use the %@AB@% %@AE@% %@AB@%.length%@AE@% command.%@CR:C6A00070021 @%%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@TE: 100 6368 02 34 42 @% %@NL@% %@4@%%@AB@%QuickHelp Formatting Flags%@AE@%%@EH@%%@NL@% %@NL@% The QuickHelp format supports a number of formatting flags that are used to highlight parts of the help database and to mark hyperlinks in the help text. %@NL@% %@NL@% Each formatting flag consists of a backslash ( \ ) followed by a character. Table 7.4 lists the formatting flags. %@NL@% %@NL@% %@AB@%Table 7.4 %@AB@%Formatting Flags%@AE@%%@AE@% %@TH: 19 773 02 34 42 @%Formatting Flag Action%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%\a Anchors text for cross-references\b, \B Turns boldface on or off\i, \I Turns italics on or off\p, \P Turns off all attributes\u, \U Turns underlining on or off\v, \V Turns invisibility on or off (hides cross-references in text)\\ Inserts a single backslash in text%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@TE: 19 773 02 34 42 @% On monochrome monitors, text labeled with the bold, italic, and underlining attributes appears in various ways, depending on the application (for example, high intensity and reverse video are commonly displayed). On color monitors, these attributes are translated by the application into suitable colors, depending on the user's default color selections. %@NL@% %@NL@% The \b, \i, \u, and \v options are toggles, turning on and off their respective attributes. You can use several of these on the same text. Use the \p attribute to turn off all attributes. Use the \v attribute to hide cross-references and hyperlinks in the text. %@NL@% %@NL@% HELPMAKE truncates the lines in QuickHelp files to the width specified with the /W option. (See Section 7.3.1, "Options for Encoding," for more information.) Only visible characters count toward the character-width limit. Lines that begin with an application-specific control character are truncated to 255 characters regardless of the width specification. See Section 7.3.1 for more information about application-specific control characters. %@NL@% %@NL@% In the example below, the \b flag initiates boldface text for %@AS@% Returns:%@AE@%, and the \p flag that follows the word reverts to plain text for the remainder of the line. %@NL@% %@NL@% %@AS@% \bReturns:\p a handle if successful, or -1 if not. %@AS@% errno: EACCES, EEXIST, EMFILE, ENOENT%@AE@%%@NL@% %@NL@% In the example below, \a anchors text for the hyperlink %@AS@% Example %@AE@%. The \v flags define the cross-reference to be %@AS@% sample_prog %@AE@% and cause the text between the flags to be invisible. Cross-references are described in the following section. %@NL@% %@NL@% %@AS@% \aExample \vsample_prog\v%@AE@%%@NL@% %@NL@% %@NL@% %@4@%%@AB@%QuickHelp Cross-References%@AE@%%@EH@%%@NL@% %@NL@% Help databases contain two types of cross-references: implicit cross-references and explicit cross-references. They are described in Section 7.1.1, "Contents of a Help File." %@NL@% %@NL@% An implicit cross-reference is any word that appears both in the topic text and as a context in the help file. For example, any time you request help on the word "close," the help window displays help on the %@AB@%close%@AE@% function. You don't need to code implicit cross-references in your help text files. %@NL@% %@NL@% %@AU@% Insert formatting flags to mark explicit cross-references.%@AE@% %@NL@% %@NL@% Explicit cross-references (hyperlinks) are words or phrases on the screen that are associated with a context. For example, the word "Example" in the initial help-screen area for any C function is an explicit cross-reference to the C program example for that function. You must insert formatting flags in your help text files to mark explicit cross-references. %@NL@% %@NL@% If the hyperlink consists of a single word, you can use invisible text to flag it in the source file. The \v formatting flag creates invisible text, as follows: %@NL@% %@NL@% %@AS@% hyperlink\vcontext\v%@AE@%%@NL@% %@NL@% Specify the first \v flag immediately following the word you want to use as the hyperlink. Following the flag, insert the context that the hyperlink crossreferences. The second \v flag marks the end of the context; that is, the end of the invisible text. HELPMAKE generates a cross-reference whose context is the invisible text, and whose hyperlink is the entire word. %@NL@% %@NL@% If the hyperlink consists of a phrase, rather than a single word, you must use anchored text to create explicit cross-references. Use the \a and \v flags to create anchored text as follows: %@NL@% %@NL@% %@AS@% \ahyperlink-words\vcontext\v%@AE@%%@NL@% %@NL@% The \a flag marks an anchor for the cross-reference. The text that follows the \a flag is the hyperlink. The hyperlink must fit entirely on one line. The first \v flag marks both the end of the hyperlink and the beginning of the invisible text that %@NL@% %@NL@% contains the cross-reference context. The second \v flag marks the end of the invisible text. %@NL@% %@NL@% The following example contains three implicit cross-references to the C routines %@AB@%abs%@AE@%, %@AB@%cabs%@AE@%, and %@AB@%fabs%@AE@%. %@NL@% %@NL@% %@AS@% See also: abs, cabs, fabs%@AE@%%@NL@% %@NL@% The following example shows the encoding for an explicit cross-reference to an example program and a function template from the help database for the C run-time library: %@NL@% %@NL@% %@AS@% See also: Example\vopen.ex\v, Template\vopen.tm\v, close%@AE@%%@NL@% %@NL@% Here, the hyperlinks are %@AS@% Example %@AE@% and %@AS@% Template%@AE@%, which reference the contexts %@AS@% open.ex %@AE@% and %@AS@% open.tm%@AE@%. The example also contains an implicit cross-reference to the %@AB@%close%@AE@% function. %@NL@% %@NL@% The following example shows the encoding for an explicit cross-reference to an entire family of functions: %@NL@% %@NL@% %@AS@% See also: \ais... functions\vis_functions\v, atoi%@AE@%%@NL@% %@NL@% The cross-reference uses anchored text to associate a phrase, rather than just a word, with a context. In this example, the hyperlink is the anchored phrase %@AS@% is... functions%@AE@%, and it cross-references the context %@AS@% is_functions%@AE@%. In addition, the example contains an implicit cross-reference to the %@AB@%atoi%@AE@% routine. %@NL@% %@NL@% The code below is an example in QuickHelp format that contains a single entry: %@NL@% %@NL@% %@AS@% .context open %@AS@% .length 13 %@AS@% \bInclude:\p <fcntl.h>, <io.h>, <sys\\types.h>, <sys\\stat.h> %@AS@% %@AS@% \bPrototype:\p int open(char *path, int flag[, int mode]); %@AS@% flag: O_APPEND O_BINARY O_CREAT O_EXCL O_RDONLY %@AS@% O_RDWR O_TEXT O_TRUNC O_WRONLY %@AS@% (can be joined by |) %@AS@% mode: S_IWRITE S_IREAD S_IREAD | S_IWRITE%@AE@%%@NL@% %@NL@% %@AS@% \bReturns:\p a handle if successful, or -1 if not. %@AS@% errno: EACCES, EEXIST, EMFILE, ENOENT %@AS@% %@AS@% \bSee also:\p \uExample\p\vopen.ex\v, \uTemplate\p\vopen.tp\v, %@AS@% access, chmod, close, creat, dup, dup2, fopen, sopen, umask%@AE@%%@NL@% %@NL@% The%@AB@% .length %@AE@%command near the beginning of the example specifies the size of the initial window for the help text. Here, the initial window displays 13 lines. %@NL@% %@NL@% The manifest constants (such as %@AB@%O_WRONLY%@AE@% and %@AB@%EEXIST%@AE@%), the C keywords (such as %@AB@%int%@AE@% and %@AB@%char%@AE@%), and the other functions (such as %@AB@%sopen%@AE@% and %@AB@%access%@AE@%) are implicit cross-references. The words %@AS@% Example %@AE@% and %@AS@% Template %@AE@% are explicit cross-references to the example %@AS@% open.ex %@AE@% and to the %@AB@%open%@AE@% template %@AS@% open.tp%@AE@%, respectively. Note the use of double backslashes in the include file names. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00070022 @%%@AB@%7.6.2 Minimally Formatted ASCII Format%@AE@%%@EH@%%@NL@% %@NL@% A minimally formatted ASCII text file comprises a sequence of topics, each preceded by one or more unique context definitions. Each context definition must be on a separate line beginning with a help delimiter (>>). Subsequent lines up to the next context definition constitute the topic text. %@NL@% %@NL@% %@AU@% Minimally formatted ASCII files cannot contain highlighting.%@AE@% %@NL@% %@NL@% Minimally formatted ASCII files can be used in two ways. You can compress the file with HELPMAKE, creating a help database, or an application can access the uncompressed file directly. Uncompressed files are somewhat larger and slower to search, however. Minimally formatted ASCII files are of fixed width, and they cannot contain highlighting (or other nondefault attributes) or cross-references. %@NL@% %@NL@% The following example, coded in minimally formatted ASCII, shows the same text as the QuickHelp example in the previous section. The first line of the example defines %@AS@% open %@AE@% as a context string. The minimally formatted ASCII help file must begin with the help delimiter (>>), so that HELPMAKE or the application can verify that the file is indeed an ASCII help file. %@NL@% %@NL@% %@AS@% >>>>open %@AS@% %@AS@% Include: <fcntl.h>, <io.h>, <sys\types.h>, <sys\stat.h> %@AS@% %@AS@% Prototype: int open(char *path, int flag[, int mode]); %@AS@% flag: O_APPEND O_BINARY O_CREAT O_EXCL O_RDONLY %@AS@% O_RDWR O_TEXT O_TRUNC O_WRONLY %@AS@% (can be joined by |) %@AS@% mode: S_IWRITE S_IREAD S_IREAD | S_IWRITE %@AS@% %@AS@% Returns: a handle if successful, or -1 if not. %@AS@% errno: EACCES, EEXIST, EMFILE, ENOENT%@AE@%%@NL@% %@NL@% %@AS@% See also: access, chmod, close, creat, dup, dup2, fopen, sopen, umask%@AE@%%@NL@% %@NL@% When displayed, the help information appears exactly as it is typed into the file. Any formatting codes are treated as ASCII text. Note that you do not need to escape backslashes in minimally formatted ASCII files. %@NL@% %@NL@% If you compress minimally formatted ASCII files, they are smaller and faster to search. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00070023 @%%@AB@%7.6.3 Rich Text Format (RTF)%@AE@%%@EH@%%@NL@% %@NL@% RTF is a Microsoft word-processing format supported by many other word processors. It allows documents to be transferred from one application to another without losing any formatting information. The HELPMAKE utility recognizes a subset of the full RTF syntax. If your file contains any RTF code that is not part of the subset, HELPMAKE ignores the code and strips it out of the file. %@NL@% %@NL@% Certain word-processing and file-conversion programs generate the RTF code automatically as output. You need not worry about inserting RTF codes yourself; you can simply format your help files directly with a word-processor that generates RTF, using the attributes supported by the subset. The only items you need to insert are the help delimiter (>>) and context string that start each entry. %@NL@% %@NL@% HELPMAKE recognizes the subset of RTF listed below: %@NL@% %@NL@% %@AB@%RTF Code%@AE@% %@AB@%Action%@AE@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% \b Boldface. The application decides how to display this; often it is intensified text. \fi <%@AI@%nnn%@AE@%> Paragraph first-line indent. \i Italic. The application decides how to display this; often it is reverse video. \li <%@AI@%nnn%@AE@%> Paragraph indent from left margin. \line New line (not new paragraph). \par End of paragraph. \pard Default paragraph formatting. \plain Default attributes. On most screens this is nonblinking normal intensity. \tab Tab character. \ul Underline. The application decides how to display this; some adapters that do not support underlining display it as blue text. \v Hidden text. Hidden text is used for cross-reference information and for some application-specific communications; it is not displayed. Using the word-processing program, you can break the topic text into paragraphs. When HELPMAKE compresses the file, it formats the text to the width given with the / W option, ignoring the paragraph formats. %@NL@% %@NL@% As with the other text formats, each entry in the database source consists of one or more context strings, followed by topic text. An RTF file can contain QuickHelp dot commands. %@NL@% %@NL@% The help delimiter (>>) at the beginning of any paragraph denotes the beginning of a new help entry. The text that follows on the same line is defined as a context for the topic. If the next paragraph also begins with the help delimiter, it also defines a context string for the same topic text. You can define any number of contexts for a block of topic text. The topic text comprises all subsequent paragraphs up to the next paragraph that begins with the help delimiter. %@NL@% %@NL@% The code below is an example of a help database that contains a single entry using subset RTF text. Note that RTF uses curly braces ({}) for nesting. Thus, the entire file is enclosed in curly braces, as is each specially formatted text item. %@NL@% %@NL@% %@AS@% {\rtf1 %@AS@% \pard >>open\par %@AS@% {\b Include:} <fcntl.h>, <io.h>, <sys\\types.h>, <sys\\stat.h>\par %@AS@% \par %@AS@% {\b Syntax:} int open( char * filename, int oflag[, int pmode ] %@AS@%);\par %@AS@% oflag: O_APPEND O_BINARY O_CREAT O_EXCL O_RDONLY\par %@AS@% O_RDWR O_TEXT O_TRUNC O_WRONLY\par %@AS@% (may be joined by |)\par %@AS@% pmode: S_IWRITE S_IREAD S_IREAD | S_IWRITE\par %@AS@% \par %@AS@% {\b Returns:} a handle if successful, or -1 if not.\par %@AS@% errno: EACCES, EEXIST, EMFILE, ENOENT\par %@AS@% \par %@AS@% {\b See also:} Examples{\v open.ex}, access, chmod, close, creat, %@AS@%dup,\par %@AS@% dup2, fopen, sopen, umask\par %@AS@% >>open.ex\par %@AS@% To build this help file, use the following command:\par %@AS@% \par %@AS@% HELPMAKE /S1 /E15 /OOPEN.HLP OPEN.RTF\par %@AS@% \par %@AS@% %@AS@% < Back >{\v !B} %@AS@% }%@AE@%%@NL@% %@NL@% Actual RTF output normally contains additional information that is not visible to the user; HELPMAKE ignores this extra information. %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@CR:C6A00080001 @%%@1@%%@AB@%Chapter 8 Customizing the Microsoft Programmer's WorkBench%@AE@%%@EH@%%@NL@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@NL@% Designed with flexibility in mind, the Microsoft Programmer's WorkBench (PWB) provides a highly extensible development platform for the Microsoft C Professional Development System. Using PWB it is easy to change basic environment features such as screen colors and key assignments, and you can add powerful new functions of your own using macros and C-language extensions. %@NL@% %@NL@% This chapter explains four methods for customizing the Programmer's WorkBench: setting switches, assigning keystrokes, writing macros, and writing C extensions. While it explains customization methods, the chapter does not document every customizable feature of the Programmer's WorkBench. Use on-line help as your primary source of information about these and other PWB features. %@NL@% %@NL@% This chapter assumes you are familiar with basic PWB operations and terminology. If you are not, read "Using the Programmer's WorkBench" in %@AI@%Installing and Using the Microsoft C Professional Development System%@AE@%. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00080002 @%%@AB@%8.1 Setting Switches%@AE@%%@EH@%%@NL@% %@NL@% The Programmer's WorkBench has a number of "switches," or user-configurable options, that control features such as screen colors. Each switch has a name and can be assigned a value. %@NL@% %@NL@% There are two ways to set PWB switches. The easiest way is by choosing Editor Settings in the Options menu. You can also edit the TOOLS.INI initialization file. These methods can also be used for more elaborate customizations, such as writing macros. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00080003 @%%@AB@%8.1.1 Editing the <assign> Pseudofile%@AE@%%@EH@%%@NL@% %@NL@% If you choose Editor Settings in the Options menu, PWB changes to the %@AB@%<assign>%@AE@% pseudofile and displays it in the current window. (A pseudofile is constructed dynamically by PWB; it exists only in memory.) The %@AB@%<assign>%@AE@% file lists all the current PWB settings. %@NL@% %@NL@% To change a switch, edit the line where it appears. For instance, the %@AB@%vscroll%@AE@% switch controls how many lines PWB scrolls vertically; its default setting is 1. To change it, move to the corresponding line: %@NL@% %@NL@% %@AS@% vscroll:1%@AE@%%@NL@% %@NL@% Change the 1 to 3 and move the cursor to another line. PWB highlights the line to indicate the change is legal. (If you make an illegal change, PWB signals an error.) The change takes effect immediately: now PWB scrolls text three vertical lines at a time. %@NL@% %@NL@% If you don't explicitly save a change, it disappears at the end of the current session. You can save a change by saving %@AB@%<assign>%@AE@% as you would any other file (by pressing ALT+A ALT+A F2). When you exit PWB, you are asked if you want to save TOOLS.INI, the PWB initialization file, which records customizations. Answer yes (type %@AS@% Y) %@AE@% to save the change. %@NL@% %@NL@% You can also use this method for more elaborate customizations, such as writing macros (see Section 8.3, "Writing Macros"). Simply insert a few blank lines in %@AB@%<assign>%@AE@% and enter the new information in them. Note that PWB only pays attention to lines you change or add to %@AB@%<assign>%@AE@%. Deleting a line has no effect. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00080004 @%%@AB@%8.1.2 Editing the TOOLS.INI Initialization File%@AE@%%@EH@%%@NL@% %@NL@% Another way to customize PWB is by editing TOOLS.INI, the initialization file used by PWB and other Microsoft language tools. This method is useful if you customize PWB extensively. %@NL@% %@NL@% While the %@AB@%<assign>%@AE@% file lists every customizable PWB item, the TOOLS.INI file contains lines only for items you have customized. Those items not mentioned in TOOLS.INI are set to a default value. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Dividing TOOLS.INI into Sections%@AE@%%@EH@%%@NL@% %@NL@% Since several tools can use TOOLS.INI, the file may contain information that doesn't relate to PWB. If you customize more than one tool, TOOLS.INI is divided into sections, one for each tool. Each section begins with a tag consisting of the tool's base name enclosed in square brackets: %@AS@% [PWB] %@AE@% for PWB.EXE, %@AS@%[NMAKE] %@AE@% for NMAKE.EXE, and so on. %@NL@% %@NL@% For example, say you set the %@AB@%vscroll%@AE@% switch to 3 and save the change, but you have not customized PWB in any other way. Your TOOLS.INI file will contain this section: %@NL@% %@NL@% %@AS@% [PWB] %@AS@% vscroll:3%@AE@%%@NL@% %@NL@% Settings following this tag are put in effect by PWB every time it starts. %@NL@% %@NL@% You can also create sections of TOOLS.INI that PWB reads only in certain circumstances. You can create sections for different video adapters, file-name extensions, and operating system versions. %@NL@% %@NL@% If you use more than one video display, TOOLS.INI can have a different section for each display: %@NL@% %@NL@% %@NL@% ■ %@AS@%[PWB-mono]%@AE@%%@NL@% %@NL@% ■ %@AS@%[PWB-cga]%@AE@%%@NL@% %@NL@% ■ %@AS@%[PWB-ega]%@AE@%%@NL@% %@NL@% ■ %@AS@%[PWB-vga]%@AE@%%@NL@% %@NL@% %@NL@% After each tag, you can set different screen colors, dimensions, and other display-specific switches. %@NL@% %@NL@% You can also create a section for files with specific extensions. For instance, your TOOLS.INI file could contain a section beginning with the tag %@NL@% %@NL@% %@AS@% [PWB-.C]%@AE@%%@NL@% %@NL@% for C source files, and %@NL@% %@NL@% %@AS@% [PWB-.ASM]%@AE@%%@NL@% %@NL@% for assembly-language (.ASM) source files. Each time you load a file with the designated extension, PWB reads the appropriate section of TOOLS.INI. For each file type, you could use a different set of macros and other customizations. %@NL@% %@NL@% TOOLS.INI can also contain sections specific to operating system versions. The following tag introduces a section specific to DOS version 3.20, for instance: %@NL@% %@NL@% %@AS@% [PWB-3.20]%@AE@%%@NL@% %@NL@% You can combine tags as needed. For example, the tag %@NL@% %@NL@% %@AS@% [PWB-3.20 PWB-10.10R]%@AE@%%@NL@% %@NL@% applies to DOS version 3.20 and OS/2 version 1.1 real mode. %@NL@% %@NL@% You can also create a section in TOOLS.INI containing switches for a userwritten extension. See Section 8.4.3, "Describing Functions and Switches." On-line help contains additional information about TOOLS.INI tags. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00080005 @%%@AB@%8.2 Assigning Keystrokes%@AE@%%@EH@%%@NL@% %@NL@% PWB allows you to assign any editing function to almost any keystroke. Reassigning keystrokes doesn't change PWB graphic interface, however. %@NL@% %@NL@% Keystrokes, like switches, are listed in the %@AB@%<assign>%@AE@% pseudofile (choose Key Assignments in the Options menu) and can be changed there. For example, say you want to assign the %@AB@%home%@AE@% cursor function to the SHIFT+HOME keystroke. The default keystroke assignment for %@AB@%home%@AE@% is: %@NL@% %@NL@% %@AS@% home:ctrl+home%@AE@%%@NL@% %@NL@% If you change the assignment to %@NL@% %@NL@% %@AS@% home:shift+home%@AE@%%@NL@% %@NL@% SHIFT+HOME moves the cursor to the home (upper left) window position. %@NL@% %@NL@% It is legal to assign more than one keystroke to the same function. For example, many keystrokes invoke the %@AB@%select%@AE@% function, which selects a text region. Thus, the previous example adds a new keystroke (SHIFT+HOME) for the %@AB@%home%@AE@% function; it does not remove the previous assignment (CTRL+HOME). %@NL@% %@NL@% There are two limitations on keystroke assignments: %@NL@% %@NL@% %@NL@% ■ You can't reassign a keystroke that PWB is using for a menu. For instance, if ALT+F pulls down the File menu, PWB ignores any attempt to reassign ALT+F.%@NL@% %@NL@% ■ You can't reassign ALT plus the number keys 1 - 9 (ALT+1, ALT+2, and so on). These keystrokes are reserved for the file history menu items.%@NL@% %@NL@% %@NL@% Each keystroke can only invoke one function. If you mistakenly assign a key-stroke to more than one function, PWB uses the most recent assignment. For example, %@NL@% %@NL@% %@AS@% home:ctrl+a %@AS@% setfile:ctrl+a%@AE@%%@NL@% %@NL@% assigns the CTRL+A keystroke to two different functions, %@AB@%home%@AE@% and %@AB@%setfile%@AE@%. The second assignment overrides the first, assigning CTRL+A to %@AB@%setfile%@AE@%. %@NL@% %@NL@% Occasionally, you may want to "unassign," or disable, a keystroke. This is done by assigning the %@AB@%unassigned%@AE@% function to the keystroke. For example, %@NL@% %@NL@% %@AS@% unassigned:ctrl+a%@AE@%%@NL@% %@NL@% disables CTRL+A. PWB signals an error when you press any unassigned key. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00080006 @%%@AB@%8.3 Writing Macros%@AE@%%@EH@%%@NL@% %@NL@% The fastest way to create a new editing function for PWB is to write a macro. The function can be as simple as inserting a long word or phrase, or it can perform complex tasks by invoking PWB functions and other macros. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00080007 @%%@AB@%8.3.1 Macro Syntax%@AE@%%@EH@%%@NL@% %@NL@% A macro can contain any combination of PWB functions, literal text, and macro operators. You can define as many as 1,024 macros at one time. %@NL@% %@NL@% %@AU@% Literal text is case sensitive.%@AE@% %@NL@% %@NL@% Literal text is anything inside double quotes. Inside literal text, you can represent a double quote as %@AS@% \"%@AE@% and a backslash as %@AS@% \\%@AE@%. Text is case sensitive inside quotes and case insensitive outside them. %@NL@% %@NL@% The following macro comments out a line of C source code: %@NL@% %@NL@% %@AS@% comment:=begline "/* " endline " */" %@AS@% comment:alt+c%@AE@%%@NL@% %@NL@% The first line names the macro and tells what it does. The %@AB@%begline%@AE@% and %@AB@%endline%@AE@% editor functions move the cursor, while the text inside quotes is printed at the current cursor position. The second line assigns a keystroke (ALT+C) to the macro. %@NL@% %@NL@% A macro definition must fit on one logical line. If necessary, you can use the backslash ( \ ) to continue the definition on the next line. For instance, the definition %@NL@% %@NL@% %@AS@% comment:=begline "/* " endline " */"%@AE@%%@NL@% %@NL@% could be written as %@NL@% %@NL@% %@AS@% comment:=begline \ %@AS@% "/* " endline \ %@AS@% " */"%@AE@%%@NL@% %@NL@% Notice the extra space before each backslash. If you want a space between the end of one line and the beginning of the other, you must precede the backslash with two spaces. %@NL@% %@NL@% You can use the %@AB@%arg%@AE@% function to pass arguments to functions. For example, the following macro passes the argument %@AS@% 15 %@AE@% to the %@AB@%plines%@AE@% function (which scrolls text down): %@NL@% %@NL@% %@AS@% movedown:=arg "15" plines%@AE@%%@NL@% %@NL@% Because %@AB@%arg%@AE@% precedes the literal text, the text doesn't appear on the screen. Instead, it is passed as an argument to the next function, %@AB@%plines%@AE@%. The macro scrolls the current text down 15 lines. %@NL@% %@NL@% Arguments can use regular expression syntax, as well (regular expressions are documented in on-line help): %@NL@% %@NL@% %@AS@% endword:=arg arg "( !.!$!\\:!;!\\)!\\(!,)" psearch%@AE@%%@NL@% %@NL@% The %@AB@%arg arg%@AE@% sequence directs the %@AB@%psearch%@AE@% function to treat the text argument as a regular expression search pattern. This search pattern tells PWB to search for the next period, end of line ($), colon, semicolon, close parenthesis, open parenthesis, or comma. %@NL@% %@NL@% A macro can invoke other macros: %@NL@% %@NL@% %@AS@% lcomment:= "/* " %@AS@% rcomment:= " */" %@AS@% commentout:=begline lcomment endline rcomment %@AS@% commentout:alt+z%@AE@%%@NL@% %@NL@% The %@AS@% commentout %@AE@% macro invokes the previously defined macros %@AS@% lcomment %@AE@% and %@AS@% %@AS@%rcomment.%@AE@% %@NL@% %@NL@% In addition to standard PWB functions, macros can invoke user-defined (extension) functions. See Section 8.4, "Writing and Building C Extensions." %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00080008 @%%@AB@%8.3.2 Macro Responses%@AE@%%@EH@%%@NL@% %@NL@% Some PWB functions ask you for confirmation. For example, the %@AB@%meta exit%@AE@% (quit without saving) function normally asks if you really want to exit. Such questions always take the answer "yes" (%@AS@%y%@AE@%) or "no" (%@AS@%n%@AE@%). %@NL@% %@NL@% When you invoke such a function in a macro, the function assumes an answer of yes and does not ask for confirmation. For example, the macro definition %@NL@% %@NL@% %@AS@% quit:=meta exit %@AS@% quit:alt+x%@AE@%%@NL@% %@NL@% invokes %@AB@%meta exit%@AE@% when you press ALT+X. Because the %@AB@%meta exit%@AE@% function is invoked from a macro, PWB exits without asking for confirmation. %@NL@% %@NL@% The following operators allow you to restore normal prompting or change the default responses: %@NL@% %@NL@% %@AB@%Operator%@AE@% %@AB@%Description%@AE@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@AB@%<%@AE@% Asks for confirmation; if not followed by another %@AB@%<%@AE@% operator, prompts for all further questions %@AB@%<y%@AE@% Assumes a response of yes %@AB@%<n%@AE@% Assumes a response of no A response operator applies to the function immediately preceding it. For instance, you can add the %@AB@%%@AE@% operator to the %@AS@% quit %@AE@% macro definition to restore the usual prompt: %@NL@% %@NL@% %@AS@% quit:=meta exit < %@AS@% quit:alt+x%@AE@%%@NL@% %@NL@% Now the macro prompts for a response before it exits. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00080009 @%%@AB@%8.3.3 Macro Arguments%@AE@%%@EH@%%@NL@% %@NL@% If you enter an argument in PWB and then invoke a macro, the argument is passed to the first function in the macro that takes an argument: %@NL@% %@NL@% %@AS@% tripleit:=copy paste paste%@AE@%%@NL@% %@NL@% The %@AS@% tripleit %@AE@% macro invokes the %@AB@%copy%@AE@% and %@AB@%paste%@AE@% editing functions. If you highlight a text area and then invoke the macro, your highlighted argument is passed to the %@AB@%copy%@AE@% function, which copies the argument to the clipboard. The macro then invokes %@AB@%paste%@AE@% twice. The effect is to insert two copies of the highlighted text. %@NL@% %@NL@% %@AU@% You cannot pass more than one argument from PWB to a macro.%@AE@% %@NL@% %@NL@% You cannot pass more than one argument from PWB to a macro, even if the macro invokes more than one function that can accept an argument. The argument always goes to the first function in the macro that takes an argument. %@NL@% %@NL@% You can also prompt for input inside a macro and pass the input as an argument using the %@AB@%prompt%@AE@% function as shown below: %@NL@% %@NL@% %@AS@% newfile:=arg "Next file: " prompt setfile < %@AS@% newfile:alt+n%@AE@%%@NL@% %@NL@% The %@AS@% newfile %@AE@% macro prompts for a file name and then switches to the specified file. The sequence %@AS@% arg "Next file: "%@AE@% passes a text argument to %@AB@%prompt%@AE@%, which prints the text on the dialog line and waits for input. The input is passed as a text argument to the %@AB@%setfile%@AE@% function, which switches to that file. For more information on the %@AB@%prompt%@AE@% function, see on-line help. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00080010 @%%@AB@%8.3.4 Macro Conditionals%@AE@%%@EH@%%@NL@% %@NL@% Macros can take different actions depending on certain conditions. Such macros take advantage of the fact that PWB editing functions generally return values─a TRUE (nonzero) value if successful or FALSE (zero) if unsuccessful. %@NL@% %@NL@% Macros can use four conditional operators: %@NL@% %@NL@% %@AB@%Operator%@AE@% %@AB@%Description%@AE@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@AB@%:>%@AE@%%@AI@%label%@AE@% Defines a %@AI@%label%@AE@% that can be targeted by other operators %@AB@%=>%@AE@%%@AI@%label%@AE@% Jumps to %@AI@%label%@AE@% %@AB@%+>%@AE@%%@AI@%label%@AE@% Jumps to %@AI@%label%@AE@% if the previous function returns TRUE %@AB@%->%@AE@%%@AI@%label%@AE@% Jumps to %@AI@%label%@AE@% if the previous function returns FALSE For example, the %@AS@% leftmarg %@AE@% macro moves the cursor to the left margin of the editing window: %@NL@% %@NL@% %@AS@% leftmarg:=:>leftmore left +>leftmore%@AE@%%@NL@% %@NL@% The macro above invokes the %@AB@%left%@AE@% function repeatedly (jumping to the label %@AS@% %@AS@%%@AE@%leftmore) until it returns FALSE, indicating the cursor has reached the left margin. %@NL@% %@NL@% The label must appear immediately after the conditional operator, with no intervening spaces. A conditional operator without a label exits the macro immediately if the condition is true. If the condition is false, the macro continues execution. The following example demonstrates this: %@NL@% %@NL@% %@AS@% turnon:=insertmode +> insertmode%@AE@%%@NL@% %@NL@% This macro turns on insert mode regardless of whether insert mode is currently on or off. If insert mode is off, the first invocation of %@AB@%insertmode%@AE@% toggles the mode on and returns TRUE, causing the %@AB@%+>%@AE@% operator to terminate the macro. If insert mode is currently on, the first invocation of %@AB@%insertmode%@AE@% turns insert mode off and returns FALSE. The macro then invokes %@AB@%insertmode%@AE@% a second time, turning insert mode back on. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00080011 @%%@AB@%8.3.5 Temporary Macros%@AE@%%@EH@%%@NL@% %@NL@% Occasionally, you may want to create a macro that lasts only through the current session. This can be done with the %@AB@%assign%@AE@% function. For example, the following steps create the %@AS@% comment %@AE@% macro described above. %@NL@% %@NL@% To create the macro: %@NL@% %@NL@% %@NL@% ■ Press ALT+A%@NL@% %@NL@% ■ Type %@AS@% %@AE@%comment:=begline "/* " endline " */" %@NL@% %@NL@% ■ Press ALT+=%@NL@% %@NL@% %@NL@% To assign the ALT+C keystroke to the macro: %@NL@% %@NL@% %@NL@% ■ Press ALT+A%@NL@% %@NL@% ■ Type %@AS@% %@AE@%comment:alt+c%@NL@% %@NL@% ■ Press ALT+=%@NL@% %@NL@% %@NL@% The macro is available immediately and then disappears at the end of the current session. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00080012 @%%@AB@%8.3.6 Macro Recordings%@AE@%%@EH@%%@NL@% %@NL@% Another way to create a macro is by recording your own actions. The entire sequence of actions is saved and can be replayed later by pressing a key. %@NL@% %@NL@% You start the recording by invoking the %@AB@%record%@AE@% function. PWB names the resulting macro %@AB@%recordvalue%@AE@% by default, but you can use other names as well. To record a macro: %@NL@% %@NL@% %@NL@% ■ Choose Record On from the Edit menu to start the recording.%@NL@% %@NL@% ■ Perform the actions you want to record.%@NL@% %@NL@% ■ Choose Record On again to end the recording.%@NL@% %@NL@% ■ If %@AB@%recordvalue%@AE@% is not already assigned, assign it to a keystroke as described above.%@NL@% %@NL@% %@NL@% After you complete these steps, a macro named %@AB@%recordvalue%@AE@% is available through the keystroke you assigned in the last step above. When you press this key, PWB replays the actions you recorded. %@NL@% %@NL@% If you don't do anything more, the recorded macro is temporary─it disappears when you exit PWB. To save the macro permanently: %@NL@% %@NL@% %@NL@% ■ Open the %@AB@%<record>%@AE@% pseudofile (press ALT+A, type %@AS@% <record>%@AE@%, press F2).%@NL@% %@NL@% ■ Copy the macro definition in %@AB@%<record>%@AE@%.%@NL@% %@NL@% ■ Paste the definition into the %@AS@% [PWB] %@AE@% section of your TOOLS.INI file.%@NL@% %@NL@% %@NL@% Studying recorded macros can teach you a lot about macros and editor functions. If you open the %@AB@%<record>%@AE@% pseudofile in a second window before you record, you can watch PWB write the macro definition function by function. %@NL@% %@NL@% If you save a recorded macro, you'll want to name it something other than %@AB@%recordvalue,%@AE@% the default name. To do this, pass the new name as an argument when you start the recording: %@NL@% %@NL@% %@NL@% ■ Press ALT+A ALT+A.%@NL@% %@NL@% ■ Type the new name.%@NL@% %@NL@% ■ Choose Record On from the Edit menu to start recording.%@NL@% %@NL@% ■ Complete the recording as usual.%@NL@% %@NL@% %@NL@% You can expand an existing macro using the same process. If you supply the name of an existing macro, PWB appends the recorded commands to the macro instead of replacing it. %@NL@% %@NL@% %@AU@% You can record a series of actions without executing them.%@AE@% %@NL@% %@NL@% You can also make a "silent" recording, which records a series of actions without executing them. Start the recording with a %@AB@%meta record%@AE@% command (press F9 SHIFT+CTRL+R). Then complete the recording process as described above. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00080013 @%%@AB@%8.4 Writing and Building C Extensions%@AE@%%@EH@%%@NL@% %@NL@% An "extension" is a file containing one or more user-written functions. PWB loads extensions at run time. Once the extension has been loaded, its functions can be assigned their own keystrokes, given arguments, and invoked in macros, exactly like other PWB functions. %@NL@% %@NL@% %@AU@% User-written functions execute more quickly than macros.%@AE@% %@NL@% %@NL@% The ability to load and call user-written functions makes PWB highly extensible. Because they consist of compiled C code, your functions can perform more complex jobs than macros can, and they execute many times faster. %@NL@% %@NL@% An extension contains executable code, but it differs from a normal executable file in some important ways:%@CR:C6A00080014 @% %@NL@% %@NL@% %@NL@% ■ It does not contain the usual C start-up code.%@NL@% %@NL@% ■ It contains special data structures that describe its functions to PWB.%@NL@% %@NL@% ■ Its functions are declared in a form that allows PWB to call them and pass arguments to them.%@NL@% %@NL@% ■ Its functions can call native PWB functions, and some, but not all, C library functions.%@NL@% %@NL@% %@NL@% This section explains how to build, load, and invoke a PWB extension. The example, CENTER.C, serves as a basis for discussion throughout the rest of this chapter.%@CR:C6A00080015 @%%@CR:C6A00080016 @% %@NL@% %@NL@% The CENTER.C extension contains one extension function, %@AS@% %@AE@%CenterLine, which centers a line or range of lines in the current file. %@NL@% %@NL@% %@AS@% /* CENTER.C: Sample PWB extension */ %@AS@% %@AS@% #define LINE_LENGTH 80 /* Assumes 80-column screen */ %@AS@% %@AS@% #include <string.h> %@AS@% /* PWB extension header file */ %@AS@% #include "ext.h" %@AS@% %@AS@% PWBFUNC CenterLine( unsigned argData, %@AS@% ARG _far *pArg, %@AS@% flagType fMeta ); %@AS@% %@AS@% /* Switch Table */ %@AS@% struct swiDesc swiTable[] = %@AS@% { %@AS@% { NULL, NULL, 0 } %@AS@% }; %@AS@% %@AS@% /* Command Table */ %@AS@% struct cmdDesc cmdTable[] = %@AS@% { %@AS@% { "CenterLine", CenterLine, 0, NOARG | LINEARG }, %@AS@% { NULL, NULL, 0, 0 } %@AS@% }; %@AS@% %@AS@% /* Initialization Function */ %@AS@% void EXTERNAL WhenLoaded( void ) %@AS@% { %@AS@% DoMessage( "Loading Center extension" ); %@AS@% } %@AS@% %@AS@% /* Extension (user-written) function */ %@AS@% PWBFUNC CenterLine( unsigned argData, %@AS@% ARG _far *pArg, %@AS@% flagType fMeta ) %@AS@% { %@AS@% PFILE pFile; %@AS@% LINE yStart, yEnd; %@AS@% int len; %@AS@% char *pBuf, buf[BUFLEN];%@AE@%%@NL@% %@NL@% %@AS@% /* Get a handle to the current file */ %@AS@% pFile = FileNameToHandle( "", "" ); %@AS@% %@AS@% /* Handle various argument types */ %@AS@% switch( pArg->argType ) %@AS@% { %@AS@% case NOARG: /* No argument. Center current line */ %@AS@% yStart = yEnd = pArg->arg.noarg.y; %@AS@% break; %@AS@% %@AS@% case LINEARG: /* Center range of lines */ %@AS@% yStart = pArg->arg.linearg.yStart; %@AS@% yEnd = pArg->arg.linearg.yEnd; %@AS@% break; %@AS@% } %@AS@% %@AS@% /* Center current line or range of lines */ %@AS@% for( ; yStart <= yEnd; yStart++ ) %@AS@% { %@AS@% /* Get a line from the current file */ %@AS@% len = GetLine( yStart, buf, pFile ); %@AS@% %@AS@% if( len > 0 ) %@AS@% { %@AS@% /* Center the text in this line */ %@AS@% pBuf = buf + strspn( buf, " \t" ); %@AS@% len = strlen( pBuf ); %@AS@% memmove( buf+(LINE_LENGTH-len) / 2, pBuf, len+1 ); %@AS@% memset( buf, ' ', (LINE_LENGTH - len) / 2 ); %@AS@% %@AS@% /* Write modified line back to the current file */ %@AS@% PutLine( yStart, buf, pFile ); %@AS@% } %@AS@% } %@AS@% return TRUE; %@AS@% }%@AE@%%@NL@% %@NL@% Building and using a PWB extension involves four basic steps:%@CR:C6A00080017 @% %@NL@% %@NL@% %@NL@% 1. Compiling%@NL@% %@NL@% 2. Linking%@NL@% %@NL@% 3. Loading the extension into PWB%@NL@% %@NL@% 4. Assigning a keystroke to each function in the extension%@NL@% %@NL@% %@NL@% You can build extensions for both real mode (DOS) and OS/2 protected mode. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00080018 @%%@AB@%8.4.1 Building Real-Mode Extensions%@AE@%%@EH@%%@NL@% %@NL@% This section describes how to build extensions for real mode.%@CR:C6A00080019 @% %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Compiling%@AE@%%@EH@%%@NL@% %@NL@% The source (.C) file for an extension must include EXT.H, the extension header file. Since an extension is not a stand-alone executable file, it doesn't have a %@AB@%main%@AE@% function; so its source file is compiled with the /c (compile, but don't link) option: %@NL@% %@NL@% %@AS@% CL /c /Gs /ACw CENTER.C%@AE@%%@NL@% %@NL@% The /Gs option turns off stack checking; the /ACw option selects the required custom memory model. %@NL@% %@NL@% PWB extension interface is designed for C programmers. However, you can write extensions in assembly language or other languages if you simulate the required C memory model (in which SS is not assumed to equal DS). %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Linking%@AE@%%@EH@%%@NL@% %@NL@% The first object file in the link command must be the stub EXTHDR.OBJ: %@NL@% %@NL@% %@AS@% link exthdr center, center.mxt;%@AE@%%@NL@% %@NL@% PWB can load a file with any name, but most programmers use the .MXT extension to distinguish a PWB extension from a normal .EXE file. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Loading the Extension%@AE@%%@EH@%%@NL@% %@NL@% Once the extension is built, you can cause PWB to load it by adding a %@AB@%load%@AE@% command to your TOOLS.INI file: %@NL@% %@NL@% %@AS@% load:center%@AE@%%@NL@% %@NL@% You don't need to supply a file extension; PWB assumes the correct file extension. To specify a path, supply the path name preceded by a dollar sign ($): %@NL@% %@NL@% %@AS@% load:$INIT:center%@AE@%%@NL@% %@NL@% The example tells PWB to search the directories specified in the INIT environment variable. If listed, the environment variable must be in uppercase. %@NL@% %@NL@% TOOLS.INI can contain multiple %@AB@%load%@AE@% commands for different extensions. However, loading each extension involves a certain amount of memory overhead, and there is no way to unload an extension from memory. To conserve memory, place all frequently used functions in a single extension and load only that extension.%@CR:C6A00080020 @% %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Assigning Keystrokes to Functions%@AE@%%@EH@%%@NL@% %@NL@% After an extension has been loaded, you must provide some way to invoke its functions from inside PWB. A keystroke is the most common means, although extension functions, like native PWB functions, can be invoked in various ways. %@NL@% %@NL@% You can assign the ALT+C keystroke to the %@AS@% CenterLine %@AE@% function with: %@NL@% %@NL@% %@AS@% CenterLine:alt+c%@AE@%%@NL@% %@NL@% Once the %@AS@% CenterLine %@AE@% function has been assigned to this keystroke, you can invoke it by pressing ALT+C. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00080021 @%%@AB@%8.4.2 Building Protected-Mode Extensions%@AE@%%@EH@%%@NL@% %@NL@% The build process for OS/2 protected mode differs only slightly from the real-mode build process.%@CR:C6A00080022 @% %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Compiling%@AE@%%@EH@%%@NL@% %@NL@% The source (.C) file for an extension must include EXT.H, the extension header file. Since an extension is not a stand-alone executable file, it doesn't have a %@AB@%main%@AE@% function; so its source file is compiled with the /c (compile, but don't link) option: %@NL@% %@NL@% %@AS@% CL /c /Gs /ACw CENTER.C%@AE@%%@NL@% %@NL@% The /Gs option turns off stack checking; the /ACw option selects the required custom memory model. %@NL@% %@NL@% PWB extension interface is designed for C programmers. However, you can write extensions in assembly language or other languages if you simulate the required C memory model (in which SS is not assumed to equal DS). %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Linking%@AE@%%@EH@%%@NL@% %@NL@% Link with EXTHRDP.OBJ instead of EXTHDR.OBJ. Specify the .PXT extension for the output file. List the EXT.DEF definitions file: %@NL@% %@NL@% %@AS@% link exthdrp center, center.pxt,, os2, ext.def%@AE@%%@NL@% %@NL@% %@NL@% %@4@%%@AB@%Loading the Extension%@AE@%%@EH@%%@NL@% %@NL@% In protected mode, PWB assumes the .PXT file extension. If your extension is not found, PWB assumes the .DLL file extension.%@CR:C6A00080023 @% %@NL@% %@NL@% %@AU@% You cannot create a bound extension.%@AE@% %@NL@% %@NL@% There is no way to create a bound extension (one that runs in both real and protected mode). However, you can build separate versions of an extension and use a single TOOLS.INI %@AB@%load%@AE@% command to load the correct extension in each mode. PWB loads the real-mode file (.MXT) in real mode and the protected-mode file (.PXT or .DLL) in protected mode. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Assigning Keystrokes to Functions%@AE@%%@EH@%%@NL@% %@NL@% After an extension has been loaded, you must provide some way to invoke its functions from inside PWB. A keystroke is the most common means, although extension functions, like native PWB functions, can be invoked in various ways. %@NL@% %@NL@% You can assign the ALT+C keystroke to the %@AS@% CenterLine %@AE@% function with: %@NL@% %@NL@% %@AS@% CenterLine:alt+c%@AE@%%@NL@% %@NL@% Once the %@AS@% CenterLine %@AE@% function has been assigned to this keystroke, you can invoke it by pressing ALT+C. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00080024 @%%@AB@%8.4.3 Describing Functions and Switches%@AE@%%@EH@%%@NL@% %@NL@% To call functions in your extension, PWB must know certain information about each function, such as the name and address of the function, what types of arguments it accepts, and what switches (if any) it employs. You provide this information in a pair of arrays─%@AB@%cmdTable%@AE@% and %@AB@%swiTable%@AE@%─that must be present in every PWB extension.%@CR:C6A00080025 @% %@NL@% %@NL@% %@NL@% %@4@%%@AB@%The cmdTable Array%@AE@%%@EH@%%@NL@% %@NL@% Every extension must contain an array of structures named %@AB@%cmdTable%@AE@%. This array provides the information PWB needs to call the extension's functions. %@NL@% %@NL@% The %@AB@%cmdTable%@AE@% array is an array of structures of type %@AB@%cmdDesc%@AE@% (which is declared in EXT.H). Each structure in the array describes one function in the extension. The array is terminated with a structure whose members are all null. %@NL@% %@NL@% For instance, the CENTER.C extension has one function, named %@AS@% CenterLine%@AE@%, so its %@AB@%cmdTable%@AE@% array contains two structures (one for %@AS@% CenterLine %@AE@% and the other to terminate the table):%@CR:C6A00080026 @% %@NL@% %@NL@% %@AS@% struct cmdDesc cmdTable[] = %@AS@% { %@AS@% { "CenterLine", CenterLine, 0, NOARG | LINEARG }, %@AS@% { NULL, NULL, 0, 0 } %@AS@% };%@AE@%%@NL@% %@NL@% Each %@AB@%cmdDesc%@AE@% structure in %@AB@%cmdTable%@AE@% contains these members: %@NL@% %@NL@% %@NL@% ■ The function's name%@NL@% %@NL@% ■ The function's address%@NL@% %@NL@% ■ Reserved item (must be 0)%@NL@% %@NL@% ■ The argument types the function accepts%@NL@% %@NL@% %@NL@% The last member in the list is an integer containing bitflags representing types of arguments that your function accepts. You can combine more than one bitflag using the %@AB@%OR%@AE@% (%@AB@% | %@AE@%) operator. %@NL@% %@NL@% For instance, the %@AS@% CenterLine %@AE@% function can handle an argument of the type %@AB@%LINEARG%@AE@%, or no arguments (%@AB@%NOARG%@AE@%). So it lists the types: %@NL@% %@NL@% %@AS@% NOARG | LINEARG%@AE@%%@NL@% %@NL@% There are many argument types in addition to these. For information about specific argument types, see the Extensions topic in on-line help. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%The swiTable Array%@AE@%%@EH@%%@NL@% %@NL@% Extension functions, such as native PWB functions, can respond to user- configurable switches. From the viewpoint of an extension function, a switch is usually a variable that the user can change at run time. Your function must be ready to respond to these changes, and PWB must have some way to convey them. The vehicle for this interchange is an array of structures named %@AB@%swiTable%@AE@%. %@NL@% %@NL@% The %@AB@%swiTable%@AE@% array is similar to the %@AB@%cmdTable%@AE@% array described above. It is an array of structures, terminated by a structure whose members are all null. Each structure in %@AB@%swiTable%@AE@% describes one switch used by a function in your extension. %@NL@% %@NL@% The CENTER.C extension doesn't take any switches, so its %@AB@%swiTable%@AE@% array only contains a terminating null structure:%@CR:C6A00080027 @% %@NL@% %@NL@% %@AS@% struct swiDesc swiTable[] = %@AS@% { %@AS@% { NULL, NULL, 0 } %@AS@% };%@AE@%%@NL@% %@NL@% Each structure in %@AB@%swiTable%@AE@% is of type %@AB@%swiDesc%@AE@%, whose members are %@NL@% %@NL@% %@NL@% ■ A pointer to the switch name%@NL@% %@NL@% ■ A pointer to the switch or a function%@NL@% %@NL@% ■ A flag that indicates the type of the switch%@NL@% %@NL@% %@NL@% A switch can be one of three types: %@AB@%SWI_BOOLEAN%@AE@% for TRUE/FALSE conditions, %@AB@%SWI_NUMERIC%@AE@% for numerics, or %@AB@%SWI_SPECIAL%@AE@% for strings. %@NL@% %@NL@% The second member of %@AB@%swiDesc%@AE@% is a pointer. It points to the switch itself if the switch is type %@AB@%SWI_BOOLEAN%@AE@% or %@AB@%SWI_NUMERIC%@AE@%, or to a string-handling function if the switch is type %@AB@%SWI_SPECIAL%@AE@%. %@NL@% %@NL@% For instance, the following code creates a numeric switch with the default value 27: %@NL@% %@NL@% %@AS@% static int n = 27; %@AS@% %@AS@% struct swiDesc swiTable[] = %@AS@% { %@AS@% { "newswitch", &n, SWI_NUMERIC | RADIX10 }, %@AS@% { NULL, NULL, 0 } %@AS@% };%@AE@%%@NL@% %@NL@% The first structure in the example above contains the name of the switch (%@AS@%"newswitch"%@AE@%), a pointer to the variable that contains the switch's value (%@AS@%&n%@AE@%), and the switch's type (%@AB@%SWI_NUMERIC%@AE@%). %@NL@% %@NL@% In this example, the third structure member contains another constant, %@AB@%RADIX10%@AE@%. If a switch is type %@AB@%SWI_NUMERIC%@AE@%, you must supply a second constant to tell PWB whether to interpret user-assigned values as decimal (%@AB@%RADIX10%@AE@%) or hexadecimal (%@AB@%RADIX16%@AE@%) numbers. %@NL@% %@NL@% If the switch is type %@AB@%SWI_SPECIAL%@AE@%, the second member of %@AB@%swiDesc%@AE@% is a pointer to an additional string-handling function that you write. This function must be of type %@AB@%int far _pascal%@AE@%. Each time the text switch changes, PWB calls your function, passing it the address of the updated string as a %@AB@%char far%@AE@% pointer. The following code stores the updated string in a buffer named %@AS@% %@AS@%mystring%@AE@%:%@CR:C6A00080028 @% %@NL@% %@NL@% %@AS@% char mystring[BUFLEN]; %@AS@% %@AS@% int far _pascal setstr( char far *ptr ) %@AS@% { %@AS@% strcpy( mystring, ptr ); %@AS@% }%@AE@%%@NL@% %@NL@% If desired, you can list switches for extension functions separately from other switches. Whenever PWB loads an extension, it looks in TOOLS.INI for a section with this form: %@NL@% %@NL@% %@AS@% [PWB-ext]%@AE@%%@NL@% %@NL@% where %@AI@%ext%@AE@% is the base name of the extension. If the extension exists, PWB recognizes the settings immediately following the tag. For instance, if your extension SAMPLE.MXT uses a numeric switch named %@AS@% numbills%@AE@%, you can set %@AS@% %@AS@%numbills %@AE@% to the value 66 with: %@NL@% %@NL@% %@AS@% [PWB-SAMPLE] %@AS@% numbills:66%@AE@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00080029 @%%@AB@%8.4.4 Initializing Functions%@AE@%%@EH@%%@NL@% %@NL@% Every PWB extension must contain a function named %@AB@%WhenLoaded%@AE@%, which PWB calls immediately after loading the extension. The %@AB@%WhenLoaded%@AE@% function provides a chance to do any initialization that your functions require. (If your functions don't need any initialization, they can simply return.) %@NL@% %@NL@% The CENTER.C extension uses %@AB@%WhenLoaded%@AE@% to display a loading message:%@CR:C6A00080030 @%%@CR:C6A00080031 @%%@CR:C6A00080032 @% %@NL@% %@NL@% %@AS@% void EXTERNAL WhenLoaded( void ) %@AS@% { %@AS@% DoMessage( "Loading Center extension" ); %@AS@% }%@AE@%%@NL@% %@NL@% %@AB@%DoMessage%@AE@% is a PWB function that displays a message on the dialog line. Section 8.4.7, "Calling PWB Functions," lists PWB functions and explains how to call them. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00080033 @%%@AB@%8.4.5 Prototyping Functions%@AE@%%@EH@%%@NL@% %@NL@% To be called by PWB, each extension function must be declared as type %@AB@%PWBFUNC%@AE@% and accept the parameters %@AB@%argData%@AE@%, %@AB@%pArg%@AE@%, and %@AB@%fMeta%@AE@%. The %@AS@% CenterLine %@AS@%%@AE@%function in the section of CENTER.C code below follows this model: %@NL@% %@NL@% %@AS@% PWBFUNC CenterLine( unsigned argData, %@AS@% ARG _far *pArg, %@AS@% flagType fMeta )%@AE@%%@NL@% %@NL@% The %@AB@%PWBFUNC%@AE@% type is actually a macro that evaluates to %@AB@%flagType _pascal %@AB@%_loadds _far%@AE@%. The %@AB@%flagType%@AE@% return type declares that the function returns either TRUE (nonzero) or FALSE (zero). Your function should return a value so that it can be used in a macro with conditionals. The modifiers %@AB@%_pascal%@AE@%, %@AB@%_loadds%@AE@%, and %@AB@%_far%@AE@% specify the calling conventions PWB expects editor functions to have. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00080034 @%%@AB@%8.4.6 Receiving Parameters%@AE@%%@EH@%%@NL@% %@NL@% Like native PWB functions, extension functions can receive parameters from the user. The CENTER.C example allows you to select a range of lines to center, for example. The selected range is passed as a parameter to the %@AS@% %@AS@%CenterLine %@AE@% function.%@CR:C6A00080035 @%%@CR:C6A00080036 @%%@CR:C6A00080037 @% %@NL@% %@NL@% Extension functions receive parameters in much the same way ordinary C programs receive command-line parameters. In both cases, the parameters are passed in a predefined data construct─%@AB@%argc%@AE@% and %@AB@%argv%@AE@% for a normal C program, and the following parameters for an extension function: %@NL@% %@NL@% %@AB@%Parameter%@AE@% %@AB@%Description%@AE@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@AB@%argData%@AE@% The keystroke used to invoke your function %@AB@%pArg%@AE@% A pointer to a structure containing arguments passed to your function %@AB@%fMeta%@AE@% TRUE (nonzero) if %@AB@%meta%@AE@% precedes the argument, otherwise FALSE (zero) The first parameter is rarely used. Most extension functions receive all their parameter data in the second parameter, %@AB@%pArg%@AE@%. This parameter is a pointer to a structure of type %@AB@%ARG%@AE@%, which contains: %@NL@% %@NL@% %@AB@%Parameter%@AE@% %@AB@%Description%@AE@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@AB@%argType%@AE@% An integer that indicates the argument type %@AB@%arg%@AE@% A union of structures, one structure for each argument type Typically, your function tests %@AB@%pArg->argType%@AE@% to find out what type of parameter PWB has passed. Once the type is known, the function responds accordingly. The following code from CENTER.C handles two argument types:%@CR:C6A00080038 @% %@NL@% %@NL@% %@AS@% switch( pArg->argType ) %@AS@% { %@AS@% case NOARG: /* No argument. Center current line */ %@AS@% yStart = yEnd = pArg->arg.noarg.y; %@AS@% break; %@AS@% %@AS@% case LINEARG: /* Center range of lines */ %@AS@% yStart = pArg->arg.linearg.yStart; %@AS@% yEnd = pArg->arg.linearg.yEnd; %@AS@% break; %@AS@% }%@AE@%%@NL@% %@NL@% %@AU@% PWB rejects invalid arguments.%@AE@% %@NL@% %@NL@% If your function takes only one argument, it doesn't need to test %@AB@%pArg->argType%@AE@% at all. PWB knows beforehand what argument types your function accepts (via %@AB@%cmdDesc%@AE@%) and rejects any invalid arguments. %@NL@% %@NL@% Once the argument type is known, your function can access the parameters through %@AB@%pArg->arg%@AE@%, a structure whose members differ for each argument type. In the %@AB@%NOARG%@AE@% (no arguments) case, it contains %@AI@%x%@AE@% and %@AI@%y%@AE@% values identifying the cursor position in the current file: %@NL@% %@NL@% %@AS@% struct noargType %@AS@% { /* no argument */ %@AS@% LINE y; /* cursor line */ %@AS@% COL x; /* cursor column */ %@AS@% };%@AE@%%@NL@% %@NL@% The CENTER.C example uses the %@AI@%y%@AE@% value in this structure (%@AB@%noarg.y%@AE@%, the cursor line) to center the current line: %@NL@% %@NL@% %@AS@% case NOARG: /* No argument. Center current line */ %@AS@% yStart = yEnd = pArg->arg.noarg.y; %@AS@% break;%@AE@%%@NL@% %@NL@% Similarly, in the %@AB@%LINEARG%@AE@% case, the %@AB@%pArg->arg%@AE@% structure contains three values: %@NL@% %@NL@% %@AS@% struct lineargType %@AS@% { /* line argument specified */ %@AS@% int cArg; /* count of args pressed */ %@AS@% LINE yStart; /* starting line of range */ %@AS@% LINE yEnd; /* ending line of range */ %@AS@% };%@AE@%%@NL@% %@NL@% The CENTER.C example uses the starting and ending values in this structure (%@AB@%yStart%@AE@% and %@AB@%yEnd%@AE@%) to center a range of selected lines: %@NL@% %@NL@% %@AS@% case LINEARG: /* Center range of lines */ %@AS@% yStart = pArg->arg.linearg.yStart; %@AS@% yEnd = pArg->arg.linearg.yEnd; %@AS@% break;%@AE@%%@NL@% %@NL@% The method is the same for other argument types. The %@AB@%pArg->arg%@AE@% structures for all argument types are described in on-line help. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00080039 @%%@AB@%8.4.7 Calling PWB Functions%@AE@%%@EH@%%@NL@% %@NL@% Many of PWB's internal functions are public. Your extension function can call them for the same purposes that PWB itself does. This section demonstrates the most commonly used PWB functions─those that manipulate the current file.%@CR:C6A00080040 @%%@CR:C6A00080041 @% %@NL@% %@NL@% A list of callable PWB functions appears near the end of this section. For complete information on specific PWB functions, consult on-line help. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Getting a File Handle%@AE@%%@EH@%%@NL@% %@NL@% Extension functions can do many different tasks, but they typically manipulate a file in some way. The extension function in the CENTER.C example rewrites a line or lines in the current file, for example. The current file is the one that appears in the editing window. Since it is already open for editing, you can access the current file without opening it. Simply assign its file handle to a variable in your function. %@NL@% %@NL@% PWB file-handling functions use file handles of type %@AB@%PFILE%@AE@%. The CENTER.C example declares the following handle variable: %@NL@% %@NL@% %@AS@% PFILE pFile;%@AE@%%@NL@% %@NL@% The %@AB@%FileNameToHandle%@AE@% function gets a handle to a file that is already open for editing: %@NL@% %@NL@% %@AS@% pFile = FileNameToHandle( "", "" );%@AE@%%@NL@% %@NL@% The function takes two string arguments. If the first string is null, as here, the %@AB@%FileNameToHandle%@AE@% function returns a handle to the current file. You can use the %@AB@%AddFile%@AE@% function to get handles to other files (in which case you may need to use other PWB functions such as %@AB@%FileRead%@AE@%).%@CR:C6A00080042 @% %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Reading a Line From the File%@AE@%%@EH@%%@NL@% %@NL@% Once your function has a file handle, it can read from the file with the %@AB@%GetLine%@AE@% function, which reads one line at a time: %@NL@% %@NL@% %@AS@% len = GetLine( yStart, buf, pFile );%@AE@%%@NL@% %@NL@% The first argument is a line number, the second a pointer to a buffer, and the third a file handle. So the above call reads line number %@AS@% yStart %@AE@% from the file whose handle is %@AS@% pFile %@AE@% into the buffer %@AS@% buf%@AE@%. Note that the first line in a file is line 0, not line 1. %@NL@% %@NL@% Once you have read a line into a local buffer, you can manipulate it as desired. CENTER.C uses its buffer %@AS@% buf %@AE@% to center the line's text. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Writing a Line to the File%@AE@%%@EH@%%@NL@% %@NL@% After modifying a line, you can write it back to the file. The %@AB@%PutLine%@AE@% function writes one line at a time: %@NL@% %@NL@% %@AS@% PutLine( yStart, buf, pFile );%@AE@%%@NL@% %@NL@% %@AB@%PutLine%@AE@% takes the same arguments as %@AB@%GetLine%@AE@%─a line number, buffer pointer, and file handle. In CENTER.C, the above call writes the line from %@AS@% buf %@AE@% to line %@AS@% %@AE@%yStart in the file whose handle is %@AS@% pFile%@AE@%. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Summary of PWB Functions%@AE@%%@EH@%%@NL@% %@NL@% If you understand how CENTER.C works, you know the basics of using PWB functions in your own functions. The rest is just a matter of learning the details of individual functions. Table 8.1 lists the PWB functions, grouping them by category. For additional information on specific functions, consult on-line help.%@CR:C6A00080043 @% %@NL@% %@NL@% %@AB@%Table 8.1 %@AB@%Callable PWB Functions%@AE@%%@AE@% %@TH: 50 2028 02 19 19 38 @%Category Function Description%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%Block Operations %@AB@%CopyBox%@AE@% Insert rectangular area %@AB@%CopyLine%@AE@% Insert range of lines %@AB@%CopyStream%@AE@% Insert stream of text %@AB@%DelBox%@AE@% Delete rectangular area %@AB@%DelLine%@AE@% Delete range of lines %@AB@%DelStream%@AE@% Delete stream of textBuild %@AB@%fGetMake%@AE@% Get %@AB@%extmake%@AE@% setting %@AB@%fSetMake%@AE@% Set %@AB@%extmake%@AE@% settingColor %@AB@%GetColor%@AE@% Get color of specified line %@AB@%PutColor%@AE@% Set color of specified lineCursor %@AB@%GetCursor%@AE@% Get cursor position %@AB@%MoveCur%@AE@% Move cursorDialog %@AB@%DoMessageBox%@AE@% Create message dialog %@AB@%PopUpBox%@AE@% Display text in dialog windowDisplay %@AB@%BadArg%@AE@% Report that argument was invalid %@AB@%Display%@AE@% Update screen %@AB@%DoMessage%@AE@% Display message on dialog lineFile %@AB@%AddFile%@AE@% Open new file and get file handle %@AB@%DelFile %@AE@% Delete contents of file buffer %@AB@%fChangeFile%@AE@% Change current file to named file %@AB@%FileNameToHandle%@AE@% Get handle to open file %@AB@%FileRead%@AE@% Copy disk file to file buffer %@AB@%FileWrite%@AE@% Copy file buffer to disk file%@TE: 50 2028 02 19 19 38 @% %@AB@%Table 8.1 %@AB@% (continued)%@AE@%%@AE@% %@TH: 71 2738 02 17 18 41 @%Category Function Description%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@AB@%pFileToTop%@AE@% Make specified file the current file %@AB@%RemoveFile%@AE@% Remove file from memoryKeyboard %@AB@%KbHook %@AE@% Restore keyboard control to PWB%@CR:C6A00080044 @% %@AB@%KbUnHook%@AE@% Remove keyboard control from PWB %@AB@%ReadChar%@AE@% Get information on next keystrokeFormat %@AB@%ReadCmd%@AE@% Get keystroke information in %@AB@%CmdDesc%@AE@%Line %@AB@%FileLength%@AE@% Get length of file %@AB@%GetLine%@AE@% Get line from file %@AB@%PutLine%@AE@% Write line to fileList %@AB@%GetListEntry%@AE@% Get item from list %@AB@%ScanList%@AE@% Process listMemory %@AB@%Falloc%@AE@% Allocate far memory %@AB@%Fdalloc%@AE@% Deallocate far memoryMiscellaneous %@AB@%fExecute%@AE@% Execute macro %@AB@%FindSwitch%@AE@% Get information about switch %@AB@%GetEditorObject%@AE@% Get internal PWB data item %@AB@%GetString%@AE@% Get input from dialog line %@AB@%mgetenv%@AE@% Get environment string %@AB@%NameToFunc%@AE@% Get information about function or macro %@AB@%NameToKeys%@AE@% Get key(s) assigned to specified function %@AB@%Replace%@AE@% Replace character %@AB@%SetEditorObject%@AE@% Set internal PWB data item %@AB@%SetKey%@AE@% Assign function to keystrokeSearch %@AB@%REsearch%@AE@% Search for regular expression %@AB@%search%@AE@% Search for stringVirtual Memory %@AB@%fpbtoVM%@AE@% Copy data to virtual memory %@AB@%VMalloc%@AE@% Allocate virtual memory %@AB@%VMFree%@AE@% Free virtual memory %@AB@%VMtofpb%@AE@% Copy data from virtual memoryWindow %@AB@%CloseWnd%@AE@% Close window %@AB@%Resize%@AE@% Resize window %@AB@%SplitWnd%@AE@% Split window%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@TE: 71 2738 02 17 18 41 @% %@CR:C6A00080045 @%%@NL@% %@3@%%@CR:C6A00080046 @%%@AB@%8.4.8 Calling C Library Functions%@AE@%%@EH@%%@NL@% %@NL@% You can write many useful extension functions using only PWB functions listed in the previous section. It is also possible to call C library routines, with some limitations. An extension written for OS/2 protected mode can call any C library routine if it is linked with EXTHDRP.OBJ and the .DLL C run-time library. The list of usable routines is shorter for real-mode (DOS) extensions linked with the non-.DLL run-time library.%@CR:C6A00080047 @% %@NL@% %@NL@% Before you call a C library routine, ask whether the task can be done with a PWB function. If the answer is yes, you should always call a PWB function in preference to the C library routine. This practice ensures compatibility between your functions and PWB. %@NL@% %@NL@% The following categories of C library routines are always safe to use in real mode: %@NL@% %@NL@% %@NL@% ■ Buffer manipulation%@NL@% %@NL@% ■ Character classification and conversion%@NL@% %@NL@% ■ Data conversion%@NL@% %@NL@% ■ String manipulation%@NL@% %@NL@% %@NL@% This list includes the library routines you are most likely to need in an extension function. If your extension function calls C library functions, you must link with the compact-model C library. %@NL@% %@NL@% The following routines should not be used in real mode: %@NL@% %@NL@% %@NL@% ■ Routines that need C start-up support (most input/output functions)%@NL@% %@NL@% ■ Memory management routines, such as %@AB@%malloc%@AE@%, and routines that call them%@NL@% %@NL@% ■ Process control routines such as %@AB@%spawn%@AE@% and %@AB@%exec%@AE@%%@NL@% %@NL@% %@NL@% If you are in doubt about a particular C library routine, you can always use it and see what happens. If the linker displays the following message,%@CR:C6A00080048 @% %@NL@% %@NL@% %@AS@% error L2044: __acrtused : symbol multiply defined, use /NOE%@AE@%%@NL@% %@NL@% the routine requires C start-up support and should not be used. %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@CR:C6A00090001 @%%@1@%%@AB@%Chapter 9 Debugging C Programs with CodeView%@AE@%%@EH@%%@NL@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@NL@% Even experienced programmers occasionally find bugs in their programs. This chapter explores techniques that will help you locate these errors quickly, using the Microsoft CodeView debugger. %@NL@% %@NL@% This chapter describes: %@NL@% %@NL@% %@NL@% ■ How to display and modify variables and memory%@NL@% %@NL@% ■ How to control the flow of execution while debugging%@NL@% %@NL@% ■ Advanced CodeView debugging techniques%@NL@% %@NL@% ■ How to control CodeView's behavior with command-line switches and the TOOLS.INI file%@NL@% %@NL@% %@NL@% CodeView supports the Microsoft mouse (or any fully compatible pointing device). All operations are described first using the mouse; the keyboard command follows. %@NL@% %@NL@% For information about debugging OS/2 programs that use threads or processes, see Chapter 15, "Creating OS/2 Multithread Applications." %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00090002 @%%@AB@%9.1 Understanding CodeView Windows%@AE@%%@EH@%%@NL@% %@NL@% CodeView divides the screen into logically separate sections called windows, so that a large amount of information can be displayed in an organized and easy-to-read fashion. Each window is a discrete section of the display that operates independently of the other windows. %@NL@% %@NL@% %@AU@% Each window displays a different type of data.%@AE@% %@NL@% %@NL@% Each CodeView window has a distinct function. The name of each window described below appears in the top of the window's frame: %@NL@% %@NL@% %@NL@% ■ The Source window displays the source code. You can open a second Source window to view an include file, another source file, or the same source file at a different location.%@NL@% %@NL@% ■ The Command window accepts debugging commands.%@NL@% %@NL@% ■ The Watch window displays the current values of selected variables.%@NL@% %@NL@% ■ The Local window lists the values of all variables local to the current function or block.%@NL@% %@NL@% ■ The Memory window shows the contents of memory. You can open a second Memory window to view a different section of memory.%@NL@% %@NL@% ■ The Register window displays the contents of the microprocessor's registers, as well as the processor flags.%@NL@% %@NL@% ■ The 8087 window displays the registers of the coprocessor or its software emulator.%@NL@% %@NL@% %@NL@% CodeView starts running with three windows displayed. The Local window is at the top, the Source window fills the middle of the screen, and the Command window is at the bottom. %@NL@% %@NL@% There are two ways to open windows. You can choose the desired window from the View menu. (Note that you can open more than one of certain windows, such as Source or Memory.) In addition, some operations (such as selecting a Watch variable) open the appropriate window automatically, if it is not already open. %@NL@% %@NL@% %@AU@% All displays are updated automatically.%@AE@% %@NL@% %@NL@% CodeView continually and automatically updates the contents of all windows. However, if you want to interact with a particular window (for instance, to enter a command, set a breakpoint, or modify a variable), you must select that window as the focus of user interaction. %@NL@% %@NL@% The selected window is called the "current" window. The current window is marked in three ways: %@NL@% %@NL@% %@NL@% ■ The window's name is highlighted in white.%@NL@% %@NL@% ■ The text cursor appears in the window.%@NL@% %@NL@% ■ The vertical and horizontal scroll bars are moved into the window.%@NL@% %@NL@% %@NL@% To select a new current window, click left in the window (position the mouse cursor in the window and press the left mouse button) that you want to be current. You can also press F6 or SHIFT+F6 to move the focus from one window to the next. %@NL@% %@NL@% Windows often contain more information than can be displayed in the area allotted to the window. There are two ways to view these additional contents. You can drag on the window's horizontal or vertical scroll bars. (Position the mouse pointer on the bar and, while holding down the left mouse button, drag the mouse in the appropriate direction.) You can also use the direction keys (LEFT, RIGHT, UP, DOWN) to move the text cursor. %@NL@% %@NL@% Typing commands into the Source window causes CodeView to temporarily shift its focus to the Command window. Whatever you type is appended to the last line in the Command window. If the Command window is closed, CodeView beeps in response to your entry and ignores the input. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Adjusting the Windows%@AE@%%@EH@%%@NL@% %@NL@% Although you cannot change the relative positions of the windows, you can change their size or remove them. The Maximize, Size, and Close commands from the View menu perform these functions, or you can press CTRL+F10, CTRL+F8, and CTRL+F4, respectively. Window manipulations are especially easy with a mouse: %@NL@% %@NL@% %@NL@% ■ To maximize a window (enlarge it so it fills the screen), click left on the up arrow at the right end of the window's top border. To restore the window to its previous size and position, click left on the double arrow at the right end of the top border.%@NL@% %@NL@% ■ To change the size of a window, position the mouse pointer anywhere along the white line at the top of the window. Press and hold down the left mouse button. When two double arrows appear on the line, you can drag the mouse to enlarge or reduce the window. The same action on a vertical border widens or narrows the window.%@NL@% %@NL@% ■ To close a window, click left on the dot at the left end of the top border. You can also close any window in the View menu whose name has a dot next to it by selecting that window from the menu or by pressing that window's acclerator key. The adjacent windows automatically expand to recover the empty space.%@NL@% %@NL@% %@NL@% CodeView stores session information in a file called CURRENT.STS, which is created in the directory pointed to by the INIT environment variable. The session information includes such items as the name of the program being debugged, which CodeView windows were open, and the breakpoint locations. This information becomes the default status the next time you run CodeView.%@CR:C6A00090003 @%%@CR:C6A00090004 @% %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00090005 @%%@AB@%9.2 Overview of Debugging Techniques%@AE@%%@EH@%%@NL@% %@NL@% There is no single best approach to debugging for all programs or users. CodeView offers a variety of debugging tools that let you pick a method appropriate to the program or your work habits. The following section may help you decide how to approach a particular program. %@NL@% %@NL@% Broadly speaking, two things can go wrong in a program: %@NL@% %@NL@% %@NL@% ■ The program doesn't manipulate the data the way you expected it to.%@NL@% %@NL@% ■ The flow of execution is incorrect.%@NL@% %@NL@% %@NL@% These problems occasionally overlap. Incorrect execution can corrupt the data, and bad data can cause execution to take an unexpected turn. Because CodeView allows you to trace program execution %@AI@%and%@AE@% display whatever combination of variables you want simultaneously, you don't have to know ahead of time whether the problem is bad data manipulation, a bad execution path, or some combination of these. %@NL@% %@NL@% CodeView has features that deal specifically with the problems of bad data and incorrect execution: %@NL@% %@NL@% %@NL@% ■ You can view and modify any program variable, any section of memory, or any processor register.%@NL@% %@NL@% ■ You can monitor the path of execution and precisely control where execution pauses.%@NL@% %@NL@% %@NL@% The following sections explain how to view and modify data and describe how execution is controlled. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00090006 @%%@AB@%9.3 Viewing and Modifying Program Data%@AE@%%@EH@%%@NL@% %@NL@% The CodeView debugger offers a variety of ways to display program variables, processor registers, and memory. You can also modify the values of all these items as the program executes. This section shows how to display and modify variables, registers, and memory. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00090007 @%%@AB@%9.3.1 Displaying Variables in the Watch Window%@AE@%%@EH@%%@NL@% %@NL@% To add a variable to the Watch window, position the cursor on the name of the variable using either the mouse or the direction keys (LEFT, RIGHT, UP, DOWN). Then select the Add Watch command from the Watch menu, or press CTRL+W. %@NL@% %@NL@% A dialog box appears with the selected variable's name displayed in the Expression field. If you don't want to watch the variable shown, type in the name of the variable you want to watch. Pressing ENTER or clicking left on the OK button adds this variable to the Watch window. %@NL@% %@NL@% The Watch window appears at the top of the screen. Adding a Watch variable automatically opens the Watch window if the window doesn't already exist. %@NL@% %@NL@% A newly added variable may be followed by the message: %@NL@% %@NL@% %@AS@% <Watch Expression Not in Context>%@AE@%%@NL@% %@NL@% This message appears when program execution has not yet reached the block where the variable is defined. (A block is a section of code enclosed in curly braces.) Global variables (those declared outside C functions) never cause CodeView to display this message; they can be watched from anywhere in the program. %@NL@% %@NL@% To remove a variable from the Watch window, use the Delete Watch command from the Watch menu, and select the variable to be removed using the list in the dialog box. You can also position the cursor on any line in the Watch window and press CTRL+Y to delete the line. %@NL@% %@NL@% %@AU@% There is no limit to how many variables you can watch.%@AE@% %@NL@% %@NL@% You can place as many variables as you like in the Watch window; the quantity is limited only by available memory. You can scroll through the Watch window to position it at those variables you want to view. CodeView automatically updates all watched variables as the program runs, including those not currently visible. %@NL@% %@NL@% Loops (%@AB@%do%@AE@%, %@AB@%for%@AE@%, or %@AB@%while%@AE@%) cause problems when they don't terminate correctly. Displaying loop variables in the Watch window is an easy way to determine whether a loop variable achieves its proper value. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00090008 @%%@AB@%9.3.2 Displaying Expressions in the Watch Window%@AE@%%@EH@%%@NL@% %@NL@% You may have noticed that the Add Watch dialog box prompts for an expression, not simply a variable name. As this suggests, you can enter an expression (that is, any valid combination of variables, constants, and operators) for CodeView to evaluate and display. %@NL@% %@NL@% %@AU@% Expressions can use the syntax of other languages.%@AE@% %@NL@% %@NL@% You are not limited to evaluating C expressions. The Language command of the Options menu offers a choice of BASIC or FORTRAN expression evaluation, if one of these languages better suits your needs. The ability to select the language evaluator is especially useful when debugging mixed-language programs. Remember that C-specific features, such as type casting or pointer conversions, are not available in other languages. %@NL@% %@NL@% %@AU@% You can display more information with expressions than with individual %@AU@%variables.%@AE@% %@NL@% %@NL@% By reducing several variables to a single, easily read value, an expression can be easier to interpret than the components that make it up. Imagine a %@AB@%for%@AE@% loop with two variables whose ratio is supposed to remain constant. You suspect that one of these variables (you aren't sure which) sometimes takes the wrong value. With %@AS@%(var1 / var2) %@AE@% displayed as an expression in the Watch window, you can easily see when this single value changes; you don't have to mentally divide two numbers. %@NL@% %@NL@% You can also display Boolean expressions. For example, if a variable is never supposed to be larger than 100 or less than 25, %@AS@% (var < 25 || var > %@AS@%100) %@AE@% evaluates to 1 (true) when %@AS@% var %@AE@% goes out-of-bounds. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00090009 @%%@AB@%9.3.3 Displaying Arrays and Structures%@AE@%%@EH@%%@NL@% %@NL@% Most program variables are scalar quantities─a single character or a single integer or floating-point value. These appear in the Watch window with the variable name to the left, followed by an equal sign (%@AB@%=%@AE@%) and the current value. %@NL@% %@NL@% %@AU@% You can view arrays and structures in expanded form.%@AE@% %@NL@% %@NL@% Arrays and structures contain multiple values, arranged in one or more layers. They are often referred to as "aggregate" data items. CodeView lets you control how much of these variables is shown; that is, whether all, part, or none of their internal structure is displayed. %@NL@% %@NL@% An array initially appears in the Watch window in this form: %@NL@% %@NL@% %@AS@% +wordholder[] = [...]%@AE@%%@NL@% %@NL@% The brackets indicate that this variable contains more than one element. The plus sign (+) indicates that the variable has not yet been expanded to display its components. %@NL@% %@NL@% To expand the array, double-click anywhere on the line. You can also position the cursor on the line and press ENTER. For example, if %@AS@% wordholder %@AS@%%@AE@% is a six-character array containing the word "Basic," the Watch window display changes to the following : %@NL@% %@NL@% %@AS@% -wordholder[] %@AS@% [0] = 66 'B' %@AS@% [1] = 97 'a' %@AS@% [2] = 115 's' %@AS@% [3] = 105 'i' %@AS@% [4] = 99 'c' %@AS@% [5] = 0 ''%@AE@%%@NL@% %@NL@% Note that both the individual character values and their ASCII decimal equivalents are listed. The minus sign (-) indicates no further expansion is possible. To contract the array, double-click on its line (or position the cursor on the line and press ENTER) again. %@NL@% %@NL@% If it is inconvenient to view a character array in this form, cast the variable's name to a character pointer by placing %@AS@% (char *) %@AE@% in front of the name. The character array is then displayed as a string delimited by apostrophes. %@NL@% %@NL@% You can display arrays with more than one dimension. Imagine a 5 x 5 integer array named %@AS@% matrix%@AE@%, whose diagonal elements are the numbers 1 through 5 and whose other elements are zero. Unexpanded, the array is displayed like this: %@NL@% %@NL@% %@AS@% +matrix[] = [...]%@AE@%%@NL@% %@NL@% Double-clicking on %@AS@% matrix %@AE@% (or pressing ENTER) changes the display: %@NL@% %@NL@% %@AS@% -matrix[] %@AS@% +[0][] = [...] %@AS@% +[1][] = [...] %@AS@% +[2][] = [...] %@AS@% +[3][] = [...] %@AS@% +[4][] = [...]%@AE@%%@NL@% %@NL@% The actual values of the elements are not shown yet. You have to descend one more level to see them. To view the elements of the third row of the array, position the cursor anywhere on the fourth line and press ENTER: %@NL@% %@NL@% %@AS@% -matrix[] %@AS@% +[0][] = [...] %@AS@% +[1][] = [...] %@AS@% -[2][] %@AS@% [0] = 0 %@AS@% [1] = 0 %@AS@% [2] = 3 %@AS@% [3] = 0 %@AS@% [4] = 0 %@AS@% +[3][] = [...] %@AS@% +[4][] = [...]%@AE@%%@NL@% %@NL@% Expanding the fifth row of the array produces this display: %@NL@% %@NL@% %@AS@% -matrix[] %@AS@% +[0][] = [...] %@AS@% +[1][] = [...] %@AS@% -[2][] %@AS@% [0] = 0 %@AS@% [1] = 0 %@AS@% [2] = 3 %@AS@% [3] = 0 %@AS@% [4] = 0 %@AS@% +[3][] = [...] %@AS@% -[4][] %@AS@% [0] = 0 %@AS@% [1] = 0 %@AS@% [2] = 0 %@AS@% [3] = 0 %@AS@% [4] = 5%@AE@%%@NL@% %@NL@% %@AU@% You can view individual elements instead of the entire array.%@AE@% %@NL@% %@NL@% Any element of an array (or structure) can be independently expanded or contracted. If you only want to view one or two elements of a large array, specify the particular array or structure elements in the Expression field of the Add Watch dialog box; you need not display every element of the variable. %@NL@% %@NL@% %@AU@% You can dereference pointers.%@AE@% %@NL@% %@NL@% You can dereference a pointer in the same way as you expand an array or structure. The pointer address is displayed, followed by all the elements of the variable to which the pointer currently refers. Multiple levels of indirection (that is, pointers referencing other pointers) can be displayed simultaneously. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00090010 @%%@AB@%9.3.4 Displaying Array Elements Dynamically%@AE@%%@EH@%%@NL@% %@NL@% You do not have to display every element of an array. If specific subscripts are given, the corresponding element is displayed. %@NL@% %@NL@% You can also specify a dynamic array element, which changes as some other variable changes. For example, suppose that the loop variable %@AS@% p %@AE@% is a subscript for the array variable %@AS@% catalogprice%@AE@%. The Watch window expression %@AS@% %@AS@%catalogprice[p] %@AE@% displays only the array element currently specified by %@AS@%p%@AE@%, not the entire array. %@NL@% %@NL@% You can mix constant and variable subscripts. For example, the expression %@AS@% %@AS@%bigarray[3][i] %@AE@% displays only the element in the third row of the array to which the index variable %@AS@% i %@AE@% points. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00090011 @%%@AB@%9.3.5 Using Quick Watch%@AE@%%@EH@%%@NL@% %@NL@% Selecting the Quick Watch command from the Watch menu (or pressing SHIFT+F9) displays the Quick Watch dialog box. If the text cursor is in the Source, Local, or Watch window, the variable at the current cursor position appears in the dialog box. If this is not the item you wish to display, type in the desired expression or variable, then press ENTER. The selected item is displayed immediately. %@NL@% %@NL@% The Quick Watch display automatically expands arrays and structures to their first level. For example, an array with three dimensions is expanded to the first dimension. You can expand or contract an element just as you would in the Watch window: position the cursor on the appropriate line and press ENTER. If the array needs more lines than the Quick Watch window can display, drag the mouse along the scroll bar, or press DOWN or PGDN to view the rest of the array. %@NL@% %@NL@% %@AU@% You can add Quick Watch variables to the Watch window.%@AE@% %@NL@% %@NL@% If you decide to add a Quick Watch item to the Watch window, select the Add Watch button. Arrays and structures appear in the Watch window expanded as they were displayed in the Quick Watch box. %@NL@% %@NL@% Quick Watch is a convenient way to take a quick look at a variable or expression. Since only one Quick Watch variable can be viewed at a time, you would not use Quick Watch for most of the variables you want to view. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00090012 @%%@AB@%9.3.6 Displaying Memory%@AE@%%@EH@%%@NL@% %@NL@% Selecting the Memory command from the View menu opens a Memory window. Up to two Memory windows can be open at one time. %@NL@% %@NL@% By default, memory is displayed as hexadecimal byte values, with 16 bytes per line. At the end of each line is a second display of the same memory in ASCII form. Values that correspond to printable ASCII characters (decimal 32 through 127) are displayed in that form. Values outside this range are shown as periods. %@NL@% %@NL@% %@AU@% You can display memory values in any form.%@AE@% %@NL@% %@NL@% Byte values are not always the most convenient way to view memory. If the area of memory you're examining contains character strings or floating-point values, you might prefer to view them in a directly readable form. The Memory Window command of the Options menu displays a dialog box with a variety of display options: %@NL@% %@NL@% %@NL@% ■ ASCII characters%@NL@% %@NL@% ■ Byte, word, or double-word binary values%@NL@% %@NL@% ■ Signed or unsigned integer decimal values%@NL@% %@NL@% ■ Short (32 bit), long (64 bit), or ten-byte (80 bit) floating-point values%@NL@% %@NL@% %@NL@% You can also directly cycle through these display formats by pressing F3. %@NL@% %@NL@% If a section of memory cannot be displayed as a valid floating-point number, the number shown includes the characters %@AS@% NAN %@AE@% (not a number). %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Displaying Variables with a Live Expression%@AE@%%@EH@%%@NL@% %@NL@% Section 9.3.4, "Displaying Array Elements Dynamically," explains how to display a specific array element by adding the appropriate expression to the Watch window. It is also possible to watch a particular memory area that your program uses to store data in the Memory window. This CodeView display feature is called a "live expression." %@NL@% %@NL@% "Live" means that the area of memory displayed changes to reflect the value of a pointer or subscript. For example, if %@AS@% buffer %@AE@% is an array and %@AS@% pbuf %@AE@% is a pointer to that array, then %@AS@% *pbuf %@AE@% points to the array element currently referenced. A live expression displays the section of memory beginning with this element. If your program changes the value of %@AS@% pbuf%@AE@%, CodeView dynamically adjusts the Memory window display. %@NL@% %@NL@% Live expressions are displayed in a Memory window, not in the Watch window. To create a live expression, select the Memory Window command of the Options menu, then select the Live Expression check box. Enter the name of the element you want to view. For example, if %@AS@% strgptr %@AE@% is a pointer to an array of characters, and you want to see what it currently points at, enter %@AS@% %@AS@%*strgptr%@AE@%. Then select the OK button or press ENTER to view that memory area. %@NL@% %@NL@% A new Memory window opens. The first memory location in the window is the first memory location of the live expression. The section of memory displayed changes to the section the pointer currently references. %@NL@% %@NL@% You can use the Memory Window command of the Options menu to display the value of the live expression in a directly readable form. This is especially convenient when the live expression represents strings or floating-point values, which are difficult to interpret in hexadecimal form. %@NL@% %@NL@% It is usually more convenient to view an item in the Watch window than as a live expression. However, some items are more easily viewed as live expressions. For example, you can examine what is currently on top of the stack. Enter SS:SP as the live expression. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00090013 @%%@AB@%9.3.7 Displaying the Processor Registers%@AE@%%@EH@%%@NL@% %@NL@% Selecting the Register command from the View menu (or pressing F2) opens a window on the right side of the screen. The current values of the microprocessor's registers appear in this window. %@NL@% %@NL@% At the bottom of the window is a group of mnemonics representing the processor flags. When you first open the Register window, all values are shown in normal-intensity video. Any subsequent changes are marked in high-intensity video. For example, suppose the overflow flag is not set when the Register window is first opened. The corresponding mnemonic is NV and it appears in light gray. If the overflow flag is subsequently set, the mnemonic changes to OV and appears in bright white. %@NL@% %@NL@% Selecting the 386 Instructions command from the Options menu displays the registers as 32-bit values, but only if your computer uses an 80386 processor, and only when running the real-mode version of CodeView. Selecting this command a second time toggles back to a 16-bit display. %@NL@% %@NL@% You can also display the registers of an 8087/287/387 coprocessor in a separate window by selecting the 8087 command from the View menu. If your program uses the coprocessor emulator, the emulated registers are displayed instead. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00090014 @%%@AB@%9.3.8 Modifying the Values of Variables, Registers, and Memory%@AE@%%@EH@%%@NL@% %@NL@% You can easily change the values of variables, memory locations, or registers displayed in the Watch, Local, Memory, Register, or 8087 windows. Simply position the cursor at the value you want to change and edit it to the appropriate value. If you change your mind, press ALT+BKSP to undo the last change you made. %@NL@% %@NL@% The starting address of each line of memory displayed is shown at the left of the Memory window, in CS:IP form. Altering the address automatically shifts the display to the corresponding section of memory. If that section is not used by your program, memory locations are displayed as double question marks (??). %@NL@% %@NL@% %@AU@% Byte display form is different from other forms.%@AE@% %@NL@% %@NL@% When you select Byte display from the Memory Window Options dialog box, CodeView presents both a hexadecimal and an ASCII representation of the data in memory. (Byte display is the default.) You can change data in memory either by entering new hex values over the hexadecimal representation of your data or by entering character values over the character representation. %@NL@% %@NL@% To toggle a processor flag, click left on its mnemonic. You can also position the cursor on a mnemonic, then press any key (except TAB or SPACE). Repeat to restore the flag to its previous setting. %@NL@% %@NL@% %@AU@% Be cautious when modifying memory or a register.%@AE@% %@NL@% %@NL@% The effect of changing a register, flag, or memory location may vary from no effect at all, to crashing the operating system. You should be cautious when altering "machine-level" values; most of the items you would want to change can be altered from the Watch window. %@NL@% %@NL@% One instance where direct manipulation of register values can be valuable is when you are debugging in-line assembly code. You can change register values to test assumptions before making changes in your source code and recompiling. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00090015 @%%@AB@%9.4 Controlling Execution%@AE@%%@EH@%%@NL@% %@NL@% There are two forms of program execution under CodeView: %@NL@% %@NL@% %@NL@% ■ Continuous; the program executes until either a previously specified "breakpoint" has been reached or the program terminates normally.%@NL@% %@NL@% ■ Single-step; the program pauses after each line of code has been executed. %@NL@% %@NL@% %@NL@% Sections 9.4.1 and 9.4.2 explain how each form of execution works and the most effective way to use each. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00090016 @%%@AB@%9.4.1 Continuous Execution%@AE@%%@EH@%%@NL@% %@NL@% Continuous execution lets you quickly execute the bug-free sections of code, which would otherwise take a long time to execute a single step at a time. %@NL@% %@NL@% The simplest form of continuous execution is to click right (position the mouse pointer and press the right mouse button) anywhere on the line of code you want to debug or examine in more detail. The program executes at full speed up to the beginning of this line, then pauses. You can do the same thing by positioning the text cursor on this line, then pressing F7. %@NL@% %@NL@% You can also pause execution at a specific line of code with a "breakpoint." There are several types of breakpoints. Breakpoints are explained in the following section. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Selecting Breakpoint Lines%@AE@%%@EH@%%@NL@% %@NL@% %@AU@% Breakpoints can be tied to lines of code.%@AE@% %@NL@% %@NL@% You can skip over the parts of the program that you don't want to examine by specifying one or more lines as "breakpoints." The program executes at full speed up to the first breakpoint, then pauses. Pressing F5 continues program execution up to the next breakpoint, and so on. (You can halt execution at any time by pressing CTRL+BREAK or ALT+SYSRQ.) %@NL@% %@NL@% %@AU@% There is no limit to the number of breakpoints.%@AE@% %@NL@% %@NL@% You can set as many breakpoints as you like (limited only by available memory). There are several ways to set breakpoints: %@NL@% %@NL@% %@NL@% ■ Double-click anywhere on the desired breakpoint line. The selected line is highlighted to show that it is a breakpoint. To remove the breakpoint, double-click on the line a second time.%@NL@% %@NL@% ■ Position the cursor anywhere on the line at which you want execution to pause. Press F9 to select the line as a breakpoint. (CodeView highlights lines that have been selected as breakpoints.) Press F9 a second time to remove the breakpoint. %@NL@% %@NL@% ■ Display the Set Breakpoint dialog box by selecting Set Breakpoint from the Watch menu. Choose one of the breakpoint options that permits a line ("location") to be specified. The line on which the text cursor currently rests is the default breakpoint line in the Location field. If this line is not the desired breakpoint, enter the line number desired. (The line number must begin with a period.) Use F9 or the Edit Breakpoints screen of the Watch menu to remove the breakpoint.%@NL@% %@NL@% %@NL@% %@AU@% Not every line can be a breakpoint.%@AE@% %@NL@% %@NL@% A breakpoint line must be a program line that represents executable code. You cannot select a blank line, a comment line, or a declaration line (such as a variable declaration or a preprocessor statement) as a breakpoint. %@NL@% %@NL@% A breakpoint can also be set at a function or an explicit address. To set a breakpoint at a function, simply enter its name in the Set Breakpoint dialog box. To set a breakpoint at an address, enter the address in CS:IP form. %@NL@% %@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% NOTE %@AI@%By default, Microsoft compilers optimize your code. In the process of %@AI@%optimization, some lines of code may be repositioned or reorganized for more %@AI@%efficient execution. These changes can prevent CodeView from recognizing the %@AI@%corresponding lines of source code as breakpoints. Therefore, it is a good %@AI@%idea to disable optimization during development (use the /Od switch). You %@AI@%can restore optimization once debugging is completed.%@AE@%%@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@%%@NL@% %@NL@% Once execution has paused, you can continue execution by pressing F5 or clicking left on the <F5> button in the display. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Setting Breakpoint Values%@AE@%%@EH@%%@NL@% %@NL@% %@AU@% Breakpoints can be tied to variables.%@AE@% %@NL@% %@NL@% Breakpoints are not limited to specific lines of code. CodeView can also break execution when a variable reaches a particular value, or just changes value. You can also combine these value breakpoints with line breakpoints, so that execution stops at a specific line only if a variable has simultaneously reached a particular value, or changed value. You must use the check boxes in the Set Breakpoint dialog box to select these other types of breakpoints. %@NL@% %@NL@% To pause execution when an expression reaches a particular value, enter that expression in the Expression field of the Set Breakpoint dialog box. For example, assume you have declared a tree structure as follows: %@NL@% %@NL@% %@AS@% struct Tagtree %@AS@% { %@AS@% char * s; /* Pointer to a string */ %@AS@% struct TAGtree * left; /* Pointer to left branch */ %@AS@% struct TAGtree * right; /* Pointer to right branch */ %@AS@% }; %@AS@% %@AS@% struct TAGtree t;%@AE@%%@NL@% %@NL@% You can then pause execution when your tree traversal reaches a terminal node by entering the expression %@AS@% (t.left == NULL) || (t.right == NULL)%@AE@%. %@NL@% %@NL@% To pause execution when a variable changes value, you need to enter only the name of the variable in the Expression field. For large variables (such as arrays or character strings), you can specify the number of bytes you want checked (up to 32K) in the Length field. %@NL@% %@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% NOTE %@AI@%When a breakpoint is tied to a variable, CodeView must check the variable's %@AI@%value after each machine instruction is executed. This slows execution %@AI@%greatly. For maximum speed when debugging, either tie conditional %@AI@%breakpoints to specific lines, or set conditional breakpoints only after you %@AI@%have reached the section of code that needs to be debugged.%@AE@%%@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@%%@NL@% %@NL@% %@NL@% %@4@%%@AB@%Using Breakpoints%@AE@%%@EH@%%@NL@% %@NL@% Here are several examples that show how breakpoints can help you find the cause of a problem. %@NL@% %@NL@% One of the most common bugs is a %@AB@%for%@AE@% loop that executes too many or too few times. If you set a breakpoint that encloses the loop statements, the program pauses after each iteration. With the loop variable or critical program variables in the Watch or Local windows, it should be easy to see what the loop is doing wrong. %@NL@% %@NL@% %@AU@% You can specify how many times a breakpoint line is executed.%@AE@% %@NL@% %@NL@% You do not have to pause at a breakpoint the first time execution reaches it. CodeView lets you specify the number of times you want to ignore the breakpoint condition before pausing. Enter the decimal number in the Pass Count field of the Set Breakpoint dialog box of the Watch menu. %@NL@% %@NL@% For example, suppose your program repeatedly calls a function to create a binary tree. You suspect that something goes wrong with the process about halfway through. You could mark the line that calls the function as the breakpoint, then specify how many times this line is to execute before execution pauses. Running the program creates a representative (but unfinished) tree structure that can be examined from the Watch window. You can then continue your analysis using single-stepping. %@NL@% %@NL@% Another programming error is erroneously assigning a value to a variable. Enter the variable in the Expression field of the Set Breakpoint dialog box. Execution breaks whenever this variable changes value. %@NL@% %@NL@% %@AU@% You can assign new values to variables while execution is paused.%@AE@% %@NL@% %@NL@% Breakpoints are a convenient way to pause the program so you can assign new values to variables. For example, if a limit value is set by a variable, you can change the value to see whether program execution is affected. Similarly, you can pass a variety of values to a %@AB@%switch%@AE@% statement to see if they are correctly processed. %@NL@% %@NL@% This ability to alter variables is an especially convenient way to test new functions without having to write a stand-alone test program. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00090017 @%%@AB@%9.4.2 Single-Stepping%@AE@%%@EH@%%@NL@% %@NL@% In single-stepping, CodeView pauses after each line of code is executed. (If a line contains more than one executable statement, CodeView executes all the statements on the line before pausing.) The next line to be executed is highlighted in reverse video. %@NL@% %@NL@% %@AU@% There are two ways to single-step.%@AE@% %@NL@% %@NL@% You can single-step through a program with the Step and Trace functions. Step (executed by pressing F10) steps over function calls. All the code in the function is executed but, to you, the function appears to execute as a single step. Trace (executed by pressing F8) traces through every step of all functions for which CodeView has symbolic information. Each line of the function is executed as a separate step. (CodeView has no symbolic information about run-time functions; therefore, they are executed as a single step.) %@NL@% %@NL@% You can alternate between Trace and Step as you like. The method you use depends only on whether you want to see what happens within a particular function. %@NL@% %@NL@% You can Trace through the program continuously (without having to press F8), using the Animate command of the Run menu. The speed of execution is controlled by the Trace Speed command from the Options menu. You can halt animated execution at any time by pressing any key. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00090018 @%%@AB@%9.5 Replaying a Debug Session%@AE@%%@EH@%%@NL@% %@NL@% CodeView can automatically create a "tape" (a disk file) with all the debugging instructions and input data you entered when testing a program. The tape is then "replayed" to repeat the debugging process. This dynamic replay feature is unique to the CodeView debugger and is activated by selecting the History On command from the Run menu. Selecting History On a second time terminates recording. %@NL@% %@NL@% You can use the recording as a bookmark. You can quit after a long debugging session, then pick up the session later in the same place. %@NL@% %@NL@% %@AU@% Dynamic replay makes it easy to correct a mistake.%@AE@% %@NL@% %@NL@% The principal use of dynamic replay is to allow you to back up when you make an error or overshoot the section of code with the bug. This feature is important because not all bugs are located when executing the program in a linear fashion. %@NL@% %@NL@% For example, you may have to manually execute a function many times before its bug appears. If you then enter a command that alters the machine's or program's status and thereby lose the information you need to find the cause of the bug, you would have had to restart the program and manually repeat every debugging step to return to that point. Even worse, if you don't remember the exact sequence of events that exposed the bug, it could take hours to find your way back. %@NL@% %@NL@% Dynamic replay eliminates this problem. Selecting the Undo command from the Run menu automatically restarts the program and rapidly executes every debug command up to (but not including) the last one you entered. You can repeat this process as many times as you like until you return to the desired point in execution. %@NL@% %@NL@% To add additional steps to an existing tape, select History On, then select Replay. When replay has completed, perform whatever new debugging steps you want, then select History On a second time to terminate recording. The new tape contains both the original and the added commands. %@NL@% %@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% NOTE %@AI@%CodeView records only those mouse commands that apply to CodeView. Mouse %@AI@%commands recognized by the application being debugged are not recorded.%@AE@%%@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@%%@NL@% %@NL@% %@NL@% %@4@%%@AB@%Replay Limitations under OS/2%@AE@%%@EH@%%@NL@% %@NL@% There are some limitations to dynamic replay when debugging under OS/2: %@NL@% %@NL@% %@NL@% ■ The program must not respond to asynchronous events.%@NL@% %@NL@% ■ Breakpoints must be specified at specific source lines or for specific symbols (rather than by absolute addresses), or replay may fail.%@NL@% %@NL@% ■ Single-thread programs behave normally during replay. However, one of the threads in a multithread program may cause an asynchronous event, violating the first restriction. Multithread programs are, therefore, more likely to fail during replay.%@NL@% %@NL@% ■ Multiprocess replay will fail. Each new process invokes a new CodeView session. The existence of multiple sessions makes it impractical to record the sequence of events if you execute commands in a session other than the original.%@NL@% %@NL@% ■ Replay under Presentation Manager is not currently supported because it violates the first restriction.%@NL@% %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00090019 @%%@AB@%9.6 Advanced CodeView Techniques%@AE@%%@EH@%%@NL@% %@NL@% Once you are comfortable displaying and changing variables, stepping through the program, and using dynamic replay, you might want to experiment with the advanced techniques explained below. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Setting Command-Line Arguments%@AE@%%@EH@%%@NL@% %@NL@% If your program retrieves command-line arguments, you can specify them with the Set Runtime Arguments command from the Run menu. Enter the arguments in the Command Line field before you begin execution. (Arguments entered after execution begins cause an automatic restart.) %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Multiple Source Windows%@AE@%%@EH@%%@NL@% %@NL@% You can open two Source windows at the same time. The windows can display two different sections of the same program, or one can show the high-level listing and the other the assembly-language listing. In the latter case, the contents of the windows track, with the next assembly-language instruction to be executed matching the next line of source code. %@NL@% %@NL@% You can move freely between these windows, executing a single line of source code or a single assembly instruction at a time. The assembly-language window must be opened in CS:IP mode. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Calling Functions%@AE@%%@EH@%%@NL@% %@NL@% Any C function in your program (whether user-written or from the library) can be called from the Command window or the Watch window, using the following format: %@NL@% %@NL@% %@AS@% ?funcname (varlist)%@AE@%%@NL@% %@NL@% The function is evaluated and the returned value is displayed in the Command window. %@NL@% %@NL@% The function does not have to be called by your program to be available for evaluation. For example, all the .OBJ code specified in the linker input response file is linked. The functions in this code can then be evaluated from the Command window. %@NL@% %@NL@% This feature allows you to run functions from within CodeView that you would not normally include in the final version of your program. For example, you could include the OS/2 API functions that control semaphores, then execute them from the Command window to manipulate the run-time environment at any point in the debugging process. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Checking for Undefined Pointers%@AE@%%@EH@%%@NL@% %@NL@% Until a pointer has been explicitly assigned a value, its value is undefined. That is, its value may be completely random, or it may be some consistent value that does not point to a useful data address (such as -1). %@NL@% %@NL@% Accessing data through an uninitialized pointer will cause unpredictable program behavior and, under OS/2, will usually result in a protection violation. Because many C programs use pointers heavily, tracking down exactly which pointer variable was left uninitialized is tedious. %@NL@% %@NL@% CodeView can help locate the problem quickly. If you use an uninitialized pointer (or "null pointer" under OS/2) the operating system will generate a protection violation. By examining the Calls menu, you can determine the last line of your code that was executed before the protection violation occurred. %@NL@% %@NL@% Under DOS, you can take advantage of the fact that global or static variables are initialized to 0 to track down uninitialized pointers. Set a conditional breakpoint that stops when location 0 changes, then start execution. Execution will pause when your program makes an assignment to that location. %@NL@% %@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% NOTE %@AI@%For near pointers, location 0 is DS:0000; for far pointers, location 0 is %@AI@%0000:0000.%@AE@%%@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@%%@NL@% %@NL@% %@NL@% %@4@%%@AB@%Using Breakpoints Efficiently%@AE@%%@EH@%%@NL@% %@NL@% Breakpoints slow execution when debugging. You can increase CodeView's speed by using the /R command-line switch if you have an 80386-based computer. This switch enables the 386's four debug registers, which support breakpoint checking in hardware rather than in software. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Printing Selected Items%@AE@%%@EH@%%@NL@% %@NL@% You can print all or part of the contents of any window with the Print command from the File menu. The check box lets you print the complete contents of the window, only the material that is currently viewable in the window, or selected text from the window. Text is selected by dragging the mouse across it, or by holding down the SHIFT key and pressing the direction keys (LEFT, RIGHT, UP, DOWN). %@NL@% %@NL@% By default, print output is to the file CODEVIEW.LST in the current directory. You can choose whether the new material will be appended to an existing file or overwrite it, using the Append/Overwrite check box. If you would like print output to go to a different file, type its name in the To File Name field. If you want the output to go to a printer, enter the appropriate device name, such as LPT1 or COM2.%@CR:C6A00090020 @%%@CR:C6A00090021 @% %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Handling Register Variables%@AE@%%@EH@%%@NL@% %@NL@% A register variable is stored in one of the microprocessor's registers, rather than in RAM. This speeds access to the variable. %@NL@% %@NL@% There are two ways for a conventional variable to become a register variable. One way is declaring the variable as a register variable; if a register is free, the compiler will store the variable there. The other way occurs during optimization, when the compiler stores an often-used variable (such as a loop variable) in a register to speed up execution. %@NL@% %@NL@% Register variables can cause problems during debugging. As with local variables, they are only visible within the function where they are defined. In addition, a register variable may not always be displayed with its current value. %@NL@% %@NL@% In general, it is a good idea to turn off all optimization and to avoid declaring register variables until the program has been fully debugged. Any side effects produced by optimization or register variables can then be easily isolated. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Redirecting CodeView Input and Output%@AE@%%@EH@%%@NL@% %@NL@% The Command window accepts DOS-like commands that redirect input and output. These commands can also be included on the command line that invokes CodeView. Whatever follows the /C option in the command line is treated as CodeView commands that are immediately executed at start-up. %@NL@% %@NL@% %@AS@% CV/c "infile; t >outfile" myprog%@AE@%%@NL@% %@NL@% Input is redirected to %@AS@% infile%@AE@%, which can contain start-up commands for CodeView. When CodeView exhausts all commands in the input file, focus automatically shifts to the command window. Output is sent to %@AS@% outfile %@AE@% and echoed to the Command window. The %@AS@% t %@AE@% must precede the %@AS@% > %@AE@% command for output to be sent to the Command window. %@NL@% %@NL@% Redirection is a useful way to automate CodeView start-up. It also lets you keep a viewable record of command-line input and output, a feature not available with dynamic replay. (No record is kept of mouse operations.) Some applications (particularly interactive ones) may need modification to allow for redirection of input to the application itself. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Using CodeView with Additional Memory%@AE@%%@EH@%%@NL@% %@NL@% If your computer uses expanded or extended memory, you can increase CodeView's functionality by selecting the /X or /E option. CodeView moves as much as it can of itself, the debugging table, and the program to higher memory (above the first megabyte). %@NL@% %@NL@% The /X option uses extended memory and gives the greatest speed increase. This option requires the HIMEM.SYS driver, which is included on your distribution disks. Add %@AS@% DEVICE = HIMEM.SYS %@AE@% to your CONFIG.SYS file to load HIMEM.SYS at boot time.%@CR:C6A00090022 @%%@CR:C6A00090023 @%%@CR:C6A00090024 @% %@NL@% %@NL@% The /E option uses expanded memory. The speed increase is not as great as that supplied by the /X option. The expanded memory manager (EMM) must be LIM 4.0, and no single module's debug information can exceed 48K. If the symbol table exceeds this limit, try reducing file-name information by not specifying paths at compile time and using /Zi only with those sections of the program that need debugging (use /Zd otherwise). %@NL@% %@NL@% If you do not specify either /X or /E (or the /D disk-overlay option), CodeView automatically searches for the HIMEM.SYS driver and extended memory so it can implement the /X option. If it fails, CodeView searches for expanded memory to implement the /E option. If that search fails, CodeView uses a default disk overlay of 64K. (See the description of the /D option below.) %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00090025 @%%@AB@%9.7 Controlling CodeView with Command-Line Options%@AE@%%@EH@%%@NL@% %@NL@% The following options can be added to the command line that invokes CodeView: %@NL@% %@NL@% %@AB@%Option%@AE@% %@AB@%Effect%@AE@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% /2 Two-monitor debugging. The display adapters must be configured for different addresses. One display shows the output of the application; the other shows CodeView. /25 Display in 25-line mode. /43 Display in 43-line mode (EGA or VGA only). /50 Display in 50-line mode (VGA only). /B Display in black and white. This assures that the display is readable when a color display is not used. /C%@AI@%commands%@AE@% All items following this switch are treated as CodeView commands to be executed immediately on start-up. Commands must be separated with a semicolon (%@AB@%;%@AE@%). /D«%@AI@%ddd%@AE@%» Use disk overlays, where %@AI@%ddd%@AE@% is the decimal size of the overlay buffer, in kilobytes. The acceptable range is 16K to 128K. The default size is 64K. DOS only. /E Use expanded memory for symbolic information. DOS only. /F Flip screen video pages. When your application does not use graphics, eight video screen pages are available. Switching from CodeView to the output screen is accomplished more quickly than swapping (/S) by directly selecting the appropriate video page. Cannot be used with /S. DOS only. /I%@AI@%number%@AE@% Turns nonmaskable interrupts and 8259-interrupt trapping on (/I1) or off (/I2). /K Disables installation of keyboard monitors for the program being debugged. /L%@AI@%dlls%@AE@% Load DLLs specified. DLLs must be separated by a semicolon (%@AB@%;%@AE@%). OS/2 only. /M Disable the mouse. /N%@AI@%number%@AE@% /N0 tells CodeView to trap; /N1 tells it not to. /O Debug child processes ("offspring"). OS/2 only. /R Use 386 hardware debug registers. DOS only. /S Swap screen in buffers. When your program uses graphics, all eight screen buffers must be used. Switching from CodeView to the output screen is accomplished by saving the previous screen in a buffer. Cannot be used with /F. DOS only. /X Use extended memory for symbolic information. DOS only. %@NL@% %@2@%%@CR:C6A00090026 @%%@AB@%9.8 Customizing CodeView with the TOOLS.INI FILE%@AE@%%@EH@%%@NL@% %@NL@% The TOOLS.INI file customizes the behavior and user interface of several Microsoft products. The TOOLS.INI file is a plain ASCII text file. You should place it in a directory pointed to the INIT environment variable. (If you do not use the INIT environment variable, CodeView looks for TOOLS.INI only in its source directory.) %@NL@% %@NL@% The CodeView section of TOOLS.INI is preceded by the following line: %@NL@% %@NL@% %@AS@% [cv]%@AE@%%@NL@% %@NL@% If you are running the protected-mode version of CodeView, use %@AS@% [cvp] %@AE@% instead. If you run both versions, include both: %@AS@% [cv cvp]%@AE@%. %@NL@% %@NL@% Most of the TOOLS.INI customizations control screen colors, but you can also specify such things as start-up commands or the name of the file that receives CodeView output. On-line help contains full information about all TOOLS.INI switches for CodeView. %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@CR:C6A-Part 03 @%%@1@%%@AB@%PART III Special Environments%@AE@%%@EH@%%@NL@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@NL@% The Microsoft C Professional Development System provides a platform from which you can build graphics applications and interface with programs written in other languages. %@NL@% %@NL@% Chapter 10 discusses using the real-world graphics functions to set video modes, draw basic shapes, and use graphic fonts. Chapter 11 describes "presentation graphics," sophisticated charts and graphics that show data relationships. Chapter 12 explains how to write C programs so that they interface with assembly language routines or routines written in other languages. Chapter 13 describes portability of Microsoft C to other environments. %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@CR:C6A00100001 @%%@1@%%@AB@%Chapter 10 Communicating with Graphics%@AE@%%@EH@%%@NL@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@NL@% A map, a chart, an illustration, a graph, or some other visual aid often can communicate more information more quickly and more vividly than would several screens of text. %@NL@% %@NL@% The extensive Microsoft C graphics library allows you to communicate your ideas graphically. The functions range from the simple to the complex; from functions that turn on a pixel to functions that draw graphs and charts complete with labels and legends. %@NL@% %@NL@% This chapter describes low-level graphics functions that draw basic shapes such as lines, circles, and rectangles. It introduces video modes, color palettes, coordinate systems, and synopses of the graphics and font functions. For complete function prototypes and example programs, use on-line help. %@NL@% %@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% NOTE %@AI@%The ANSI C standard does not define any standard graphics functions. The %@AI@%functions described in this section are unique to Microsoft C and are not %@AI@%portable to other implementations of C.%@AE@%%@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@%%@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00100002 @%%@AB@%10.1 Video Modes%@AE@%%@EH@%%@NL@% %@NL@% Graphics adapters are boards or cards inside the computer that are responsible for displaying text and graphics on the screen. Commonly used adapters include: %@NL@% %@NL@% %@NL@% ■ CGA (Color Graphics Adapter)%@NL@% %@NL@% ■ EGA (Enhanced Graphics Adapter)%@NL@% %@NL@% ■ HGC (Hercules Graphics Card)%@NL@% %@NL@% ■ MCGA (Multicolor Graphics Array)%@NL@% %@NL@% ■ MDPA (Monochrome Display Printer Adapter)%@NL@% %@NL@% ■ VGA (Video Graphics Array)%@NL@% %@NL@% %@NL@% In addition, there are Olivetti versions of the CGA, EGA, and VGA (called OCGA, OEGA, and OVGA in this chapter). %@NL@% %@NL@% %@AU@% The video modes available at run time depend on your graphics adapter and %@AU@%monitor.%@AE@% %@NL@% %@NL@% Adapters can enter one or more "video modes." The video mode controls the resolution and number of colors on the video display. Microsoft C supports 17 video modes, which fall into two broad categories: %@NL@% %@NL@% %@NL@% ■ "Text modes," where characters are displayed%@NL@% %@NL@% ■ "Graphics modes," where individual pixels can be turned on and off%@NL@% %@NL@% %@NL@% The graphics adapter and the type of monitor in use determine which of the 17 video modes are available at run time. See Section 10.1.2 for a list of video modes. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00100003 @%%@AB@%10.1.1 Sample Low-Level Graphics Program%@AE@%%@EH@%%@NL@% %@NL@% The program ERESBOX.C below shows, in a few lines, the steps you follow to enter and exit a graphics mode. It sets the video mode %@AB@%_ERESCOLOR%@AE@%, draws a box, waits for a keypress, and returns to default mode, which is the video mode in effect when the program began running.%@CR:C6A00100004 @%%@CR:C6A00100005 @%%@CR:C6A00100006 @% %@NL@% %@NL@% %@AS@% /* ERESBOX.C -- Enters _ERESCOLOR mode and draws a box */ %@AS@% %@AS@% #include <graph.h> /* graphics functions */ %@AS@% #include <stdio.h> /* puts */ %@AS@% #include <conio.h> /* getch */ %@AS@% %@AS@% main() %@AS@% { %@AS@% if( _setvideomode( _ERESCOLOR ) ) /* EGA 640x350 mode */ %@AS@% { %@AS@% _rectangle( _GBORDER, 10, 10, 110, 110 ); /* draw */ %@AS@% getch(); /* wait for a keypress */ %@AS@% _setvideomode( _DEFAULTMODE ); /* return to default */ %@AS@% } else puts( "Can't enter _ERESCOLOR graphics mode." ) %@AS@% }%@AE@%%@NL@% %@NL@% The program above illustrates the steps you follow to display graphics: %@NL@% %@NL@% %@NL@% ■ Include the header file GRAPH.H. It contains function prototypes, macros, useful structures, and symbolic constants such as %@AB@%_ERESCOLOR%@AE@%, %@AB@%_GBORDER%@AE@%, and %@AB@%_DEFAULTMODE%@AE@%. %@NL@% %@AS@% #include <graph.h>%@AE@%%@NL@% %@NL@% %@NL@% ■ Call the %@AB@%_setvideomode%@AE@% function, which sets the desired video mode. The function returns 0 if the hardware does not support the requested mode. (See Section 10.1.2, "Setting a Video Mode.") %@NL@% %@AS@% if( _setvideomode( _ERESCOLOR ) )%@AE@%%@NL@% %@NL@% %@NL@% ■ Draw the graphics on the screen. The example program calls the %@AB@%_rectangle%@AE@% function. (See Section 10.4.3, "Drawing Points, Lines, and Shapes.") %@NL@% %@AS@% _rectangle( _GBORDER, 10, 10, 110, 110 )%@AE@%%@NL@% %@NL@% %@NL@% ■ Exit the graphics mode and return to whatever video mode was in effect before the program began. Call %@AB@%_setvideomode%@AE@%, passing the constant %@AB@%_DEFAULTMODE%@AE@%. In some cases, you might want to skip this step, exiting the program with the graphics screen still in place. %@NL@% %@AS@% _setvideomode( _DEFAULTMODE );%@AE@%%@NL@% %@NL@% %@NL@% %@NL@% In addition, you must link with the GRAPHICS.LIB library, which contains the function code. If you use window-coordinate functions (which require floating-point calculations) and if you have not created a standard combined library containing a floating-point component, you must explicitly link with a floating-point math library. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00100007 @%%@AB@%10.1.2 Setting a Video Mode%@AE@%%@EH@%%@NL@% %@NL@% The %@AB@%_setvideomode%@AE@% function turns on one of the 17 available video modes. Pass it a single integer that tells it which mode to display. The constants in Table 10.1 are defined in the GRAPH.H file. The dimensions are listed in pixels for video graphics mode and in columns for video text mode. %@NL@% %@NL@% %@AB@%Table 10.1 %@AB@%Constants that Represent Video Modes%@AE@%%@AE@% %@TH: 45 2006 02 17 40 19 @%Constant (Name) Description Mode/Hardware%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%_DEFAULTMODE%@AE@% Restores the original mode All/All%@AB@%_ERESCOLOR%@AE@% 640 x 350, 4 or 16 color Graphics/EGA%@AB@%_ERESNOCOLOR%@AE@% 640 x 350, BW Graphics/EGA%@AB@%_HRES16COLOR%@AE@% 640 x 200, 16 color Graphics/EGA%@AB@%_HERCMONO%@AE@%*%@AB@% %@AE@% 720 x 348, BW Graphics/HGC%@AB@%_HRESBW%@AE@% 640 x 200, BW Graphics/CGA%@AB@%_MAXCOLORMODE%@AE@% Graphics mode with the most colors Graphics/All┼%@AB@%_MAXRESMODE%@AE@% Graphics mode with the highest Graphics/All┼ resolution %@AB@%_MRES4COLOR%@AE@% 320 x 200, 4 color Graphics/All%@AB@%_MRES16COLOR%@AE@% 320 x 200, 16 color Graphics/EGA%@AB@%_MRES256COLOR%@AE@% 320 x 200, 256 color Graphics/VGA%@AB@%_MRESNOCOLOR%@AE@% 320 x 200, 4 gray Graphics/CGA%@AB@%_ORESCOLOR%@AE@% 640 x 400, 1 of 16 colors Graphics/Olivetti%@AB@%_TEXTBW40%@AE@% 40 column text, 16 gray Text/CGA%@AB@%_TEXTBW80%@AE@% 80 column text, 16 gray Text/CGA%@AB@%_TEXTC40%@AE@% 40 column text, 16/8 color Text/CGA%@AB@%_TEXTC80%@AE@% 80 column text, 16/8 color Text/CGA%@AB@%_TEXTMONO%@AE@% 80 column text, BW Text/MDPA%@AB@%_VRES2COLOR%@AE@% 640 x 480, BW Graphics/VGA%@AB@%_VRES16COLOR%@AE@% 640 x 480, 16 color Graphics/VGA%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@TE: 45 2006 02 17 40 19 @% *%@AB@% %@AE@%Before attempting to enter%@AB@% _HERCMONO%@AE@% mode, you must install the terminate-and-stay-resident program MSHERC.COM, which comes in the Microsoft C package. If you have both a Hercules adapter and an additional graphics adapter in the same computer, use the /H option to put the Hercules into %@AB@%HALF %@AE@%mode to avoid unpredictable and undesirable results. ┼ %@AB@%_MAXRESMODE%@AE@% and%@AB@% _MAXCOLORMODE %@AE@%support all adapters except the MDPA. See Section %@NL@% %@NL@% %@NL@% If the hardware does not support the selected mode, %@AB@%_setvideomode%@AE@% returns 0. %@NL@% %@NL@% Some graphics adapters are able to enter additional video modes: %@NL@% %@NL@% %@NL@% ■ EGA adapters can display all CGA modes. %@NL@% %@NL@% ■ HGC adapters can enter %@AB@%_TEXTMONO%@AE@% mode. %@NL@% %@NL@% ■ MCGA adapters can display all CGA modes, plus %@AB@%_VRES2COLOR%@AE@% and %@AB@%_MRES256COLOR%@AE@%.%@NL@% %@NL@% ■ VGA adapters can display all EGA and CGA modes. %@NL@% %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00100008 @%%@AB@%10.1.3 Reading the videoconfig Structure%@AE@%%@EH@%%@NL@% %@NL@% At any time, you can inquire about the current video configuration by passing the %@AB@%_getvideoconfig%@AE@% function a structure of type %@AB@%videoconfig%@AE@%. The structure contains 11 members, all of which are short integers. They are listed in Table 10.2. %@NL@% %@NL@% %@AB@%Table 10.2 %@AB@%Members of a videoconfig Structure%@AE@%%@AE@% %@TH: 14 967 02 23 53 @%Member Description%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%adapter%@AE@%* Active display adapter%@AB@%bitsperpixel%@AE@% Number of bits per pixel%@AB@%memory%@AE@% Adapter video memory in kilobytes%@AB@%mode%@AE@%* Current video mode%@AB@%monitor%@AE@%* Active display monitor%@AB@%numcolors%@AE@% Number of color indexes%@AB@%numtextcols%@AE@% Number of text columns available%@AB@%numtextrows%@AE@% Number of text rows available%@AB@%numvideopages%@AE@% Number of video pages available%@AB@%numxpixels%@AE@% Number of pixels on the %@AI@%x%@AE@% axis%@AB@%numypixels%@AE@% Number of pixels on the %@AI@%y%@AE@% axis%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@TE: 14 967 02 23 53 @% * Possible values for the mode, adapter, and monitor items are listed in the GRAPH.H file.%@NL@% %@NL@% %@NL@% The %@AB@%_getvideoconfig%@AE@% function initializes these values. Most of the values are self-explanatory. For example, if %@AB@%numxpixels%@AE@% holds 640, the current video mode contains 640 horizontal pixels, numbered 0 - 639. %@NL@% %@NL@% The READVC.C example program below illustrates how to initialize and examine a %@AB@%videoconfig%@AE@% structure: %@NL@% %@NL@% %@AS@% /* READVC.C -- Reads the videoconfig structure */ %@AS@% %@AS@% #include <graph.h> %@AS@% #include <stdio.h> %@AS@% %@AS@% main() %@AS@% { %@AS@% struct videoconfig vc; %@AS@% %@AS@% _getvideoconfig( &vc ); %@AS@% printf( "Text Rows = %i.\n", vc.numtextrows ); %@AS@% }%@AE@%%@NL@% %@NL@% First, the program declares a structure %@AS@% vc %@AE@% of type %@AB@%videoconfig%@AE@%. Next, it calls %@AB@%_getvideoconfig%@AE@% to initialize the structure. Finally, it prints a member of the structure. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00100009 @%%@AB@%10.1.4 Maximizing Resolution or Color%@AE@%%@EH@%%@NL@% %@NL@% Two symbolic constants are new to Microsoft C 6.0:%@AB@% _MAXRESMODE%@AE@% and %@AB@%_MAXCOLORMODE%@AE@%. The first selects the highest possible resolution for the graphics adapter and monitor currently in use. The second selects the graphics mode with the greatest number of colors. The constants work with all graphics adapters except the MDPA. (See Table 10.3.) %@NL@% %@NL@% %@AB@%Table 10.3 %@AB@%Constants for Maximum Resolution and Color%@AE@%%@AE@% %@TH: 14 988 02 17 15 44 @%Adapter/Monitor _MAXRESMODE _MAXCOLORMODE%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%CGA %@AB@%_HRESBW%@AE@% %@AB@%_MRES4COLOR%@AE@%EGA color %@AB@%_HRES16COLOR%@AE@% %@AB@%_HRES16COLOR%@AE@%EGA ecd 64K %@AB@%_ERESCOLOR%@AE@% %@AB@%_HRES16COLOR%@AE@%EGA ecd 256K %@AB@%_ERESCOLOR%@AE@% %@AB@%_ERESCOLOR%@AE@%EGA mono %@AB@%_ERESNOCOLOR%@AE@% %@AB@%_ERESNOCOLOR%@AE@%HGC %@AB@%_HERCMONO%@AE@% %@AB@%_HERCMONO%@AE@%MCGA %@AB@%_VRES2COLOR%@AE@% %@AB@%_MRES256COLOR%@AE@%MDPA Fails FailsOCGA %@AB@%_ORESCOLOR%@AE@% %@AB@%_MRES4COLOR%@AE@%OEGA color %@AB@%_ORESCOLOR%@AE@% %@AB@%_ERESCOLOR%@AE@%VGA/OVGA %@AB@%_VRES16COLOR%@AE@% %@AB@%_MRES256COLOR%@AE@%%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@TE: 14 988 02 17 15 44 @% %@NL@% %@3@%%@CR:C6A00100010 @%%@AB@%10.1.5 Selecting Your Own Video Modes%@AE@%%@EH@%%@NL@% %@NL@% A program that will run only on a single machine with a known graphics adapter can enter the appropriate video mode immediately. However, if you attempt to run the program on another machine with a different adapter, it may not run correctly, if at all. %@NL@% %@NL@% If your program might run on a variety of computers and you prefer to select your own video modes, initialize a %@AB@%videoconfig %@AE@%structure by calling the %@AB@%_getvideoconfig%@AE@% function. Then check the %@AB@%adapter %@AE@%member and use a %@AB@%switch %@AB@%%@AE@%statement to enter the selected video mode. %@NL@% %@NL@% For example, suppose you know that a program will run on monochrome systems equipped with either an EGA adapter or a Hercules adapter. To enter the appropriate mode, use code such as this: %@NL@% %@NL@% %@AS@% struct videoconfig vc; %@AS@% %@AS@% _getvideoconfig( &vc ); %@AS@% %@AS@% switch( vc.adapter ) %@AS@% { %@AS@% case _EGA: %@AS@% _setvideomode( _ERESNOCOLOR ); %@AS@% break; %@AS@% case _HGC: %@AS@% _setvideomode( _HERCMONO ); %@AS@% break; %@AS@% }%@AE@%%@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00100011 @%%@AB@%10.2 Mixing Colors and Changing Palettes%@AE@%%@EH@%%@NL@% %@NL@% Depending on the graphics card installed and the video mode in effect, you can display 2, 4, 8, 16, or 256 colors on the screen at the same time. You specify a color by selecting a color index (sometimes called a "pixel value" or "color attribute"). The color indexes are numbered from 0 to %@AI@%n%@AE@%-1, where %@AI@%n%@AE@% is the number of colors in the palette. %@NL@% %@NL@% CGA adapters offer four different palettes containing predefined fixed color sets. %@NL@% %@NL@% %@AU@% All video modes that support color offer a color palette.%@AE@% %@NL@% %@NL@% EGA, MCGA, and VGA adapters have palettes that can be redefined to suit your needs. You can change the visible color associated with any color index by remapping to a color index a color value that describes the true color (the amount of red, green, and blue) you want to display. %@NL@% %@NL@% Olivetti adapters (OCGA, OEGA, and OVGA) support the standard CGA, EGA, and VGA modes (and palettes), plus an additional Olivetti mode described in Section 10.2.2, "Olivetti Palettes." %@NL@% %@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% NOTE %@AI@%The distinction between a color index and a color value is important. A %@AI@%color index is always a short integer. A color value is always a long %@AI@%integer. The only exception to this rule involves %@AB@%_setbkcolor%@AE@%%@AI@%, which uses a %@AI@%color index cast to a long integer in CGA and text modes.%@AE@%%@AE@%%@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00100012 @%%@AB@%10.2.1 CGA Palettes%@AE@%%@EH@%%@NL@% %@NL@% The CGA (Color Graphics Adapter) supports two color video modes: %@AB@%_MRES4COLOR%@AE@% and %@AB@%_MRESNOCOLOR%@AE@%, which display four colors selected from one of several predefined palettes of colors. They display these foreground colors against a background color that can be any one of the 16 available colors. With the CGA hardware, the palette of foreground colors is predefined and cannot be changed. Each palette number is an integer. (See Table 10.4.) %@NL@% %@NL@% %@AB@%Table 10.4 %@AB@%CGA Palettes in _MRES4COLOR Mode%@AE@%%@AE@% %@TH: 14 585 04 16 14 16 30 @% Color Index Palette 1 2 3Number %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%0 Green Red Brown1 Cyan Magenta Light Gray2 Light Green Light Red Yellow3 Light Cyan Light Magenta White%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@TE: 14 585 04 16 14 16 30 @% %@AU@% _MRESNOCOLOR produces palettes with shades of gray on monochrome monitors.%@AE@% %@NL@% %@NL@% The %@AB@%_MRESNOCOLOR%@AE@% video mode produces palettes containing various shades of gray on monochrome monitors. However, the %@AB@%_MRESNOCOLOR%@AE@% mode displays colors when used with a color display. Only two palettes are available in this mode. Table 10.5 shows the colors available in the two palettes. %@NL@% %@NL@% %@AB@%Table 10.5 %@AB@%CGA Palettes in _MRESNOCOLOR Mode%@AE@%%@AE@% %@TH: 10 463 04 16 13 14 33 @% Color Index Palette 1 2 3Number %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%0 Blue Red Light Gray1 Light Blue Light Red White%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@TE: 10 463 04 16 13 14 33 @% You can use the %@AB@%_selectpalette%@AE@% function only in the %@AB@%_MRES4COLOR%@AE@%, %@AB@%_MRESNOCOLOR%@AE@%, and %@AB@%_ORESCOLOR%@AE@% graphics modes. To change palettes in other video modes, use the %@AB@%_remappalette%@AE@% or %@AB@%_remapallpalette%@AE@% functions. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00100013 @%%@AB@%10.2.2 Olivetti(R) Palettes%@AE@%%@EH@%%@NL@% %@NL@% Olivetti graphics adapters are found in most Olivetti computers (including the M24, M28, M240, M280, and M380) and in the AT&T 6300 series computers. These adapters function the same as their non-Olivetti equivalents; that is, the OCGA, OEGA, and OVGA adapters support CGA, EGA, and VGA modes, respectively. In addition, Olivetti adapters can enter the high resolution %@AB@%_ORESCOLOR%@AE@% mode. %@NL@% %@NL@% In %@AB@%_ORESCOLOR%@AE@% mode, you can choose one of 16 foreground colors by passing a value in the range 0 -15 to the %@AB@%_selectpalette%@AE@% function. The background color is always black. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00100014 @%%@AB@%10.2.3 VGA Palettes%@AE@%%@EH@%%@NL@% %@NL@% Depending on the video mode currently in effect, a VGA (Video Graphics Array) screen has 2, 16, or 256 color indexes chosen from a pool of 262,144 (256K) color values. %@NL@% %@NL@% To name a color value, specify a level of intensity ranging from 0 - 63 for each of the red, green, and blue components. The long integer that defines a color value contains four bytes (32 bits): %@NL@% %@NL@% %@AU@%(This figure may be found in the printed book.)%@AE@%%@NL@% %@NL@% The most-significant byte should contain zeros. The two high bits in the remaining three bytes should also be zero (these bits are ignored). %@NL@% %@NL@% To mix a light red (pink), turn red all the way up, and mix in some green and blue: %@NL@% %@NL@% %@AU@%(This figure may be found in the printed book.)%@AE@%%@NL@% %@NL@% The number 0x0020203FL represents this value in hexadecimal notation. You can also use the following macro: %@NL@% %@NL@% %@AS@% #define RGB ( r, g, b ) (0x3F3F3FL & ((long)(b) << 16 | (g) << 8 | (r)))%@AE@%%@NL@% %@NL@% To create pure yellow (100% red plus 100% green) and assign it to a variable %@AS@% yel%@AE@%, use this line: %@NL@% %@NL@% %@AS@% yel = RGB( 63, 63, 0 );%@AE@%%@NL@% %@NL@% For white, turn all the colors on: %@AS@% RGB( 63, 63, 63)%@AE@%. For black, set all colors to 0: %@AS@% RGB( 0, 0, 0 )%@AE@%. %@AS@% %@AE@%%@NL@% %@NL@% Once you have the color value, %@NL@% %@NL@% %@NL@% ■ Call %@AB@%_remappalette%@AE@%, passing a color index and a color value.%@NL@% %@NL@% ■ Call %@AB@%_setcolor%@AE@% to make that color index the current color.%@NL@% %@NL@% ■ Draw something.%@NL@% %@NL@% %@NL@% The program YELLOW.C below shows how to remap a color. It draws a rectangle in color index 3 and then changes index 3 to the color value 0x00003F3FL (yellow). %@NL@% %@NL@% %@AS@% /* YELLOW.C -- Draws a yellow box on the screen */ %@AS@% /* Requires VGA or EGA */ %@AS@% %@AS@% #include <graph.h> /* graphics functions */ %@AS@% #include <conio.h> /* getch */ %@AS@% %@AS@% main() %@AS@% { %@AS@% short int index3 = 3; %@AS@% long int yellow = 0x00003F3FL; %@AS@% long int old3;%@AE@%%@NL@% %@NL@% %@AS@% if( _setvideomode( _HRES16COLOR ) ) %@AS@% { %@AS@% /* set current color to index 3*/ %@AS@% _setcolor( index3 ); %@AS@% /* draw a rectangle in that color */ %@AS@% _rectangle( _GBORDER, 10, 10, 110, 110 ); %@AS@% /* wait for a keypress */ %@AS@% getch(); %@AS@% /* change index 3 to yellow */ %@AS@% old3 = _remappalette( index3, yellow ); %@AS@% /* wait for a keypress */ %@AS@% getch(); %@AS@% /* restore the old color */ %@AS@% _remappalette( index3, old3 ); %@AS@% getch(); %@AS@% /* back to default mode */ %@AS@% _setvideomode( _DEFAULTMODE ); %@AS@% } else _outtext( "This program requires EGA or VGA." ); %@AS@% }%@AE@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00100015 @%%@AB@%10.2.4 MCGA Palettes%@AE@%%@EH@%%@NL@% %@NL@% In terms of color mixing, the MCGA (Multicolor Graphics Array) adapter is the same as the VGA. It can display any of 256K colors. It cannot enter all of the VGA video modes, however. It is limited to CGA modes and %@AB@%_VRES2COLOR%@AE@% and %@AB@%_MRES256COLOR%@AE@%. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00100016 @%%@AB@%10.2.5 EGA Palettes%@AE@%%@EH@%%@NL@% %@NL@% Mixing colors in EGA (Enhanced Graphics Adapter) is similar to the VGA mixing described in Section 10.2.3, but there are fewer levels of intensity for the red, green, and blue (RGB) components. In the modes that offer 64 colors, the RGB values include two bits and can range in value from 0 - 3. The long integer that defines a color value looks like this: %@NL@% %@NL@% %@AU@%(This figure may be found in the printed book.)%@AE@%%@NL@% %@NL@% The bits marked %@AS@% 0 %@AE@% should be zeros; the bits marked %@AS@% ? %@AE@% are ignored. EGA color values are defined this way to maintain compatibility with VGA color values. %@NL@% %@NL@% To form a pure red color value, use the constant 0x00000030L. For cyan (blue plus green), use 0x00303000L. The RGB macro defined above for VGA color mixing can be used as is, or you can modify it for EGA monitors: %@NL@% %@NL@% %@AS@% #define EGARGB( r, g, b ) (0x303030L & ((long)(b) << 20 | (g) << 12 | (r %@AS@% << 4)))%@AE@%%@NL@% %@NL@% In this macro, you would pass values in the range 0 -3 instead of 0 - 63. %@NL@% %@NL@% For an example program that remaps a color index to a color value, see YELLOW.C in Section 10.2.3, "VGA Palettes." %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00100017 @%%@AB@%10.2.6 Symbolic Constants%@AE@%%@EH@%%@NL@% %@NL@% The GRAPH.H file defines the following constants, which can be used as ready-made color values for EGA and VGA adapters: %@NL@% %@NL@% %@TH: 7 448 01 14 15 47 @%%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%_BLACK%@AE@% _GREEN %@AB@%_LIGHTYELLOW%@AE@%%@AB@%_BLUE%@AE@% _LIGHTBLUE %@AB@%_MAGENTA%@AE@%%@AB@%_BRIGHTWHITE%@AE@% _LIGHTCYAN %@AB@%_RED%@AE@%%@AB@%_BROWN%@AE@% _LIGHTGREEN %@AB@%_WHITE%@AE@%%@AB@%_CYAN%@AE@% _LIGHTMAGENTA%@AB@%_GRAY%@AE@% _LIGHTRED%@TE: 7 448 01 14 15 47 @% For example, to change color index 1 to red, use the line%@AB@% %@AE@%%@NL@% %@NL@% %@AS@% _remappalette( 1, _RED );%@AE@%%@NL@% %@NL@% which causes any object currently drawn with color index 1 to change to red. The default color value associated with index 1 is blue. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00100018 @%%@AB@%10.3 Specifying Points within Coordinate Systems%@AE@%%@EH@%%@NL@% %@NL@% A coordinate system describes points on the screen in terms of their horizontal (%@AI@%x%@AE@%) and vertical (%@AI@%y%@AE@%) positions. You specify a certain location by providing two values that map to a unique position.%@CR:C6A00100019 @%%@AI@% %@AE@%%@NL@% %@NL@% %@AU@% Graphics functions usually use viewport and window coordinates.%@AE@% %@NL@% %@NL@% Coordinates on the physical screen never change. Only five functions, listed in Section 10.3.1, use physical coordinates. All other graphics functions use one of these two coordinate systems: %@NL@% %@NL@% %@NL@% ■ Viewport coordinates (short integers)%@NL@% %@NL@% ■ Window coordinates (double-precision floating-point numbers)%@NL@% %@NL@% %@NL@% Viewports and windows can occupy all of the physical screen or just part of it. The three coordinate systems and conventions for naming points and regions of the screen are described below. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00100020 @%%@AB@%10.3.1 Physical Coordinates%@AE@%%@EH@%%@NL@% %@NL@% Within the physical screen, the upper left corner is called the "origin." The %@AI@%x%@AE@% and %@AI@%y%@AE@% coordinates for the origin are always (0, 0). The %@AI@%x%@AE@% axis extends in the positive direction left to right, while the %@AI@%y%@AE@% axis extends in the positive direction top to bottom.%@CR:C6A00100021 @% %@NL@% %@NL@% For example, the video mode %@AB@%_VRES16COLOR%@AE@% has a resolution of 640 x 480, which means the %@AI@%x%@AE@% axis contains the values 0 - 639 (left to right), and the %@AI@%y%@AE@% axis contains 0 - 479 (top to bottom). (See Figure 10.1.) %@NL@% %@NL@% %@AU@%(This figure may be found in the printed book.)%@AE@%%@NL@% %@NL@% Only five functions use physical coordinates: %@AB@%_setcliprgn%@AE@%, %@AB@%_setvieworg%@AE@%, %@AB@%_setviewport%@AE@%,%@AB@% _getviewcoord%@AE@%, and%@AB@% _getphyscoord%@AE@%. %@NL@% %@NL@% The %@AB@%_setcliprgn%@AE@% function establishes a "clipping region." Attempts to draw inside the region succeed, while attempts to draw outside the region are clipped (ignored). When you first enter a graphics mode, the clipping region defaults to the entire screen. %@NL@% %@NL@% The %@AB@%_setvieworg%@AE@% function changes the current location of the origin. When a program first enters a graphics mode, the physical origin and the viewport origin are in the upper left corner. The following code moves the viewport origin to the physical screen location (50, 100):%@CR:C6A00100022 @% %@NL@% %@NL@% %@AS@% _setvieworg( 50, 100 );%@AE@%%@NL@% %@NL@% The effect on the screen is illustrated in Figure 10.2. Note that the number of pixels remains constant, but the range of legal %@AI@%x%@AE@% values changes from a range of 0 to 639 (physical screen) to -50 to 589. The legal %@AI@%y%@AE@% values change as well. %@NL@% %@NL@% %@AU@%(This figure may be found in the printed book.)%@AE@%%@NL@% %@NL@% All graphics functions are affected by the new origin, including %@AB@%_arc%@AE@%, %@AB@%_ellipse%@AE@%, %@AB@%_lineto%@AE@%, %@AB@%_moveto%@AE@%, %@AB@%_outgtext%@AE@%,%@AB@% %@AE@% %@AB@%_pie%@AE@%, and %@AB@%_rectangle%@AE@%. %@NL@% %@NL@% The third function that uses physical coordinates is %@AB@%_setviewport%@AE@%, described below, which establishes the boundaries of the current viewport. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00100023 @%%@AB@%10.3.2 Viewport Coordinates%@AE@%%@EH@%%@NL@% %@NL@% The default viewport coordinate system is identical to the physical screen coordinate system. The %@AB@%_setviewport%@AE@% function creates a new viewport within the boundaries of the physical screen. A standard viewport has two distinguishing features:%@CR:C6A00100024 @%%@CR:C6A00100025 @% %@NL@% %@NL@% %@NL@% ■ The origin of a viewport initially lies in the upper left corner of the viewport, not the upper left corner of the physical screen.%@NL@% %@NL@% ■ The clipping region matches the outer boundaries of the viewport.%@NL@% %@NL@% %@NL@% %@AU@% Graphics output functions require viewport or window coordinate values.%@AE@% %@NL@% %@NL@% In other words, the %@AB@%_setviewport%@AE@% function does the same thing as would two separate calls to %@AB@%_setvieworg%@AE@% and %@AB@%_setcliprgn%@AE@%. All graphics output functions require values that are either viewport coordinates or window coordinates. %@NL@% %@NL@% For example, %@NL@% %@NL@% %@AS@% _setviewport( 50, 50, 200, 100 );%@AE@%%@NL@% %@NL@% creates the viewport illustrated in Figure 10.3. The values passed to the %@AB@%_setviewport%@AE@% function are physical screen locations of opposite corners. After the viewport is created, the viewport origin lies in the upper left corner. %@NL@% %@NL@% %@AU@%(This figure may be found in the printed book.)%@AE@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00100026 @%%@AB@%10.3.3 Window Coordinates%@AE@%%@EH@%%@NL@% %@NL@% The %@AB@%_setwindow%@AE@% function allows you to use floating-point coordinates instead of integers. More importantly, it scales the screen coordinates to almost any size within the current viewport. Window functions take double-precision arguments and have names that end with the suffixes %@AB@%_w%@AE@% or %@AB@%_wxy%@AE@%. The function %@AB@%_lineto_w%@AE@% is the window-coordinate equivalent of the viewport function %@AB@%_lineto%@AE@%.%@CR:C6A00100027 @% %@NL@% %@NL@% To create a window for charting 12 months of average temperatures ranging from - 40 to 100, use this line: %@NL@% %@NL@% %@AS@% _setwindow( TRUE, 1.0, -40.0, 12.0, 100.0 );%@AE@%%@NL@% %@NL@% The first argument is the invert flag, which puts the lowest %@AI@%y%@AE@% value at the bottom of the screen instead of the top. The minimum and maximum coordinates follow. The new organization of the screen is shown in Figure 10.4. %@NL@% %@NL@% %@AU@%(This figure may be found in the printed book.)%@AE@%%@NL@% %@NL@% If you plot a point with %@AB@%_setpixel_w%@AE@% or draw a line with %@AB@%_lineto_w%@AE@%, the values are automatically scaled to the established window. %@NL@% %@NL@% Window-coordinate graphics provide a lot of flexibility. You can fit an axis into a small range (such as 151.25 to 151.45) or into a large range (-50,000 to 80,000), depending on the type of data to be graphed. In addition, by changing the window coordinates and redrawing a figure, you can create the effects of zooming in or panning across a figure. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00100028 @%%@AB@%10.3.4 Screen Locations%@AE@%%@EH@%%@NL@% %@NL@% A coordinate system needs two values (a horizontal and a vertical position) to describe the location of a point on the screen. There are times, however, when it is more convenient to use one variable instead of two.%@CR:C6A00100029 @%%@CR:C6A00100030 @% %@NL@% %@NL@% Some graphics functions require you to pass the location of a point on the screen. Others return a value that represents a location. The GRAPH.H file defines two structures that allow you to refer to a point with a single variable. %@NL@% %@NL@% %@NL@% ■ An %@AB@%xycoord %@AE@%structure contains two short integers called %@AB@%xcoord %@AE@%and %@AB@%ycoord%@AE@% for use in viewport graphics.%@NL@% %@NL@% ■ A %@AB@%_wxycoord %@AE@%structure contains two %@AB@%doubles%@AE@% called %@AB@%wx %@AE@%and %@AB@%wy %@AE@%for use in window-coordinate graphics.%@NL@% %@NL@% %@NL@% For example, you pass four %@AB@%doubles%@AE@% to the %@AB@%_rectangle_w%@AE@% function: an %@AI@%x%@AE@% and %@AI@%y%@AE@% position for the upper left corner of the window and an %@AI@%x%@AE@% and %@AI@%y%@AE@% position for the lower right corner. The %@AB@%_rectangle_wxy%@AE@% function takes two %@AB@%_wxycoord%@AE@% structures. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00100031 @%%@AB@%10.3.5 Bounding Rectangles%@AE@%%@EH@%%@NL@% %@NL@% Certain figures such as arcs and ellipses are centered within a "bounding rectangle," specified by two points that define the opposite corners of the rectangle. The center of the rectangle becomes the center of the figure, and the rectangle's borders determine the size of the figure. Figure 10.5 shows start and end vectors and a bounding rectangle in which a pie shape has been drawn with the %@AB@%_pie%@AE@% function. The first two sets of coordinates are %@AI@%x1%@AE@%, %@AI@%y1%@AE@%, %@AI@%x2%@AE@%, and %@AI@%y2%@AE@%. They define the boundaries of the rectangle. The pie shape needs two other points, %@AI@%x3%@AE@%, %@AI@%y3%@AE@%, %@AI@%x4%@AE@%, and %@AI@%y4%@AE@%, which indicate the starting and ending lines. %@NL@% %@NL@% %@AU@%(This figure may be found in the printed book.)%@AE@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00100032 @%%@AB@%10.3.6 The Pixel Cursor%@AE@%%@EH@%%@NL@% %@NL@% A "pixel cursor" is a location on the screen. The %@AB@%_moveto%@AE@% function positions this cursor at a given spot. Nothing visible appears. If you call %@AB@%_lineto%@AE@%, a line is drawn from the current pixel cursor to another point. The %@AB@%_lineto%@AE@% function also changes the location of the pixel cursor. When you call %@AB@%_outgtext%@AE@% to display fonted text, the characters are drawn at the current pixel cursor location. %@NL@% %@NL@% To draw a series of connected lines, call %@AB@%_lineto%@AE@% several times. %@NL@% %@NL@% The %@AB@%_getcurrentposition%@AE@% function returns the cursor location in an %@AB@%xycoord%@AE@% structure. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00100033 @%%@AB@%10.4 Graphics Functions%@AE@%%@EH@%%@NL@% %@NL@% This section lists the functions that work in one or more bit-mapped graphics modes. Most of these functions are present in several forms. The function names that end with %@AB@%_w%@AE@% use %@AB@%double%@AE@% values as arguments and the window coordinate system. Functions that end with %@AB@%_wxy%@AE@% use the window coordinate system and a %@AB@%_wxycoord%@AE@% structure to define the coordinates. Functions with no suffix use the viewport coordinate system.%@CR:C6A00100034 @% %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00100035 @%%@AB@%10.4.1 Controlling Video Modes%@AE@%%@EH@%%@NL@% %@NL@% The functions described below affect the current video mode, coordinate systems, clipping regions, viewports, and windows. For more information, use on-line help. %@NL@% %@NL@% %@AB@%_clearscreen%@AE@% - Erases the text or graphics screen and fills it with the current background color (note that setting the video mode automatically clears the screen). Pass one of the constants %@AB@%_GCLEARSCREEN%@AE@%, %@AB@%_GVIEWPORT%@AE@%, or %@AB@%_GWINDOW%@AE@%. No return value.%@NL@% %@NL@% %@AB@%_getphyscoord%@AE@% - Converts viewport coordinates to physical coordinates. Pass an %@AI@%x%@AE@% and %@AI@%y%@AE@% coordinate from the viewport. The function returns an %@AB@%xycoord%@AE@% structure, which includes an %@AI@%x%@AE@% and a %@AI@%y%@AE@% position from the physical screen.%@CR:C6A00100036 @%%@NL@% %@NL@% %@AB@%_getvideoconfig%@AE@% - Obtains the status of the current graphics environment. Pass it the address of a structure of type %@AB@%_videoconfig%@AE@%. See Section 10.1.3. "Reading the videoconfig Structure."%@NL@% %@NL@% %@AB@%_getviewcoord%@AE@% - Converts physical coordinates to viewport coordinates. Pass two integers: an %@AI@%x%@AE@% and %@AI@%y%@AE@% coordinate. The function returns an %@AB@%xycoord%@AE@% structure containing the equivalent position within the viewport.%@NL@% %@NL@% %@AB@%_getviewcoord_w%@AE@% - Converts window coordinates to viewport coordinates. Pass two %@AB@%doubles%@AE@% that name points within the window. Returns the equivalent viewport coordinates as an %@AB@%xycoord%@AE@% structure.%@NL@% %@NL@% %@AB@%_getviewcoord_wxy%@AE@% - Converts window coordinates to viewport coordinates in an %@AB@%xycoord%@AE@% structure. Pass a %@AB@%_wxycoord%@AE@% structure.%@NL@% %@NL@% %@AB@%_getwindowcoord%@AE@% - Converts viewport coordinates to window coordinates. Pass two integers representing viewport coordinates. Returns a %@AB@%_wxycoord%@AE@% structure.%@NL@% %@NL@% %@AB@%_setcliprgn%@AE@% - Limits graphic output to part of the screen, called the "clipping region." Pass four values: the %@AI@%x%@AE@% and %@AI@%y%@AE@% coordinate of the upper left corner (on the physical screen) and the coordinates of the lower right corner. The default clipping region is the entire screen. See Section 10.3.1, "Physical Coordinates."%@NL@% %@NL@% %@AB@%_setvideomode%@AE@% - Selects an operating mode for the display screen. Pass a constant, such as %@AB@%_HRES16COLOR%@AE@%. Returns 0 if the video mode selected is not supported by the hardware. See Section 10.1.2, "Setting a Video Mode."%@NL@% %@NL@% %@AB@%_setvideomoderows%@AE@% - Sets the video mode and the number of rows for text operations. Pass two values: a video mode and the desired number of text rows (25, 30, 43, 50, or 60). Pass the symbolic constant %@AB@%_MAXTEXTROWS%@AE@% to get the largest available number of rows. Returns the number of rows or 0 if unsuccessful.%@NL@% %@NL@% %@AB@%_setvieworg%@AE@% - Repositions the viewport origin. Pass an %@AI@%x%@AE@% and %@AI@%y%@AE@% position: the physical screen location that will become the new origin. Returns the previous origin in an %@AB@%xycoord%@AE@% structure.%@NL@% %@NL@% %@AB@%_setviewport%@AE@% - Creates a viewport, including a clipping region and a new origin in the upper left corner of the viewport. Subsequent calls to graphics routines will be limited to the viewport area. Pass four short integers that indicate the physical screen locations of the %@AI@%x%@AE@% and %@AI@%y%@AE@% coordinates in the upper left and lower right corners of the viewport. No return value.%@NL@% %@NL@% %@AB@%_setwindow%@AE@% - Defines a window coordinate system. Pass five values: a short invert flag (TRUE or FALSE) and four %@AB@%doubles%@AE@% that represent the extreme values in the upper left and lower right portions of the current viewport. See Section 10.3.3, "Window Coordinates."%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00100037 @%%@AB@%10.4.2 Changing Colors%@AE@%%@EH@%%@NL@% %@NL@% The functions below control colors and color palettes. For an introduction to this topic, see Section 10.2, "Mixing Colors and Changing Palettes." For function prototypes and more information, consult on-line help.%@CR:C6A00100038 @%%@CR:C6A00100039 @% %@NL@% %@NL@% %@AB@%_getbkcolor%@AE@% - Reports the current background color as a long integer. In EGA, MCGA, and VGA video modes, this is a color value. In CGA and text modes, it is a color index.%@NL@% %@NL@% %@AB@%_getcolor%@AE@% - Returns the current color index.%@NL@% %@NL@% %@AB@%_remapallpalette%@AE@% - Assigns new color values to all color indexes. Pass a pointer to an array of color values. Returns 0 if unsuccessful.%@NL@% %@NL@% %@AB@%_remappalette%@AE@% - Assigns a color value to a specific color index. Pass a short color index and a long color value (which specifies the amount of red, green, and blue). Returns the previous color value for that index or -1 if unsuccessful. See Section 10.2.1, "CGA Palettes."%@NL@% %@NL@% %@AB@%_selectpalette%@AE@% - Selects a predefined palette. This function applies only to the CGA video modes %@AB@%_MRES4COLOR%@AE@% and %@AB@%_MRESNOCOLOR%@AE@% and the Olivetti graphics mode%@AB@% _ORESCOLOR%@AE@%. To change palettes in other color video modes, use %@AB@%_remappalette%@AE@% instead. Pass a short integer in the range 0 - 4 for CGA, or 0 -15 for Olivetti mode. Returns the value of the previous palette.%@NL@% %@NL@% %@AB@%_setbkcolor%@AE@% - Sets the current background color. Always pass a long integer. In EGA, MCGA, and VGA modes, this value is a color value. In CGA and text modes, this is a color index cast to a long integer. Returns the old background color or -1 if unsuccessful.%@NL@% %@NL@% %@AB@%_setcolor%@AE@% - Sets the color index to be used for graphic output. It affects later calls to functions such as %@AB@%_arc%@AE@%, %@AB@%_ellipse%@AE@%, %@AB@%_floodfill%@AE@%, %@AB@%_lineto%@AE@%, %@AB@%_outgtext%@AE@%, %@AB@%_outtext%@AE@%, %@AB@%_pie%@AE@%, %@AB@%_rectangle%@AE@%, and %@AB@%_setpixel%@AE@%. Returns the previous color or -1 if unsuccessful.%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00100040 @%%@AB@%10.4.3 Drawing Points, Lines, and Shapes%@AE@%%@EH@%%@NL@% %@NL@% The functions described below draw points, lines, and shapes. For a definition of bounding rectangle and pixel cursor, see Sections 10.3.5 and 10.3.6.%@CR:C6A00100041 @% %@NL@% %@NL@% %@AB@%_arc%@AE@% - Draws an elliptical arc. Pass eight short integers: four pairs of %@AI@%x%@AE@% and %@AI@%y%@AE@% coordinates. The first two pairs are the corners of the bounding rectangle. The third and fourth are the starting and ending points of the arc. Returns 0 if unsuccessful.%@NL@% %@NL@% %@AB@%_arc_wxy%@AE@% - Draws an arc within the window. Pass four %@AB@%wxycoord%@AE@% structures. The first two are the corners of the bounding rectangle. The third and fourth are the starting and ending points of the arc. Returns 0 if unsuccessful.%@NL@% %@NL@% %@AB@%_ellipse%@AE@% - Draws an ellipse or a circle. Pass a short fill flag (%@AB@% _GBORDER%@AE@% or %@AB@%_GFILLINTERIOR%@AE@%) and four short integers representing the corners of the bounding rectangle. Returns 0 if unsuccessful.%@NL@% %@NL@% %@AB@%_ellipse_w%@AE@% - Draws an ellipse or a circle within a window. Pass a short fill flag (%@AB@% _GBORDER%@AE@% or %@AB@%_GFILLINTERIOR%@AE@%) and four %@AB@%doubles%@AE@% representing the corners of the bounding rectangle. Returns 0 if unsuccessful.%@NL@% %@NL@% %@AB@%_ellipse_wxy%@AE@% - Draws an ellipse or a circle. Pass a short fill flag (%@AB@% %@AB@%_GBORDER%@AE@% or %@AB@%_GFILLINTERIOR%@AE@%) and two %@AB@%_wxycoord%@AE@% structures representing the two corners of the bounding rectangle. Returns 0 if unsuccessful.%@NL@% %@NL@% %@AB@%_getcurrentposition%@CR:C6A00100042 @%%@AE@% - Returns the current pixel cursor position in viewport coordinates as an %@AB@%xycoord%@AE@% structure. The current position can be changed by %@AB@%_arc%@AE@%, %@AB@%_lineto%@AE@%, and %@AB@%_moveto%@AE@%. The default position is the center of the viewport.%@NL@% %@NL@% %@AB@%_getcurrentposition_w%@AE@% - Returns the current position of the pixel cursor as a %@AB@%_wxycoord%@AE@% structure containing the %@AI@%x%@AE@% and %@AI@%y%@AE@% coordinates. Pass nothing.%@NL@% %@NL@% %@AB@%_getpixel%@AE@% - Returns a pixel's color index. Pass a short %@AI@%x%@AE@% and %@AI@%y%@AE@% coordinate (in viewport coordinates). If the point is outside the clipping region, the function returns -1.%@NL@% %@NL@% %@AB@%_getpixel_w%@AE@% - Returns a pixel's color index. Pass two doubles: an %@AI@%x%@AE@% and %@AI@%y%@AE@% coordinate.%@NL@% %@NL@% %@AB@%_lineto%@AE@% - Draws a line from the current pixel cursor position to a specified point. Pass a short %@AI@%x%@AE@% and a short %@AI@%y%@AE@% position. Returns 0 if unsuccessful.%@NL@% %@NL@% %@AB@%_lineto_w%@AE@% - Draws a line from the current pixel position to a specified window coordinate point. Pass a %@AB@%double%@AE@% %@AI@%x%@AE@% and %@AI@%y%@AE@% position. Returns 0 if unsuccessful.%@NL@% %@NL@% %@AB@%_moveto%@AE@% - Moves the pixel cursor to a specified point (with no graphic output). Pass an %@AI@%x%@AE@% and %@AI@%y%@AE@% position. Returns the coordinates of the previous position in an %@AB@%xycoord%@AE@% structure.%@NL@% %@NL@% %@AB@%_moveto_w%@AE@% - Moves the pixel cursor to a specified point in a window. Pass two doubles: an %@AI@%x%@AE@% and a %@AI@%y%@AE@% coordinate. Returns the previous position as a %@AB@%_wxycoord%@AE@% structure.%@NL@% %@NL@% %@AB@%_ pie%@AE@% - Draws a figure shaped like a pie slice. Pass a short fill flag and eight short integers. The first four describe the bounding rectangle. The final four represent the starting vector and ending vector. Returns 0 if unsuccessful.%@NL@% %@NL@% %@AB@%_ pie_wxy%@AE@% - Draws a pie-slice figure within a window. Pass a short fill flag and four %@AB@%_wxycoord%@AE@% structures. The first two describe the bounding rectangle. The second two represent the starting vector and ending vector. Returns 0 if unsuccessful.%@NL@% %@NL@% %@AB@%_rectangle%@AE@% - Draws a rectangle in the current line style. Pass a short fill flag (%@AB@% _GFILLINTERIOR%@AE@% or %@AB@%_GBORDER%@AE@%) and four short integers: the %@AI@%x%@AE@% and %@AI@%y%@AE@% coordinates of opposite corners. Returns 0 if unsuccessful.%@NL@% %@NL@% %@AB@%_rectangle_w%@AE@% - Draws a rectangle in the current line style. Pass a short fill flag (%@AB@% _GFILLINTERIOR%@AE@% or %@AB@%_GBORDER%@AE@%) and four doubles: the %@AI@%x%@AE@% and %@AI@%y%@AE@% window coordinates of opposite corners. Returns 0 if unsuccessful.%@NL@% %@NL@% %@AB@%_rectangle_wxy%@AE@% - Draws a rectangle in the current line style. Pass a short fill flag (%@AB@% _GFILLINTERIOR%@AE@% or %@AB@%_GBORDER%@AE@%) and two %@AB@%_wxycoord%@AE@% structures describing the %@AI@%x%@AE@% and %@AI@%y%@AE@% coordinates of opposite corners. Returns 0 if unsuccessful.%@NL@% %@NL@% %@AB@%_setpixel%@AE@% - Sets a pixel to the current color (which is selected by %@AB@%_setcolor%@AE@%). Pass it integer %@AI@%x%@AE@% and %@AI@%y%@AE@% coordinates. Returns the previous value of the pixel or -1 if unsuccessful.%@NL@% %@NL@% %@AB@%_setpixel_w%@AE@% - Sets a pixel to the current color (which is selected by %@AB@%_setcolor%@AE@%). Pass it %@AB@%double%@AE@% %@AI@%x%@AE@% and %@AI@%y%@AE@% coordinates describing a position within the window. Returns the previous value of the pixel or -1 if unsuccessful.%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00100043 @%%@AB@%10.4.4 Defining Patterns%@AE@%%@EH@%%@NL@% %@NL@% The following functions control the style in which straight lines are drawn and the fill pattern used for solid shapes. For more information, use on-line help.%@CR:C6A00100044 @% %@NL@% %@NL@% %@AB@%_floodfill%@AE@% - Fills a bounded shape with the fill pattern set by %@AB@%_setfillmask%@AE@% in the current color established by %@AB@%_setcolor%@AE@%. Pass an %@AI@%x%@AE@% and %@AI@%y%@AE@% coordinate and a boundary color (the color index that marks the edge of the shape to be filled). Returns 0 if unsuccessful.%@NL@% %@NL@% %@AB@%_floodfill_w%@AE@% - Fills a bounded shape with the fill pattern set by %@AB@%_setfillmask%@AE@%. Pass %@AB@%doubles%@AE@% that describe an %@AI@%x%@AE@% and %@AI@%y%@AE@% position within the window and a boundary color (the color index that marks the edge of the shape to be filled). Returns 0 if unsuccessful.%@NL@% %@NL@% %@AB@%_getfillmask%@AE@% - Returns the address of the current fill mask, an eight-character array, or 0 if the fill mask is not currently defined.%@NL@% %@NL@% %@AB@%_getlinestyle%@AE@% - Returns the line style, a short integer whose bits correspond to the screen pixels turned on or off within a line.%@NL@% %@NL@% %@AB@%_setfillmask%@AE@% - Sets the current fill mask used by %@AB@%_floodfill %@AE@%and functions that draw solid shapes (%@AB@%_ellipse%@AE@%, %@AB@%_pie%@AE@%, and %@AB@%_rectangle%@AE@%). Pass the address of an array of eight unsigned characters, where each bit represents a pixel. The pixels are drawn in the current color. No return value.%@NL@% %@NL@% %@AB@%_setlinestyle%@AE@% - Sets the current style, which is used to draw the straight lines within %@AB@%_lineto%@AE@%, %@AB@%_rectangle%@AE@%, and %@AB@%_pie%@AE@%. Pass an unsigned short integer within which the bits correspond to the pixels on screen. For example, 0xFFFF represents a solid line, 0xAAAA is a dotted line, and 0xF0F0 is dashed.%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00100045 @%%@AB@%10.4.5 Manipulating Images%@AE@%%@EH@%%@NL@% %@NL@% The functions described below can be used to create animated graphics. The %@AB@%_getimage %@AE@%and %@AB@%_putimage %@AE@%functions act like a rubber stamp; after capturing a shape, you can make copies anywhere on the screen.%@CR:C6A00100046 @% %@NL@% %@NL@% %@AB@%_getimage%@AE@% - Stores a screen image in memory. Pass four integers (the coordinates of the bounding rectangle) and a pointer to a storage buffer. Call %@AB@%_imagesize%@AE@% to find out how much memory is required. No return value.%@NL@% %@NL@% %@AB@%_getimage_w%@AE@% - Stores a screen image in memory. Pass four %@AB@%doubles%@AE@% (the coordinates of the bounding rectangle) and a pointer to a storage buffer. Call %@AB@%_imagesize_w%@AE@% to find out how much memory is required. No return value.%@NL@% %@NL@% %@AB@%_getimage_wxy%@AE@% - Same as %@AB@%_getimage_w%@AE@%, but you pass two %@AB@%_wxycoord%@AE@% structures and a pointer to memory.%@NL@% %@NL@% %@AB@%_imagesize%@AE@% - Returns a long integer representing the size of an image in bytes. Call this function in preparation for a call to %@AB@%_getimage%@AE@%. Pass four integers: the %@AI@%x%@AE@% and %@AI@%y%@AE@% coordinates of opposite corners of the portion of the screen to be saved.%@NL@% %@NL@% %@AB@%_imagesize_w%@AE@% - Returns the size of an image in bytes in preparation for a call to %@AB@%_getimage_w%@AE@% and %@AB@%_putimage_w%@AE@%. Pass four doubles: the %@AI@%x%@AE@% and %@AI@%y%@AE@% window coordinates of opposite corners of the portion of the screen to be saved.%@NL@% %@NL@% %@AB@%_imagesize_wxy%@AE@% - Same as %@AB@%_imagesize_w%@AE@%, but you pass two %@AB@%_wxycoord%@AE@% structures.%@NL@% %@NL@% %@AB@%_putimage%@AE@% - Retrieves an image from memory and displays it on the active screen page. The image should previously have been saved to memory with %@AB@%_getimage%@AE@%. Pass two short integers (coordinates where the image is to be placed), a pointer to the image, and a short integer indicating what kind of action to take: %@AB@%_GAND%@AE@%, %@AB@%_GOR%@AE@%, %@AB@%_GPRESET%@AE@%, %@AB@%_GPSET%@AE@%, or %@AB@%_GXOR%@AE@%. No return value.%@NL@% %@NL@% %@AB@%_putimage_w%@AE@% - Displays an image from memory within a window. The image should previously have been saved to memory with %@AB@%_getimage_w%@AE@%. Pass two %@AB@%doubles%@AE@% (coordinates where the image is to be placed), a pointer to the image, and a short integer indicating what kind of action to take: %@AB@%_GAND%@AE@%, %@AB@%_GOR%@AE@%, %@AB@%_GPRESET%@AE@%, %@AB@%_GPSET%@AE@%, or %@AB@%_GXOR%@AE@%. No return value.%@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00100047 @%%@AB@%10.5 Using Graphic Fonts%@AE@%%@EH@%%@NL@% %@NL@% A "font" is a collection of stylized text characters. Each font consists of a typeface with several type sizes.%@CR:C6A00100048 @% %@NL@% %@NL@% A "typeface" is the name of the displayed text─Courier, for example, or Roman. The list on the next page shows six of the typefaces available with the Microsoft C font library. %@NL@% %@NL@% "Type size" measures the screen area occupied by individual characters in units of screen pixels. For example, "Courier 12 x 9" denotes text of Courier typeface, with each character occupying a screen area of 12 vertical pixels by 9 horizontal pixels. %@NL@% %@NL@% A font's spacing can be fixed or proportional. "Fixed" means that all characters have the same width in pixels. "Proportional" means the width varies. An %@AI@%i%@AE@%, for example, is thinner than an %@AI@%M%@AE@%. %@NL@% %@NL@% The Microsoft C font functions use two methods to create fonts. The first technique generates Courier, Helv, and Tms Rmn fonts through a "bit-mapping" (or "raster-mapping") technique. Bit-mapping defines character images with binary data. Each bit in the map corresponds to a screen pixel. If a bit is 1, its associated pixel is set to the current screen color. %@NL@% %@NL@% The second method creates the remaining three type styles─Modern, Script, and Roman─as "vector-mapped" fonts. Vector-mapping represents each character in terms of lines and arcs. %@NL@% %@NL@% Each method has advantages and disadvantages. Bit-mapped characters are more completely formed since the pixel mapping is predetermined. However, they cannot be scaled. Vector-mapped text can be scaled to any size, but the characters tend to lack the solid appearance of the bit-mapped characters. %@NL@% %@NL@% The following list shows six sample typefaces: %@NL@% %@NL@% %@AU@%(This figure may be found in the printed book.)%@AE@%%@NL@% %@NL@% Table 10.6 lists available sizes for each font. Note that the bit-mapped fonts come in preset sizes as measured in pixels. The vector-mapped fonts can be scaled to any size. %@NL@% %@NL@% %@AB@%Table 10.6 %@AB@%Typefaces and Type Sizes in the C Library%@AE@%%@AE@% %@TH: 21 759 02 10 09 18 39 @%Typeface Mapping Size (in pixels) Spacing%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%Courier Bit 10 x 8, 12 x 9, Fixed 15 x 12 Helv Bit 10 x 5, 12 x 7, Proportional 15 x 8, 18 x 9, 22 x 12, 28 x 16 Tms Rmn Bit 10 x 5, 12 x 6, Proportional 15 x 8, 16 x 9, 20 x 12, 26 x 16 Modern Vector Scaled ProportionalScript Vector Scaled ProportionalRoman Vector Scaled Proportional%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@TE: 21 759 02 10 09 18 39 @% %@NL@% %@3@%%@CR:C6A00100049 @%%@AB@%10.5.1 Using the C Font Library%@AE@%%@EH@%%@NL@% %@NL@% Data for both bit-mapped and vector-mapped fonts reside in .FON files. For example, the files MODERN.FON, ROMAN.FON, and SCRIPT.FON hold data for the three vector-mapped fonts.%@CR:C6A00100050 @%%@CR:C6A00100051 @% %@NL@% %@NL@% %@AU@% You can use Microsoft Windows .FON files.%@AE@% %@NL@% %@NL@% The Microsoft C .FON files are identical to the .FON files used in the Microsoft Windows operating environment. If you have access to Windows, you can use any of its .FON files with Microsoft C font functions. In addition, several vendors offer software that creates or modifies .FON files, allowing you to design your own fonts. %@NL@% %@NL@% Your programs should follow these three steps to display fonted text: %@NL@% %@NL@% %@NL@% 1. Register the fonts.%@NL@% %@NL@% 2. Set the current font from the register.%@NL@% %@NL@% 3. Display text using the current font.%@NL@% %@NL@% %@NL@% The following sections describe each of the three steps in detail. An example program in Section 10.5.5 demonstrates these steps. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00100052 @%%@AB@%10.5.2 Registering the Fonts%@AE@%%@EH@%%@NL@% %@NL@% The fonts must first be organized into a list in memory, a process called "registering." Register fonts by calling the function %@AB@%_registerfonts%@AE@%. This function reads header information from specified .FON files, building a list of file information but not reading any mapping data from the files.%@CR:C6A00100053 @%%@CR:C6A00100054 @% %@NL@% %@NL@% The GRAPH.H file prototypes the %@AB@%_registerfonts%@AE@% function as %@NL@% %@NL@% %@AS@% short far _registerfonts( unsigned char far * );%@AE@%%@NL@% %@NL@% The argument points to a string containing a file name. The file name is the name of the .FON file for the desired font. The file name can include wild cards, allowing you to register several fonts with one call to %@AB@%_registerfonts%@AE@%. %@NL@% %@NL@% If it successfully reads one or more .FON files, %@AB@%_registerfonts%@AE@% returns the number of fonts. If the function fails, it returns a negative error code. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00100055 @%%@AB@%10.5.3 Setting the Current Font%@AE@%%@EH@%%@NL@% %@NL@% Call the function %@AB@%_setfont%@AE@% to select a current font. This function checks to see if the requested font is registered, then reads the mapping data from the appropriate .FON file. A font must be registered and marked current before your program can display text in that font. %@NL@% %@NL@% The GRAPH.H file prototypes the%@AB@%_setfonts%@AE@% function as %@NL@% %@NL@% %@AS@% short far _setfont( unsigned char far * );%@AE@%%@NL@% %@NL@% The function's argument is a pointer to a character string. The string consists of letter codes that describe the desired font, as outlined here: %@NL@% %@NL@% %@AB@%Option Code%@AE@% %@AB@%Meaning%@AE@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@AB@%b%@AE@% The best fit from the registered fonts. This option instructs %@AB@%_setfont%@AE@% to accept the closest-fitting font if a font of the specified size is not registered. If at least one font is registered, the %@AB@%%@AE@% %@AB@%b%@AE@% option always sets a current font. If you do not specify the %@AB@%b%@AE@% option and an exact matching font is not registered, the%@AB@%%@AE@% %@AB@%_setfont%@AE@% function will fail. In this case, any existing current font remains current. Refer to on-line help for a description of error codes returned by%@AB@%%@AE@% %@AB@%_setfont%@AE@%. The %@AB@%_setfont%@AE@% function uses four criteria for selecting the best fit. In descending order of precedence, the four criteria are pixel height, typeface, pixel width, and spacing (fixed or proportional). If you request a vector-mapped font,%@AB@% _setfont%@AE@% sizes the font to correspond with the specified pixel height and width. If you request a raster-mapped (bit-mapped) font,%@AB@%%@AE@% %@AB@%_setfont%@AE@% chooses the closest available size. If the requested type size for a raster-mapped font fits exactly between two registered fonts, the smaller size takes precedence. %@AB@%f%@AE@% Fixed-spaced font. %@AB@%h%@AE@%%@AI@%y%@AE@% Character height, where %@AI@%y%@AE@% is the height in pixels. %@AB@%n%@AE@%%@AI@%x%@AE@% Font number %@AI@%x%@AE@%, where %@AI@%x%@AE@% is less than or equal to the value returned by %@AB@%%@AE@% %@AB@%_registerfonts%@AE@%. For example, the option %@AB@%%@AE@% %@AB@%n%@AE@%3 makes the third registered font current, if three or more fonts are registered. %@AB@%p%@AE@% Proportional-spaced font. %@AB@%r%@AE@% Raster-mapped (bit-mapped) font. %@AB@%t`%@AE@%%@AI@%fontname%@AE@%%@AB@%'%@AE@% Typeface of the font in single quotes. The %@AI@%fontname%@AE@% string is one of the following: courier modern helv script tms rmn roman Note the space in tms rmn. Additional font files use other names for %@AI@%fontname%@AE@%. Refer to the vendor's documentation for these names. %@AB@%v%@AE@% Vector-mapped font. %@AB@%w%@AE@%%@AI@%x%@AE@% Character width, where %@AI@%x%@AE@% is the width in pixels. Option codes are not case sensitive and can be listed in any order. You can separate codes with spaces or any other character that is not a valid option code. The %@AB@%_setfont%@AE@% function ignores all invalid codes. %@NL@% %@NL@% The %@AB@%_setfont%@AE@% function updates a data area with parameters of the current font. The data area is in the form of a structure, defined in GRAPH.H as follows: %@NL@% %@NL@% %@AS@% struct _fontinfo %@AS@% { %@AS@% int type; /* set = vector,clear = bit map */ %@AS@% int ascent; /* pix dist from top to base */ %@AS@% int pixwidth; /* character width in pixels */ %@AS@% int pixheight; /* character height in pixels */ %@AS@% int avgwidth; /* average character width */ %@AS@% char filename[81]; /* file name including path */ %@AS@% char faceName[32]; /* font name */ %@AS@% };%@AE@%%@NL@% %@NL@% If you want to retrieve the parameters of the current font, call the function %@AB@%_getfontinfo%@AE@%. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00100056 @%%@AB@%10.5.4 Displaying Text%@AE@%%@EH@%%@NL@% %@NL@% The last step, displaying text, consists of two parts. First you must select a screen position for the text with the graphics function %@AB@%_moveto%@AE@%. Then display fonted text at that position with the function %@AB@%_outgtext%@AE@%. The %@AB@%_moveto%@AE@% function takes pixel coordinates as arguments. The coordinates locate the top left of the first character in the text string. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00100057 @%%@AB@%10.5.5 A Sample Program%@AE@%%@EH@%%@NL@% %@NL@% The program SAMPLER.C displays sample text in all the available fonts, then exits when a key is pressed. Make sure the .FON files are in the current directory before running the program. %@NL@% %@NL@% %@AS@% /* SAMPLER.C: Displays sample text in various fonts. */ %@AS@% %@AS@% #include <stdio.h> %@AS@% #include <conio.h> %@AS@% #include <stdlib.h> %@AS@% #include <graph.h> %@AS@% #include <string.h> %@AS@% #define NFONTS 6 %@AS@% %@AS@% main() %@AS@% %@AS@% { %@AS@% static unsigned char *text[2*NFONTS] = %@AS@% { %@AS@% "COURIER", "courier", %@AS@% "HELV", "helv", %@AS@% "TMS RMN", "tms rmn", %@AS@% "MODERN", "modern", %@AS@% "SCRIPT", "script", %@AS@% "ROMAN", "roman" %@AS@% }; %@AS@% static unsigned char *face[NFONTS] = %@AS@% { %@AS@% "t'courier'", %@AS@% "t'helv'", %@AS@% "t'tms rmn'", %@AS@% "t'modern'", %@AS@% "t'script'", %@AS@% "t'roman'" %@AS@% };%@AE@%%@NL@% %@NL@% %@AS@% static unsigned char list[20]; %@AS@% struct videoconfig vc; %@AS@% int mode = _VRES16COLOR; %@AS@% register i;%@AE@%%@NL@% %@NL@% %@AS@% /* Read header info from all .FON files in %@AS@% * current directory %@AS@% */ %@AS@% %@AS@% if( _registerfonts( "*.FON" ) < 0 ) %@AS@% { %@AS@% _outtext( "Error: can't register fonts" ); %@AS@% exit( 0 ); %@AS@% } %@AS@% %@AS@% /* Set highest available video mode */ %@AS@% %@AS@% if( _setvideomode( _MAXRESMODE ) == 0 ) %@AS@% exit ( 0 ); %@AS@% %@AS@% /* Copy video configuration into structure vc */ %@AS@% %@AS@% _getvideoconfig( &vc ); %@AS@% %@AS@% /* Display six lines of sample text */ %@AS@% %@AS@% for( i = 0; i < NFONTS; i++ ) %@AS@% { %@AS@% strcpy( list, face[i] ); %@AS@% strcat( list, "h30w24b" ); %@AS@% %@AS@% if( _setfont( list ) >= 0 ) %@AS@% { %@AS@% _setcolor( i + 1 ); %@AS@% _moveto( 0, (i * vc.numypixels) / NFONTS ); %@AS@% _outgtext( text[i * 2] ); %@AS@% _moveto( vc.numxpixels / 2, %@AS@% (i * vc.numypixels) / NFONTS ); %@AS@% _outgtext( text[(i * 2) + 1] ); %@AS@% } %@AS@% else %@AS@% { %@AS@% _setvideomode( _DEFAULTMODE ); %@AS@% _outtext( "Error: can't set font" ); %@AS@% exit( 0 ); %@AS@% } %@AS@% }%@AE@%%@NL@% %@NL@% %@AS@% getch(); %@AS@% _setvideomode( _DEFAULTMODE ); %@AS@% %@AS@% /* Return memory when finished with fonts */ %@AS@% %@AS@% _unregisterfonts(); %@AS@% exit( 0 ); %@AS@% }%@AE@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00100058 @%%@AB@%10.5.6 Using Fonts Effectively%@AE@%%@EH@%%@NL@% %@NL@% Displaying fonts is simply another form of graphics; using fonts effectively requires little programming effort. Still, there are a few things to watch:%@CR:C6A00100059 @%%@CR:C6A00100060 @% %@NL@% %@NL@% %@NL@% ■ Remember that the video mode should be set only once. If you generate an image with presentation graphics and want to add text to it, do not reset the video mode prior to calling the font routines. Doing so will blank the screen, destroying the original image.%@NL@% %@NL@% ■ The %@AB@%_setfont%@AE@% function reads specified .FON files to obtain mapping data for the current font. Each call to %@AB@%_setfont%@AE@% causes a disk access and overwrites the old font data in memory. If you want to show text of different styles on the same screen, display all text of one font before moving on to the others. Minimizing the number of calls to %@AB@%_setfont%@AE@% saves time spent in disk I/O and memory reloads. %@NL@% %@NL@% ■ When your program finishes using the fonts library, you may want to free the memory occupied by the register list by calling %@AB@%_unregisterfonts%@AE@%. This function frees the memory allocated by %@AB@%_registerfonts%@AE@%. The register information for each type size of each font takes up approximately 140 bytes of memory. %@NL@% %@NL@% ■ Aesthetic suggestions for the printed page also apply to screen text. Typefaces are more effective when they do not compete with each other for attention. Restricting the number of styles per screen to one or two generally results in a more pleasing, less cluttered image.%@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@CR:C6A00110001 @%%@1@%%@AB@%Chapter 11 Creating Charts and Graphs%@AE@%%@EH@%%@NL@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@NL@% The low-level graphics functions described in Chapter 10, "Communicating with Graphics," draw points, lines, and shapes. Although it is possible to use them to generate charts and graphs, an additional set of high-level graphics functions is better suited to this task. %@NL@% %@NL@% "Presentation graphics" is a set of high-level functions that displays presentation-quality graphics. These functions transform numeric data into pie charts, bar and column charts, line graphs, and scatter diagrams. %@NL@% %@NL@% This chapter describes how to use presentation graphics. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00110002 @%%@AB@%11.1 Overview of Presentation Graphics%@AE@%%@EH@%%@NL@% %@NL@% The presentation graphics library PGCHART.LIB contains 22 functions. They are listed in Table 11.1 for convenient reference. %@NL@% %@NL@% %@AB@%Table 11.1 %@AB@%Presentation Graphics Function%@AE@%%@AE@% %@TH: 11 968 02 20 22 34 @%Primary Functions Secondary Functions%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%_pg_chart%@AE@% %@AB@%_pg_analyzechart%@AE@% %@AB@%_pg_hlabelchart%@AE@%%@AB@%_pg_chartms%@AE@% %@AB@%_pg_analyzechartms%@AE@% %@AB@%_pg_resetpalette%@AE@%%@AB@%_pg_chartpie%@AE@% %@AB@%_pg_analyzepie%@AE@% %@AB@%_pg_resetstyleset%@AE@%%@AB@%_pg_chartscatter%@AE@% %@AB@%_pg_analyzescatter%@AE@% %@AB@%_pg_setchardef%@AE@%%@AB@%_pg_chartscatterms%@AE@% %@AB@%_pg_analyzescatterms%@AE@% %@AB@%_pg_setpalette%@AE@%%@AB@%_pg_defaultchart%@AE@% %@AB@%_pg_getchardef%@AE@% %@AB@%_pg_setstyleset%@AE@%%@AB@%_pg_initchart%@AE@% %@AB@%_pg_getpalette%@AE@% %@AB@%_pg_vlabelchart%@AE@% %@AB@%_pg_getstyleset%@AE@%%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@TE: 11 968 02 20 22 34 @% %@AU@% The seven primary functions initialize variables and display selected chart %@AU@%types.%@AE@% %@NL@% %@NL@% In most cases, you will be using only seven "primary functions." These functions initialize variables and display selected chart types. The 15 "secondary functions" of presentation graphics do not directly display charts. Most of them retrieve or set data in the presentation graphics chart environment. %@NL@% %@NL@% Among the secondary functions are the "analysis functions," identified by the prefix %@AB@%_pg_analyze%@AE@%. These five functions calculate default values that pertain to a given chart type and data set. Calling an analysis function has the same effect as calling a corresponding primary function, except that the chart is not displayed. This allows you to pass on to the library the burden of calculating values. You can then make modifications to the resulting values and call a primary routine to display the chart. %@NL@% %@NL@% Use the %@AB@%_pg_hlabelchart%@AE@% and %@AB@%_pg_vlabelchart%@AE@% functions to display text that is not part of a title or axis label on your chart. These functions enable you to attach notes or other messages to your chart. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00110003 @%%@AB@%11.2 Parts of a Graph%@AE@%%@EH@%%@NL@% %@NL@% This section describes the terms used to refer to the different kinds of information that can be plotted. The various types of charts and graphs are also defined. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Data Series%@AE@%%@EH@%%@NL@% %@NL@% Data that are related by a common idea or purpose constitute a "series." For example, the prices of a futures commodity over the course of a year form a single series of data. The volume forms a second data series. %@NL@% %@NL@% When you include several series in one chart, characteristics such as color and pattern can help distinguish one from another. You can more readily differentiate series on a color monitor than you can on a monochrome monitor. The number of series that can appear on the same chart depends on the chart type and the number of available colors. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Categories%@AE@%%@EH@%%@NL@% %@NL@% "Categories" are nonnumeric data. A set of categories forms a frame of reference for the comparison of numeric data. For example, the months of the year are categories against which numeric data such as inches of rainfall can be plotted. %@NL@% %@NL@% Regional sales provide another example. A chart can compare a company's sales in different parts of the country. Each region forms a category. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Values%@AE@%%@EH@%%@NL@% %@NL@% "Values" are numeric data. Sales, stock prices, air temperatures, and populations are all series of values that can be plotted against categories or against other values. %@NL@% %@NL@% Presentation graphics allows you to overlay different series of value data on a single graph. For example, average monthly temperatures or monthly sales of heating oil during different years─or a combination of temperatures and sales─can be plotted together on the same graph. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Pie Charts%@AE@%%@EH@%%@NL@% %@NL@% "Pie charts" are used to represent data by showing the relationship of each part to the whole. A good example is a company's annual budget. A pie chart allows you to view each area of revenue or spending by its relative size within the context of the entire company budget. %@NL@% %@NL@% Presentation graphics can display either a standard or an "exploded" pie chart. The exploded view shows the pie with one or more pieces separated for emphasis. You can label each slice of a pie chart with a percentage figure if you wish. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Bar and Column Charts%@AE@%%@EH@%%@NL@% %@NL@% As the name implies, a "bar chart" shows data as horizontal bars. Bar charts show comparisons among items rather than absolute value. %@NL@% %@NL@% "Column charts" are vertical bar charts. Column charts are frequently used to show variations over a period of time, since they suggest time flow better than a bar chart. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Line Graphs%@AE@%%@EH@%%@NL@% %@NL@% "Line graphs" illustrate trends or changes in data. They show how a series of values varies against a particular category─for example, average temperatures throughout one year. %@NL@% %@NL@% Traditionally, line graphs show a collection of data points connected by lines. Presentation graphics can also plot points that are not connected by lines. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Scatter Diagrams%@AE@%%@EH@%%@NL@% %@NL@% A "scatter diagram" is the only type of graph available in presentation graphics that directly compares values with values. A scatter diagram simply plots points. %@NL@% %@NL@% Scatter diagrams illustrate the relationship between numeric values in different groups of data. They graphically show trends and correlations not easily detected from rows and columns of raw numbers. %@NL@% %@NL@% Scatter diagrams are most useful with large amounts of data. Consider, for example, the relationship between personal income and family size. If you poll one thousand wage earners for their income and family size, you have a scatter diagram with one thousand points. If you combine your results so that you are left with one average income for each family size, you have a line graph. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Axes%@AE@%%@EH@%%@NL@% %@NL@% All presentation graphics charts except pie charts are displayed with two perpendicular reference axes. The vertical, or %@AI@%y%@AE@%, axis runs from top to bottom of the chart and is placed against the left side of the screen. The horizontal, or %@AI@%x%@AE@%, axis runs from left to right across the bottom of the screen. %@NL@% %@NL@% %@AU@% The chart type determines the axis used for category data and the axis for %@AU@%value data.%@AE@% %@NL@% %@NL@% The %@AI@%x%@AE@% axis is the category axis for column and line charts and the value axis for bar charts. The %@AI@%y%@AE@% axis is the value axis for column and line charts and the category axis for bar charts. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Chart Windows%@AE@%%@EH@%%@NL@% %@NL@% The "chart window" defines that part of the screen on which the chart is drawn. By default, the window fills the entire screen, but presentation graphics allows you to resize the window for smaller graphs. By redefining the chart window to different screen locations, you can view separate graphs together on the same screen. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Data Windows%@AE@%%@EH@%%@NL@% %@NL@% While the chart window defines the entire graph including axes and labels, the "data window" defines only the actual plotting area. This is the portion of the graph to the right of the %@AI@%y%@AE@% axis and above the %@AI@%x%@AE@% axis. You cannot specify or adjust the size of the data window. Presentation graphics automatically determines its size based on the dimensions of the chart window. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Chart Styles%@AE@%%@EH@%%@NL@% %@NL@% Each of the five types of presentation graphics charts can appear in two different "chart styles," as described in Table 11.2. %@NL@% %@NL@% %@AB@%Table 11.2 %@AB@%Presentation Graphics Chart Styles%@AE@%%@AE@% %@TH: 8 488 02 12 20 44 @%Chart Type Chart Style #1 Chart Style #2%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%Pie With percentages Without percentagesBar Side-by-side StackedColumn Side-by-side StackedLine Points with lines Points onlyScatter Points with lines Points only%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@TE: 8 488 02 12 20 44 @% Bar and column charts have only one style when displaying a single series of data. The styles "side-by-side" and "stacked" are applicable when more than one series appears on the same chart. The first style arranges the bars or columns for the different series side by side, showing relative heights or lengths. The stacked style, illustrated for a column chart in Figure 11.3, emphasizes relative sizes between bars or columns. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Legends%@AE@%%@EH@%%@NL@% %@NL@% %@AU@% Legends help identify individual data series.%@AE@% %@NL@% %@NL@% When displaying more than one data series on a chart, presentation graphics uses different colors, line styles, or patterns to differentiate them. Presentation graphics also can display a "legend" that labels the different series of a chart. For a pie chart, the legend labels individual slices of the pie. %@NL@% %@NL@% A sample of the color and pattern used to graph the series appears next to the series label. This identifies the set of data to which the labels belong. %@NL@% %@NL@% You may change the font displayed by calling the %@AB@%_registerfonts%@AE@% and %@AB@%_setfont%@AE@% functions (see Section 10.5 for more information about using fonts). If you don't select a font, presentation graphics defaults to an internal font. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00110004 @%%@AB@%11.3 Writing a Presentation Graphics Program%@AE@%%@EH@%%@NL@% %@NL@% To write a C program that uses presentation graphics, follow these steps: %@NL@% %@NL@% %@NL@% 1. Include the required header files, GRAPH.H and PGCHART.H, as well as any other header files your program may need.%@NL@% %@NL@% 2. Set the video mode to a graphics mode. See Chapter 10, "Communicating with Graphics," for a description of video modes.%@NL@% %@NL@% 3. Initialize the presentation graphics chart environment. Presentation graphics places charting parameters in data structures. The amount of initialization that must be done by your program depends on how extensively it relies on the defaults.%@NL@% %@NL@% 4. Assemble the plot data. Data can be collected in a variety of ways: by calculating it elsewhere in the program, reading it from files, or entering it from the keyboard. All plot data must be assembled in arrays because the presentation graphics functions locate them through pointers.%@NL@% %@NL@% 5. Call presentation graphics functions to display the chart. Pause while the chart is on the screen.%@NL@% %@NL@% 6. Reset the video mode. When your program detects the signal to continue, it should reset the video to its original (default) mode.%@NL@% %@NL@% %@NL@% After compiling the program, link it to the library modules PGCHART.LIB and GRAPHICS.LIB. %@NL@% %@NL@% The sample programs in Sections 11.3.1-11.3.3 use 5 of the 22 presentation graphics functions: %@AB@%_pg_initchart%@AE@%, %@AB@%_pg_defaultchart%@AE@%, %@AB@%_pg_chartpie%@AE@%, %@AB@%_pg_chart%@AE@%, and %@AB@%_pg_chartscatter%@AE@%. Each program is commented so that you can recognize the steps given in this section. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00110005 @%%@AB@%11.3.1 Pie Chart%@AE@%%@EH@%%@NL@% %@NL@% The following program uses presentation graphics to display a pie chart for monthly sales of orange juice over a year. The chart, which is shown in Figure 11.1, remains on the screen until a key is pressed. %@NL@% %@NL@% %@AS@% /* PIE.C: Create sample pie chart. */ %@AS@% %@AS@% #include <conio.h> %@AS@% #include <string.h> %@AS@% #include <graph.h> %@AS@% #include <pgchart.h> %@AS@% %@AS@% #define MONTHS 12 %@AS@% %@AS@% typedef enum {FALSE, TRUE} boolean; %@AS@% %@AS@% float far value[MONTHS] = %@AS@% { %@AS@% 33.0, 27.0, 42.0, 64.0,106.0,157.0, %@AS@% 182.0,217.0,128.0, 62.0, 43.0, 36.0 %@AS@% }; %@AS@% char far *category[MONTHS] = %@AS@% { %@AS@% "Jan", "Feb", "Mar", "Apr", %@AS@% "May", "Jun", "Jly", "Aug", %@AS@% "Sep", "Oct", "Nov", "Dec" %@AS@% }; %@AS@% short far explode[MONTHS] = {0};%@AE@%%@NL@% %@NL@% %@AS@% main() %@AS@% { %@AS@% chartenv env; %@AS@% int mode = _VRES16COLOR;%@AE@%%@NL@% %@NL@% %@AS@% /* Set highest video mode available */ %@AS@% %@AS@% if( _setvideomode( _MAXRESMODE ) == 0 ) %@AS@% exit( 0 ); %@AS@% %@AS@% /* Initialize chart library and a default pie chart */ %@AS@% %@AS@% _pg_initchart(); %@AS@% _pg_defaultchart( &env, _PG_PIECHART, _PG_PERCENT ); %@AS@% %@AS@% /* Add titles and some chart options */ %@AS@% %@AS@% strcpy( env.maintitle.title, "Good Neighbor Grocery" ); %@AS@% env.maintitle.titlecolor = 6; %@AS@% env.maintitle.justify = _PG_RIGHT; %@AS@% strcpy( env.subtitle.title, "Orange Juice Sales" ); %@AS@% env.subtitle.titlecolor = 6; %@AS@% env.subtitle.justify = _PG_RIGHT; %@AS@% env.chartwindow.border = FALSE; %@AS@% %@AS@% /* Parameters for call to _pg_chartpie are: %@AS@% * %@AS@% * env - Environment variable %@AS@% * category - Category labels %@AS@% * value - Data to chart %@AS@% * explode - Separated pieces %@AS@% * MONTHS - Number of data values %@AS@% */ %@AS@% if( _pg_chartpie( &env, category, value, %@AS@% explode, MONTHS ) ) %@AS@% { %@AS@% _setvideomode( _DEFAULTMODE ); %@AS@% _outtext( "Error: can't draw chart" ); %@AS@% } %@AS@% else %@AS@% { %@AS@% getch(); %@AS@% _setvideomode( _DEFAULTMODE ); %@AS@% } %@AS@% return( 0 ); %@AS@% }%@AE@%%@NL@% %@NL@% %@AU@%(This figure may be found in the printed book.)%@AE@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00110006 @%%@AB@%11.3.2 Bar, Column, and Line Charts%@AE@%%@EH@%%@NL@% %@NL@% The code for the PIE.C program needs only minor alterations to produce bar, column, and line charts for the same data: %@NL@% %@NL@% %@NL@% ■ Replace the call to %@AB@%_pg_chartpie%@AE@% with %@AB@%_pg_chart%@AE@%. This function produces bar, column, and line charts depending on the value of the second argument for %@AB@%_pg_defaultchart%@AE@%.%@NL@% %@NL@% ■ Give new arguments to %@AB@%_pg_defaultchart%@AE@% that specify chart type and style.%@NL@% %@NL@% ■ Assign titles for the %@AI@%x%@AE@% axis and %@AI@%y%@AE@% axis in the structure %@AS@% env%@AE@%.%@NL@% %@NL@% ■ Remove references to array %@AS@% explode%@AE@%, which is applicable only to pie charts. %@AS@% %@AE@%%@NL@% %@NL@% %@NL@% The following example produces a bar chart for the store owner's data. The result is shown in Figure 11.2. %@NL@% %@NL@% %@AS@% /* BAR.C: Create sample bar chart. */ %@AS@% %@AS@% #include <conio.h> %@AS@% #include <string.h> %@AS@% #include <graph.h> %@AS@% #include <pgchart.h> %@AS@% %@AS@% #define MONTHS 12 %@AS@% %@AS@% typedef enum {FALSE, TRUE} boolean; %@AS@% %@AS@% float far value[MONTHS] = %@AS@% { %@AS@% 33.0, 27.0, 42.0, 64.0,106.0,157.0, %@AS@% 182.0,217.0,128.0, 62.0, 43.0, 36.0 %@AS@% }; %@AS@% char far *category[MONTHS] = %@AS@% { %@AS@% "Jan", "Feb", "Mar", "Apr", %@AS@% "May", "Jun", "Jly", "Aug", %@AS@% "Sep", "Oct", "Nov", "Dec" %@AS@% }; %@AS@% %@AS@% main() %@AS@% { %@AS@% chartenv env; %@AS@% int mode = _VRES16COLOR; %@AS@% %@AS@% /* Set highest video mode available */ %@AS@% %@AS@% if( _setvideomode( _MAXRESMODE ) == 0 ) %@AS@% exit( 0 ); %@AS@% %@AS@% /* Initialize chart library and a default bar chart */ %@AS@% _pg_initchart(); %@AS@% _pg_defaultchart( &env, _PG_BARCHART, _PG_PLAINBARS ); %@AS@% %@AS@% /* Add titles and some chart options */ %@AS@% %@AS@% strcpy( env.maintitle.title, "Good Neighbor Grocery" ); %@AS@% env.maintitle.titlecolor = 6; %@AS@% env.maintitle.justify = _PG_RIGHT; %@AS@% strcpy( env.subtitle.title, "Orange Juice Sales" ); %@AS@% env.subtitle.titlecolor = 6; %@AS@% env.subtitle.justify = _PG_RIGHT; %@AS@% strcpy( env.yaxis.axistitle.title, "Months" ); %@AS@% strcpy( env.xaxis.axistitle.title, "Quantity (cases)" ); %@AS@% env.chartwindow.border = FALSE;%@AE@%%@NL@% %@NL@% %@AS@% /* Parameters for call to _pg_chart are: %@AS@% * env - Environment variable %@AS@% * category - Category labels %@AS@% * value - Data to chart %@AS@% * MONTHS - Number of data values %@AS@% */ %@AS@% if( _pg_chart( &env, category, value, MONTHS ) ) %@AS@% { %@AS@% _setvideomode( _DEFAULTMODE ); %@AS@% _outtext( "Error: can't draw chart" ); %@AS@% } %@AS@% else %@AS@% { %@AS@% getch(); %@AS@% _setvideomode( _DEFAULTMODE ); %@AS@% } %@AS@% return( 0 ); %@AS@% }%@AE@%%@NL@% %@NL@% %@AU@%(This figure may be found in the printed book.)%@AE@%%@NL@% %@NL@% The grocer's bar chart becomes a column chart in two easy steps. Simply specify the new chart type when calling %@AB@%_pg_defaultchart%@AE@% and change the axis titles. To produce a column chart for the grocer's data, replace the call to %@AB@%_pg_defaultchart%@AE@% with %@NL@% %@NL@% %@AS@% _pg_defaultchart( &env, _PG_COLUMNCHART, _PG_PLAINBARS );%@AE@%%@NL@% %@NL@% Replace the last two calls to %@AB@%strcpy%@AE@% with %@NL@% %@NL@% %@AS@% strcpy( env.xaxis.axistitle.title, "Months" ); %@AS@% strcpy( env.yaxis.axistitle.title, "Quantity (cases)" );%@AE@%%@NL@% %@NL@% Note that now the %@AI@%x%@AE@% axis is labeled "Months" and the %@AI@%y %@AE@%axis is labeled "Quantity (cases)." Figure 11.3 shows the resulting column chart. %@NL@% %@NL@% %@AU@%(This figure may be found in the printed book.)%@AE@%%@NL@% %@NL@% Creating an equivalent line chart requires only one change. Use the same code as for the column chart and replace the call to %@AB@%_pg_defaultchart%@AE@% with %@NL@% %@NL@% %@AS@% _pg_defaultchart( &env, _PG_LINECHART, _PG_POINTANDLINE );%@AE@%%@NL@% %@NL@% Figure 11.4 shows the line chart for the grocer's data.%@NL@% %@NL@% %@AU@%(Please refer to the printed book.)%@AE@%%@NL@% %@NL@% %@AU@%(This figure may be found in the printed book.)%@AE@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00110007 @%%@AB@%11.3.3 Scatter Diagram%@AE@%%@EH@%%@NL@% %@NL@% The program SCATTER.C displays a scatter diagram that illustrates the relationship between the sales of orange juice and hot chocolate throughout a 12-month period. Figure 11.5 shows the results of SCATTER.C. Notice that the scatter points form a slightly curved line, indicating that a correlation exists between the sales of the two products. The demand for orange juice is roughly inverse to the demand for hot chocolate. %@NL@% %@NL@% %@AS@% /* SCATTER.C: Create sample scatter diagram. */ %@AS@% %@AS@% #include <conio.h> %@AS@% #include <string.h> %@AS@% #include <graph.h> %@AS@% #include <pgchart.h> %@AS@% %@AS@% #define MONTHS 12 %@AS@% %@AS@% typedef enum {FALSE, TRUE} boolean;%@AE@%%@NL@% %@NL@% %@AS@% /* Orange juice sales */ %@AS@% %@AS@% float far xvalue[MONTHS] = %@AS@% { %@AS@% 33.0, 27.0, 42.0, 64.0,106.0,157.0, %@AS@% 182.0,217.0,128.0, 62.0, 43.0, 36.0 %@AS@% }; %@AS@% %@AS@% /* Hot chocolate sales */ %@AS@% %@AS@% float far yvalue[MONTHS] = %@AS@% { %@AS@% 37.0, 37.0, 30.0, 19.0, 10.0, 5.0, %@AS@% 2.0, 1.0, 7.0, 15.0, 28.0, 39.0 %@AS@% }; %@AS@% %@AS@% main() %@AS@% { %@AS@% chartenv env; %@AS@% int mode = _VRES16COLOR; %@AS@% %@AS@% /* Set highest video mode available */ %@AS@% %@AS@% if( _setvideomode( _MAXRESMODE ) == 0 ) %@AS@% exit( 0 ); %@AS@% /* Initialize chart library and default %@AS@% * scatter diagram %@AS@% */ %@AS@% _pg_initchart(); %@AS@% _pg_defaultchart( &env, _PG_SCATTERCHART, %@AS@% _PG_POINTONLY ); %@AS@% %@AS@% /* Add titles and some chart options */ %@AS@% %@AS@% strcpy( env.maintitle.title, "Good Neighbor Grocery" ); %@AS@% env.maintitle.titlecolor = 6; %@AS@% env.maintitle.justify = _PG_RIGHT; %@AS@% strcpy( env.subtitle.title, %@AS@% "Orange Juice vs Hot Chocolate" ); %@AS@% env.subtitle.titlecolor = 6; %@AS@% env.subtitle.justify = _PG_RIGHT; %@AS@% env.yaxis.grid = TRUE; %@AS@% strcpy( env.xaxis.axistitle.title, %@AS@% "Orange Juice Sales" ); %@AS@% strcpy( env.yaxis.axistitle.title, %@AS@% "Hot Chocolate Sales" ); %@AS@% env.chartwindow.border = FALSE;%@AE@%%@NL@% %@NL@% %@AS@% /* Parameters for call to _pg_chartscatter are: %@AS@% * env - Environment variable %@AS@% * xvalue - X-axis data %@AS@% * yvalue - Y-axis data %@AS@% * MONTHS - Number of data values %@AS@% */ %@AS@% if( _pg_chartscatter( &env, xvalue, %@AS@% yvalue, MONTHS ) ) %@AS@% { %@AS@% _setvideomode( _DEFAULTMODE ); %@AS@% _outtext( "Error: can't draw chart" ); %@AS@% } %@AS@% else %@AS@% { %@AS@% getch(); %@AS@% _setvideomode( _DEFAULTMODE ); %@AS@% } %@AS@% return( 0 ); %@AS@% } %@AE@%%@NL@% %@NL@% %@AU@%(This figure may be found in the printed book.)%@AE@%%@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00110008 @%%@AB@%11.4 Manipulating Colors and Patterns%@AE@%%@EH@%%@NL@% %@NL@% Presentation graphics displays each data series in a way that makes it discernible from other series. It does this by defining a separate "palette" for every data series in a chart. Palettes consist of entries that determine color, line style, fill pattern, and point character used to graph the series. %@NL@% %@NL@% Presentation graphics maintains its palettes as an array of structures. The header file PGCHART.H defines the palette structures as shown below: %@NL@% %@NL@% %@AS@% /* Typedef for pattern bitmap */ %@AS@% typedef unsigned char fillmap[8]; %@AS@% %@AS@% /* Typedef for palette entry definition */ %@AS@% typedef struct %@AS@% { %@AS@% unsigned short color; %@AS@% unsigned short style; %@AS@% fillmap fill; %@AS@% char plotchar; %@AS@% } paletteentry; %@AS@% %@AS@% /* Typedef for palette definition */ %@AS@% typedef paletteentry palettetype[_PG_PALETTELEN];%@AE@%%@NL@% %@NL@% Do not confuse the presentation graphics palettes with the adapter display palettes, which are register values kept by the video controller. The function %@AB@%_selectpalette%@AE@% described in Chapter 10, "Communicating with Graphics," sets the display palette. It does not define the data series palettes used by presentation graphics. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00110009 @%%@AB@%11.4.1 Color Pool%@AE@%%@EH@%%@NL@% %@NL@% %@AU@% The color pool determines the colors of graphic elements (axes, labels, %@AU@%legends, titles).%@AE@% %@NL@% %@NL@% Presentation graphics organizes all chart colors into a "color pool." The color pool holds the color index values valid for the current graphics mode. (Refer to Chapter 10, "Communicating with Graphics," for more information about the color index.) Palette structures contain color codes that refer to the color pool. A palette's color index determines the colors used to graph the data series associated with the palette. The colors of labels, titles, legends, and axes are determined by the contents of the color pool. %@NL@% %@NL@% The first element of the color pool is always 0, which is the color index for the screen background color. The second element is always the highest color index available for the graphics mode. The remaining elements repeat the sequences of available pixel values, beginning with 1. %@NL@% %@NL@% As shown in the example in Section 11.4, the first member of a palette data structure is %@NL@% %@NL@% %@AS@% unsigned short color;%@AE@%%@NL@% %@NL@% This member defines the color index for the data series associated with the palette. %@NL@% %@NL@% An example should make this clearer. A graphics mode of %@AB@%_MRES4COLOR%@AE@% (320 by 200 pixels) provides four colors for display. Color index values from 0 to 3 determine the possible colors─say, black, green, red, and brown, respectively. The first eight elements of this color pool are shown below. %@NL@% %@NL@% %@TH: 11 550 02 18 13 45 @%Color Pool Index Color Index Color%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%0 0 Black1 3 Brown2 1 Green3 2 Red4 3 Brown5 1 Green6 2 Red7 3 Brown%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@TE: 11 550 02 18 13 45 @% Notice that the sequence of available foreground colors repeats from the third element. The first data series in this case would be plotted in brown, the second series in green, the third series in red, the fourth series again in brown, and so forth. %@NL@% %@NL@% Video adapters such as the EGA or the Hercules(R) InColor(tm) Card allow 16 on-screen colors. This allows presentation graphics to graph more series without duplicating colors. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00110010 @%%@AB@%11.4.2 Style Pool%@AE@%%@EH@%%@NL@% %@NL@% Presentation graphics matches the color pool with a collection of different line styles called the "style pool." Entries in the style pool define the appearance of lines such as axes and grids. Lines can be solid, dotted, dashed, or some combination of styles. %@NL@% %@NL@% The second member of a palette structure defines a style code as %@NL@% %@NL@% %@AS@% unsigned short style;%@AE@%%@NL@% %@NL@% Each palette contains a style code that refers to an entry in the style pool in the same way that it contains a color code that refers to an entry in the color pool. The style code value in a palette is applicable only to line graphs and lined scatter diagrams. The style code determines the appearance of the lines drawn between points. %@NL@% %@NL@% %@AU@% Use the different line styles in the style pool to differentiate series.%@AE@% %@NL@% %@NL@% The palette's style code adds further variety to the lines of a multiseries graph. It is most useful when the number of lines in a chart exceeds the number of available colors. For example, a graph of nine different data series must repeat colors if only three foreground colors are available for the display. However, the style code for each color repetition will be different, ensuring that none of the lines looks the same. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00110011 @%%@AB@%11.4.3 Pattern Pool%@AE@%%@EH@%%@NL@% %@NL@% Presentation graphics also maintains a pool of "fill patterns" that determine the fill design for column, bar, and pie charts. The third member of the palette structure holds the fill pattern. The pattern member is an array:%@CR:C6A00110012 @% %@NL@% %@NL@% %@AS@% fillmap fill;%@AE@%%@NL@% %@NL@% where %@AS@% fillmap %@AE@% is type-defined as %@NL@% %@NL@% %@AS@% typedef unsigned char fillmap[8];%@AE@%%@NL@% %@NL@% Each fill pattern array holds an 8-by-8 bit map that defines the fill pattern for the data series associated with the palette. Table 11.3 shows how a fill pattern of diagonal stripes is created with the %@AS@% fill %@AE@% pattern array. %@NL@% %@NL@% The bit map in Table 11.3 corresponds to screen pixels. Each of the eight layers of the map is a binary number, where a solid circle signifies 1 and an open circle signifies 0. Thus the first layer of the map─that is, the first byte─represents the binary number 10011001, which is the decimal number 153. %@NL@% %@NL@% %@AB@%Table %@AB@%11.3 Fill Patterns%@AE@%%@AE@% %@TH: 11 766 02 36 40 @%Bit Map Value in Fill%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% ∙ ∙ ∙ ∙ %@AS@%fill[0]%@AE@% = 153 ∙ ∙ ∙ ∙ %@AS@%fill[1]%@AE@% = 204∙ ∙ ∙ ∙ %@AS@%fill[2]%@AE@% = 102∙ ∙ ∙ ∙ %@AS@%fill[3]%@AE@% = 51 ∙ ∙ ∙ ∙ %@AS@%fill[4]%@AE@% = 153 ∙ ∙ ∙ ∙ %@AS@%fill[5]%@AE@% = 204∙ ∙ ∙ ∙ %@AS@%fill[6]%@AE@% = 102∙ ∙ ∙ ∙ %@AS@%fill[7]%@AE@% = 51%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@TE: 11 766 02 36 40 @% For example, if you want to create the pattern in Table 11.3 for your chart's first data series, you must reset the %@AS@% fill%@AE@%%@AB@% %@AE@%array for the first palette structure. You can do this in five steps:%@CR:C6A00110013 @% %@NL@% %@NL@% %@NL@% 1. Declare a structure of type %@AB@%palettetype%@AE@% to hold the palette parameters.%@NL@% %@NL@% 2. Call %@AB@%_pg_initchart%@AE@% to initialize the palettes with default values.%@NL@% %@NL@% 3. Call the presentation graphics function %@AB@%_pg_getpalette%@AE@% to retrieve a copy of the current palette data.%@NL@% %@NL@% 4. Assign the values given in Table 11.3 to the array %@AS@% fill %@AE@% for the first palette.%@NL@% %@NL@% 5. Call the presentation graphics function %@AB@%_pg_setpalette%@AE@% to load the modified palette values.%@NL@% %@NL@% %@NL@% The following lines of code demonstrate these five steps: %@NL@% %@NL@% %@AS@% /* Declare a structure array for palette data. */ %@AS@% %@AS@% palettetype palette_struct; %@AS@% . %@AS@% . %@AS@% . %@AS@% /* Initialize chart library */ %@AS@% %@AS@% _pg_initchart(); %@AS@% . %@AS@% . %@AS@% . %@AS@% /* Copy current palette data into palette_struct */ %@AS@% %@AS@% _pg_getpalette( palette_struct ); %@AS@% %@AS@% /* Reinitialize fill pattern for first palette using %@AS@% values in Table .3 */ %@AS@% %@AS@% palette_struct[1].fill[0] = 153; %@AS@% palette_struct[1].fill[1] = 204; %@AS@% palette_struct[1].fill[2] = 102; %@AS@% palette_struct[1].fill[3] = 51; %@AS@% palette_struct[1].fill[4] = 153; %@AS@% palette_struct[1].fill[5] = 204; %@AS@% palette_struct[1].fill[6] = 102; %@AS@% palette_struct[1].fill[7] = 51; %@AS@% %@AS@% /* Load new palette data */ %@AS@% %@AS@% _pg_setpalette( palette_struct );%@AE@%%@NL@% %@NL@% Now when you display your bar or column chart, the first series appears filled with the striped pattern shown in Table 11.3. %@NL@% %@NL@% Palette structures are used differently with pie charts. Instead of clarifying multiple series, fill patterns, line styles, and colors, palette structures are used to distinguish individual slices in a pie chart. Palettes are recycled if the number of slices exceeds %@AB@%_PG_PALETTELEN%@AE@%. Thus, the first palette dictates not only the appearance of the first slice, but of slice number %@AB@%_PG_PALETTELEN%@AE@% as well. The second palette determines the appearance of both the second slice and of slice number %@AB@%_PG_PALETTELEN%@AE@% + 1, and so forth.%@CR:C6A00110014 @% %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00110015 @%%@AB@%11.4.4 Character Pool%@AE@%%@EH@%%@NL@% %@NL@% The last member of a palette structure is an index number in a pool of ASCII characters: %@NL@% %@NL@% %@AS@% char plotchar;%@AE@%%@NL@% %@NL@% The member %@AB@%plotchar%@AE@% represents plot points on line graphs and scatter diagrams. Each palette uses a different character to distinguish plot points between data series. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00110016 @%%@AB@%11.5 Customizing the Chart Environment%@AE@%%@EH@%%@NL@% %@NL@% The presentation graphics functions are designed to be flexible. You can use the system of default values to produce professional-looking charts with a minimum of programming effort. Or you can fine-tune the appearance of your charts by overriding default values and initializing variables explicitly in your program. %@NL@% %@NL@% The header file PGCHART.H defines a structure type %@AB@%chartenv%@AE@%, which organizes the chart environment variables. The chart environment describes everything about a chart except the plots themselves. It is the blank page, in other words, ready for plotting data. The environment determines the appearance of text, axes, grid lines, and legends. %@NL@% %@NL@% Colors and line styles in the chart environment are taken from palettes. In this way, the appearance of titles and axis lines matches the colors and line styles of plotted data series. %@NL@% %@NL@% %@AU@% You can reset any variable in the environment.%@AE@% %@NL@% %@NL@% Calling the %@AB@%_pg_defaultchart%@AE@% function fills the chart environment with default values. Presentation graphics allows you to reset any variable in the environment before displaying a chart. Except for adjusting the palette values, all initialization of data is done through a %@AB@%chartenv%@AE@% type structure. %@NL@% %@NL@% The sample chart programs provided in Section 11.3, "Writing a Presentation Graphics Program," illustrate how to adjust variables in the chart environment. These programs create a structure %@AS@% env %@AE@% of type %@AB@%chartenv%@AE@%. The structure %@AS@% env %@AE@% contains the chart environment variables, initialized by the call to the %@AB@%_pg_defaultchart%@AE@% function. Environment variables such as the chart title are then given specific values, as in %@NL@% %@NL@% %@AS@% strcpy( env.maintitle.title, "Good Neighbor Grocery" );%@AE@%%@NL@% %@NL@% Environment variables that determine colors and line styles deserve special mention. The chart environment holds several such variables, which can be recognized by their names. For example, the variable %@AB@%titlecolor%@AE@% specifies the color of title text. Similarly, the variable %@AB@%gridstyle%@AE@% specifies the line style used to draw the chart grid. %@NL@% %@NL@% These variables are index numbers, but do not refer directly to the color pool or line pool. They correspond instead to palette numbers. If you set %@AB@%titlecolor%@AE@% to 2, presentation graphics uses the color code in the second palette to determine the title's color. Thus, the title in this case would be the same color as the chart's second data series. If you change the color code in the palette, you'll also change the title's color. %@NL@% %@NL@% A structure of type %@AB@%chartenv%@AE@% consists of four types of secondary structures. The file PGCHART.H type-defines these secondary structures: %@AB@%titletype%@AE@%, %@AB@%axistype%@AE@%, %@AB@%windowtype%@AE@%, and %@AB@%legendtype%@AE@%. %@NL@% %@NL@% The remainder of this section describes the chart environment of presentation graphics. It first examines structures of the four secondary structures that make up the chart environment structure. The section concludes with a description of the %@AB@%chartenv%@AE@% structure type. Each section begins with a brief explanation of the structure's purpose, followed by a listing of the structure type definition as it appears in the PGCHART.H file. All symbolic constants are defined in the file PGCHART.H. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00110017 @%%@AB@%11.5.1 titletype Structures%@AE@%%@EH@%%@NL@% %@NL@% Structures of type %@AB@%titletype%@AE@% determine text, color, and placement of titles appearing in the graph. The PGCHART.H file defines the structure type as %@NL@% %@NL@% %@AS@% typedef struct %@AS@% { %@AS@% char title[_PG_TITLELEN]; /* Title text */ %@AS@% short titlecolor; /* Palette color %@AS@% for title text */ %@AS@% short justify; /* _PG_LEFT, _PG_CENTER, %@AS@% _PG_RIGHT */ %@AS@% } titletype;%@AE@%%@NL@% %@NL@% The following list describes %@AB@%titletype%@AE@% members: %@NL@% %@NL@% %@AB@%Member Variable%@AE@% %@AB@%Description%@AE@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@AI@%justify%@AE@% An integer specifying how the title is justified within the chart window. The symbolic constants defined in PGCHART.H for this variable are %@AB@%%@AE@% %@AB@%_PG_LEFT%@AE@%,%@AB@%%@AE@% %@AB@%_PG_CENTER%@AE@%, and %@AB@%_PG_RIGHT%@AE@%. %@AI@%titlecolor%@AE@% An integer between 1 and %@AB@%_PG_PALETTELEN%@AE@% that specifies a title's color. The default value for%@AI@%%@AE@% %@AI@%titlecolor%@AE@% is 1. %@AI@%title%@AE@%%@AB@%[_PG_TITLELEN]%@AE@% A character array containing title text. For example, if %@AS@% env %@AE@% is a structure of type%@AB@% chartenv%@AE@%, then %@AS@% env.maintitle.title%@AE@% %@AS@%%@AE@% holds the character string used for the main title of the chart. Similarly, %@AS@%%@AE@% %@AS@%env.xaxis.axistitle.title %@AE@% contains the %@AI@%%@AE@% %@AI@%x%@AE@% axis title. The number of characters in a title must be one less than %@AB@%%@AE@% %@AB@%_PG_TITLELEN%@AE@% to allow room for a null terminator. %@NL@% %@3@%%@CR:C6A00110018 @%%@AB@%11.5.2 axistype Structures%@AE@%%@EH@%%@NL@% %@NL@% Structures of type %@AB@%axistype%@AE@% contain variables for the axes such as color, scale, grid style, and tick marks. The PGCHART.H file defines the structure type as the following: %@NL@% %@NL@% %@AS@% typedef struct %@AS@% { %@AS@% short grid; /* TRUE=grid lines drawn; %@AS@% FALSE=no lines */ %@AS@% short gridstyle; /* Style bytes for grid */ %@AS@% titletype axistitle; /* Title definition %@AS@% for axis */ %@AS@% short axiscolor; /* Color for axis */ %@AS@% short labeled; /* TRUE=ticks marks and titles %@AS@% drawn */ %@AS@% short rangetype; /* _PG_LINEARAXIS, %@AS@% _PG_LOGAXIS */ %@AS@% float logbase; /* Base used if log axis */ %@AS@% short autoscale; /* TRUE=next 7 values %@AS@% calculated by system */ %@AS@% float scalemin; /* Minimum value of scale */ %@AS@% float scalemax; /* Maximum value of scale */ %@AS@% float scalefactor; /* Scale factor for data on %@AS@% this axis */ %@AS@% titletype scaletitle; /* Title definition for %@AS@% scaling factor */ %@AS@% float ticinterval; /* Distance between tick marks %@AS@% (world coord.) */ %@AS@% short ticformat; /* _PG_EXPFORMAT or %@AS@% _PG_DECFORMAT */ %@AS@% short ticdecimals; /* Number of decimals for tick %@AS@% labels (max=9) */ %@AS@% } axistype;%@AE@%%@NL@% %@NL@% The following list describes %@AB@%axistype%@AE@% member variables: %@NL@% %@NL@% %@AB@%Member Variable%@AE@% %@AB@%Description%@AE@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@AI@%autoscale%@AE@% A Boolean variable. If %@AI@%autoscale%@AE@% is set to %@AB@%TRUE%@AE@%, presentation graphics automatically determines values for %@AI@%scalefactor%@AE@%, %@AI@%scalemax%@AE@%, %@AI@%%@AE@% %@AI@%scalemin%@AE@%, %@AI@%%@AE@% %@AI@%scaletitle%@AE@%, %@AI@%ticdecimals%@AE@%, %@AI@%ticformat%@AE@%, and %@AI@%%@AE@% %@AI@%ticinterval%@AE@% (see below). If %@AI@%autoscale%@AE@% equals %@AB@%FALSE%@AE@%, these seven variables must be specified in your program. %@AI@%axiscolor%@AE@% An integer between 1 and %@AB@%_PG_PALETTELEN%@AE@% that specifies the color used for the axis and parallel grid lines. (See description for %@AI@%gridstyle%@AE@% below.) Note that this member does not determine the color of the axis title. That selection is made through the%@AB@%%@AE@% %@AB@%axistitle%@AE@% structure. %@AI@%axistitle%@AE@% A %@AB@%titletype%@AE@% structure that defines the title of the associated axis. The title of the %@AI@%y%@AE@% axis displays vertically to the left of the %@AI@%y%@AE@% axis, and the title of the %@AI@%x%@AE@% axis displays horizontally below the %@AI@%x%@AE@% axis. %@AI@%grid%@AE@% A Boolean true/false value that determines whether grid lines are drawn for the associated axis. Grid lines span the data window perpendicular to the axis. %@AI@%gridstyle%@AE@% An integer between 1 and %@AB@%_PG_PALETTELEN%@AE@% that specifies the grid's line style. Lines can be solid, dashed, dotted, or some combination. The default value for %@AI@%%@AE@% %@AI@%gridstyle%@AE@% is 1. Note that the color of the parallel axis determines the color of the grid lines. Thus, the %@AI@%x%@AE@% axis grid is the same color as the %@AI@%y%@AE@% axis, and the %@AI@%y%@AE@% axis grid is the same color as the %@AI@%x%@AE@% axis. %@AI@%labeled%@AE@% A Boolean value that determines whether tick marks and labels are drawn on the axis. Axis labels should not be confused with axis titles. Axis labels are numbers or descriptions such as "23.2" or "January" attached to each tick mark. %@AI@%logbase%@AE@% If%@AI@% rangetype%@AE@% is logarithmic, the %@AI@%logbase%@AE@% variable determines the log base used to scale the axis. The default value is 10. %@AI@%rangetype%@AE@% An integer that determines whether the scale of the axis is linear or logarithmic. The variable %@AI@%rangetype%@AE@% applies only to value data. Specify a linear scale with %@AB@%%@AE@% %@AB@%_PG_LINEARAXIS%@AE@%. A linear scale is best when the difference between axis minimum and maximum is relatively small. For example, a linear axis range 0 - 10 results in 10 tick marks evenly spaced along the axis. Use %@AB@%_PG_LOGAXIS%@AE@% to specify a logarithmic %@AI@%rangetype%@AE@%. Logarithmic scales are useful when the range is very large or when the data varies exponentially. Line graphs of exponentially varying data can be made straight with a logarithmic%@AI@%%@AE@% %@AI@%rangetype%@AE@%. %@AI@%scalefactor%@AE@% All numeric data are scaled by dividing each value by %@AI@%scalefactor%@AE@%. For relatively small values,%@AI@%%@AE@% %@AI@%scalefactor%@AE@% should be 1, which is the default. But data with large values should be scaled by an appropriate factor. For example, data in the range 2 million - 20 million should be plotted with%@AI@%%@AE@% %@AI@%scalemin%@AE@% set to 2, %@AI@%scalemax%@AE@% set to 20, and%@AI@%%@AE@% %@AI@%scalefactor%@AE@% set to 1 million. If %@AI@%autoscale%@AE@% is set to %@AB@%TRUE%@AE@%, presentation graphics automatically determines a suitable value for%@AI@%%@AE@% %@AI@%scalefactor%@AE@% based on the range of data to be plotted. Presentation graphics selects only values that are a factor of 1 thousand─that is, values such as 1 thousand, 1 million, or 1 billion. It then labels the%@AI@%%@AE@% %@AI@%scaletitle%@AE@% appropriately (see below). If you desire some other value for scaling, you must set %@AI@%autoscale%@AE@% to %@AB@%FALSE%@AE@% and set %@AI@%%@AE@% %@AI@%scalefactor%@AE@% to the desired scaling value. %@AI@%scalemax%@AE@% Highest value represented by the axis. %@AI@%scalemin%@AE@% Lowest value represented by the axis. %@AI@%scaletitle%@AE@% A %@AB@%titletype%@AE@% structure defining a string of text that describes the value of %@AI@%scalefactor%@AE@%. If %@AI@%%@AE@% %@AI@%autoscale%@AE@% is %@AB@%TRUE%@AE@%, presentation graphics automatically writes a scale description to %@AI@%scaletitle%@AE@%. If%@AI@% autoscale%@AE@% equals %@AB@%FALSE%@AE@% and %@AI@%scalefactor%@AE@% is 1, %@AI@%scaletitle.title%@AE@% should be blank. Otherwise your program should copy an appropriate scale description to %@AI@%scaletitle.title%@AE@%, such as "( x 1000)," "(in millions of units)," or "times 10 thousand dollars." For the %@AI@%y%@AE@% axis, the %@AI@%scaletitle%@AE@% text displays vertically between the axis title and the %@AI@%y%@AE@% axis. For the %@AI@%x%@AE@% axis, the scale title appears below the %@AI@%x%@AE@% axis title. %@AI@%ticdecimals %@AE@% Number of digits to display after the decimal point in tick labels. Maximum value is 9. (This variable applies only to axes with value data and is ignored for the category axis.) %@AI@%ticformat%@AE@% An integer that determines format of the labels assigned to each tick mark. Set %@AI@%%@AE@% %@AI@%ticformat%@AE@% to%@AB@%%@AE@% %@AB@%_PG_EXPFORMAT%@AE@% for exponential format or to %@AB@%_PG_DECFORMAT%@AE@% for decimal. The default is %@AB@%_PG_DECFORMAT%@AE@%. (This variable applies only to axes with value data and is ignored for the category axis.) %@AI@%ticinterval%@AE@% Sets interval between tick marks on the axis. The tick interval is measured in the same units as the numeric data associated with the axis. For example, if 2 sequential tick marks correspond to the values 20 and 25, the tick interval between them is 5. (This variable applies only to axes with value data and is ignored for the category axis.) %@NL@% %@3@%%@CR:C6A00110019 @%%@AB@%11.5.3 windowtype Structures%@AE@%%@EH@%%@NL@% %@NL@% Structures of type %@AB@%windowtype%@AE@% contain sizes, locations, and color codes for the three windows produced by presentation graphics: the chart window, the data window, and the legend. Windows are located on the screen relative to the screen's logical origin. By changing the logical origin, you can display charts that are partly or completely off the screen. %@NL@% %@NL@% The PGCHART.H file defines %@AB@%windowtype%@AE@% as the following: %@NL@% %@NL@% %@AS@% typedef struct %@AS@% { %@AS@% short x1; /* Left edge of window in %@AS@% pixels */ %@AS@% short y1; /* Top edge of window in %@AS@% pixels */ %@AS@% short x2; /* Right edge of window in %@AS@% pixels */ %@AS@% short y2; /* Bottom edge of window in %@AS@% pixels */ %@AS@% short border; /* TRUE for border, FALSE %@AS@% otherwise */ %@AS@% short background; /* Internal palette color for %@AS@% window background */ %@AS@% short borderstyle; /* Style bytes for window %@AS@% border */ %@AS@% short bordercolor; /* Internal palette color for %@AS@% window border */ %@AS@% } windowtype;%@AE@%%@NL@% %@NL@% The following list describes %@AB@%windowtype%@AE@% member variables: %@NL@% %@NL@% %@AB@%Member Variable%@AE@% %@AB@%Description%@AE@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@AI@%background%@AE@% An integer between 1 and %@AB@%_PG_PALETTELEN%@AE@% that specifies the window's background color. The default value for %@AI@%background%@AE@% is 1. %@AI@%border%@AE@% A Boolean variable that determines whether a border frame is drawn around a window. %@AI@%bordercolor%@AE@% An integer between 1 and %@AB@%_PG_PALETTELEN%@AE@% that specifies the color of the window's border frame. The default value is 1. %@AI@%borderstyle%@AE@% An integer between 1 and %@AB@%_PG_PALETTELEN%@AE@% that specifies the line style of the window's border frame. The default value is 1. %@AI@%x1, y1, x2, y2%@AE@% Window coordinates in pixels. The ordered pair (%@AI@%x1%@AE@%, %@AI@%y1%@AE@%) specifies the coordinate of the upper left corner of the window. The ordered pair ( %@AI@%x2%@AE@%, %@AI@%y2%@AE@% ) specifies the coordinate of the lower right corner. The reference point for the coordinates depends on the type of window. The chart window is located relative to the logical origin, usually the upper left corner of the screen. The data and legend windows are located relative to the upper left corner of the chart window. This allows you to change the position of the chart window without having to redefine coordinates for the other two windows. %@NL@% %@3@%%@CR:C6A00110020 @%%@AB@%11.5.4 legendtype Structures%@AE@%%@EH@%%@NL@% %@NL@% Structures of type %@AB@%legendtype%@AE@% contain size, location, and colors of the chart legend. The PGCHART.H file defines the structure type as the following: %@NL@% %@NL@% %@AS@% typedef struct %@AS@% { %@AS@% short legend; /* TRUE=draw legend; %@AS@% FALSE=no legend */ %@AS@% short place; /* _PG_RIGHT, _PG_BOTTOM, %@AS@% _PG_OVERLAY */ %@AS@% short textcolor; /* Palette color for text*/ %@AS@% short autosize; /* TRUE=system calculates %@AS@% legend size */ %@AS@% windowtype legendwindow; /* Window definition for %@AS@% legend */ %@AS@% } legendtype;%@AE@%%@NL@% %@NL@% The following list describes %@AB@%legendtype%@AE@% member variables: %@NL@% %@NL@% %@AB@%Member Variable%@AE@% %@AB@%Description%@AE@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@AI@%autosize%@AE@% A Boolean true/false variable that determines whether presentation graphics is to automatically calculate the size of the legend. If %@AI@%%@AE@% %@AI@%autosize%@AE@% equals %@AB@%FALSE%@AE@%, the legend window must be specified in the %@AI@%legendwindow%@AE@% structure (see below). %@AI@%legend%@AE@% A Boolean true/false variable that determines whether a legend is to appear on the chart. The %@AI@%legend%@AE@% variable is ignored by functions that graph single-series charts. %@AI@%legendwindow%@AE@% A %@AB@%windowtype%@AE@% structure that defines coordinates, background color, and border frame for the legend. Coordinates given in %@AI@%legendwindow%@AE@% are ignored if %@AI@%%@AE@% %@AI@%autosize%@AE@% is set to %@AB@%TRUE%@AE@%. %@AI@%place%@AE@% An integer that specifies the location of the legend relative to the data window. Setting %@AI@%place%@AE@% equal to the constant %@AB@%_PG_RIGHT%@AE@% positions the legend to the right of the data window. Setting %@AI@%place%@AE@% to%@AB@%%@AE@% %@AB@%_PG_BOTTOM%@AE@% positions the legend below the data window. Setting %@AI@%place%@AE@% to %@AB@%%@AE@% %@AB@%_PG_OVERLAY%@AE@% positions the legend within the data window. These settings influence the size of the data window. If %@AI@%place%@AE@% equals %@AB@%_PG_RIGHT%@AE@% or %@AB@%_PG_BOTTOM%@AE@%, presentation graphics automatically sizes the data window to accommodate the legend. If %@AI@%place%@AE@% equals %@AB@%%@AE@% %@AB@%_PG_OVERLAY%@AE@%, the data window is sized without regard to the legend. %@AI@%textcolor%@AE@% An integer between 1 and %@AB@%_PG_PALETTELEN%@AE@% that specifies the color of text within the legend window. %@NL@% %@3@%%@CR:C6A00110021 @%%@AB@%11.5.5 chartenv Structures%@AE@%%@EH@%%@NL@% %@NL@% A structure of type%@AB@% chartenv%@AE@% defines the chart environment. The following listing shows that a %@AB@%chartenv%@AE@% type structure consists almost entirely of structures of the four types described above. %@NL@% %@NL@% The PGCHART.H file defines the %@AB@%chartenv%@AE@% structure type as the following: %@NL@% %@NL@% %@AS@% typedef struct %@AS@% { %@AS@% short charttype; /* Chart type */ %@AS@% short chartstyle; /* Chart style */ %@AS@% windowtype chartwindow; /* Window definition for %@AS@% overall chart */ %@AS@% windowtype datawindow; /* Window definition for data %@AS@% part of chart */ %@AS@% titletype maintitle; /* Main chart title */ %@AS@% titletype subtitle; /* Chart subtitle */ %@AS@% axistype xaxis; /* Definition for x axis */ %@AS@% axistype yaxis; /* Definition for y axis */ %@AS@% legendtype legend; /* Definition for legend */ %@AS@% } chartenv;%@AE@%%@NL@% %@NL@% %@AU@% Initialize the chart environment with the _pg_defaultchart function.%@AE@% %@NL@% %@NL@% The data in a %@AB@%chartenv%@AE@% type structure is initialized by calling the function%@AB@% %@AB@%_pg_defaultchart%@AE@%. If your program does not call %@AB@%_pg_defaultchart%@AE@%, it must explicitly define every variable in the chart environment─a tedious procedure. The recommended method for adjusting the appearance of your chart is to initialize variables for the proper chart type by calling the %@AB@%_pg_defaultchart%@AE@% function, and then to reassign selected environment variables such as titles. %@NL@% %@NL@% The following list describes %@AB@%chartenv%@AE@% member variables: %@NL@% %@NL@% %@AB@%Member Variable%@AE@% %@AB@%Description%@AE@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@AI@%chartstyle%@AE@% An integer that determines the style of the chart (see Table 11.2). Legal values for %@AI@%%@AE@% %@AI@%chartstyle%@AE@% are %@AB@%_PG_PERCENT%@AE@% and %@AB@%%@AE@% %@AB@%_PG_NOPERCENT%@AE@% for pie charts; %@AB@%%@AE@% %@AB@%_PG_PLAINBARS%@AE@% and %@AB@%_PG_STACKEDBARS%@AE@% for bar and column charts; and %@AB@%_PG_POINTONLY%@AE@% and %@AB@%_PG_POINTANDLINE%@AE@% for line graphs and scatter diagrams. This variable corresponds to the third argument for the %@AB@%_pg_defaultchart%@AE@% function. %@AI@%charttype%@AE@% An integer that determines the type of chart displayed. The value of %@AI@%charttype%@AE@% is %@AB@%_PG_BARCHART%@AE@%, %@AB@%_PG_COLUMNCHART%@AE@%, %@AB@%%@AE@% %@AB@%_PG_LINECHART%@AE@%, %@AB@%_PG_SCATTERCHART%@AE@%, or %@AB@%%@AE@% %@AB@%_PG_PIECHART%@AE@%. This variable corresponds to the second argument for the %@AB@%%@AE@% %@AB@%_pg_defaultchart%@AE@% function. %@AI@%chartwindow%@AE@% A %@AB@%windowtype%@AE@% structure that defines the appearance of the chart window. %@AI@%datawindow%@AE@% A %@AB@%windowtype%@AE@% structure that defines the appearance of the data window. %@AI@%legend%@AE@% A %@AB@%legendtype%@AE@% structure that defines the appearance of the legend window. %@AI@%maintitle%@AE@% A %@AB@%titletype%@AE@% structure that defines the appearance of the main title of the chart. %@AI@%subtitle%@AE@% A %@AB@%titletype%@AE@% structure that defines the appearance of the chart's subtitle. %@AI@%xaxis%@AE@% An %@AB@%axistype%@AE@% structure that defines the appearance of the %@AI@%x%@AE@% axis. (This variable is not applicable for pie charts.) %@AI@%yaxis%@AE@% An %@AB@%axistype%@AE@% structure that defines the appearance of the %@AI@%y%@AE@% axis. (This variable is not applicable for pie charts.) %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@CR:C6A00120001 @%%@1@%%@AB@%Chapter 12 Programming with Mixed Languages%@AE@%%@EH@%%@NL@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@NL@% There are times when your Microsoft C programs need to call programs written in other languages or when programs written in other languages need to call your C functions. This is called mixed-language programming. For example, when a particular subprogram is available commercially in a language other than C or when algorithms are described more naturally in a different language, you need to use more than one language. %@NL@% %@NL@% This chapter describes the elements of mixed-language programming─how to make calls from programs written in one language to routines written in another. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00120002 @%%@AB@%12.1 Making Mixed-Language Calls%@AE@%%@EH@%%@NL@% %@NL@% Mixed-language programming always involves a call to a function, procedure, or subroutine. For example, a BASIC main module may need to execute a specific task that you would like to program separately. Instead of calling a BASIC subprogram, however, you decide to call a C function. %@NL@% %@NL@% Mixed-language calls involve calling functions in separate modules. Instead of compiling all of your source modules with the same compiler, you use different compilers. In the instance mentioned above, you would compile the mainmodule source file with the BASIC compiler, another source file (written in C) with the C compiler, and then link the two object files. %@NL@% %@NL@% Figure 12.1 illustrates how the syntax of a mixed-language call works, using the instance mentioned above. %@NL@% %@NL@% %@AU@%(This figure may be found in the printed book.)%@AE@%%@NL@% %@NL@% In Figure 12.1, the BASIC call to C is %@AS@% CALL Prn%@AE@%, similar to a call to a BASIC subprogram. There are two differences between this mixed-language call and a call between two BASIC modules: %@NL@% %@NL@% %@NL@% 1. The subprogram %@AS@% Prn %@AE@% is implemented in C, using standard C syntax.%@NL@% %@NL@% 2. The implementation of the call in BASIC is affected by the %@AB@%DECLARE%@AE@% statement, which uses the %@AB@%CDECL%@AE@% keyword to create compatibility with C. The %@AB@%DECLARE%@AE@% statement (which is described in detail in the %@AI@%Microsoft BASIC Language Reference%@AE@% and the %@AI@%Microsoft BASIC %@AI@% Programmer's Guide%@AE@%) is an example of a mixed-language "interface" statement. These interface statements override default naming and calling conventions. Each language provides its own form of interface.%@NL@% %@NL@% %@NL@% You can make mixed-language calls to routines regardless of whether they have return values. (In this chapter, "routine" refers to any function, procedure, or subroutine that can be called from another module.) %@NL@% %@NL@% Table 12.1 shows the correspondence between calls to routines in different languages. %@NL@% %@NL@% %@AB@%Table 12.1 %@AB@%Language Equivalents for Routine Calls%@AE@%%@AE@% %@TH: 8 553 02 20 21 35 @%Language Return Value No Return Value%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%Assembly Language Procedure ProcedureBASIC FUNCTION procedure SubprogramC function (%@AB@%void%@AE@%) functionFORTRAN FUNCTION SUBROUTINEPascal Function Procedure%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@TE: 8 553 02 20 21 35 @% For example, a C module can make a subprogram call to a FORTRAN subroutine. You can prototype a FORTRAN subroutine as a function with a %@AB@% void%@AE@% type. %@NL@% %@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% NOTE %@AI@%BASIC %@AI@%DEF FN%@AE@%%@AI@% functions and GOSUB%@AE@%%@AI@% subroutines cannot be called from another %@AI@%language.%@AE@%%@AE@%%@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@%%@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00120003 @%%@AB@%12.2 Language Convention Requirements%@AE@%%@EH@%%@NL@% %@NL@% To mix languages, the calling program must observe the same conventions as the called program. The conventions described in this section govern the following: %@NL@% %@NL@% %@NL@% ■ How compilers treat identifiers, including function and variable names (naming convention)%@NL@% %@NL@% ■ How the subprogram call is implemented (calling convention)%@NL@% %@NL@% ■ How parameters are passed (parameter-passing convention)%@NL@% %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00120004 @%%@AB@%12.2.1 Naming Convention Requirement%@AE@%%@EH@%%@NL@% %@NL@% Both the calling program and the called subprogram must agree on the names of identifiers. Identifiers can refer to subprograms (functions, procedures, and subroutines) or to variables that have a public or global scope. Each language alters the names of identifiers.%@CR:C6A00120005 @% %@NL@% %@NL@% The term "naming convention" refers to the way a compiler alters the name of the routine before placing it in an object file. Languages may alter the identifier names differently. You can choose between several naming conventions to ensure that the names in the calling program agree with those in the called program. If the names of called routines are stored differently in each object file, the linker will not be able to find a match. It will instead report unresolved external references. %@NL@% %@NL@% Microsoft compilers place machine code into object files; they also place the names of all publicly accessed routines and variables in object files. The linker can then compare the name of a routine called in one module with the name of a routine defined in another module, and recognize a match. Names are stored in the ASCII (American Standard Code for Information Interchange) character set. %@NL@% %@NL@% %@AU@% Some languages translate names to uppercase.%@AE@% %@NL@% %@NL@% BASIC, FORTRAN, and Pascal use similar naming conventions. They translate each letter to uppercase. BASIC type declaration characters (%, &, !, #, $) are dropped. %@NL@% %@NL@% Each language recognizes a different number of characters. FORTRAN recognizes the first 31 characters of any name (unless identifier names are truncated), Pascal the first 8, and BASIC the first 40. If a name is longer than the language will recognize, additional characters are simply not placed in the object file. %@NL@% %@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% NOTE %@AI@%Versions of Microsoft FORTRAN previous to version 5.0 truncated identifiers %@AI@%to six characters. As of version 5.0, FORTRAN retains up to 31 characters of %@AI@%significance unless you use the /4Yt option.%@AE@%%@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@%%@NL@% %@NL@% %@AU@% C is a case-sensitive language.%@AE@% %@NL@% %@NL@% The C compiler does not translate any letters to uppercase. It inserts a leading underscore ( _ ) in front of the name of each routine. C recognizes the first 31 characters of a name. %@NL@% %@NL@% Differences in naming conventions are dealt with automatically by mixedlanguage keywords, as long as you follow two rules:%@CR:C6A00120006 @% %@NL@% %@NL@% %@NL@% 1. If you use any FORTRAN routines that were compiled with the /4Yt command-line option or with the %@AB@%$TRUNCATE%@AE@% metacommand enabled, make all names 6 characters or less. Make all names 6 characters or less when using FORTRAN routines compiled with versions of the FORTRAN compiler prior to 5.0.%@NL@% %@NL@% 2. Do not use the /NOIGNORECASE linker option (which causes the linker to treat identifiers in a case-sensitive manner). With C modules, this means that you must be careful not to rely upon differences between uppercase and lowercase letters when programming.%@NL@% %@NL@% %@STUB@% CL automatically uses the /NOIGNORECASE option when linking. To solve the problems created by this behavior, either link separately with the LINK utility, or use all lowercase letters in your C function names and public variables (global variables that are not declared as static).%@NL@% %@NL@% %@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% NOTE %@AI@%If you use the command-line option /Gc (generate Pascal-style function %@AI@%calls) when you compile, or if you declare a function or variable with the %@AB@%_pascal%@AE@%%@AI@% keyword, the compiler will translate your identifiers to uppercase.%@AE@%%@AE@%%@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@%%@NL@% %@NL@% Figure 12.2 illustrates a complete mixed-language development example, showing how naming conventions enter into the process. %@NL@% %@NL@% %@AU@%(This figure may be found in the printed book.)%@AE@%%@NL@% %@NL@% In Figure 12.2, note that the BASIC compiler inserts a leading underscore in front of %@AS@% Prn %@AE@% as it places the name into the object file, because the %@AB@%CDECL%@AE@% keyword directs the BASIC compiler to use the C naming convention. BASIC will also convert all letters to lowercase when this keyword is used. (Converting letters to lowercase is not part of the C naming convention; however, it is consistent with the programming style of many C programs.)%@CR:C6A00120007 @% %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00120008 @%%@AB@%12.2.2 Calling Convention Requirement%@AE@%%@EH@%%@NL@% %@NL@% The term "calling convention" refers to the way a language implements a call. The choice of calling convention affects the machine instructions that a compiler generates to execute (and return from) a function, procedure, or subroutine call.%@CR:C6A00120009 @% %@NL@% %@NL@% It is crucial that the two routines concerned (the routine issuing a call and the routine being called) use the same protocol. Otherwise, the processor may receive inconsistent instructions, causing the program to behave incorrectly. %@NL@% %@NL@% The use of a calling convention affects programming in three ways: %@NL@% %@NL@% %@NL@% 1. The calling routine uses a calling convention to determine the order in which to pass arguments (parameters) to another routine. This convention can be specified in a mixed-language interface statement or declaration.%@NL@% %@NL@% 2. The called routine uses a calling convention to determine the order in which to receive the parameters passed to it. In most languages, this convention can be specified in the routine's heading. BASIC, however, always uses its own convention to receive parameters.%@NL@% %@NL@% 3. Both the calling routine and the called routine must agree on which of them is responsible for adjusting the stack after all parameters are removed.%@NL@% %@NL@% %@NL@% In other words, each call to a routine uses a certain calling convention; each routine heading specifies or assumes some calling convention. The two conventions must be compatible. With all languages except BASIC, it is possible to change the calling convention at the point of the call or at the declaration of the called routine. Usually, however, it is easier to adopt the convention of the called routine. For example, a C function would use its own convention to call another C function, and would use the Pascal convention to call Pascal. %@NL@% %@NL@% BASIC, FORTRAN, and Pascal use the same standard calling convention. C uses a different convention. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Effects of Calling Conventions%@AE@%%@EH@%%@NL@% %@NL@% Calling conventions dictate three things:%@CR:C6A00120010 @%%@CR:C6A00120011 @% %@NL@% %@NL@% %@NL@% 1. The way parameters are communicated from one routine to another (in Microsoft mixed-language programming, parameters or pointers to the parameters are passed on the stack)%@NL@% %@NL@% 2. The order in which parameters are passed from one routine to another%@NL@% %@NL@% 3. The part of the program responsible for adjusting the stack%@NL@% %@NL@% %@NL@% %@AU@% Some languages pass parameters in a different order than C.%@AE@% %@NL@% %@NL@% The BASIC, FORTRAN and Pascal calling conventions push parameters onto the stack in the order in which they appear in the source code. For example, the BASIC statement %@NL@% %@NL@% %@AS@% CALL Calc( A, B )%@AE@%%@NL@% %@NL@% pushes argument %@AS@% A %@AE@% onto the stack before it pushes %@AS@% B%@AE@%. These conventions also specify that the stack is adjusted by the called routine just before returning control to the caller. %@NL@% %@NL@% The C calling convention pushes parameters onto the stack in the reverse order from their appearance in the source code. For example, the C function call %@NL@% %@NL@% %@AS@% calc( a, b );%@AE@%%@NL@% %@NL@% pushes %@AS@% b %@AE@% onto the stack before it pushes %@AS@% a%@AE@%. In contrast with the other high-level languages, the C calling convention specifies that a calling routine always adjusts the stack immediately after the called routine returns control. %@NL@% %@NL@% The BASIC, FORTRAN, and Pascal conventions produce slightly less object code. However, the C convention makes calling with a variable number of parameters possible. (Because the first parameter is always the last one pushed, it is always on the top of the stack; therefore it has the same address relative to the frame pointer, regardless of how many parameters were actually passed.) %@NL@% %@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% NOTE %@AI@%The %@AB@%_fastcall%@AE@%%@AI@% keyword, which specifies that parameters are to be passed in %@AI@%registers, is incompatible with programs written in other languages. Avoid %@AI@%using %@AE@%%@AI@%%@AB@%_fastcall%@AE@%%@AE@%%@AI@% or the /Gr command-line option for C functions that you %@AI@%intend to make public to BASIC, FORTRAN, or Pascal programs.%@AE@%%@AE@%%@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00120012 @%%@AB@%12.2.3 Parameter-Passing Requirement%@AE@%%@EH@%%@NL@% %@NL@% Your programs must agree on the calling convention and the naming convention; they must also agree on the order in which they pass parameters. It is important that your routines send parameters in the same way to ensure proper data transmission and correct program results.%@CR:C6A00120013 @% %@NL@% %@NL@% Microsoft compilers support three methods for passing a parameter: %@NL@% %@NL@% %@AB@%Method%@AE@% %@AB@%Description%@AE@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% Near reference Passes a variable's near (offset) address. This address is expressed as an offset from the default data segment. This method gives the called routine direct access to the variable itself. Any change the routine makes to the parameter changes the variable in the calling routine. Far reference Passes a variable's far (segmented) address. This method is similar to passing by near reference, except that a longer address is passed. This method is slower than passing by near reference, but is necessary when you pass data that is outside the default data segment. (This is an issue in BASIC or Pascal only if you have specifically requested far memory.) Value Passes only the variable's value, not its address. With this method, the called routine knows the value of the parameter but has no access to the original variable. Changes to a value passed by a parameter have no affect on the value of the parameter in the calling routine. These different parameter-passing methods mean that you must consider the following when programming with mixed languages: %@NL@% %@NL@% %@NL@% ■ You need to make sure that the called routine and the calling routine use the same method for passing each parameter (argument). In most cases, you will need to check the parameter-passing defaults used by each language and possibly make adjustments. Each language has keywords or language features that allow you to change parameter-passing methods.%@NL@% %@NL@% ■ You may want to choose a specific parameter-passing method rather than using the defaults of any language.%@NL@% %@NL@% %@NL@% Table 12.2 summarizes the parameter-passing defaults for each language. %@NL@% %@NL@% %@AB@%Table 12.2 %@AB@%Parameter-Passing Defaults%@AE@%%@AE@% %@TH: 13 662 02 10 22 22 22 @%Language Near Reference Far Reference By Value%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%BASIC All --- ---C Near arrays Far arrays All data except arraysFORTRAN All (medium model) All (large model) With attributes%@AU@%(1)%@AE@%Pascal %@AB@%VAR, CONST%@AE@% %@AB@%VARS, CONSTS%@AE@% Other parameters %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@TE: 13 662 02 10 22 22 22 @% %@AU@%(1) %@AE@% When a PASCAL or C attribute is applied to a FORTRAN routine, passing by value becomes the default. %@NL@% %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00120014 @%%@AB@%12.3 Compiling and Linking%@AE@%%@EH@%%@NL@% %@NL@% After you have written your source files and decided on a naming convention, a calling convention, and a parameter-passing convention, you are ready to compile and link individual modules.%@CR:C6A00120015 @%%@CR:C6A00120016 @%%@CR:C6A00120017 @% %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00120018 @%%@AB@%12.3.1 Compiling with Correct Memory Models%@AE@%%@EH@%%@NL@% %@NL@% With BASIC, FORTRAN, and Pascal, no special options are required to compile source files that are part of a mixed-language program. %@NL@% %@NL@% %@AU@% With C, not all memory models are compatible with other languages. %@AE@% %@NL@% %@NL@% BASIC, FORTRAN, and Pascal use only far (segmented) code addresses. Therefore, you must use one of two techniques with C programs that call one of these languages: compile C modules in medium, large, or huge model (using the /A%@AI@%X%@AE@% command-line options), because these models also use far code addresses; or apply the %@AB@%_far%@AE@% keyword to the definitions of C functions you make public. If you use the /A%@AI@%X%@AE@% command-line option to specify medium, large, or huge model, all your function calls become far by default. This means you don't have to declare your functions explicitly with the %@AB@%_far%@AE@% keyword. %@NL@% %@NL@% Choice of memory model affects the default data pointer size in C and FORTRAN, although this default can be overridden with the %@AB@%_near%@AE@% and %@AB@%_far%@AE@% keywords. With C and FORTRAN, choice of memory model also affects whether data objects are located in the default data segment; if a data object is not located in the default data segment, it cannot be passed by near reference. %@NL@% %@NL@% For more information about code and data address sizes in C, refer to Chapter 2, "Managing Memory." %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00120019 @%%@AB@%12.3.2 Linking with Language Libraries%@AE@%%@EH@%%@NL@% %@NL@% In most cases, you can easily link modules compiled with different languages. Do any of the following to ensure that all required libraries link in the correct order: %@NL@% %@NL@% %@NL@% ■ Put all language libraries in the same directory as the source files.%@NL@% %@NL@% ■ List directories containing all needed libraries in the LIB environment variable.%@NL@% %@NL@% ■ Let the linker prompt you for libraries.%@NL@% %@NL@% %@NL@% In each of the cases above, the linker finds libraries in the order that it requires them. If you enter the library names on the command line, make sure you enter them in an order that allows the linker to resolve your program's external references. Here are some points to observe when specifying libraries on the command line: %@NL@% %@NL@% %@NL@% ■ If you are using FORTRAN to write one of your modules, you need to link with the /NOD (no default libraries) option and explicitly specify all the libraries you need on the link command line. You can also specify these libraries with an automatic-response file (or batch file), but you cannot use a default-library search.%@NL@% %@NL@% ■ If your program uses both FORTRAN and C, specify the library for the most recent of the two language products first. In addition, make sure that you choose a C-compatible library when you install FORTRAN.%@NL@% %@NL@% ■ If you are listing BASIC libraries on the LINK command line, specify those libraries first.%@NL@% %@NL@% %@NL@% The following example shows how to link two modules, %@AS@% mod1 %@AE@% and %@AS@% mod2%@AE@%, with a user library, GRAFX, the C run-time library, LLIBCE, and the FORTRAN run-time library, LLIBFORE: %@NL@% %@NL@% %@AS@% LINK /NOD mod1 mod2,,,GRAFX+LLIBCE+LLIBFORE%@AE@%%@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00120020 @%%@AB@%12.4 C Calls to High-Level Languages%@AE@%%@EH@%%@NL@% %@NL@% Just as you can call Microsoft C routines from other Microsoft languages, you can call routines written in Microsoft FORTRAN and Pascal from C. With FORTRAN, Pascal, and C, freestanding routines can be written with no restriction. When calling BASIC routines, however, you must write the main program in BASIC; any subprograms are free to call one another, whether they are written in C or BASIC. %@NL@% %@NL@% For information about how to pass particular kinds of data, see Section 12.9, "Handling Data in Mixed-Language Programming." %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Executing a Mixed-Language Call%@AE@%%@EH@%%@NL@% %@NL@% The C interface to other languages uses standard C prototypes, with the %@AB@%_fortran%@AE@% or %@AB@%_pascal%@AE@% keyword. Using either of these keywords causes the routine to be called with the FORTRAN/Pascal naming and calling convention. (The FORTRAN/Pascal convention also works for BASIC.) Here are the recommended steps for executing a mixed-language call from C: %@NL@% %@NL@% %@NL@% 1. Write a prototype for each mixed-language routine called. The prototype should declare the routine %@AB@%extern%@AE@% for the purpose of program documentation.%@NL@% %@NL@% %@STUB@% Instead of using the %@AB@%_fortran%@AE@% or %@AB@%_pascal%@AE@% keyword, you can simply compile with the Pascal calling convention option (/Gc). The /Gc option causes all functions in the module to use the FORTRAN/Pascal naming and calling conventions, except where you apply the %@AB@%_cdecl%@AE@% keyword.%@NL@% %@NL@% 2. Pass the values of variables or pointers to variables. You can obtain a pointer to a variable with the address-of (%@AB@%&%@AE@%) operator.%@NL@% %@NL@% %@STUB@% In C, array names are always passed as pointers to the first element of the array; they are always passed by reference.%@NL@% %@NL@% %@STUB@% The prototype you declare for your function ensures that you are passing the correct length address (that is, near or far). %@NL@% %@NL@% 3. Issue a function call in your program as though you were calling a C function.%@NL@% %@NL@% 4. Always compile the C module in either medium, large, or huge model, or use the %@AB@%_far %@AE@%keyword in your function prototype. This ensures that a far (intersegment) call is made to the routine. %@NL@% %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Using the _fortran or _pascal Keyword%@AE@%%@EH@%%@NL@% %@NL@% There are two rules of syntax that apply when you use the %@AB@%_fortran%@AE@% or %@AB@%_pascal%@AE@% keyword:%@CR:C6A00120021 @%%@CR:C6A00120022 @% %@NL@% %@NL@% %@NL@% 1. The %@AB@%_fortran%@AE@% and %@AB@%_pascal%@AE@% keywords modify only the item immediately to their right.%@NL@% %@NL@% 2. The %@AB@%_near%@AE@% and %@AB@%_far%@AE@% keywords can be used with the %@AB@%_fortran%@AE@% and %@AB@%_pascal%@AE@% keywords in prototypes. The sequences %@AB@%_fortran _far%@AE@% and %@AB@%_far _fortran%@AE@% are equivalent.%@NL@% %@NL@% %@NL@% The keywords %@AB@%_pascal%@AE@% and %@AB@%_fortran%@AE@% have the same effect on the program; using one or the other makes no difference except for internal program documentation. Use %@AB@%_fortran%@AE@% to declare a FORTRAN routine, %@AB@%_pascal%@AE@% to declare a Pascal rou-tine, and either keyword to declare a BASIC routine. %@NL@% %@NL@% The following examples demonstrate the syntax rules presented above. %@NL@% %@NL@% The example below declares %@AB@%func%@AE@% to be a BASIC, Pascal, or FORTRAN function taking two %@AB@%short%@AE@% parameters and returning a %@AB@%short%@AE@% value. %@NL@% %@NL@% %@AS@% short _pascal func( short sarg1, short sarg2 );%@AE@%%@NL@% %@NL@% The example below declares %@AB@%func%@AE@% to be pointer to a BASIC, Pascal, or FORTRAN routine that takes a %@AB@%long%@AE@% parameter and returns no value. The keyword %@AB@%void%@AE@% is appropriate when the called routine is a BASIC subprogram, Pascal procedure, or FORTRAN subroutine, since it indicates that the function returns no value. %@NL@% %@NL@% %@AS@% void ( _fortran * func )( long larg );%@AE@%%@NL@% %@NL@% The example below declares %@AB@%func%@AE@% to be a %@AB@%_near%@AE@% BASIC, Pascal, or FORTRAN routine. The routine receives a %@AB@%double%@AE@% parameter by reference (because it expects a pointer to a %@AB@%double%@AE@%) and returns a %@AB@%short%@AE@% value. %@NL@% %@NL@% %@AS@% short _near _pascal func( _near double * darg );%@AE@%%@NL@% %@NL@% The example below is equivalent to the preceding example (%@AB@% _pascal _near%@AE@% is equivalent to %@AB@%_near _pascal%@AE@%). %@NL@% %@NL@% %@AS@% short _pascal _near func( _near double * darg );%@AE@%%@NL@% %@NL@% %@AU@% You can make C adopt the conventions of other languages.%@AE@% %@NL@% %@NL@% When you call a BASIC subprogram, you must use the FORTRAN/Pascal conventions to make the call. When you call FORTRAN or Pascal, however, you have a choice. You can make C adopt the conventions described in the previous section, or you can make the FORTRAN or Pascal routine adopt the C conventions. %@NL@% %@NL@% To make a FORTRAN or Pascal routine adopt the C conventions, put the %@AB@%C%@AE@% attribute in the heading of the routine's definition. The following example shows the syntax for the %@AB@%C%@AE@% attribute in a FORTRAN subroutine-definition heading: %@NL@% %@NL@% %@AS@% SUBROUTINE FFROMC [C] (N) %@AS@% INTEGER*2 N%@AE@%%@NL@% %@NL@% The following example shows the syntax for the %@AB@%C%@AE@% attribute in a Pascal procedure-definition heading: %@NL@% %@NL@% %@AS@% PROCEDURE Pfromc( n : INTEGER ) [C];%@AE@%%@NL@% %@NL@% To make a C function adopt the FORTRAN/Pascal conventions, declare the function as %@AB@%_fortran%@AE@% or %@AB@%_pascal%@AE@%. For example, %@NL@% %@NL@% %@AS@% void _pascal CfromP( int n );%@AE@%%@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00120023 @%%@AB@%12.5 C Calls to BASIC%@AE@%%@EH@%%@NL@% %@NL@% No BASIC routine can be executed unless the main program is in BASIC, because a BASIC routine requires the environment to be initialized in a way that is unique to BASIC. No other language will perform this special initialization. %@NL@% %@NL@% However, your program can start up in BASIC, call a C function that does most of the work of the program, and then call BASIC subprograms and function procedures as needed. Figure 12.3 illustrates how to do this. %@NL@% %@NL@% %@AU@%(This figure may be found in the printed book.)%@AE@%%@NL@% %@NL@% Follow these rules when you call BASIC from C: %@NL@% %@NL@% %@NL@% 1. Start up in a BASIC main module. You will need to use the %@AB@%DECLARE%@AE@% statement to provide an interface to the C module. %@NL@% %@NL@% 2. In the C module, write a prototype for the BASIC routine and include type information for parameters. Use either the %@AB@%_fortran%@AE@% or %@AB@%_pascal%@AE@% keyword to modify the routine itself.%@NL@% %@NL@% 3. Make sure that all data are passed as near pointers. BASIC can pass data in a variety of ways but is unable to receive data in any form other than near reference. With near pointers, the program assumes that the data are in the default data segment. If you want to pass data that are not in the default data segment, copy the data to a variable in the default data segment.%@NL@% %@NL@% 4. Compile the C module in medium or large model to ensure far (intersegment) calls.%@NL@% %@NL@% %@NL@% The example below demonstrates a BASIC program that calls a C function. The C function then calls a BASIC function that returns twice the number passed to it and a BASIC subprogram that prints two numbers. %@NL@% %@NL@% %@AS@% ' BASIC source %@AS@% ' %@AS@% ' The main program is in BASIC because of BASIC's start-up %@AS@% ' requirements. The BASIC main program calls the C function %@AS@% ' Cprog. %@AS@% ' %@AS@% ' Cprog calls the BASIC subroutine Dbl. %@AS@% ' %@AS@% DEFINT A-Z %@AS@% DECLARE SUB Cprog CDECL() %@AS@% CALL Cprog %@AS@% END %@AS@% ' %@AS@% FUNCTION Dbl(N) STATIC %@AS@% Dbl = N*2 %@AS@% END FUNCTION %@AS@% ' %@AS@% SUB Printnum(A,B) STATIC %@AS@% PRINT "The first number is ";A %@AS@% PRINT "The second number is ";B %@AS@% END SUB %@AS@% %@AS@% %@AS@% /* C source; compile in medium or large model */ %@AS@% %@AS@% int _fortran dbl( int _near * N ); %@AS@% void _fortran printnum( int _near * A, int _near * B ); %@AS@% %@AS@% void cprog() %@AS@% { %@AS@% int a = 5; %@AS@% int b = 6; %@AS@% %@AS@% printf( "%d times 2 is %d\n", a, dbl( &a ) ); %@AS@% printnum( &a, &b ); %@AS@% }%@AE@%%@NL@% %@NL@% In the previous example, note that the addresses of %@AS@% a %@AE@% and %@AS@% b %@AE@% are passed, since BASIC expects to receive addresses for parameters. This is important because C passes parameters by value unless you use the address-of (%@AB@%&%@AE@%) operator to obtain the address, or are passing an array. Also note that the function prototype for %@AS@% printnum %@AE@% declares the parameters as near pointers. The prototype causes the %@NL@% %@NL@% variables to be passed by near reference. If %@AS@% a %@AE@% or %@AS@% b %@AE@% is declared as %@AB@%_far%@AE@%, the C compiler issues a warning that you are converting a far pointer to a near pointer and that a segment was lost in the conversion. %@NL@% %@NL@% Calling and naming conventions are resolved by the %@AB@%CDECL%@AE@% keyword in the BASIC declaration of %@AB@%Cprog%@AE@%, and by the %@AB@%_fortran%@AE@% keyword in the C declaration of %@AS@% dbl %@AE@% and %@AS@% printnum%@AE@%. %@NL@% %@NL@% %@AU@% BASIC can invoke one of your functions as part of the termination %@AU@%procedure.%@AE@% %@NL@% %@NL@% Versions of QuickBASIC later than 4.0 provide a "user entry point," %@AB@%B_OnExit%@AE@%, which can be called directly from C. The %@AB@%B_OnExit%@AE@% function enables you to make sure you have performed an orderly termination. The following code shows how to use %@AB@%B_OnExit%@AE@%. %@NL@% %@NL@% %@AS@% #include <malloc.h> /* For declaration of _fmalloc */ %@AS@% #include <stdlib.h> /* For declaration of onexit_t */ %@AS@% %@AS@% /* The prototype for B_OnExit declares it as a function %@AS@% * returning type onexit_t that takes one parameter. The %@AS@% * parameter is a far pointer to a function that returns %@AS@% * no value. %@AS@% */ %@AS@% extern onexit_t _pascal _far B_OnExit( onexit_t ); %@AS@% void TermProc( void ); %@AS@% %@AS@% int * p_IntArray; %@AS@% %@AS@% void InitProc( void ) %@AS@% { %@AS@% /* Allocate far space for 20-integer array */ %@AS@% %@AS@% p_IntArray = (int *)_fmalloc( 20 * sizeof( int ) ); %@AS@% %@AS@% /* Log termination routine (TermProc) with BASIC. */ %@AS@% %@AS@% B_OnExit( TermProc ); %@AS@% } %@AS@% %@AS@% void TermProc( void ) %@AS@% { %@AS@% free( p_IntArray ); /* Release far space allocated */ %@AS@% } /* previously by InitProc. */%@AE@%%@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00120024 @%%@AB@%12.6 C Calls to FORTRAN%@AE@%%@EH@%%@NL@% %@NL@% This section shows two examples of C-FORTRAN programs. There are two types of subprogram calls to FORTRAN routines: calls to subroutines and calls to functions. Functions return a value, while subroutines do not. The examples in the next sections illustrate how to handle the difference between function and subroutine calls. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00120025 @%%@AB@%12.6.1 Calling a FORTRAN Subroutine from C%@AE@%%@EH@%%@NL@% %@NL@% The example below demonstrates a C main module calling a FORTRAN subroutine, %@AB@%MAXPARAM%@AE@%. This subroutine adjusts the lower of two arguments to be equal to the higher argument. %@NL@% %@NL@% %@AS@% /* C source file - calls FORTRAN subroutine %@AS@% * Compile in medium or large model %@AS@% */ %@AS@% %@AS@% extern void _fortran maxparam( int _near * I, int _near * J ); %@AS@% %@AS@% /* Declare as void, because there is no return value. %@AS@% * FORTRAN keyword causes C to use FORTRAN/Pascal %@AS@% * calling and naming conventions. %@AS@% * Two integer parameters, passed by near reference. %@AS@% */ %@AS@% %@AS@% main() %@AS@% { %@AS@% int a = 5; %@AS@% int b = 7; %@AS@% %@AS@% printf( "a = %d, b = %d", a, b ); %@AS@% maxparam( &a, &b ); %@AS@% printf( "a = %d, b = %d", a, b ); %@AS@% } %@AS@% %@AS@% C FORTRAN source file, subroutine MAXPARAM %@AS@% C %@AS@% $NOTRUNCATE %@AS@% %@AS@% SUBROUTINE MAXPARAM (I, J) %@AS@% INTEGER*2 I [NEAR] %@AS@% INTEGER*2 J [NEAR] %@AS@% C %@AS@% C I and J received by near reference, %@AS@% C because of NEAR attribute %@AS@% C %@AS@% IF (I .GT. J) THEN %@AS@% J = I %@AS@% ELSE %@AS@% I = J %@AS@% ENDIF %@AS@% END%@AE@%%@NL@% %@NL@% In the previous example, the C program adopts the naming convention and call-ing convention of the FORTRAN subroutine. The two programs must agree on whether parameters are to be passed by reference or by value. The following keywords affect how the two programs interface: %@NL@% %@NL@% %@NL@% ■ The %@AB@%_fortran%@AE@% keyword directs C to call %@AS@% maxparam %@AE@% with the FORTRAN/ Pascal naming convention (as %@AS@% MAXPARAM%@AE@%);%@AB@% _fortran%@AE@% also directs C to call %@AS@% maxparam %@AE@% with the FORTRAN/Pascal calling convention.%@NL@% %@NL@% ■ Since the FORTRAN subroutine %@AS@% MAXPARAM %@AE@% may alter the value of either parameter, both parameters must be passed by reference. In this case, near reference was chosen; this method is specified in C by the use of near pointers, and in FORTRAN by applying the %@AB@%NEAR%@AE@% keyword to the parameter declarations.%@NL@% %@NL@% %@STUB@% Far reference could have been specified by using far pointers in C. In that case, you would not declare the FORTRAN subroutine %@AS@% MAXPARAM %@AE@% with the %@AB@%NEAR%@AE@% keyword. If you compile the FORTRAN program in medium model, declare %@AS@% MAXPARAM %@AE@% using the %@AB@%FAR%@AE@% keyword.%@NL@% %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00120026 @%%@AB@%12.6.2 Calling a FORTRAN Function from C%@AE@%%@EH@%%@NL@% %@NL@% The example below demonstrates a C main module calling the FORTRAN function %@AS@% fact%@AE@%. This function returns the factorial of an integer value. %@NL@% %@NL@% %@AS@% /* C source file - calls FORTRAN function. %@AS@% * Compile in medium or large model. %@AS@% */ %@AS@% %@AS@% int _fortran fact( int N ); %@AS@% %@AS@% /* FORTRAN keyword causes C to use FORTRAN/Pascal %@AS@% * calling and naming conventions. %@AS@% * Integer parameter passed by value. %@AS@% */ %@AS@% %@AS@% main() %@AS@% { %@AS@% int x = 3; %@AS@% int y = 4; %@AS@% %@AS@% printf( "The factorial of x is %4d", fact( x ) ); %@AS@% printf( "The factorial of y is %4d", fact( y ) ); %@AS@% printf( "The factorial of x+y is %4d", fact( x + y ) ); %@AS@% }%@AE@%%@NL@% %@NL@% %@AS@% C FORTRAN source file - factorial function %@AS@% C %@AS@% $NOTRUNCATE %@AS@% INTEGER*2 FUNCTION FACT (N) %@AS@% INTEGER*2 N [VALUE] %@AS@% C %@AS@% C N is received by value, because of VALUE attribute %@AS@% C %@AS@% INTEGER*2 I %@AS@% FACT = 1 %@AS@% DO 100 I = 1, N %@AS@% FACT = FACT * I %@AS@% 100 CONTINUE %@AS@% RETURN %@AS@% END%@AE@%%@NL@% %@NL@% In the example above, the C program adopts the naming convention and calling convention of the FORTRAN subroutine. Both programs must agree on whether parameters are passed by reference or by value. Note that the C program passes the parameters by value rather than by reference. Passing parameters by value is the default for C. To accept parameters passed by value, the keyword %@AB@%VALUE%@AE@% is used in the declaration of %@AS@% N %@AE@% in the FORTRAN function. The %@AB@%_fortran%@AE@% keyword directs C to call %@AS@% fact %@AE@% with the FORTRAN/Pascal naming convention (as %@AS@% FACT%@AE@%); %@AB@%_fortran%@AE@% also directs C to call %@AS@% fact %@AE@% with the FORTRAN/Pascal calling convention. %@NL@% %@NL@% When passing a parameter that should not be changed, pass the parameter by value. Passing by value is the default method in C and is specified in FORTRAN by applying the %@AB@%VALUE%@AE@% attribute to the parameter declaration. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00120027 @%%@AB@%12.7 C Calls to Pascal%@AE@%%@EH@%%@NL@% %@NL@% This section shows two examples of C-Pascal programs. There are two types of subprogram calls to Pascal routines: calls to procedures and calls to functions. Functions return a value, while procedures do not. The examples in the next sections illustrate how to handle the difference between function and procedure calls. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00120028 @%%@AB@%12.7.1 Calling a Pascal Procedure from C%@AE@%%@EH@%%@NL@% %@NL@% The following example demonstrates a C main module calling a Pascal procedure, %@AS@% maxparam%@AE@%. This procedure adjusts the lower of two arguments to be equal to the higher argument. %@NL@% %@NL@% %@AS@% /* C source file - calls Pascal procedure. %@AS@% * Compile in medium or large model. %@AS@% */ %@AS@% %@AS@% void _pascal maxparam( int _near * a, int _near * b ); %@AS@% %@AS@% /* Declare as void, because there is no return value. %@AS@% * The _pascal keyword causes C to use FORTRAN/Pascal %@AS@% * calling and naming conventions. %@AS@% * Two integer params, passed by near reference. %@AS@% */ %@AS@% %@AS@% main() %@AS@% { %@AS@% int a = 5; %@AS@% int b = 7; %@AS@% %@AS@% printf( "a = %d, b = %d", a, b ); %@AS@% maxparam( &a, &b ); %@AS@% printf( "a = %d, b = %d", a, b ); %@AS@% } %@AS@% %@AS@% { Pascal source code - Maxparam procedure. } %@AS@% %@AS@% MODULE Psub; %@AS@% PROCEDURE Maxparam( VAR a:INTEGER; VAR b:INTEGER ); %@AS@% %@AS@% { Two integer parameters are received by near reference. } %@AS@% { Near reference is specified with the VAR keyword. } %@AS@% %@AS@% BEGIN %@AS@% if a > b THEN %@AS@% b := a %@AS@% ELSE %@AS@% a := b %@AS@% END; %@AS@% END.%@AE@%%@NL@% %@NL@% In the example above, the C program adopts the Pascal naming convention and calling convention. Both programs must agree on whether parameters are passed by reference or by value; the following keywords affect the conventions: %@NL@% %@NL@% %@NL@% ■ The %@AB@%_pascal%@AE@% keyword directs C to call %@AS@% Maxparam %@AE@% with the FORTRAN/ Pascal naming convention (as %@AS@% MAXPARAM%@AE@%); %@AB@%_pascal%@AE@% also directs C to call %@AS@%Maxparam %@AE@% with the FORTRAN/Pascal calling convention.%@NL@% %@NL@% ■ Since the procedure %@AS@% Maxparam %@AE@% can alter the value of either parameter, both parameters must be passed by reference. In this case, near reference is used; this method is specified in C by the use of near pointers, and in Pascal with the %@AB@%VAR%@AE@% keyword.%@NL@% %@NL@% %@STUB@% Far reference could have been specified by using far pointers in C. To specify far reference in Pascal, use the %@AB@%VARS%@AE@% keyword instead of %@AB@%VAR%@AE@%.%@NL@% %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00120029 @%%@AB@%12.7.2 Calling a Pascal Function from C%@AE@%%@EH@%%@NL@% %@NL@% The example below demonstrates a C main module calling Pascal function %@AS@% %@AS@%fact%@AE@%. This function returns the factorial of an integer value. %@NL@% %@NL@% %@AS@% /* C source file - calls Pascal function. %@AS@% * Compile in medium or large model. %@AS@% */ %@AS@% %@AS@% int _pascal fact(int n); %@AS@% %@AS@% /* PASCAL keyword causes C to use FORTRAN/Pascal %@AS@% * calling and naming conventions. %@AS@% * Integer parameter passed by value. %@AS@% */ %@AS@% %@AS@% main() %@AS@% { %@AS@% int x = 3; %@AS@% int y = 4; %@AS@% %@AS@% printf( "The factorial of x is %4d", fact( x ) ); %@AS@% printf( "The factorial of y is %4d", fact( y ) ); %@AS@% printf( "The factorial of x+y is %4d", fact( x + y ) ); %@AS@% } %@AS@% %@AS@% { Pascal source code - factorial function. } %@AS@% %@AS@% MODULE Pfun; %@AS@% FUNCTION Fact (n : INTEGER) : INTEGER; %@AS@% %@AS@% {Integer parameters received by value, the Pascal default. } %@AS@% %@AS@% BEGIN %@AS@% Fact := 1; %@AS@% WHILE n > 0 DO %@AS@% BEGIN %@AS@% Fact := Fact * n; %@AS@% n := n - 1; {Parameter n modified.} %@AS@% END; %@AS@% END; %@AS@% END.%@AE@%%@NL@% %@NL@% In the example above, the C program adopts the Pascal naming convention and calling convention. Both programs must agree on whether parameters are passed by reference or by value. The %@AB@%_pascal%@AE@% keyword directs C to call %@AS@% fact %@AS@%%@AE@% with the FORTRAN/Pascal naming convention (as %@AS@% FACT%@AE@%); %@AB@% _pascal%@AE@% also directs C to call %@AS@%fact %@AE@% with the FORTRAN/Pascal calling convention. %@NL@% %@NL@% The Pascal function %@AS@% fact %@AE@% should receive a parameter by value. Otherwise, the Pascal function will corrupt the parameter's value in the calling module. Passing by value is the default method for both C and Pascal. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00120030 @%%@AB@%12.8 C Calls to Assembly Language%@AE@%%@EH@%%@NL@% %@NL@% In Microsoft C, Version 6.0, you can write assembly-language programs either by using the in-line assembler or by creating a stand-alone module using the Microsoft Macro Assembler (MASM). If you use the in-line assembler, you do not need to take any special precautions other than those outlined in Chapter 3, "Using the In-Line Assembler." This section explains the techniques for interfacing your assembly-language routines with your C program. %@NL@% %@NL@% When deciding whether to use the in-line assembler or MASM, there are several considerations. Here is a list of advantages MASM provides over the in-line assembler: %@NL@% %@NL@% %@NL@% ■ MASM supports declaration of data in MASM format; in-line assembly does not.%@NL@% %@NL@% ■ MASM has a more powerful macro capability than in-line assembly.%@NL@% %@NL@% ■ Modules written for MASM can be interfaced more easily with modules written in more than one Microsoft high-level language.%@NL@% %@NL@% ■ MASM assembles large assembly-language programs more quickly than the in-line assembler.%@NL@% %@NL@% ■ MASM supports assembly-language code written prior to the existence of the in-line assembler.%@NL@% %@NL@% ■ MASM error messages and warnings are more complete than those of the in-line assembler.%@NL@% %@NL@% %@NL@% The in-line assembler is far more efficient for some assembly-language programming tasks. Here are some of the benefits of the in-line assembler: %@NL@% %@NL@% %@NL@% ■ You can do spot optimizations by including short sections of assemblylanguage code in your C programs with the in-line assembler.%@NL@% %@NL@% ■ Code written in in-line assembler does not necessarily incur the overhead of a function call; code assembled using MASM always does.%@NL@% %@NL@% ■ You can include in-line assembly code in your C source files; code written for MASM must be in a separate file.%@NL@% %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00120031 @%%@AB@%12.8.1 Writing the Assembly-Language Procedure%@AE@%%@EH@%%@NL@% %@NL@% You must write your assembly-language procedure so that it uses the same call-ing conventions and naming conventions as your C program. If you follow these conventions, you will be able to write recursive procedures (procedures that call themselves), and you will be able to use the CodeView debugger to locate errors in the code. %@NL@% %@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% NOTE %@AI@%This section discusses only the simplified segment directives provided with %@AI@%the Microsoft Macro Assembler, version 5.0. If you are using a version prior %@AI@%to 5.0, you have to specify complete %@AI@%SEGMENT %@AE@%%@AI@%directives.%@AE@%%@AE@%%@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@%%@NL@% %@NL@% The standard assembly-language interface method consists of these steps: %@NL@% %@NL@% %@NL@% 1. Setting up the procedure%@NL@% %@NL@% 2. Entering the procedure%@NL@% %@NL@% 3. Allocating local data (optional)%@NL@% %@NL@% 4. Preserving register values%@NL@% %@NL@% 5. Accessing parameters%@NL@% %@NL@% 6. Returning a value (optional)%@NL@% %@NL@% 7. Exiting the procedure%@NL@% %@NL@% %@NL@% The next sections describe each of these steps in detail. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00120032 @%%@AB@%12.8.2 Setting Up the Procedure%@AE@%%@EH@%%@NL@% %@NL@% The linker cannot combine the assembly-language procedure with the C program unless you define compatible segments and declare the procedure properly. Perform the following steps to set up the procedure: %@NL@% %@NL@% %@NL@% 1. Use the %@AB@%.MODEL%@AE@% directive at the beginning of the source file; this directive automatically causes the appropriate kind of returns to be generated (%@AB@%NEAR%@AE@% for tiny, small or compact models, %@AB@%FAR%@AE@% for medium, large, or huge models).%@NL@% %@NL@% %@STUB@% If you are using a version of MASM prior to 5.0, declare the procedure %@AB@%NEAR%@AE@% for small or compact model, %@AB@%FAR%@AE@% for medium, large, or huge models.%@NL@% %@NL@% 2. Use the simplified segment directives %@AB@%.CODE%@AE@% and %@AB@%.DATA%@AE@% to declare the code and data segments.%@NL@% %@NL@% %@STUB@% If you are using a version of MASM prior to 5.0, declare the segments using the %@AB@%SEGMENT%@AE@%, %@AB@%GROUP%@AE@%, and %@AB@%ASSUME%@AE@% directives. These directives are described in the %@AI@%Microsoft%@AE@% %@AI@%Macro Assembler%@AE@% %@AI@%Reference %@AE@%.%@NL@% %@NL@% 3. Use the %@AB@%PUBLIC %@AE@%directive to declare the procedure label public. This declaration makes the procedure visible to other modules. Also declare any data you want to make public as %@AB@%PUBLIC%@AE@%.%@NL@% %@NL@% 4. Use the %@AB@%EXTRN %@AE@%directive to declare any global data or procedures accessed by the routine as external. The safest way to use%@AB@% EXTRN%@AE@% is to place the directive outside any segment definition; however, place near data inside the data segment.%@NL@% %@NL@% 5. Observe the C naming convention; precede all procedure names and global data names with an underscore.%@NL@% %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00120033 @%%@AB@%12.8.3 Entering the Procedure%@AE@%%@EH@%%@NL@% %@NL@% When you enter the procedure, in most cases you will want to set up a "stack frame." This allows you to access parameters passed on the stack and to allocate local data on the stack. You do not need to set up the stack frame if your procedure accepts no arguments and does not use the stack. %@NL@% %@NL@% To set up the stack frame, issue the instructions: %@NL@% %@NL@% %@AS@% push bp %@AS@% mov bp,sp%@AE@%%@NL@% %@NL@% This sequence establishes BP as the frame pointer. You cannot use SP for this purpose because it is not an index or base register. Also, the value of SP may change as more data are pushed onto the stack. However, the value of the base register BP remains constant for the life of the procedure unless your program changes it, so each parameter can be addressed as an offset from BP. %@NL@% %@NL@% The instruction sequence above preserves the value of BP, since it will be needed in the calling procedure as soon as your assembly-language procedure returns. It then transfers the value in SP to BP to establish a stack frame on entry to the procedure. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00120034 @%%@AB@%12.8.4 Allocating Local Data%@AE@%%@EH@%%@NL@% %@NL@% Your assembly-language procedure can use the same technique for allocating temporary storage for local data that is used by high-level languages. To set up local data space, decrease the contents of SP just after setting up the stack frame. (To ensure correct execution, always increase or decrease SP by an even number.) Decreasing SP reserves space on the stack for local data. You must restore the space at the end of the procedure as follows: %@NL@% %@NL@% %@AS@% push bp %@AS@% mov bp,sp %@AS@% sub sp,space%@AE@%%@NL@% %@NL@% In the example above, %@AS@% space %@AE@% is the total size in bytes of the local data you want to allocate. Local variables are then accessed as fixed negative displacements from BP. %@NL@% %@NL@% In the following example, the entry sequence establishes a stack frame and allocates temporary local storage for two words (4 bytes) of data. Later in the example, the program accesses the local storage, initializing both to 0. %@NL@% %@NL@% %@AS@% push bp ; Save old stack frame. %@AS@% mov bp,sp ; Set up new stack frame. %@AS@% sub sp,4 ; Allocate 4 bytes of local storage. %@AS@% . %@AS@% . %@AS@% . %@AS@% mov WORD PTR [bp-2],0 %@AS@% mov WORD PTR [bp-4],0%@AE@%%@NL@% %@NL@% Note that local variables are also called dynamic, stack, or automatic variables. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00120035 @%%@AB@%12.8.5 Preserving Register Values%@AE@%%@EH@%%@NL@% %@NL@% A procedure called from C should preserve the values of SI, DI, SS, and DS (in addition to BP, which is already saved). You should push any register value that your procedure modifies onto the stack after setting up the stack frame and allocating local storage, but prior to entering the main body of the procedure. Registers that your procedure does not alter need not be preserved. %@NL@% %@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% %@AU@%WARNING%@AE@%%@NL@% %@NL@% Routines that your assembly-language procedure calls must not alter the SI, DI, SS, DS, or BP registers. If they do, and you have not preserved the registers, they can corrupt the calling program's register variables, segment registers, and stack frame, causing program failure. If your procedure modifies the direction flag using the %@AI@%STD%@AE@%%@AB@% %@AE@%or %@AI@%CLD %@AE@%instructions, you must preserve the flags register.%@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% %@NL@% The example below shows an entry sequence that sets up a stack frame, allocates 4 bytes of local data space on the stack, then preserves the SI, DI, and flags registers. %@NL@% %@NL@% %@AS@% push bp ; Save caller's stack frame. %@AS@% mov bp,sp ; Establish new stack frame. %@AS@% sub sp,4 ; Allocate local data space. %@AS@% push si ; Save SI and DI registers. %@AS@% push di %@AS@% pushf ; Save the flags register. %@AS@% . %@AS@% . %@AS@% .%@AE@%%@NL@% %@NL@% In the example above, you must exit the procedure with the following code: %@NL@% %@NL@% %@AS@% popf ; Restore the flags register. %@AS@% pop di ; Restore the old value in the DI %@AS@% register. %@AS@% pop si ; Restore the old value in the SI %@AS@% register. %@AS@% mov sp,bp ; Restore the stack pointer. %@AS@% pop bp ; Restore the frame pointer. %@AS@% ret ; Return to the calling routine.%@AE@%%@NL@% %@NL@% If you do not issue the instructions above in the order shown, you will place incorrect data in registers. Follow the rules below when restoring the calling program's registers, stack pointer, and frame pointer: %@NL@% %@NL@% %@NL@% ■ Pop all registers that you preserve in the reverse order from which they were pushed onto the stack. So, in the example above, SI and DI are pushed, and DI and SI are popped.%@NL@% %@NL@% ■ Restore the stack pointer by transferring the value of BP into SP before restoring the value of the frame pointer.%@NL@% %@NL@% ■ Always restore the frame pointer last.%@NL@% %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00120036 @%%@AB@%12.8.6 Accessing Parameters%@AE@%%@EH@%%@NL@% %@NL@% Once you have established the frame pointer, allocated local storage (if required), and pushed any registers that need to be preserved, you can write the main body of the procedure. Figure 12.4 shows how functions that observe the C calling convention use the stack frame. %@NL@% %@NL@% %@AU@%(This figure may be found in the printed book.)%@AE@%%@NL@% %@NL@% The stack frame for the assembly-language procedure shown in Figure 12.4 is established by the following: %@NL@% %@NL@% %@NL@% 1. The calling program pushes each of the parameters onto the stack, after which SP points to the last parameter pushed.%@NL@% %@NL@% 2. The calling program issues a %@AB@%CALL%@AE@% instruction, which causes the return address (the place in the calling program to which control will ultimately return) to be placed on the stack. This address can be either two bytes long (for near calls) or four bytes long (for far calls). SP now points to this address.%@NL@% %@NL@% 3. The first instruction of the called procedure saves the old value of BP, with the instruction %@AS@% push bp%@AE@%. SP now points to the saved copy of BP.%@NL@% %@NL@% 4. BP is used to hold the current value of SP, with the instruction %@AS@% mov %@AS@% bp%@AE@%,%@AS@%sp%@AE@%. BP therefore now points to the old value of BP (saved on the stack).%@NL@% %@NL@% 5. While BP remains constant throughout the procedure, SP is often decreased to provide room on the stack for local data or saved registers.%@NL@% %@NL@% %@NL@% In general, the displacement (from BP) for a parameter %@AI@%x%@AE@% is equal to the size of return address plus 2 plus the total size of parameters between %@AI@%x%@AE@% and BP. %@NL@% %@NL@% To calculate the size of parameters between %@AI@%x%@AE@% and BP, you must start with the rightmost parameter because C pushes parameters from right to left. For example, consider a %@AB@%FAR%@AE@% procedure that has one argument of type %@AB@%int%@AE@% (two bytes). The displacement of the parameter is %@NL@% %@NL@% %@AS@% Argument's displacement = size of far return address + 2 %@AS@% = 4 + 2 %@AS@% = 6%@AE@%%@NL@% %@NL@% The argument can thus be loaded into BP with the following instruction: %@NL@% %@NL@% %@AS@% mov bx,[bp+6]%@AE@%%@NL@% %@NL@% Once you determine the displacement of each parameter, you can use %@AB@%EQU %@AB@%%@AE@%directives or structures to refer to the parameter with a single identifier name in your assembly source code. For example, you can use a more readable name to reference the parameter at %@AS@% BP+6 %@AE@% if you put the following statement at the beginning of the assembly source file: %@NL@% %@NL@% %@AS@% Arg1 EQU [bp+6]%@AE@%%@NL@% %@NL@% You can then refer to the first parameter in your source as %@AS@% Arg1 %@AE@% in any instruction. Use of this feature is optional. %@NL@% %@NL@% For far (segmented) addresses, Microsoft C pushes the segment address before pushing the offset address. When pushing arguments larger than two bytes, high-order words are always pushed before low-order words, and parameters larger than two bytes are stored on the stack in most-significant, least-significant order. %@NL@% %@NL@% This standard for pushing segment addresses before pushing offset addresses facilitates the use of the assembly-language instructions %@AB@%LDS%@AE@% (load data segment) and %@AB@%LES%@AE@% (load extra segment). %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00120037 @%%@AB@%12.8.7 Returning a Value%@AE@%%@EH@%%@NL@% %@NL@% Your assembly-language procedure can return a value to a C calling program. All return values of four bytes or less are passed in registers. Far pointers to return values larger than four bytes are returned in the DX and AX registers. The DX register contains the segment address; the AX register contains the offset relative to the segment contained in DX. %@NL@% %@NL@% Table 12.3 shows the register conventions for returning simple data types to a C program. %@NL@% %@NL@% %@AB@%Table %@AB@%12.3 Register Conventions for Simple Return Values%@AE@%%@AE@% %@TH: 13 641 02 34 42 @%Data Type Registers%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%char%@AE@% AL%@AB@%int%@AE@%, %@AB@%short%@AE@%, %@AB@%_near *%@AE@% AX%@AB@%long%@AE@%, %@AB@%_far *%@AE@% High-order portion (or segment address) in DX; low-order portion (or offset address) in AX%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@TE: 13 641 02 34 42 @% %@AU@% Your procedures can return structures.%@AE@% %@NL@% %@NL@% To return a structure from a procedure that uses the C calling convention, you must copy the structure to a global variable, then return a pointer to that variable in the AX register (DX:AX, if you compiled in compact, large, or huge model). %@NL@% %@NL@% Procedures that use the FORTRAN/Pascal calling convention return structures similarly, with the following exceptions: %@NL@% %@NL@% %@NL@% ■ The calling program allocates space for the return value on the stack.%@NL@% %@NL@% ■ The calling program passes a pointer to the location where the return value is to be placed in a hidden parameter.%@NL@% %@NL@% ■ Instead of copying your structure into a global data item, you copy it into the location pointed to by the hidden parameter.%@NL@% %@NL@% ■ You must still return the pointer to that location in the AX register (or DX:AX for far data models).%@NL@% %@NL@% %@NL@% %@AU@% You can return floating-point values from your procedures.%@AE@% %@NL@% %@NL@% Procedures that use the C calling convention and return type %@AB@%float%@AE@% or type %@AB@%double%@AE@% must always copy their return values into the global variable %@AB@%fac%@AE@%. To return floating-point values from procedures declared with the FORTRAN/Pascal calling convention, you must return the result on the stack, just as you would a structure. %@NL@% %@NL@% To return a value of type %@AB@%long double%@AE@%, you must place the value on the %@AB@%NDP%@AE@%(80%@AI@%x%@AE@%87) stack using the %@AB@%FLD %@AE@%instruction. The C run-time math routines guarantee that the only value on the %@AB@%NDP %@AE@%stack is a return value; your routines must observe the same rule. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00120038 @%%@AB@%12.8.8 Exiting the Procedure%@AE@%%@EH@%%@NL@% %@NL@% Before you exit your assembly-language procedure, you must perform several steps to restore the calling program's environment. Some of these steps are dependent on actions you took in allocating space for local variables and preserving registers. %@NL@% %@NL@% You must follow these steps (if appropriate to your procedure) in the order shown: %@NL@% %@NL@% %@NL@% 1. If you saved any of the registers SS, DS, SI, or DI, they must be popped off the stack in the reverse order from which they were saved. If you pop these registers in any other order, your program will behave incorrectly.%@NL@% %@NL@% 2. If you allocated local data space at the beginning of the procedure, you must restore SP with the instruction %@AS@% mov s %@AE@% p %@AS@% ,bp%@AE@%.%@NL@% %@NL@% 3. Restore BP with the instruction %@AS@% pop bp%@AE@%. This step is always necessary.%@NL@% %@NL@% 4. Return to the calling program by issuing the %@AB@%ret%@AE@% instruction.%@NL@% %@NL@% %@NL@% The following example shows the simplest possible entry and exit sequence. In the entry sequence, no registers are saved and no local data space is allocated. %@NL@% %@NL@% %@AS@% push bp %@AS@% mov bp,sp ; Set up the new stack frame. %@AS@% . %@AS@% . %@AS@% . %@AS@% pop bp ; Restore the caller's stack frame. %@AS@% ret%@AE@%%@NL@% %@NL@% The following example shows an entry and exit sequence for a procedure that saves SI and DI and allocates local data space on the stack. %@NL@% %@NL@% %@AS@% push bp %@AS@% mov bp,sp ; Establish local stack frame. %@AS@% sub sp,4 ; Allocate space for local data. %@AS@% push si ; Preserve the SI and DI registers. %@AS@% push di %@AS@% . %@AS@% . %@AS@% . %@AS@% pop di ; Pop saved registers. %@AS@% pop si %@AS@% mov sp,bp ; Free local data space. %@AS@% pop bp ; Restore old stack frame. %@AS@% ret%@AE@%%@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00120039 @%%@AB@%12.9 Handling Data in Mixed-Language Programming%@AE@%%@EH@%%@NL@% %@NL@% This section contains detailed information about naming and calling conventions in a mixed-language program. It also describes how various languages represent strings, numerical data, arrays, and logical data. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00120040 @%%@AB@%12.9.1 Default Naming and Calling Conventions%@AE@%%@EH@%%@NL@% %@NL@% Each language has its own default naming and calling conventions (Table 12.4). %@NL@% %@NL@% %@AB@%Table 12.4 %@AB@%Default Naming and Calling Conventions%@AE@%%@AE@% %@TH: 15 723 03 10 19 19 28 @% Calling Naming Parameter Language Convention Convention Passing%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%BASIC FORTRAN/Pascal Case insensitive Near referenceC C Case sensitive Value (scalar variables), reference (arrays and pointers)FORTRAN FORTRAN/Pascal Case insensitive ReferencePascal FORTRAN/Pascal Case insensitive Value%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@TE: 15 723 03 10 19 19 28 @% %@NL@% %@4@%%@AB@%BASIC Conventions%@AE@%%@EH@%%@NL@% %@NL@% When you call BASIC routines from C, you must pass all arguments by near reference (near pointer). You can modify the conventions observed by BASIC routines that interface with C functions by using the %@AB@%DECLARE%@AE@%, %@AB@%BYVAL%@AE@%, %@AB@%SEG%@AE@%, and %@AB@%CALLS%@AE@% keywords. For more information on these keywords, see the %@AI@%Microsoft BASIC Language Reference%@AE@% or the %@AI@%Microsoft BASIC Programmer's %@AI@%Guide%@AE@%. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%FORTRAN Conventions%@AE@%%@EH@%%@NL@% %@NL@% You can modify the conventions observed by FORTRAN routines that call C functions by using the %@AB@%INTERFACE%@AE@%, %@AB@%VALUE%@AE@%, %@AB@%PASCAL%@AE@%, and %@AB@%C%@AE@% keywords. For more information about the use of these keywords, see the%@AI@% Microsoft FORTRAN%@AE@% %@AI@%Reference.%@AE@% %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Pascal Conventions%@AE@%%@EH@%%@NL@% %@NL@% You can modify the conventions observed by Pascal routines that interface with C functions by using the %@AB@%VAR%@AE@%, %@AB@%CONST%@AE@%, %@AB@%ADR%@AE@%, %@AB@%VARS%@AE@%, %@AB@%CONSTS%@AE@%, %@AB@%ADRS%@AE@%, and %@AB@%C%@AE@% keywords. For more information about the use of these keywords, see the %@AI@%Microsoft Pascal Compiler User's Guide.%@AE@% %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00120041 @%%@AB@%12.9.2 Numeric Data Representation%@AE@%%@EH@%%@NL@% %@NL@% Table 12.5 shows how to declare numeric variables of similar type in different languages. %@NL@% %@NL@% %@AB@%Table 12.5 %@AB@%Equivalent Numeric Data Types%@AE@%%@AE@% %@TH: 34 1857 02 14 20 23 19 @%BASIC C FORTRAN Pascal%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AI@%x%@AE@%%@AB@%%%@AE@% %@AB@%short%@AE@% %@AB@%INTEGER*2 %@AE@% %@AB@%INTEGER2%@AE@%%@AB@%INTEGER%@AE@% %@AB@%int%@AE@% --- %@AB@%INTEGER %@AE@% (default)--- %@AB@%unsigned short%@AE@%%@AU@%(1)%@AE@% --- %@AB@%WORD%@AE@%--- %@AB@%unsigned%@AE@% --- ---%@AI@%x%@AE@%%@AB@%&%@AE@% %@AB@%long%@AE@% %@AB@%INTEGER*4%@AE@% %@AB@%INTEGER4%@AE@%%@AB@%LONG%@AE@% --- %@AB@%INTEGER%@AE@% (default) ------ %@AB@%unsigned long%@AE@%%@AU@%(1)%@AE@% --- ---%@AI@%x%@AE@%%@AB@%!%@AE@% %@AB@%float%@AE@% %@AB@%REAL*4%@AE@% %@AB@%REAL4%@AE@%%@AI@%x%@AE@% (default) --- %@AB@%REAL%@AE@% %@AB@%REAL%@AE@% (default)%@AB@%SINGLE%@AE@% --- --- ---%@AI@%x%@AE@%%@AB@%#%@AE@% %@AB@%double%@AE@% %@AB@%REAL*8%@AE@% %@AB@%REAL8%@AE@%%@AB@%DOUBLE%@AE@% --- %@AB@%DOUBLE %@AE@% --- %@AB@%PRECISION%@AE@% --- %@AB@%long double%@AE@% %@AB@%REAL*16%@AE@% %@AB@%REAL16%@AE@%--- %@AB@%unsigned char%@AE@% %@AB@%CHARACTER*1%@AE@%%@AU@%(2)%@AE@% %@AB@%CHAR%@AE@%%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@TE: 34 1857 02 14 20 23 19 @% %@AU@%(1) %@AE@% Types %@AB@%unsigned short%@AE@% and %@AB@%unsigned long%@AE@% are not supported by BASIC or FORTRAN. Type %@AB@%unsigned long %@AE@%is not supported by Pascal. A signed integral type can be substituted, but the maximum range will be less. %@AU@%(2) %@AE@% The FORTRAN type %@AB@%CHARACTER*1 %@AE@%is not the same as %@AB@%LOGICAL%@AE@%. %@NL@% %@NL@% %@NL@% The FORTRAN types %@AB@%COMPLEX*8%@AE@% and %@AB@%COMPLEX*16%@AE@% are not implemented in C but can be represented with structures. %@NL@% %@NL@% The FORTRAN types %@AB@%LOGICAL*2%@AE@% and %@AB@%LOGICAL*4%@AE@% are not implemented in C. %@AB@%LOGICAL*2%@AE@% is stored as a one-byte Boolean indicator followed by an unused byte; %@AB@%LOGICAL*4%@AE@% is stored as a one-byte Boolean indicator followed by three unused bytes. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00120042 @%%@AB@%12.9.3 Strings%@AE@%%@EH@%%@NL@% %@NL@% Each language implements strings differently. This section describes the ways that strings are implemented in Microsoft languages. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%C String Format%@AE@%%@EH@%%@NL@% %@NL@% C stores strings as arrays of bytes and uses a null character ( %@AS@% '\0' %@AE@% ) as an end-of-string delimiter. For example, consider the following string: %@NL@% %@NL@% %@AS@% char c_string[] = "C text string";%@AE@%%@NL@% %@NL@% This string is represented in memory as follows: %@NL@% %@NL@% %@AU@%(This figure may be found in the printed book.)%@AE@%%@NL@% %@NL@% Because %@AS@% c_string %@AE@% is an array like any other, C passes it by reference in function calls. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%BASIC String Format%@AE@%%@EH@%%@NL@% %@NL@% BASIC stores strings as four-byte descriptors pointing to the actual string data. The format of the descriptor is as follows: %@NL@% %@NL@% %@AU@%(This figure may be found in the printed book.)%@AE@%%@NL@% %@NL@% The first field of the string descriptor contains an integer indicating the length (in bytes) of the string. The second field contains the address of the string in the default data segment. %@NL@% %@NL@% Do not attempt to alter the length of BASIC strings, because they are managed by BASIC string-space management routines. You cannot count on a particular string remaining at a given offset during the execution of a BASIC program because the BASIC string-space management routines allocate strings to different areas of memory depending on program requirements. %@NL@% %@NL@% The format of the string at DS:%@AI@%Address%@AE@% is a simple array of characters. The string is exactly the length indicated in the descriptor. %@NL@% %@NL@% %@AU@% To pass a BASIC string to C, append a null character.%@AE@% %@NL@% %@NL@% Because C needs the null character to delimit the end of the string, you should append %@AS@% chr$( 0 ) %@AE@% to your BASIC string before passing it to your C function. For example, %@NL@% %@NL@% %@AS@% A$ = "I am a BASIC string" %@AS@% A$ = A$ + chr$( 0 ) %@AS@% %@AS@% CALL CFunc( SADD(A$) )%@AE@%%@NL@% %@NL@% Note that the BASIC call is made by near reference using the %@AB@%SADD %@AE@%keyword. %@NL@% %@NL@% %@AU@% Use a string descriptor to pass a C string to BASIC.%@AE@% %@NL@% %@NL@% To pass a C string to BASIC, create a structure for the string descriptor. For example, %@NL@% %@NL@% %@AS@% char c_string[] = "C String Data"; %@AS@% %@AS@% struct tagBASICStringDes %@AS@% { %@AS@% char * sd_addr; %@AS@% int sd_len; %@AS@% } str_des; %@AS@% %@AS@% str_des.sd_addr = c_string; %@AS@% str_des.sd_len = strlen( c_string ); %@AS@% %@AS@% BASICFunction( &str_des );%@AE@%%@NL@% %@NL@% %@NL@% %@4@%%@AB@%FORTRAN String Format%@AE@%%@EH@%%@NL@% %@NL@% FORTRAN stores strings as a series of bytes at a fixed location in memory. There is no delimiter at the end of the string. Consider the string declared as follows: %@NL@% %@NL@% %@AS@% STR = 'FORTRAN STRING'%@AE@%%@NL@% %@NL@% The string is stored in memory as follows: %@NL@% %@NL@% %@AU@%(This figure may be found in the printed book.)%@AE@%%@NL@% %@NL@% FORTRAN passes strings by reference, as it does all other data. %@NL@% %@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% NOTE %@AI@%FORTRAN's variable length strings cannot be used in mixed-language %@AI@%programming because the temporary variable used to communicate string length %@AI@%is not accessible to other languages.%@AE@%%@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@%%@NL@% %@NL@% To pass a C string to FORTRAN (or Pascal), pass the variable by reference as you normally would. In your FORTRAN or Pascal routine, you must specify the length of the string; strings that are passed as arguments from one language to another must be of fixed length. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Pascal String Format%@AE@%%@EH@%%@NL@% %@NL@% Pascal represents strings as fixed-length arrays of %@AB@%CHAR%@AE@% or as strings with a length byte followed by the string data. %@NL@% %@NL@% %@AU@% To pass a fixed-length string to C, append a null character.%@AE@% %@NL@% %@NL@% To pass a fixed-length string to a C function, use the concatenation operator (%@AB@%*%@AE@%) to append a null character. Then pass the string to the C function by reference (by declaring the string as %@AB@%CONST%@AE@%, %@AB@%CONSTS%@AE@%, %@AB@%VAR%@AE@%, or %@AB@%VARS%@AE@%). For example, %@NL@% %@NL@% %@AS@% PROGRAM PasStr( input, output ); %@AS@% type %@AS@% stype15 = string(15); { fixed-length } %@AS@% var %@AS@% str : stype15; %@AS@% %@AS@% PROCEDURE PasStrToC( VAR s1 : stype15 ) [C]; EXTERN; %@AS@% %@AS@% BEGIN %@AS@% str := 'Pass this to C' * chr( 0 ); %@AS@% PasStrToC( str ); %@AS@% END.%@AE@%%@NL@% %@NL@% A more flexible way to pass Pascal strings to C functions is to declare them as type %@AB@%ADRMEM%@AE@% or %@AB@%ADSMEM%@AE@%, then pass the address of the string. For example, %@NL@% %@NL@% %@AS@% PROCEDURE PasStrToC( s1adr : ADRMEM ) [C]; EXTERN;%@AE@%%@NL@% %@NL@% Then you can call the C function with this code: %@NL@% %@NL@% %@AS@% PasStrToC( ADR str );%@AE@%%@NL@% %@NL@% Using this method, you can pass strings of different lengths to C functions. %@NL@% %@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% NOTE %@AI@%The Pascal type %@AI@%LSTRING %@AE@%%@AI@%is not compatible with C; you can pass a string %@AI@%declared as LSTRING %@AE@%%@AI@%by first assigning it to another variable of type %@AI@%STRING%@AE@%%@AI@%, then passing that variable.%@AE@%%@AE@%%@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@%%@NL@% %@NL@% Whenever you pass a variable of type %@AB@%STRING%@AE@% or type %@AB@%LSTRING%@AE@% by value, Pascal pushes the whole string onto the stack and passes the length of the string as another parameter. C cannot access strings passed in this manner. %@NL@% %@NL@% %@AU@% Before passing a string from C to Pascal, make sure enough space is %@AU@%allocated.%@AE@% %@NL@% %@NL@% Passing a string from a C function to a Pascal function or procedure is identical to passing a string from a C function to a FORTRAN routine. The only provision you must make is to specify the length of the string to your Pascal function. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00120043 @%%@AB@%12.9.4 Arrays%@AE@%%@EH@%%@NL@% %@NL@% When you use an array in a program written in a single language, the method for array handling is consistent. When you mix languages, you need to be aware of the differences between array-handling techniques in various languages. %@NL@% %@NL@% Unlike most Microsoft languages, BASIC keeps an array descriptor, which is similar to the BASIC string descriptor discussed in Section 12.9.3, "Strings." This array descriptor is necessary because BASIC handles memory allocation for arrays dynamically (at run time). Dynamic allocation requires BASIC to shift arrays in memory. %@NL@% %@NL@% %@AU@% To pass a BASIC array to a C function, use the %@AE@%%@AB@%VARPTR%@AE@% and %@AB@%VARSEG %@AE@%keywords. %@NL@% %@NL@% The %@AB@%VARPTR %@AE@%and %@AB@%VARSEG %@AE@%keywords obtain the address of the first element of the array and its segment, respectively. The example below shows how to call a C function with a near reference and a far reference to an array: %@NL@% %@NL@% %@AS@% DIM ARRAY%( 20 ) %@AS@% DECLARE CNearArray CDECL( BYVAL Addr AS INTEGER ) %@AS@% DECLARE CFarArray CDECL( BYVAL Addr AS INTEGER, BYVAL Seg AS INTEGER ) %@AS@% . %@AS@% . %@AS@% . %@AS@% CALL CNearArray( VARPTR( ARRAY%(0) ) ) %@AS@% CALL CFarArray( VARPTR( ARRAY%(0) ), VARSEG( ARRAY%(0) ) )%@AE@%%@NL@% %@NL@% The C functions receiving %@AS@% ARRAY %@AE@% can be declared as follows: %@NL@% %@NL@% %@AS@% _cdecl CNearArray( int * array ); %@AS@% _cdecl CFarArray( int far * array );%@AE@%%@NL@% %@NL@% The routine that receives the array must not make a call back to BASIC. If it does, the location of the array data could change, and the address that was passed to the routine would become meaningless. %@NL@% %@NL@% If you only need to pass one member of the array from BASIC to your C function, you can pass it by value as follows: %@NL@% %@NL@% %@AS@% CALL CFunc( ARRAY%(8) )%@AE@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00120044 @%%@AB@%12.9.5 Array Declaration and Indexing%@AE@%%@EH@%%@NL@% %@NL@% Each language varies in the way that arrays are declared and indexed. Array indexing is a source-level consideration and involves no transformation of data. There are two differences in the way elements are indexed by each language: %@NL@% %@NL@% %@NL@% 1. The value of the lower array bound is different among Microsoft languages.%@NL@% %@NL@% %@STUB@% By default, FORTRAN indexes the first element of an array as 1. BASIC and C index it as 0. Pascal lets you begin indexing at any integer value. Recent versions of BASIC and FORTRAN also give you the option of specifying lower bounds at any integer value.%@NL@% %@NL@% 2. Some languages vary subscripts in row-major order; others vary subscripts in column-major order.%@NL@% %@NL@% %@STUB@% This issue only affects arrays with more than one dimension. With row-major order (used by C and Pascal), the rightmost dimension changes first. With column-major order (used by FORTRAN, and BASIC by default), the leftmost dimension changes first. Thus, in C, the first four elements of an array declared as %@AS@% X[3][3] %@AE@% are%@NL@% %@NL@% %@AS@% X[0][0] X[0][1] X[0][2] X[1][0]%@AE@%%@NL@% %@NL@% %@STUB@% In FORTRAN, the four elements are%@NL@% %@NL@% %@AS@% X(1,1) X(2,1) X(3,1) X(1,2)%@AE@%%@NL@% %@NL@% %@STUB@% The C and FORTRAN arrays shown above illustrate the difference between row-major and column-major order as well as the difference in the assumed lower bound between C and FORTRAN. Table 12.6 shows equivalences for array declarations in each language. In this table, %@AI@%r%@AE@% is the number of elements of the row dimension (which changes most slowly), and %@AI@%c%@AE@% is the number of elements of the column dimension (which changes most quickly).%@NL@% %@AB@%Table 12.6 %@AB@%Equivalent Array Declarations%@AE@%%@AE@% %@TH: 14 951 02 10 33 33 @%Language Array Declaration Notes%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%BASIC %@AB@%DIM%@AE@% %@AI@%x%@AE@%(%@AI@%r%@AE@%-1, %@AI@%c%@AE@%-1) With default lower bounds of 0C type %@AI@%x%@AE@%[%@AI@%r%@AE@%][%@AI@%c%@AE@%]%@AB@%%@AE@% When passed by reference %@AB@%struct %@AE@%{ %@AI@%type%@AE@% %@AI@%x%@AE@%[%@AI@%r%@AE@%][%@AI@%c%@AE@%]; } %@AI@%x%@AE@% When passed by valueFORTRAN %@AI@%type x%@AE@%(%@AI@%c%@AE@%, %@AI@%r%@AE@%) With default lower bounds of 1Pascal %@AI@%x%@AE@% : %@AB@%ARRAY%@AE@% [%@AI@%a%@AE@%..%@AI@%a%@AE@%+%@AI@%r%@AE@%-1, %@AI@%b%@AE@%..%@AI@%b%@AE@%+%@AI@%c%@AE@%-1]%@AB@% %@AE@% %@AB@%OF%@AE@% %@AI@%type%@AE@%%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@TE: 14 951 02 10 33 33 @% %@NL@% %@NL@% The order of indexing extends to any number of dimensions you declare. For example, the C declaration %@NL@% %@NL@% %@AS@% int arr1[2][10][15][20];%@AE@%%@NL@% %@NL@% is equivalent to the FORTRAN declaration %@NL@% %@NL@% %@AS@% INTEGER*2 ARR1( 20, 15, 10, 2 )%@AE@%%@NL@% %@NL@% The constants used in a C array declaration represent dimensions, not upper bounds as they do in other languages. Therefore, the last element in the C array declared as %@AS@% int arr[5][5] %@AE@% is %@AS@% arr[4][4]%@AE@%, not %@AS@% arr[5][5]%@AE@%. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00120045 @%%@AB@%12.9.6 Structures, Records, and User-Defined Types%@AE@%%@EH@%%@NL@% %@NL@% The C %@AB@%struct %@AE@%type, the BASIC user-defined type, the FORTRAN record (defined with the %@AB@%STRUCTURE %@AE@%keyword), and the Pascal %@AB@%record %@AE@%type are equivalent. Therefore, these data types can be passed between C, FORTRAN, Pascal, and BASIC. %@NL@% %@NL@% These types can be affected by the storage method. By default, C, FORTRAN, and Pascal use word alignment for types shorter than one word (type %@AB@%char %@AE@%and %@AB@%unsigned char%@AE@%). This storage method specifies that occasional bytes can be inserted as padding so that word and double-word objects start on an even boundary. (In addition, all nested structures and records start on a word boundary.) %@NL@% %@NL@% If you are passing a structure or record across a mixed-language interface, your calling routine and called routine must agree on the storage method and parameter-passing convention. Otherwise, data will not be interpreted correctly. %@NL@% %@NL@% Because Pascal, FORTRAN, and C use the same storage method for structures and records, you can interchange data between routines without taking any special precautions unless you modify the storage method. Make sure the storage methods agree before interchanging data between C, FORTRAN, and Pascal. %@NL@% %@NL@% BASIC packs user-defined types, so your C function must also pack structures (using the /Zp command-line option or the %@AB@%pack%@AE@% pragma) to agree. %@NL@% %@NL@% You can pass structures as parameters by value or by reference. Both the calling program and the called program must agree on the parameter-passing convention. See Section 12.2.3, "Parameter-Passing Requirement," for more information about the language you are using. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00120046 @%%@AB@%12.9.7 External Data%@AE@%%@EH@%%@NL@% %@NL@% External data refers to data that is both static and public; that is, the data is stored in a set place in memory as opposed to being allocated on the stack, and the data is visible to other modules. %@NL@% %@NL@% External data can be defined in C, Pascal, and assembly language. Note that a data definition is distinct from an external declaration. A data definition causes a compiler to create a data object; an external declaration informs a compiler that the object is to be found in another module. FORTRAN can only define external data in COMMON blocks. (See Section 12.9.9, "Common Blocks," for more information about sharing external data with FORTRAN programs.) %@NL@% %@NL@% There are three requirements for programs that share external data between languages: %@NL@% %@NL@% %@NL@% 1. One of the modules must define the data.%@NL@% %@NL@% %@STUB@% You can define a static data object in a C module by defining a data object outside all functions. (If you use the %@AB@%static%@AE@% keyword in C, however, the data object will not be made public.)%@NL@% %@NL@% 2. The other modules that will access the data must declare the data as external.%@NL@% %@NL@% %@STUB@% In C, you can declare data as external by using an %@AB@%extern%@AE@% declaration, similar to the %@AB@%extern%@AE@% declaration for functions. In FORTRAN and Pascal, you can declare data as external by adding the %@AB@%EXTERN %@AB@% %@AE@%attribute to the data declaration.%@NL@% %@NL@% 3. Resolve naming-convention differences.%@NL@% %@NL@% %@STUB@% In C, you can adopt the FORTRAN/Pascal naming convention by applying %@AB@%_fortran %@AE@%or %@AB@%_pascal %@AE@%to the data declaration. In FORTRAN and Pascal, you can adopt the C naming convention by applying the %@AB@%C %@AE@%attribute to the data declaration.%@NL@% %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00120047 @%%@AB@%12.9.8 Pointers and Address Variables%@AE@%%@EH@%%@NL@% %@NL@% Rather than passing data directly, you may want to pass the address of a piece of data. Passing the address amounts to passing the data by reference. In some cases, such as in BASIC arrays, there is no other way to pass a data item as a parameter. %@NL@% %@NL@% C programs always pass array variables by address. All other types are passed by value unless you use the address-of (%@AB@%&%@AE@%) operator to obtain the address. %@NL@% %@NL@% The Pascal %@AB@%ADR %@AE@%and %@AB@%ADS %@AE@%types are equivalent to near and far pointers, respectively, in C. You can pass %@AB@%ADR %@AE@%and %@AB@%ADS %@AE@%variables as %@AB@%ADRMEM %@AE@%or %@AB@%ADSMEM%@AE@%. BASIC and FORTRAN do not have formal address types. However, they do provide ways for storing and passing addresses. %@NL@% %@NL@% BASIC programs can access a variable's segment address with the %@AB@%VARSEG %@AB@%%@AE@%function and its offset address with the %@AB@%VARPTR%@AE@% function. The values returned by these intrinsic functions should then be passed or stored as ordinary integer variables. If you pass them to another language, pass by value. Otherwise you will be attempting to pass the address of the address, rather than the address itself. %@NL@% %@NL@% To pass a near address, pass only the offset; if you need to pass a far address, you may have to pass the segment and the offset separately. Pass the segment address first, unless %@AB@%CDECL %@AE@%is in effect. %@NL@% %@NL@% FORTRAN programs can determine near and far addresses with the %@AB@%LOC %@AE@%and %@AB@%LOCFAR %@AE@%functions. Store the result of the %@AB@%LOC %@AE@%function as %@AB@%INTEGER*2 %@AE@%and the result of the %@AB@%LOCFAR %@AE@%function as %@AB@%INTEGER*4%@AE@%. %@NL@% %@NL@% As with BASIC, if you pass the result of %@AB@%LOC %@AE@%or %@AB@%LOCFAR %@AE@%to another language, be sure to pass by value. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00120048 @%%@AB@%12.9.9 Common Blocks%@AE@%%@EH@%%@NL@% %@NL@% You can pass individual members of a FORTRAN or BASIC common block in an argument list, just as you can any data item. However, you can also give a different language module access to the entire common block at once. %@NL@% %@NL@% C modules can reference the items of a common block by first declaring a structure with fields that correspond to the common-block variables. Having defined a structure with the appropriate fields, the C module must then connect with the common block itself. The next two sections present methods for gaining access to common blocks. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Passing the Address of a Common Block%@AE@%%@EH@%%@NL@% %@NL@% To pass the address of a common block, simply pass the address of the first variable in the block. (In other words, pass the first variable by reference.) The receiving C module should expect to receive a structure by reference. %@NL@% %@NL@% In the example below, the C function %@AS@% initcb %@AE@% receives the address of the variable %@AS@% N%@AE@%, which it considers to be a pointer to a structure with three fields: %@NL@% %@NL@% %@AS@% C FORTRAN SOURCE CODE %@AS@% C %@AS@% COMMON /CBLOCK/N, X, Y %@AS@% INTEGER*2 N %@AS@% REAL*8 X, Y %@AS@% . %@AS@% . %@AS@% . %@AS@% CALL INITCB( N ) %@AS@% %@AS@% %@AS@% /* C source code */ %@AS@% %@AS@% %@AS@% /* Explicitly set structure packing to word-alignment */ %@AS@% #pragma pack( 2 ); %@AS@% %@AS@% struct block_type %@AS@% { %@AS@% int n; %@AS@% double x; %@AS@% double y; %@AS@% }; %@AS@% %@AS@% initcb( struct block_type * block_hed ) %@AS@% { %@AS@% block_hed-n = 1; %@AS@% block_hed-x = 10.0; %@AS@% block_hed-y = 20.0; %@AS@% }%@AE@%%@NL@% %@NL@% %@NL@% %@4@%%@AB@%Accessing Common Blocks Directly%@AE@%%@EH@%%@NL@% %@NL@% You can access FORTRAN common blocks directly by defining a structure with the appropriate fields and then using the methods described in Section 12.9.7, "External Data." Here is an example of accessing common blocks directly: %@NL@% %@NL@% %@AS@% struct block_type %@AS@% { %@AS@% int n; %@AS@% double x; %@AS@% double y; %@AS@% }; %@AS@% %@AS@% extern struct block_type fortran cblock;%@AE@%%@NL@% %@NL@% %@AU@% You cannot access common blocks directly using BASIC common blocks.%@AE@% %@NL@% %@NL@% Note that the technique of accessing common blocks directly works with FORTRAN common blocks, but not with BASIC common blocks. If your C module must work with both FORTRAN and BASIC common blocks, pass the address of the common block as a parameter to the function. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00120049 @%%@AB@%12.9.10 Using a Varying Number of Parameters%@AE@%%@EH@%%@NL@% %@NL@% Some C functions (for example %@AB@%printf%@AE@%) accept a variable number of parameters. To call such a function from another language, you need to suppress the type-checking that normally forces a call to be made with a fixed number of parameters. In BASIC, you can remove this type-checking by omitting a parameter list from the %@AB@%DECLARE %@AE@%statement. In FORTRAN or Pascal, you can call routines with a variable number of parameters by including the %@AB@%VARYING %@AE@%attribute in your interface to the routine, along with the %@AB@%C %@AB@%%@AE@%attribute. You must use the %@AB@%C%@AE@% attribute because a variable number of parameters is feasible only with the C calling convention. %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@CR:C6A00130001 @%%@1@%%@AB@%Chapter 13 Writing Portable Programs%@AE@%%@EH@%%@NL@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@NL@% Because C compilers exist on a variety of computers, some C applications developed for one computer system can be ported to other systems. However, some aspects of language behavior depend on how a particular C compiler is implemented and how a specific computer operates. Therefore, when designing a program to be ported to another system, it is important that you examine programming assumptions. %@NL@% %@NL@% This chapter describes programming assumptions that can affect writing portable programs. %@NL@% %@NL@% The American National Standards Institute Standard for the C Language (the ANSI Standard) details every instance where language behavior is defined by the implementation. Appendix C summarizes implementation-defined behavior for Microsoft C. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00130002 @%%@AB@%13.1 Assumptions about Hardware%@AE@%%@EH@%%@NL@% %@NL@% To make C programs portable, you must examine two aspects of your code: hardware assumptions and compiler dependency. This section deals with hardware assumptions. Section 13.2, "Assumptions about the Compiler," deals with compiler dependency. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00130003 @%%@AB@%13.1.1 Size of Basic Types%@AE@%%@EH@%%@NL@% %@NL@% In C, the size of basic types (%@AB@%char%@AE@%, %@AB@%signed%@AE@% %@AB@%int%@AE@%, %@AB@%unsigned int%@AE@%, %@AB@%float%@AE@%, %@AB@%double%@AE@%, and %@AB@%long double%@AE@%) is implementation-defined, so relying on a particular data type to be a given size reduces the portability of a program. %@NL@% %@NL@% %@AU@% Don't make assumptions about the size of data types.%@AE@% %@NL@% %@NL@% Because the size of basic types is left to the implementation, do not make assumptions about the size or alignment of data types within aggregate types. Use only the %@AB@%sizeof %@AE@%operator to determine the size or amount of storage required for a variable or a type. %@NL@% %@NL@% Following are some rules governing the size of data types. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Type char%@AE@%%@EH@%%@NL@% %@NL@% Type %@AB@%char%@AE@% is the smallest of the basic types, but it must be large enough to hold any of the characters in the implementation's basic character set. Normally, variables of type %@AB@%char%@AE@% are one byte. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Type int and Type short int%@AE@%%@EH@%%@NL@% %@NL@% Type %@AB@%int%@AE@% and type %@AB@%short int%@AE@% often correspond to the register size of the target machine. Both %@AB@%int%@AE@% and %@AB@%short%@AE@% are greater than or equal to the size of type %@AB@%char%@AE@% but less than or equal to the size of type %@AB@%long%@AE@%. %@NL@% %@NL@% If you assume that type %@AB@%int%@AE@% is a certain size, your code may not be portable because %@NL@% %@NL@% %@NL@% ■ An %@AB@%int%@AE@% can be defined as a 16-bit (two-byte) or a 32-bit quantity.%@NL@% %@NL@% ■ An %@AB@%int%@AE@% is not always large enough to hold array indexes. For large arrays, you must use %@AB@%unsigned int%@AE@%; for extremely large arrays, use %@AB@%long%@AE@%. To be certain your code is portable, define your array indexes as type %@AB@%size_t%@AE@%. You may not know, before porting your code, the maximum value to expect an array index of type %@AB@%int%@AE@% to hold. The file LIMITS.H contains manifest constants, listed below, for the maximum and minimum values of each basic integral type.%@NL@% %@NL@% %@NL@% %@AB@%Constant%@AE@% %@AB@%Value%@AE@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@AB@%CHAR_BIT%@AE@% Number of bits in a variable of type %@AB@%%@AE@% %@AB@%char%@AE@% %@AB@%CHAR_MIN%@AE@% Minimum value a variable of type %@AB@%char%@AE@% can hold %@AB@%CHAR_MAX%@AE@% Maximum value a variable of type %@AB@%char%@AE@% can hold %@AB@%SCHAR_MIN%@AE@% Minimum value a variable of type %@AB@%signed%@AE@% %@AB@%%@AE@% %@AB@%char%@AE@% can hold %@AB@%SCHAR_MAX%@AE@% Maximum value a variable of type %@AB@%signed%@AE@% %@AB@%%@AE@% %@AB@%char%@AE@% can hold %@AB@%UCHAR_MAX%@AE@% Maximum value a variable of type %@AB@%%@AE@% %@AB@%unsigned%@AE@% %@AB@%char%@AE@% can hold %@AB@%SHRT_MIN%@AE@% Minimum value a variable of type %@AB@%short%@AE@% can hold %@AB@%SHRT_MAX%@AE@% Maximum value a variable of type %@AB@%short%@AE@% can hold %@AB@%USHRT_MAX%@AE@% Maximum value a variable of type %@AB@%%@AE@% %@AB@%unsigned short%@AE@% can hold %@AB@%INT_MIN%@AE@% Minimum value a variable of type %@AB@%int%@AE@% can hold %@AB@%INT_MAX%@AE@% Maximum value a variable of type %@AB@%int%@AE@% can hold %@AB@%UINT_MAX%@AE@% Maximum value a variable of type %@AB@%%@AE@% %@AB@%unsigned int%@AE@% can hold %@AB@%LONG_MIN%@AE@% Minimum value a variable of type %@AB@%long%@AE@% can hold %@AB@%LONG_MAX%@AE@% Maximum value a variable of type %@AB@%long%@AE@% can hold %@AB@%ULONG_MAX%@AE@% Maximum value a variable of type %@AB@%%@AE@% %@AB@%unsigned long%@AE@% can hold %@NL@% %@4@%%@AB@%Type float, Type double, and Type long double%@AE@%%@EH@%%@NL@% %@NL@% Type %@AB@%float%@AE@% is the smallest of the basic floating-point types. Type %@AB@%double%@AE@% is usually larger than type %@AB@%float%@AE@%, and type %@AB@%long double%@AE@% is usually the largest of the floating-point types. You can make only these portability assumptions about floating-point types: %@NL@% %@NL@% %@NL@% ■ Any value that can be represented as type %@AB@%float%@AE@% can be represented as type %@AB@%double%@AE@% (type %@AB@%float%@AE@% is a subset of type %@AB@%double%@AE@%).%@NL@% %@NL@% ■ Any value that can be represented as type %@AB@%double%@AE@% can be represented as type %@AB@%long double%@AE@% (type %@AB@%double%@AE@% is a subset of type %@AB@%long double%@AE@%).%@NL@% %@NL@% %@NL@% The file FLOAT.H contains manifest constants, listed below, for the maximum and minimum values of each basic floating-point type. %@NL@% %@NL@% %@AB@%Constant%@AE@% %@AB@%Value%@AE@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@AB@%DBL_DIG%@AE@% Number of decimal digits of precision a variable of type %@AB@%double%@AE@% can hold %@AB@%DBL_MAX%@AE@% Maximum value a variable of type %@AB@%double%@AE@% can hold %@AB@%DBL_MAX_10_EXP%@AE@% Maximum value (base 10) the exponent of a variable of type %@AB@%double%@AE@% can hold %@AB@%DBL_MAX_EXP%@AE@% Maximum value (base 2) the exponent of a variable of type %@AB@%double%@AE@% can hold %@AB@%DBL_MIN%@AE@% Minimum positive value a variable of type %@AB@%double%@AE@% can hold %@AB@%DBL_MIN_10_EXP%@AE@% Minimum value (base 10) the exponent of a variable of type %@AB@%double%@AE@% can hold %@AB@%DBL_MIN_EXP%@AE@% Minimum value (base 2) the exponent of a variable of type %@AB@%double%@AE@% can hold %@AB@%FLT_DIG%@AE@% Number of decimal digits of precision a variable of type %@AB@%float%@AE@% can hold %@AB@%FLT_MAX%@AE@% Maximum value a variable of type %@AB@%float%@AE@% can hold %@AB@%FLT_MAX_10_EXP%@AE@% Maximum value (base 10) the exponent of a variable of type %@AB@%float%@AE@% can hold %@AB@%FLT_MAX_EXP%@AE@% Maximum value (base 2) the exponent of a variable of type %@AB@%float%@AE@% can hold %@AB@%FLT_MIN%@AE@% Minimum positive value a variable of type %@AB@%float%@AE@% can hold %@AB@%FLT_MIN_10_EXP%@AE@% Minimum value (base 10) the exponent of a variable of type %@AB@%float%@AE@% can hold %@AB@%FLT_MIN_EXP%@AE@% Minimum value (base 2) the exponent of a variable of type %@AB@%float%@AE@% can hold %@AB@%LDBL_DIG%@AE@% Number of decimal digits of precision a variable of type %@AB@%long double%@AE@% can hold %@AB@%LDBL_MAX%@AE@% Maximum value a variable of type %@AB@%long %@AE@% %@AB@%double%@AE@% can hold %@AB@%LDBL_MAX_10_EXP%@AE@% Maximum value (base 10) the exponent of a variable of type %@AB@%long double%@AE@% can hold %@AB@%LDBL_MAX_EXP%@AE@% Maximum value (base 2) the exponent of a variable of type %@AB@%long double%@AE@% can hold %@AB@%LDBL_MIN%@AE@% Minimum positive value a variable of type %@AB@%long double%@AE@% can hold %@AB@%LDBL_MIN_10_EXP%@AE@% Minimum value (base 10) the exponent of a variable of type %@AB@%long double%@AE@% can hold %@AB@%LDBL_MIN_EXP%@AE@% Minimum value (base 2) the exponent of a variable of type %@AB@%long double%@AE@% can hold %@NL@% %@4@%%@AB@%Microsoft C Type Sizes%@AE@%%@EH@%%@NL@% %@NL@% Table 13.1 summarizes the size of the basic types in Microsoft C. %@NL@% %@NL@% %@AB@%Table 13.1 %@AB@%Size of Basic Types in Microsoft C%@AE@%%@AE@% %@TH: 22 848 03 38 38 @% Number Type of Bytes%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%char%@AE@%, %@AB@%unsigned char%@AE@% 1%@AB@%int%@AE@%, %@AB@%short%@AE@%,%@AB@% unsigned int%@AE@%,%@AB@%%@AE@% 2%@AB@%unsigned short%@AE@% %@AB@%near pointer%@AE@% 2%@AB@%long%@AE@%, %@AB@%unsigned long%@AE@% 4%@AB@%far pointer%@AE@% 4%@AB@%float%@AE@% 4%@AB@%double%@AE@% 8%@AB@%long double%@AE@% 10%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@TE: 22 848 03 38 38 @% %@NL@% %@3@%%@CR:C6A00130004 @%%@AB@%13.1.2 Storage Order and Alignment%@AE@%%@EH@%%@NL@% %@NL@% The C language does not define any specific layout for the storage of data items relative to one another. The layout for storage of structure elements, or unions within a structure or union, is defined by the implementation. %@NL@% %@NL@% Some processors require that data longer than one byte be word-aligned (aligned to an even-byte address). Other processors, such as the 80%@AI@%x%@AE@%86 family, do not have such a restriction. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Structure Order and Alignment%@AE@%%@EH@%%@NL@% %@NL@% The example below illustrates how alignment can affect your program. In the example, a structure is cast to type %@AB@%long%@AE@% because the programmer knew the order in which a particular implementation stored data. %@NL@% %@NL@% %@AS@% /* Nonportable code */ %@AS@% struct time %@AS@% { %@AS@% char hour; /* 0 < hour < 24 -- fits in a char */ %@AS@% char minute; /* 0 < minute < 60 -- fits in a char */ %@AS@% char second; /* 0 < second < 60 -- fits in a char */ %@AS@% }; %@AS@% %@AS@% . %@AS@% . %@AS@% . %@AS@% struct time now, alarm_time; %@AS@% . %@AS@% . %@AS@% . %@AS@% if ( (long)now >= (long)alarm_time ) %@AS@% { %@AS@% /* sound an alarm */ %@AS@% }%@AE@%%@NL@% %@NL@% The preceding code makes these nonportable assumptions: %@NL@% %@NL@% %@NL@% ■ The data for %@AS@% hour %@AE@% will be stored in a higher order position than %@AS@% %@AS@% minute %@AE@% or %@AS@% second%@AE@%. Because C does not guarantee storage order or alignment of structures or unions, the code may not be portable to other machines.%@NL@% %@NL@% ■ Three variables of type %@AB@%char %@AE@%will be shorter than or the same length as a variable of type %@AB@%long%@AE@%. Thus, the code is not portable according to the rules governing the size of basic types, as described in Section 13.1.1.%@NL@% %@NL@% %@NL@% If either of these assumptions proves false, the comparison (%@AB@%if %@AE@%statement) is invalid. %@NL@% %@NL@% %@AU@% You can write code that makes no assumptions about storage order.%@AE@% %@NL@% %@NL@% To make the program in the preceding example portable, you can break the comparison between the two long integers into a component-by-component comparison. This technique is illustrated in the following example: %@NL@% %@NL@% %@AS@% /* Portable code */ %@AS@% struct time %@AS@% { %@AS@% char hour; /* 0 < hour < 24 -- fits in a char */ %@AS@% char minute; /* 0 < minute < 60 -- fits in a char */ %@AS@% char second; /* 0 < second < 60 -- fits in a char */ %@AS@% }; %@AS@% %@AS@% . %@AS@% . %@AS@% . %@AS@% struct time now, alarm_time; %@AS@% . %@AS@% . %@AS@% . %@AS@% if ( time_cmp( now, alarm_time ) >= 0 ) %@AS@% { %@AS@% /* sound an alarm */ %@AS@% } %@AS@% . %@AS@% . %@AS@% . %@AS@% %@AS@% int time_cmp( struct time t1, struct time t2 ) %@AS@% { %@AS@% if( t1.hour != t2.hour ) %@AS@% return( t2.hour - t1.hour ); %@AS@% if( t1.minute != t2.minute ) %@AS@% return( t2.minute - t1.minute ); %@AS@% return( t2.second - t1.second ); %@AS@% }%@AE@%%@NL@% %@NL@% %@NL@% %@4@%%@AB@%Union Order and Alignment%@AE@%%@EH@%%@NL@% %@NL@% Programmers use unions most often for two purposes: to store data whose exact type is not known until run time or to access the same data in different ways. %@NL@% %@NL@% Unions falling into the second category are usually not portable. For example, the union below is not portable: %@NL@% %@NL@% %@AS@% union tag_u %@AS@% { %@AS@% char bytes_in_long[4]; %@AS@% long a_long; %@AS@% };%@AE@%%@NL@% %@NL@% The intent of the union above is to access the individual bytes of a variable of type %@AB@%long%@AE@%. However, the union may not work as intended when ported to other computers because %@NL@% %@NL@% %@NL@% ■ It relies on a constant size for type %@AB@%long%@AE@%.%@NL@% %@NL@% ■ It may assume byte ordering within a variable of type %@AB@%long%@AE@%. (Byte ordering is described in detail in Section 13.1.3, "Byte Order in a Word.")%@NL@% %@NL@% %@NL@% The first problem can be addressed by coding the union as follows: %@NL@% %@NL@% %@AS@% union tag_u %@AS@% { %@AS@% char bytes_in_long[sizeof( long ) / sizeof( char )]; %@AS@% long a_long; %@AS@% };%@AE@%%@NL@% %@NL@% Note the use of the %@AB@%sizeof%@AE@% operator to determine the size of a data type. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00130005 @%%@AB@%13.1.3 Byte Order in a Word%@AE@%%@EH@%%@NL@% %@NL@% The order of bytes within a word (%@AB@%int %@AE@%or %@AB@%short%@AE@%) or a double word (%@AB@%long%@AE@%) can vary among machines. Code that assumes an internal order is not portable, as shown by this example: %@NL@% %@NL@% %@AS@% /* %@AS@% * Nonportable structure to access an %@AS@% * int in bytes. %@AS@% */ %@AS@% struct tag_int_bytes %@AS@% { %@AS@% char lobyte; %@AS@% char hibyte; %@AS@% };%@AE@%%@NL@% %@NL@% A more portable way to access the individual bytes in a word is to define two macros that rely on the constant %@AB@%CHAR_BIT%@AE@%, defined in LIMITS.H: %@NL@% %@NL@% %@AS@% #define LOBYTE(a) (char)((a) & 0xff) %@AS@% #define HIBYTE(a) (char)((unsigned)(a) >> CHAR_BIT)%@AE@%%@NL@% %@NL@% The %@AB@%LOBYTE%@AE@% macro is still not completely portable. It assumes that a %@AB@%char %@AE@%is eight bits long, and it uses the constant %@AS@% 0xff %@AE@% to mask the high-order eight bits. Because portable programs cannot rely on a given number of bits in a byte, consider the revision below: %@NL@% %@NL@% %@AS@% #define LOBYTE(a) (char)((a) & ((unsigned)~0>>CHAR_BIT)) %@AS@% #define HIBYTE(a) (char)((unsigned)(a) >> CHAR_BIT)%@AE@%%@NL@% %@NL@% The new %@AB@%LOBYTE %@AE@%macro performs a bitwise complement on 0; that is, all zero bits are turned into ones. It then takes that unsigned quantity and shifts it right far enough to create a mask of the correct length for the implementation. %@NL@% %@NL@% The following code assumes that the order of bytes in a word will be leastsignificant first: %@NL@% %@NL@% %@AS@% int c; %@AS@% . %@AS@% . %@AS@% . %@AS@% fread( &c, sizeof( char ), 1, fp );%@AE@%%@NL@% %@NL@% The code attempts to read one byte as an %@AB@%int%@AE@%, without converting it from a %@AB@%char%@AE@%. However, the code will fail in any implementation where the low-order byte is not the first byte of an %@AB@%int%@AE@%. The following solution is more portable. In the example below, the data is read into an intermediate variable of type %@AB@%char%@AE@% before being assigned to the integer variable. %@NL@% %@NL@% %@AS@% int c; %@AS@% char ch; %@AS@% . %@AS@% . %@AS@% . %@AS@% fread( &ch, sizeof( char ), 1, fp ); %@AS@% c = ch;%@AE@%%@NL@% %@NL@% The example below shows how to use the C run-time function %@AB@%fgetc%@AE@% to return the value. The %@AB@%fgetc%@AE@% function returns type %@AB@%char%@AE@%, but the value is promoted to type %@AB@%int%@AE@% when it is assigned to a variable of type %@AB@%int%@AE@%. %@NL@% %@NL@% %@AS@% int c; %@AS@% . %@AS@% . %@AS@% . %@AS@% c = fgetc( fp );%@AE@%%@NL@% %@NL@% %@NL@% %@4@%%@AB@%Microsoft C Specific%@AE@%%@EH@%%@NL@% %@NL@% Microsoft C normally aligns data types longer than one byte to an even-byte address for improved performance. See the /Zp compiler option and the %@AB@%pack%@AE@% pragma in the %@AI@%Microsoft C Reference%@AE@% and in on-line help for information about controlling structure packing in Microsoft C. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00130006 @%%@AB@%13.1.4 Reading and Writing Structures%@AE@%%@EH@%%@NL@% %@NL@% Many C programs read data from disk into structures and write data to disk from structures. The functions that perform disk I/O in C require you to specify the number of bytes to be transferred. You should always use the %@AB@%sizeof%@AE@% operator to obtain the size of the data to be read or written because differing data type sizes or alignment schemes may alter the size of a given structure. For example, %@NL@% %@NL@% %@AS@% fread( &my_struct, sizeof(my_struct), 1, fp );%@AE@%%@NL@% %@NL@% %@NL@% %@4@%%@AB@%Microsoft C Specific%@AE@%%@EH@%%@NL@% %@NL@% When performing disk input and output in Microsoft C, structures may be different sizes depending on the structure-packing option you have selected (see the /Zp compiler option and the %@AB@%pack%@AE@% pragma in the %@AI@%Microsoft C %@AI@%Reference%@AE@%). %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00130007 @%%@AB@%13.1.5 Bit Fields in Structures%@AE@%%@EH@%%@NL@% %@NL@% The Microsoft C compiler implements bit fields. However, many C compilers do not. %@NL@% %@NL@% Bit fields allow you to access the individual bits within a data item. While the practice of accessing the bits in a data item is inherently nonportable, you can %@NL@% %@NL@% improve your chances of porting a program that uses bit fields if you make no assumptions about order of assignment, or size and alignment of bit fields. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Order of Assignment%@AE@%%@EH@%%@NL@% %@NL@% The order of assignment of bit fields in memory is left to the implementation, so you cannot rely on a particular entry in a bit field structure to be in a higher order position than another. (This problem is similar to the portability constraint imposed by alignment of basic data types in structures. The C language does not define any specific layout for the storage of data items relative to one another.) See Section 13.1.2, "Storage Order and Alignment" for more information. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Size and Alignment of Bit Fields%@AE@%%@EH@%%@NL@% %@NL@% The Microsoft C compiler supports bit fields up to the size of the type %@AB@%long%@AE@%. Each individual member of the bit field structure can be up to the size of the declared type. Some compilers do not support bit field-structure elements that are longer than type %@AB@%int%@AE@%. %@NL@% %@NL@% The example below defines a bit field, %@AS@% short_bitfield%@AE@%, that is shorter than type %@AB@%int%@AE@%: %@NL@% %@NL@% %@AS@% struct short_bitfield %@AS@% { %@AS@% unsigned usr_bkup : 1; /* 0 <= usr_bkup < 1 */ %@AS@% unsigned usr_sec : 4; /* 9 <= usr_sec < 16 */ %@AS@% };%@AE@%%@NL@% %@NL@% The example below defines a bit field, %@AS@% long_bitfield%@AE@%, that has elements longer than type %@AB@%int%@AE@%: %@NL@% %@NL@% %@AS@% struct long_bitfield %@AS@% { %@AS@% unsigned long disk_pos : 22; /* 0 <= disk_pos < 4,194,304 */ %@AS@% unsigned long rec_no : 10; /* 0 <= rec_no < 1,024 */ %@AS@% };%@AE@%%@NL@% %@NL@% The bit field %@AS@% short_bitfield %@AE@% is likely to be supported by more implementations than %@AS@% long_bitfield%@AE@%. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Microsoft C Specific%@AE@%%@EH@%%@NL@% %@NL@% The example below introduces another portability issue: alignment of data defined in bit fields. The Microsoft C compiler does not allow an element in a structure to extend across two words. The first two elements, %@AS@% day %@AE@% and %@AS@% %@AS@%month%@AE@%, take up nine bits. The third, %@AS@% year%@AE@%, would extend across a word boundary, so it must begin on the next word boundary. %@NL@% %@NL@% %@AS@% struct long_bitfield %@AS@% { %@AS@% unsigned int day : 5; /* 0 <= day < 32 */ %@AS@% unsigned int month : 4; /* 0 <= month < 16 */ %@AS@% unsigned int year : 11; /* 0 <= year < 2048 */ %@AS@% };%@AE@%%@NL@% %@NL@% Figure 13.1 illustrates the example above. %@NL@% %@NL@% %@AU@%(This figure may be found in the printed book.)%@AE@%%@NL@% %@NL@% Other compilers may not use the same storage techniques. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00130008 @%%@AB@%13.1.6 Processor Arithmetic Mode%@AE@%%@EH@%%@NL@% %@NL@% Two types of arithmetic are common on digital computers: one's-complement arithmetic and two's-complement arithmetic. Some programs assume that all target computers perform two's-complement arithmetic. If you take advantage of the fact that a given operation causes a particular bit pattern to be set on either a one's-complement or two's-complement computer, your program will not be portable. For example, two's-complement machines represent the eight-bit integer value -1 as a binary 11111111. A one's-complement machine represents the same decimal value (-1) as 11111110. Some programmers assume that -1 will fill a byte or a word with ones, and use it to construct a mask template that they later shift. This will not work correctly on one's-complement machines, but the error will not surface until the least-significant bit is used. %@NL@% %@NL@% In two's-complement arithmetic, there is only one value that represents zero. In one's-complement arithmetic, there is a value for zero and a value for negative zero. Use the C relational operators to handle this anomaly correctly; if you write code that deliberately circumvents the C relational operators, tests for zero or %@AB@%NULL %@AE@%may not operate correctly. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Microsoft C Specific%@AE@%%@EH@%%@NL@% %@NL@% Microsoft C produces code only for the Intel 80%@AI@%x%@AE@%86 processors, which all perform two's-complement arithmetic. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00130009 @%%@AB@%13.1.7 Pointers%@AE@%%@EH@%%@NL@% %@NL@% One of the most powerful but potentially dangerous features of the C language is its use of indirect addressing through pointers. Bugs introduced by misusing pointers can be difficult to detect and isolate because the error often corrupts memory unpredictably. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Casting Pointers%@AE@%%@EH@%%@NL@% %@NL@% Be sure you do not make nonportable assumptions when casting pointers to different types. %@NL@% %@NL@% %@AS@% /* Nonportable coercion */ %@AS@% char c[4]; %@AS@% long *lp; %@AS@% %@AS@% lp = (long *)c; %@AS@% *lp = 0x12345678L;%@AE@%%@NL@% %@NL@% This code is nonportable because using a cast to change an array of %@AB@%char%@AE@% to a pointer of type %@AB@%long%@AE@% assumes a particular byte-ordering scheme. This is discussed in greater detail in Section 13.1.3, "Byte Order in a Word." %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Pointer Size%@AE@%%@EH@%%@NL@% %@NL@% A pointer can be assigned (or cast) to any integer type large enough to hold it, but the size of the integer type depends on the machine and the implementation. (In fact, it can even depend on the memory model.) Therefore, you cannot assume: %@NL@% %@NL@% %@AS@% sizeof( char * ) == sizeof( int )%@AE@%%@NL@% %@NL@% To determine the size of any unmodified data pointer, use %@NL@% %@NL@% %@AS@% sizeof( void * )%@AE@%%@NL@% %@NL@% the size of a generic data pointer. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Pointer Subtraction%@AE@%%@EH@%%@NL@% %@NL@% Code that assumes that pointer subtraction yields an %@AB@%int%@AE@% value is nonportable. Pointer subtraction yields a result of type %@AB@%ptrdiff_t%@AE@% (defined in STDDEF.H). Portable code must always use variables of type %@AB@%ptrdiff_t%@AE@% for storing the result of pointer subtraction. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%The Null Pointer%@AE@%%@EH@%%@NL@% %@NL@% In most implementations, %@AB@%NULL%@AE@% is defined as 0. In Microsoft C, it is defined as %@AS@% ((void *)0)%@AE@%. Because code pointers and data pointers are often different sizes, using 0 for the null pointer for both can lead to nonportability. The difference in size between code pointers and data pointers will cause problems for functions that expect pointer arguments longer than an %@AB@%int%@AE@%. To avoid these problems, use the null pointer, as defined in the include file STDDEF.H; use prototypes; or explicitly cast %@AB@%NULL %@AE@%to the correct data type. Here is a portable way to use the null pointer: %@NL@% %@NL@% %@AS@% /* Portable use of the NULL pointer */ %@AS@% main() %@AS@% { %@AS@% func1( (char *)NULL ); %@AS@% func2( (void *(*)())NULL ); %@AS@% } %@AS@% %@AS@% void func1( char * c ) %@AS@% { %@AS@% } %@AS@% %@AS@% void func2( void *(* func)() ) %@AS@% { %@AS@% }%@AE@%%@NL@% %@NL@% The invocations of %@AS@% func1 %@AE@% and %@AS@% func2 %@AE@% explicitly cast %@AB@%NULL %@AE@%to the correct size. In the case of %@AS@% func1%@AE@%, %@AB@%NULL %@AE@%is cast to type %@AB@%char *%@AE@%; in the case of %@AS@% %@AS@%func2%@AE@%, it is cast to a pointer to a function that returns type %@AB@%void%@AE@%. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Microsoft C Specific%@AE@%%@EH@%%@NL@% %@NL@% Subtraction of pointers to huge arrays that have more than 32,767 elements may yield a %@AB@%long%@AE@% result. The %@AB@%_huge%@AE@% keyword is implementation-defined by Microsoft C and is not portable. Here is how to subtract pointers to huge arrays:%@CR:C6A00130010 @% %@NL@% %@NL@% %@AS@% char _huge *a; %@AS@% char _huge *b; %@AS@% long d; %@AS@% . %@AS@% . %@AS@% . %@AS@% d = (long)( a - b );%@AE@%%@NL@% %@NL@% In Microsoft C, the memory model selected and the special keywords %@AB@%_near%@AE@%, %@AB@%_far%@AE@%, and %@AB@%_huge %@AE@%can change the size of a pointer. The Microsoft memory models and extended keywords are nonportable, but you should be aware of their effects.%@CR:C6A00130011 @%%@CR:C6A00130012 @%%@CR:C6A00130013 @% %@NL@% %@NL@% Sizes of generic pointers and default pointer sizes are shown in Tables 13.2 and 13.3, respectively. %@NL@% %@NL@% %@AB@%Table 13.2 %@AB@%Size of Generic Pointers%@AE@%%@AE@% %@TH: 6 438 02 15 23 38 @%Declaration Name Size%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%void _near *%@AE@% Generic near pointer 16 bits%@AB@%void _far *%@AE@% Generic far pointer 32 bits%@AB@%void _huge *%@AE@% Generic huge pointer 32 bits%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@TE: 6 438 02 15 23 38 @% %@AB@%Table 13.3 %@AB@%Default Pointer Sizes%@AE@%%@AE@% %@TH: 9 518 02 14 19 43 @%Memory Model Code Pointer Size Data Pointer Size%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%Tiny 16 bits 16 bitsSmall 16 bits 16 bitsMedium 32 bits 16 bitsCompact 16 bits 32 bitsLarge 32 bits 32 bitsHuge 32 bits 32 bits%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@TE: 9 518 02 14 19 43 @% %@NL@% %@3@%%@CR:C6A00130014 @%%@AB@%13.1.8 Address Space%@AE@%%@EH@%%@NL@% %@NL@% The amount of available memory and the address space on systems varies, depending on many factors outside your control. A program designed with portability in mind should handle insufficient-memory situations. To ensure that your program handles these situations, you should always check the error return from any of the dynamic memory allocation routines, such as %@AB@%malloc%@AE@%, %@AB@%calloc%@AE@%, %@AB@%strdup%@AE@%, and %@AB@%realloc%@AE@%. %@NL@% %@NL@% These situations occur not only because of a lack of installed memory but also because too many other applications are using memory. For example, %@NL@% %@NL@% %@NL@% ■ Installed resident software can cause your program to fail. In DOS, these programs are usually device drivers or terminate-and-stay-resident (TSR) utilities.%@NL@% %@NL@% ■ An event or combination of events in a multitasking operating system such as OS/2 or XENIX can cause your program to fail. These failures are complex and difficult to predict. Here is an example: the user has installed a daemon to "pop up" every so often and check the system status. The user is running your application along with enough other large applications to cause a critical shortage of memory. When the daemon pops up, your program may fail on a memory allocation request.%@NL@% %@NL@% ■ An application running under Windows can use an extraordinary amount of the global heap and not return it to the free pool. This type of behavior will cause Windows to deny a %@AB@%GlobalAlloc%@AE@% request.%@NL@% %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00130015 @%%@AB@%13.1.9 Character Set%@AE@%%@EH@%%@NL@% %@NL@% The C language does not define the character set used in an implementation. This means that any programs that assume the character set to be ASCII are nonportable. %@NL@% %@NL@% The only restrictions on the character set are these: %@NL@% %@NL@% %@NL@% ■ No character in the implementation's character set may be larger than the size of type %@AB@%char%@AE@%.%@NL@% %@NL@% ■ Each character in the set must be represented as a positive value by type %@AB@%char%@AE@%, whether it is treated as signed or unsigned. So, in the case of the ASCII character set and an eight-bit %@AB@%char%@AE@%, the maximum value is 127 (128 is a negative number when stored in a %@AB@%char%@AE@% variable).%@NL@% %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Character Classification%@AE@%%@EH@%%@NL@% %@NL@% The standard C run-time support contains a complete set of characterclassification macros and functions. These functions are defined in the CTYPE.H file and are guaranteed to be portable: %@NL@% %@NL@% %@AB@%isalnum isdigit isprint isupper%@AE@% %@AB@%isalpha isgraph ispunct isxdigit%@AE@% %@AB@%iscntrl islower isspace The following code fragment is not portable to implementations that do not use the ASCII character set: %@NL@% %@NL@% %@AS@% /* Nonportable */ %@AS@% if( c >= 'A' && c <= 'Z' ) %@AS@% /* uppercase alphabetic */%@AE@%%@NL@% %@NL@% Instead, consider using this: %@NL@% %@NL@% %@AS@% /* Portable */ %@AS@% if( isalpha(c) && isupper(c) ) %@AS@% /* uppercase alphabetic */%@AE@%%@NL@% %@NL@% The first example above is nonportable, because it assumes that uppercase %@AS@% A %@AS@%%@AE@% is represented by a smaller value than uppercase %@AS@% Z%@AE@%, and that no lowercase characters fall between the values of %@AS@% A %@AE@% and %@AS@% Z%@AE@%. The second example is portable, because it uses the character classification functions to perform the tests. %@NL@% %@NL@% In a portable program, you should not perform any comparison on variables of type %@AB@%char%@AE@% except strict equality (==). You cannot assume the character set follows an increasing sequence─that may not be true on a different machine. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Case Translation%@AE@%%@EH@%%@NL@% %@NL@% Translation of characters from upper- to lowercase or from lowerto uppercase is called "case translation." The following example shows a coding technique for case translation not portable to implementations using a non-ASCII character set. %@NL@% %@NL@% %@AS@% #define make_upper(c) ((c)&0xcf) %@AS@% #define make_lower(c) ((c)|0x20)%@AE@%%@NL@% %@NL@% This code takes advantage of the fact that you can map uppercase to lowercase simply by changing the state of bit 6. It is extremely efficient but nonportable. To write portable code, use the case-translation macros %@AB@%toupper%@AE@% and %@AB@%tolower%@AE@% (defined in CTYPE.H). %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00130016 @%%@AB@%13.2 Assumptions about the Compiler%@AE@%%@EH@%%@NL@% %@NL@% Different compilers translate C source code into object code in different ways. The ANSI draft standard for the C programming language defines how many of these translations must be done; others are implementation-defined. %@NL@% %@NL@% This section describes assumptions about how the compiler translates your C code, which can make your programs nonportable. For a complete description of how Microsoft C handles implementation-defined operations, see Appendix C, "Implementation-Defined Behavior." %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00130017 @%%@AB@%13.2.1 Sign Extension%@AE@%%@EH@%%@NL@% %@NL@% "Sign extension" is the propagation of the sign bit to fill unoccupied space when promoting to a more-significant type or when performing bitwise right-shift operations. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Promotion from Shorter Types%@AE@%%@EH@%%@NL@% %@NL@% Integral promotions from shorter types occur when you make an assignment, perform arithmetic, perform a comparison, or perform an explicit cast. %@NL@% %@NL@% The behavior of integral promotion is well defined, except for type %@AB@%char%@AE@%. The implementation defines whether type %@AB@%char%@AE@% is treated as signed or unsigned. The code fragment below is an example of promotion as a result of assignment: %@NL@% %@NL@% %@AS@% char c1 = -3; %@AS@% int i1; %@AS@% %@AS@% i1 = c1;%@AE@%%@NL@% %@NL@% In this example, the expected result of the assignment statement is that %@AS@% i1 %@AS@%%@AE@% will be set to -3. If the implementation defines type %@AB@%char%@AE@% as unsigned, however, sign extension will not occur, and %@AS@% i1 %@AE@% will be 253 (on a two's-complement machine). %@NL@% %@NL@% Promotion can also occur as a result of a comparison of different types: %@NL@% %@NL@% %@AS@% char c; %@AS@% %@AS@% if( c == 0x80 ) %@AS@% . %@AS@% . %@AS@% .%@AE@%%@NL@% %@NL@% This comparison will never evaluate as true on an implementation that signextends %@AB@%char%@AE@% types but treats hexadecimal constants as unsigned. Use a character constant of the form %@AB@%'\x80'%@AE@%, or explicitly cast the constant to type %@AB@%char%@AE@% to perform the comparison correctly. %@NL@% %@NL@% The following comparison, which is an example of promotion as a result of a cast, is also nonportable: %@NL@% %@NL@% %@AS@% char c; %@AS@% unsigned int u; %@AS@% %@AS@% if( u == (unsigned)c )%@AE@%%@NL@% %@NL@% There are two problems with this code: %@NL@% %@NL@% %@NL@% ■ The %@AB@%char%@AE@% type may be treated as signed or unsigned, depending on the implementation.%@NL@% %@NL@% ■ If the %@AB@%char%@AE@% type is treated as signed, it can be converted to %@AB@%unsigned%@AE@% in two different ways: the %@AB@%char%@AE@% value may first be sign-extended to %@AB@%int%@AE@%, then converted to %@AB@%unsigned%@AE@%; or the %@AB@%char%@AE@% may be converted to %@AB@%unsigned char%@AE@%, then sign-extended to %@AB@%int%@AE@% length.%@NL@% %@NL@% %@NL@% It is always safe to compare a %@AB@%signed int%@AE@% with a %@AB@%char%@AE@% constant because C requires all character constants to be positive. %@NL@% %@NL@% Variables of type %@AB@%char%@AE@% are promoted to type %@AB@%int%@AE@% when passed as arguments to a function. This will cause sign extension on some machines. Consider the following code: %@NL@% %@NL@% %@AS@% char c = 128; %@AS@% %@AS@% printf( "%d\n", c );%@AE@%%@NL@% %@NL@% %@NL@% %@4@%%@AB@%Microsoft C Specific%@AE@%%@EH@%%@NL@% %@NL@% Microsoft C allows you to treat type %@AB@%char%@AE@% as signed or unsigned. By default, a %@AB@%char%@AE@% is considered signed, but if you change the default %@AB@%char%@AE@% type using the /J compiler option, you can treat it as unsigned. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Bitwise Right-Shift Operations%@AE@%%@EH@%%@NL@% %@NL@% Positive or unsigned integral types (%@AB@%char%@AE@%, %@AB@%short%@AE@%, %@AB@%int%@AE@%, and %@AB@%long%@AE@%) yield positive or zero values after a right bitwise shift (>>) operation. For example, %@NL@% %@NL@% %@AS@% (char)120 >> 4%@AE@%%@NL@% %@NL@% yields 7, %@NL@% %@NL@% %@AS@% (unsigned char)240 >> 8%@AE@%%@NL@% %@NL@% yields 0, %@NL@% %@NL@% %@AS@% (int)500 >> 8%@AE@%%@NL@% %@NL@% yields 1, and %@NL@% %@NL@% %@AS@% (unsigned int)65535 >> 4%@AE@%%@NL@% %@NL@% yields 4,095. %@NL@% %@NL@% Negative-signed integral types yield implementation-defined values after a bitwise right-shift operation. This means that you must know whether you want to do a signed or unsigned shift, then code accordingly. %@NL@% %@NL@% If you don't know how the implementation performs, you may get unexpected results. For example, %@AS@% (signed char)0x80 >> 3 %@AE@% yields 0xf0 if the imple-mentation performs sign extension on right bitwise shifts. If the implementation does not perform the sign extension, the result is 0x10. %@NL@% %@NL@% You can use right shifts to speed up division when the divisor can be represented by powers of 2 and the dividend is positive. To maintain portability, you should use the division operator. %@NL@% %@NL@% To perform an unsigned shift, explicitly cast the data to an unsigned type. To perform a shift that extends the sign bit, use the division operator as follows: divide by 2n, where %@AI@%n%@AE@% is the number of bits you want to shift. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00130018 @%%@AB@%13.2.2 Length and Case of Identifiers%@AE@%%@EH@%%@NL@% %@NL@% Some implementations do not support long identifiers. Some allow only 6 characters, while others allow as many as 32. They may report each identifier that exceeds the maximum length or truncate identifiers to a given length. Truncation causes serious problems, especially if you have a number of similarly named variables within the scope of a block of code, such as the following: %@NL@% %@NL@% %@AS@% double acct_receivable_30_days; %@AS@% double acct_receivable_60_days; %@AS@% double acct_receivable_90_days; %@AS@% double current_interest_rate; %@AS@% %@AS@% acct_receivable_30_days *= current_interest_rate;%@AE@%%@NL@% %@NL@% If your target system retains only six significant characters, you will have to rename all your %@AS@% acct_receivable %@AE@% variables. %@NL@% %@NL@% Case sensitivity also affects portability. C is usually a case-sensitive language. That is, %@AS@% CalculateInterest %@AE@% is not considered the same identifier as %@AS@%calculateinterest%@AE@%. Some systems are not case sensitive, however, so to write portable code, differentiate your identifiers by something other than case. %@NL@% %@NL@% These problems with identifiers can occur in two locations: the compiler and the linker or loader. Even if the compiler can handle long and case-differentiated identifiers, if the linker or loader cannot, you can get duplicate definitions or other unexpected errors. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Microsoft C Specific%@AE@%%@EH@%%@NL@% %@NL@% The Microsoft C compiler issues the /NOIGNORECASE command to the Microsoft Segmented-Executable Linker (LINK), specifically instructing it to consider the case of identifiers. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00130019 @%%@AB@%13.2.3 Register Variables%@AE@%%@EH@%%@NL@% %@NL@% The number and type of register variables in a function depend on the implementation. You can declare more variables as %@AB@%register %@AE@%than the number of physical registers the implementation uses. In such a case, the compiler treats the excess register variables as %@AB@%automatic%@AE@%. %@NL@% %@NL@% Since the types that qualify for %@AB@%register%@AE@% class differ among implementations, invalid %@AB@%register %@AE@%declarations are treated as %@AB@%automatic%@AE@%. %@NL@% %@NL@% If you declare variables as %@AB@%register %@AE@%to optimize performance, declare them in decreasing order of importance to ensure that the compiler allocates a register to the most important variables. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Microsoft C Specific%@AE@%%@EH@%%@NL@% %@NL@% The compiler ignores %@AB@%register%@AE@% declarations if you select the global register allocation optimization. You can select global register allocation as follows: %@NL@% %@NL@% %@AB@%Environment%@AE@% %@AB@%Selection%@AE@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% CL command line Specify either the /Oe or /Ox option. PWB Select the Global Register Allocation option in the Debug Build Options or Release Build Options dialog boxes. pragma Use the %@AB@%optimize%@AE@% pragma with the %@AB@%e%@AE@% parameter. %@NL@% %@3@%%@CR:C6A00130020 @%%@AB@%13.2.4 Functions with a Variable Number of Arguments%@AE@%%@EH@%%@NL@% %@NL@% Functions that accept a variable number of arguments are not portable. Although both the ANSI Standard and %@AI@%The C Programming Language%@AE@% specify how to write these functions and how they behave, differences still exist among compiler implementors about how to use variable argument lists. %@NL@% %@NL@% Many UNIX(R) systems support a standard that differs from the ANSI Standard for variable arguments. Although this may change, it currently presents a portability concern. %@NL@% %@NL@% Microsoft C run-time libraries and macros allow you to use whichever version of variable argument support you expect to be most portable for your application. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00130021 @%%@AB@%13.2.5 Evaluation Order%@AE@%%@EH@%%@NL@% %@NL@% The C language does not guarantee the evaluation order of most expressions. Avoid writing constructs that depend on evaluation within an expression to proceed in a particular manner. For example, %@NL@% %@NL@% %@AS@% i = 0; %@AS@% func( i++, i++ ); %@AS@% . %@AS@% . %@AS@% . %@AS@% func( int a, int b ) %@AS@% {%@AE@%%@NL@% %@NL@% A compiler could evaluate this code fragment and pass 0 as %@AS@% a %@AE@% and 1 as %@AS@% b%@AE@%. It could also pass 1 as %@AS@% a %@AE@% and 0 as %@AS@% b %@AE@% and conform equally with the standards. %@NL@% %@NL@% The C language does guarantee that an expression will be completely evaluated at any given "sequence point." A sequence point is a point in the syntax of the language at which all side effects of an expression or series of expressions have been completed. %@NL@% %@NL@% These are the sequence points in the C language: %@NL@% %@NL@% %@NL@% 1. The semicolon (;) statement separator%@NL@% %@NL@% 2. The call to a function after the arguments have been evaluated%@NL@% %@NL@% 3. The end of the first operand of one of the following: %@NL@% ■ Logical AND (%@AB@%&&%@AE@%)%@NL@% %@NL@% ■ Logical OR (%@AB@%||%@AE@%)%@NL@% %@NL@% ■ Conditional (%@AB@%?%@AE@%)%@NL@% %@NL@% ■ Comma separator (%@AB@%,%@AE@%) when used to separate statements or in expressions; the comma separator is not a sequence point when it is used between variables in declaration statements or between parameters in a function invocation%@NL@% %@NL@% %@NL@% 4. The end of a full expression, such as %@NL@% ■ An initializer%@NL@% %@NL@% ■ The expression in an expression statement (for example, any expression inside parentheses)%@NL@% %@NL@% ■ The controlling expression of a %@AB@%while %@AE@%or %@AB@%do %@AE@%statement%@NL@% %@NL@% ■ Any of the three expressions of a %@AB@%for %@AE@%statement%@NL@% %@NL@% ■ The expression in a %@AB@%return %@AE@%statement%@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00130022 @%%@AB@%13.2.6 Function and Macro Arguments with Side Effects%@AE@%%@EH@%%@NL@% %@NL@% Run-time support functions can be implemented either as functions or as macros. Avoid including expressions with side effects inside function invocations unless you are sure the function will not be implemented as a macro. Here is an illustration of how an argument with side effects can cause problems: %@NL@% %@NL@% %@AS@% #define limit_number(a) ((a>1000)?1000:(a)) %@AS@% %@AS@% a = limit_number( a++ );%@AE@%%@NL@% %@NL@% If %@AS@% a ≤%@AE@% 1000, it is incremented once. If %@AS@% a %@AE@%> 1000, it is incremented twice, which is probably not the intended behavior. %@NL@% %@NL@% A macro can be used safely with an argument that has side effects if it evaluates its parameter only once. You can determine whether a macro is safe only by inspecting the code. %@NL@% %@NL@% A common example of a run-time support function that is often implemented as a macro is %@AB@%toupper%@AE@%. You will find your program's behavior confusing if you use the following code: %@NL@% %@NL@% %@AS@% char c; %@AS@% %@AS@% c = toupper( getc() );%@AE@%%@NL@% %@NL@% If %@AS@% toupper %@AE@% is implemented as a function, %@AS@% getc %@AE@% will be called only once, and its return value will be translated to uppercase. However, if %@AS@% toupper %@AE@% is implemented as a macro, %@AS@% getc %@AE@% will be called once or twice, depending on whether %@AS@% c %@AE@%is upper- or lowercase. Consider the following macro example: %@NL@% %@NL@% %@AS@% #define toupper(c) ( (islower(c)) ? _toupper(c) : (c) )%@AE@%%@NL@% %@NL@% If you include the %@AB@%toupper%@AE@% macro in your code, the preprocessor expands it as follows: %@NL@% %@NL@% %@AS@% /* What you wrote */ %@AS@% c = toupper( getc() ); %@AS@% %@AS@% /* Macro expansion */ %@AS@% ch = (islower( (getc()) ) ? _toupper( getc() ) : (getc()) );%@AE@%%@NL@% %@NL@% The expansion of the macro shows that the argument to %@AS@% toupper %@AE@% will always be called twice: once to determine if the character is lowercase and the next time to perform case translation (if necessary). In the example, this double evaluation calls the %@AB@%getc%@AE@% function twice. Because %@AS@% getc %@AE@% is a function whose side effect is to read a character from the standard input device, the example requests two characters from standard input. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00130023 @%%@AB@%13.2.7 Environment Differences%@AE@%%@EH@%%@NL@% %@NL@% Many programs perform some file I/O. When writing these programs for portability, consider the following: %@NL@% %@NL@% %@NL@% ■ Do not hard-code file or path names. Use constants you define either in a header file or at the beginning of the program.%@NL@% %@NL@% ■ Do not assume the use of any particular file system. For example, the UNIX-model, hierarchical file system is prevalent on small computers. On larger systems, the file system often follows a different model.%@NL@% %@NL@% ■ Do not assume a particular display size (number of rows and columns).%@NL@% %@NL@% ■ Do not assume that display attributes exist. Some environments do not support such attributes as color, underlined text, blinking text, highlighted text, inverse text, protected text, or dim text.%@NL@% %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00130024 @%%@AB@%13.3 Portability of Data Files%@AE@%%@EH@%%@NL@% %@NL@% Data files are rarely portable across different CPUs. Structures, unions, and arrays have varying internal layout and alignment requirements on different machines. In addition, byte ordering within words and actual word length may vary. %@NL@% %@NL@% The best way to achieve data-file portability is to write and read data files as one-dimensional character arrays. This procedure prevents alignment and padding problems if the data are written and read as characters. The only portability problem you are likely to encounter if you follow this course is a conflict in character sets; many computers have character-set conversion utilities. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00130025 @%%@AB@%13.4 Portability Concerns Specific to Microsoft C%@AE@%%@EH@%%@NL@% %@NL@% Microsoft C offers extensions that let you take advantage of the full capabilities of the computer. These extensions are not portable to other compilers or environments. The following list shows keywords specific to Microsoft C: %@NL@% %@NL@% %@AB@%_asm _far _huge pascal%@AE@% %@AB@%_based _fastcall _interrupt _pascal%@AE@% %@AB@%cdecl fortran near _saveregs%@AE@% %@AB@%_cdecl _fortran _near _segment%@AE@% %@AB@%_export huge _loadds _segname%@AE@% %@AB@%far The %@AI@%Microsoft C Reference%@AE@% contains compatibility information for every function in the run-time library. Any function or macro that does not have the ANSI box marked may not be portable to other compilers or computer systems. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00130026 @%%@AB@%13.5 Microsoft C Byte Ordering%@AE@%%@EH@%%@NL@% %@NL@% Tables 13.4 and 13.5 summarize Microsoft C byte ordering for %@AB@%short%@AE@% and %@AB@%long%@AE@% types, respectively. In these tables, the least-significant byte of the data item is b0; the next byte is denoted by b1, and so on. %@NL@% %@NL@% Since byte ordering is machine specific, any program that uses this byte ordering will not be portable. %@NL@% %@NL@% %@AB@%Table 13.4 %@AB@%Byte Ordering for Short Types%@AE@%%@AE@% %@TH: 9 473 02 28 48 @%CPU Byte Order%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%8086 b0 b180286 b0 b1PDP-11(R) b0 b1VAX-11(R) b0 b1M68000 b1 b0Z8000(R) b1 b0%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@TE: 9 473 02 28 48 @% %@AB@%Table 13.5 %@AB@%Byte Ordering for Long Types%@AE@%%@AE@% %@TH: 9 494 02 25 51 @%CPU Byte Order%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%8086 b0 b1 b2 b380286 b0 b1 b2 b3PDP-11 b2 b3 b0 b1VAX-11 b0 b1 b2 b3M68000 b3 b2 b1 b0Z8000 b3 b2 b1 b0%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@TE: 9 494 02 25 51 @% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@CR:C6A-Part 04 @%%@1@%%@AB@%PART IV OS/2 Support%@AE@%%@EH@%%@NL@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@NL@% The Microsoft C Professional Development System provides support for OS/2 development. %@NL@% %@NL@% Chapter 14 explains many of the general issues of OS/2 development, including accessing the OS/2 system functions, creating module-definition files, and using the OS/2-specific features of utilities such as the linker and BIND. Chapter 15 focuses on how to create a multithread application, including information about C run-time library support, potential problem areas, and how to use CodeView to debug multithread applications. Chapter 16 concentrates on the creation of dynamic-link libraries, including C run-time library support, application program interface with DLLs, and debugging DLLs with CodeView. %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@CR:C6A00140001 @%%@1@%%@AB@%Chapter 14 Building OS/2 Applications%@AE@%%@EH@%%@NL@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@NL@% Using Microsoft C 6.0, you can create applications for OS/2. This chapter explains features in the compiler and the utilities that %@NL@% %@NL@% %@NL@% ■ Call the OS/2 operating system directly from C functions%@NL@% %@NL@% ■ Perform multitasking within your program by starting multiple execution paths known as "threads"%@NL@% %@NL@% ■ Create dynamic-link libraries that can be used by multiple applications%@NL@% %@NL@% ■ Work in either OS/2 or DOS to create programs for both environments%@NL@% %@NL@% ■ Develop "dual-mode" applications that will run under both OS/2 and DOS from a single executable program file%@NL@% %@NL@% %@NL@% This chapter contains information about accessing the OS/2 Applications Program Interface (API) from your C programs. It also discusses compile options that affect applications you develop for OS/2, module-definition files and import libraries, linker options specific to developing OS/2 applications, and using the BIND utility to create dual-mode applications. %@NL@% %@NL@% Chapters 15 and 16, "Creating Multithread OS/2 Applications" and "Dynamic-Linking with OS/2," contain detailed information about how Microsoft C supports these advanced OS/2 features. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00140002 @%%@AB@%14.1 The OS/2 Applications Program Interface%@AE@%%@EH@%%@NL@% %@NL@% The entire set of OS/2 system calls is known as the OS/2 API. You need to access the OS/2 API for the low-level functions provided by the operating system, such as %@NL@% %@NL@% %@NL@% ■ Requests for information about the display%@NL@% %@NL@% ■ Requests to display information%@NL@% %@NL@% ■ Requests for information from the pointing device (mouse)%@NL@% %@NL@% ■ Requests for information from the keyboard%@NL@% %@NL@% ■ Requests for blocks of memory%@NL@% %@NL@% ■ Requests for disk actions, including reading and writing%@NL@% %@NL@% %@NL@% You can call all of the OS/2 system services directly from programs written in C. Under DOS, the API operates at a lower level, requiring programs to set up hardware registers and generate a software interrupt to access the system services. Under OS/2, programs use function calls to access the operating system services. %@NL@% %@NL@% Sections 14.1.1-14.1.3 describe the calling conventions and precautions you must observe when accessing OS/2 API functions. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00140003 @%%@AB@%14.1.1 Calling the OS/2 API%@AE@%%@EH@%%@NL@% %@NL@% Your program must declare calls to the OS/2 API with both the %@AB@%_far%@AE@% and %@AB@%_pascal%@AE@% keywords. Adding the %@AB@%_pascal%@AE@% keyword to the function declaration ensures that the FORTRAN/Pascal calling convention is used. The %@AB@%_far%@AE@% keyword directs the compiler to generate an intersegment call instruction. A sample declaration for the OS/2 API function %@AB@%DosExit%@AE@% follows:%@CR:C6A00140004 @% %@NL@% %@NL@% %@AS@% void _far _pascal DosExit( unsigned int, unsigned int );%@AE@%%@NL@% %@NL@% You must be sure that all pointers passed to OS/2 API functions are far pointers, even if you are writing a program using the small or medium memory models. This process can be simplified if you include the OS2.H header file. %@NL@% %@NL@% %@AU@% OS/2 API function calls are far and must use the FORTRAN/ Pascal calling %@AU@%convention.%@AE@% %@NL@% %@NL@% OS/2 API functions use the FORTRAN/Pascal language calling convention. They expect arguments to be pushed onto the stack in left-to-right order, with the last argument in the list pushed onto the stack last. OS/2 API functions remove their arguments from the stack before returning to the caller. Standard C functions push their arguments from right to left, with the first argument being the last one pushed. %@NL@% %@NL@% All OS/2 API functions return 0 if the operation is successful. They return an error code if the operation fails. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00140005 @%%@AB@%14.1.2 Including the OS/2 Header Files%@AE@%%@EH@%%@NL@% %@NL@% You do not have to construct your own API declarations if you use the OS2.H header file. It is the first file of a set of header files that supply function prototypes for every OS/2 API call and definitions of special OS/2 structures, data types, and constants. %@NL@% %@NL@% The API function prototypes define all functions as far procedures with the FORTRAN/Pascal calling convention. They also take care of casting all near pointers to far pointers and other similar type coercions. %@NL@% %@NL@% %@AU@% Define a constant before including OS2.H.%@AE@% %@NL@% %@NL@% When you include OS2.H, the most commonly used data types and macros are automatically defined. To minimize compile time for the C preprocessor, other definitions are grouped by function. They are included only if your source file defines the appropriate constant before including OS2.H. The following list shows how these manifest constants affect functions from the OS/2 API: %@NL@% %@NL@% %@AB@%Constant%@AE@% %@AB@%Effect%@AE@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@AB@%INCL_BASE%@AE@% All error constants, kernel, keyboard, video, and mouse definitions (same as %@AB@%%@AE@% %@AB@%INCL_DOS%@AE@% +%@AB@% INCL_SUB%@AE@% + %@AB@%INCL_DOSERRORS%@AE@%) %@AB@%INCL_DOS%@AE@% All kernel system definitions %@AB@%INCL_DOSERRORS%@AE@% All error constants %@AB@%INCL_KBD%@AE@% All keyboard definitions %@AB@%INCL_MOU%@AE@% All mouse definitions %@AB@%INCL_SUB%@AE@% All keyboard, video, and mouse definitions (same as %@AB@%INCL_KBD%@AE@% + %@AB@%INCL_VIO%@AE@% + %@AB@%INCL_MOU)%@AE@% %@AB@%INCL_VIO%@AE@% All video-display definitions %@AB@%INCL_WIN%@AE@% Basic set of Presentation Manager definitions The header files have additional constants that let you include smaller subsets or functions not defined in the standard sets. %@NL@% %@NL@% %@AU@% The statement #define INCL_DOS affects the functions defined.%@AE@% %@NL@% %@NL@% The program in the example below calls the OS/2 kernel to request a nonshareable, nondiscardable memory segment for an 8K buffer. The %@AB@%INCL_DOS%@AE@% constant in the %@AB@%#define%@AE@% statement instructs the C preprocessor to include all of the kernel function definitions. The function prototype for %@AB@%DosAllocSeg%@AE@% declares the first and third arguments as %@AB@%USHORT%@AE@% (unsigned short integers). The second argument is a far pointer to the OS/2 data type %@AB@%SEL%@AE@%, which is used for segment selectors. %@NL@% %@NL@% %@AS@% #define INCL_DOS %@AS@% #include <os2.h> %@AS@% %@AS@% VOID GetMemorySegment() %@AS@% { %@AS@% SEL selector; %@AS@% %@AS@% if ( DosAllocSeg( 8192, &selector, 0 ) ) %@AS@% puts( "Allocation failed\n" ); %@AS@% else %@AS@% puts( "Successful allocation\n" ); %@AS@% }%@AE@%%@NL@% %@NL@% The function call in the example works correctly even in a small or medium memory model program where the selector variable is a %@AB@%near data%@AE@% type. All three arguments are coerced by the function prototype to the proper types, regardless of the memory model used. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00140006 @%%@AB@%14.1.3 Creating Dual-Mode Programs as Family Applications%@AE@%%@EH@%%@NL@% %@NL@% The OS/2 API has a subset of system functions that have direct DOS equivalents. This subset is known as the "Family Applications Program Interface" (Family API). Programs that use only the Family API can be run under DOS and the OS/2 compatibility box, as well as under OS/2. %@NL@% %@NL@% %@AU@% You can build a single executable file for use under both OS/2 and DOS.%@AE@% %@NL@% %@NL@% By creating a Family API application, you can distribute the same executable file to both OS/2 and DOS users. The Microsoft C compiler, linker, and object module librarian are examples of family applications. The benefit of having a single executable file is offset by a few disadvantages: %@NL@% %@NL@% %@NL@% ■ The executable file is larger, because it includes a special loader and OS/2 API-simulator routines for running in DOS mode.%@NL@% %@NL@% ■ In real mode, the application loads more slowly than a program created specifically for either OS/2 or DOS. There is no performance penalty in loading or running in OS/2 protected mode.%@NL@% %@NL@% ■ When running in real mode, the program cannot use advanced OS/2 features such as multiple threads or system calls that are not part of the Family API. If you take special precautions (described in Section 14.5, "The BIND Utility"), the program can take advantage of these features when running in OS/2 protected mode. %@NL@% %@NL@% %@NL@% Follow the same steps to build both family and protected-mode applications but add an extra step at the end to create the Family API program. This step links functions from the dynamic-link libraries directly into a stand-alone executable file that can run in both real and protected mode. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Restrictions on Family Applications%@AE@%%@EH@%%@NL@% %@NL@% Programs that use the Family API are subject to certain restrictions: %@NL@% %@NL@% %@NL@% ■ They cannot overcommit memory; they must fit into the DOS 640K environment.%@NL@% %@NL@% ■ They cannot use advanced OS/2 features, such as threads and semaphores, that do not have DOS counterparts.%@NL@% %@NL@% ■ They must restrict their use of some calls to the defined common subset. For example, some of the file-mode options for the %@AB@%DosOpen%@AE@% function are not available in real mode.%@NL@% %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Family API Functions%@AE@%%@EH@%%@NL@% %@NL@% The system calls that make up Family API are listed below. The calls marked with an asterisk (*) have different options or behavior, depending on whether they are running in real mode or protected mode. The %@AI@%Microsoft OS/2 %@AI@%Programmer's Reference%@AE@% explains the functions and the differences between their real- and protected-mode implementations. %@NL@% %@NL@% %@AB@%DosAllocHuge* DosHoldSignal* DosSubSet%@AE@% %@AB@%DosAllocSeg* DosInsMessage* DosWrite%@AE@% %@AB@%DosBeep DosMkDir KbdCharIn*%@AE@% %@AB@%DosBufReset DosMove KbdFlushBuffer*%@AE@% %@AB@%DosCaseMap* DosNewSize KbdGetStatus*%@AE@% %@AB@%DosChdir DosOpen* KbdPeek*%@AE@% %@AB@%DosChgFilePtr DosPutMessage* KbdSetStatus*%@AE@% %@AB@%DosCLIAccess DosQCurDir KbdStringIn*%@AE@% %@AB@%DosClose DosQCurDisk VioGetBuf%@AE@% %@AB@%DosCreateCSAlias* DosQFHandState VioGetConfig%@AE@% %@AB@%DosDelete DosQFileInfo VioGetCurPos%@AE@% %@AB@%DosDevConfig DosQFileMode VioGetCurType%@AE@% %@AB@%DosDevIOCtl* DosQFSInfo VioGetMode%@AE@% %@AB@%DosDupHandle DosQHandType VioGetPhysBuf%@AE@% %@AB@%DosErrClass DosQVerify VioReadCellStr%@AE@% %@AB@%DosError* DosRead* VioReadCharStr%@AE@% %@AB@%DosExecPgm* DosReallocHuge* VioScrLock*%@AE@% %@AB@%DosExit* DosReallocSeg* VioScrollDn%@AE@% %@AB@%DosFileLocks DosRmDir VioScrollLf%@AE@% %@AB@%DosFindClose DosSelectDisk VioScrollRt%@AE@% %@AB@%DosFindFirst DosSetCp VioScrollUp%@AE@% %@AB@%DosFindNext* DosSetDateTime VioScrUnLock%@AE@% %@AB@%DosFreeSeg* DosSetFHandState* VioSetCurPos%@AE@% %@AB@%DosGetCollate* DosSetFileInfo VioSetCurType%@AE@% %@AB@%DosGetCp DosSetFileMode VioSetMode%@AE@% %@AB@%DosGetCtryInfo* DosSetFSInfo VioShowBuf%@AE@% %@AB@%DosGetDateTime DosSetSigHandler* VioWrtCellStr%@AE@% %@AB@%DosGetDBSCEv* DosSetVec* VioWrtCharStr%@AE@% %@AB@%DosGetEnv DosSetVerify VioWrtCharStrAtt%@AE@% %@AB@%DosGetHugeShift DosSizeSeg VioWrtNAttr%@AE@% %@AB@%DosGetMachineMode DosSleep VioWrtNCell%@AE@% %@AB@%DosGetMessage* DosSubAlloc VioWrtNChar%@AE@% %@AB@%DosGetVersion DosSubFree VioWrtTTy %@AE@% %@2@%%@CR:C6A00140007 @%%@AB@%14.2 Compile Options for the CL Command%@AE@%%@EH@%%@NL@% %@NL@% This section describes the compile options you must specify in the Programmer's WorkBench or on the CL command line to designate a program's target environment (OS/2, DOS, or both). It also introduces options you should use with certain types of OS/2 applications, such as multithread programs, dynamic-link libraries, and programs calling C function dynamic-link libraries. For an in-depth discussion of topics that affect multithread processes and dynamic-link libraries, see Chapter 15, "Creating Multithread OS/2 Applications," and Chapter 16, "Dynamic-Linking with OS/2." %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00140008 @%%@AB@%14.2.1 The Link Mode Options (/Lp, /Lr, and /Lc)%@AE@%%@EH@%%@NL@% %@NL@% The /L%@AI@%x%@AE@% options (/Lp, /Lr, and /Lc) provide the flexibility of programming for both OS/2 and DOS in either environment. Regardless of the host operating system, you can build applications for either target operating system. You do not have to switch to the target system to build the program. %@NL@% %@NL@% The /Lp option produces an OS/2 protected-mode program; the /Lr option creates a DOS real-mode program. /Lc is a synonym for /Lr.%@CR:C6A00140009 @%%@CR:C6A00140010 @%%@CR:C6A00140011 @%%@CR:C6A00140012 @% %@NL@% %@NL@% To use these options, the mode-specific combined libraries must be installed. Unless you choose a default operating environment, each mode-specific library has the letter P or R at the end of its base name. For example, the protected-mode small memory model library with the emulator floating-point option is named SLIBCEP.LIB. The corresponding real-mode library is named SLIBCER.LIB. The default name, however, is SLIBCE.LIB. %@NL@% %@NL@% %@AI@%Installing and Using the Microsoft C Professional Development System%@AE@% describes how to create mode-specific libraries with the SETUP program. It also explains how to establish a default target environment by renaming libraries. A default environment is useful if you work mainly in one mode (OS/2 or DOS) but sometimes write programs for the other mode. When you set up OS/2 as the default mode, SLIBCEP.LIB, for example, becomes SLIBCE.LIB. %@NL@% %@NL@% %@AU@% Don't use /Lx options unless you have mode-specific libraries.%@AE@% %@NL@% %@NL@% When you use the /L%@AI@%x%@AE@% options, you instruct the compiler to override the default library name in the object module's library search record and to substitute the mode-specific combined library name. The compiler also generates a link response file with the /NODEFAULTLIBRARYSEARCH (/NOD) linker option to override the default library. See Section 14.4, "Link Command-Line Options," for more information about the /NOD option. %@NL@% %@NL@% Do not use the /Lp option to specify protected mode when OS/2 is the default environment. If you do this, the compiler uses the name of the mode-specific library (e.g., SLIBCEP.LIB). Because SETUP renamed the library to SLIBCE.LIB to create a default environment, the library search fails. This caution also applies to specifying /Lr when you have installed DOS as the default environment. %@NL@% %@NL@% If you invoke the linker in a separate step from the compilation, you must specify the /NOD link option. %@NL@% %@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% NOTE %@AI@%There is a special library, LLIBCMT, for building multithread OS/2 %@AI@%applications. Another special library, LLIBCDLL, supports multithread %@AI@%dynamic-link libraries. If you use LLIBCMT or LLIBCDLL, you must use one of %@AI@%the library selection options described in Section 14.2.3 instead of %@AI@%/%@AE@%%@AI@% Lp.%@AE@%%@AE@%%@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00140013 @%%@AB@%14.2.2 Creating Bound Programs Option (/Fb)%@AE@%%@EH@%%@NL@% %@NL@% The /Fb option allows you to compile, link, and bind an application in one step. Binding an executable file creates a Family API program that can run under both OS/2 and DOS.%@CR:C6A00140014 @%%@CR:C6A00140015 @%%@CR:C6A00140016 @% %@NL@% %@NL@% When you use /Fb, the compiler invokes the BIND utility program immediately after the link step. You can also execute BIND directly (as described in Section 14.5, "The BIND Utility"). You must have the API.LIB and OS2.LIB files in the path specified by the LIB environment variable or in your current working directory. %@NL@% %@NL@% The syntax for the /Fb option is %@NL@% %@NL@% %@AS@% /Fb«bound-exe»%@AE@%%@NL@% %@NL@% %@AU@% You can specify a separate name for a bound-executable file.%@AE@% %@NL@% %@NL@% The optional %@AI@%bound-exe%@AE@% parameter specifies the name of the bound program. It must directly follow the /Fb option, without intervening spaces. The %@AI@%bound-exe%@AE@% name can be a file specification, a drive name, or a directory specification. If you specify a file name without an extension, the compiler appends the .EXE extension to the name. If you give a directory specification for %@AI@%bound-exe%@AE@%, the name must end with a backslash ( \ ) so the compiler can distinguish it from an ordinary file name. If you do not supply a name, BIND uses the name of the unbound program and overwrites it. %@NL@% %@NL@% When creating both bound and protected-mode versions with different names, consider this example: %@NL@% %@NL@% %@AS@% CL /Lp /Fbsampleb sample.c%@AE@%%@NL@% %@NL@% The protected-mode executable file that this command creates is called SAMPLE.EXE; the bound-executable file is called SAMPLEB.EXE. %@NL@% %@NL@% %@AU@% You may need to run BIND as a separate step instead of using the /Fb %@AU@%option.%@AE@% %@NL@% %@NL@% The /Fb option works only if you are doing a single-step compile and link. If the CL command line includes the /c (compile without link) option, the compiler ignores the /Fb option. If you use /c, you must run the BIND utility as a separate step of the program build. %@NL@% %@NL@% If your program includes calls to API functions that are not in the FAPI subset, you must use the /n option of the BIND utility, described in Section 14.5, to build the dual-mode executable file. If you need to use the /n BIND option, you cannot compile with /Fb. You must compile without linking by using the /c option at the compile stage; then link the program and run the BIND utility with the /n option. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00140017 @%%@AB@%14.2.3 Library Selection Options (/MT, /ML, /MD, /Zl)%@AE@%%@EH@%%@NL@% %@NL@% Special libraries are provided for building OS/2 multithread applications and dynamic-link libraries. You must not use these libraries with any other C run-time library.%@CR:C6A00140018 @% %@NL@% %@NL@% %@AU@% Special libraries must be the only C run-time libraries linked with your %@AU@%program.%@AE@% %@NL@% %@NL@% If you use one of these special libraries, apply one of the library selection options (/ML, /MD, or /MT) to tell the compiler to replace the default library name in the object file with the name of the special library. This ensures that the linker does not bring in code from the default libraries. If you do not specify one of the options when compiling, you must link with the /NOD option to prevent search of a default library, such as SLIBCE.LIB. %@NL@% %@NL@% If you fail to include any of these options, the linker searches the default library and may select the wrong version of a library function. It might, for example, select the single thread version of the %@AB@%printf%@AE@% function for a multithread program that has more than one thread calling %@AB@%printf%@AE@%. %@NL@% %@NL@% Because the /Lp option (see Section 14.2.1, "The Link Mode Options") instructs the compiler to specify the default protected-mode libraries rather than the special multithread or DLL-specific libraries, do not use it with /Zl or /Mx. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Multithread Library Option (/MT)%@AE@%%@EH@%%@NL@% %@NL@% When you specify the /MT option, the compiler embeds the LLIBCMT.LIB library name in the object file. Chapter 15, "Creating Multithread OS/2 Applications," explains how to build multithread applications using LLIBCMT.LIB. The /MT option also has the effect of combining these command-line options: %@NL@% %@NL@% %@AS@% /ALw /FPi /G2 /D MT%@AE@%%@NL@% %@NL@% %@NL@% %@4@%%@AB@%C Run-Time Library for Building DLLs (/ML)%@AE@%%@EH@%%@NL@% %@NL@% Use the /ML option to specify that you are building a dynamic-link library that calls functions in LLIBCDLL.LIB, the C run-time library for dynamic-link libraries. The library name is embedded in the object file. The /ML option also has the effect of combining these command-line options: %@NL@% %@NL@% %@AS@% /ALw /FPa /G2 /D MT%@AE@%%@NL@% %@NL@% %@NL@% %@4@%%@AB@%C Run-Time Library for DLLs (/MD)%@AE@%%@EH@%%@NL@% %@NL@% Use the /MD option to create a dynamic-link library of C run-time routines. With this option, the object file does not have any library search records. The /MD option has the effect of combining these command-line options: %@NL@% %@NL@% %@AS@% /ALw /FPi /G2 /DDLL /D MT%@AE@%%@NL@% %@NL@% Chapter 16, "Dynamic Linking with OS/2," describes the process of building and using dynamic-link libraries with LLIBCDLL.LIB. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Suppress Default Library Option (/Zl)%@AE@%%@EH@%%@NL@% %@NL@% Use the /Zl option when you want to suppress selection of a default library. It tells the compiler not to place the default library name in the object file.%@CR:C6A00140019 @% %@NL@% %@NL@% %@AU@% You can specify libraries and additional LINK options on the CL command %@AU@%line.%@AE@% %@NL@% %@NL@% You can specify link options or the names of libraries on the CL command line with the /LINK option. You can also give the library name, with its .LIB extension, before the /LINK option. Each command below selects the multithread C run-time library: %@NL@% %@NL@% %@AS@% CL /Zl myprog.c llibcmt.lib %@AS@% %@AS@% CL /Zl myprog.c /link llibcmt%@AE@%%@NL@% %@NL@% If you compile with the /c (compile without link) option, your link command must include the library name: %@NL@% %@NL@% %@AS@% LINK myprog, myprog.exe, myprog.map, llibcmt.lib, myprog.def%@AE@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00140020 @%%@AB@%14.2.4 Memory-Model Options (/Ax)%@AE@%%@EH@%%@NL@% %@NL@% You must select the memory model appropriate to your application. For protected-mode applications, the large model provides the most convenient interface with the special libraries. It provides the additional benefit of placing code and data into multiple segments, allowing OS/2 to swap parts of the program to disk efficiently. %@NL@% %@NL@% %@AU@% Use the large memory model with LLIBCMT (/AL and /MT).%@AE@% %@NL@% %@NL@% The multithread run-time C library, LLIBCMT.LIB, is a large-model library. All library function calls must be far calls. In addition, all pointers passed to functions in the library must be far pointers. If you do not compile with the /AL option, you use must use the keyword %@AB@%_far%@AE@% when declaring pointers. Variables can be declared either near or far as long as they are either passed by value or cast to a far address. %@NL@% %@NL@% If you want to call %@AB@%fopen %@AE@%for example, you must use code such as the following: %@NL@% %@NL@% %@AS@% FILE _far * fp; %@AS@% fp = fopen( ... );%@AE@%%@NL@% %@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% NOTE %@AI@%If you are using the compact, large, or huge memory model, data pointers are %@AI@%far by default, so you do not need to explicitly specify %@AB@%_far%@AE@%%@AI@%.%@AE@%%@AE@%%@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@%%@NL@% %@NL@% %@AU@% Because each thread has its own stack, you have to compile in an SS != DS %@AU@%model.%@AE@% %@NL@% %@NL@% Multithread applications require that each thread have its own stack. As a result, you cannot safely assume that the stack segment is in the default data group (DGROUP). That means that the stack segment can be different from the data segment (SS != DS). %@NL@% %@NL@% To specify that you have selected an SS != DS model, you must use the /Au or /Aw option. The /MT option is a shorthand way of specifying this combination of options to the compiler: %@NL@% %@NL@% %@AS@% /ALw/FPi/G2/DMT%@AE@%%@NL@% %@NL@% The /MT option also causes the compiler to place a library search record for LLIBCMT in the object file. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00140021 @%%@AB@%14.3 Module-Definition Files and Import Libraries%@AE@%%@EH@%%@NL@% %@NL@% A module-definition file tells the linker about the characteristics of an application or dynamic-link library. It describes names, segments, memory requirements, and import and export definitions. Export definitions make functions in the OS/2 dynamic-link libraries (DLLs) available to other programs. Each export definition specifies a function name. A program using these functions must have import definitions in order to find each dynamic-link function. Each import definition specifies a function name and the name of the dynamic-link library where the function resides. %@NL@% %@NL@% The IMPLIB utility generates a library of import definitions that can be examined during the link. For imported functions, the import library can be used in place of a module-definition file. %@NL@% %@NL@% Module-definition files are optional for most OS/2 programs. Two types of programs must use them: %@NL@% %@NL@% %@NL@% ■ Dynamic-link libraries%@NL@% %@NL@% ■ Programs with I/O privileges%@NL@% %@NL@% %@NL@% Each module-definition file contains one or more module statements defining attributes of the executable program. The statements and their associated attributes are listed below: %@NL@% %@NL@% %@AB@%Statement%@AE@% %@AB@%Attribute%@AE@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@AB@%CODE%@AE@% Gives default attributes for code segments %@AB@%DATA%@AE@% Gives default attributes for data segments %@AB@%DESCRIPTION%@AE@% Describes the module in one line %@AB@%EXETYPE%@AE@% Identifies the operating system %@AB@%EXPORTS%@AE@% Defines exported functions %@AB@%HEAPSIZE%@AE@% Specifies local heap size, in bytes %@AB@%IMPORTS%@AE@% Defines imported functions %@AB@%LIBRARY%@AE@% Names a dynamic-link library %@AB@%NAME%@AE@% Names an application %@AB@%OLD%@AE@% Preserves import information from a previous version of the library %@AB@%PROTMODE%@AE@% Specifies that the module runs only in OS/2 protected mode %@AB@%REALMODE%@AE@% Relaxes some restrictions that the linker imposes for protected-mode programs %@AB@%SEGMENTS%@AE@% Gives attributes for specific segments %@AB@%STACKSIZE%@AE@% Specifies local stack size, in bytes %@AB@%STUB%@AE@% Adds a DOS 3.x executable file to the beginning of the module, usually to terminate the program when run in real mode In addition to the keywords listed above, each statement includes one or more fields to complete the attribute description. All keywords must be entered in uppercase. You can include comments in the module-definition file by beginning the line with a semicolon (;). For a complete list of the keywords and their meaning, see on-line help for information about module-definition files. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00140022 @%%@AB@%14.3.1 Adding a Module-Definition File to the LINK Command%@AE@%%@EH@%%@NL@% %@NL@% The module-definition file name is the last field of the link command: %@NL@% %@NL@% %@AS@% LINK objects «,«exe» » «, «map» » «, «lib» » «, «def» » «;»%@AE@%%@NL@% %@NL@% This example uses the default libraries: %@NL@% %@NL@% %@AS@% LINK sample, sample.exe, sample.map,,sample.def%@AE@%%@NL@% %@NL@% When you use a module-definition file, you must use the /c option on the CL command line and link in a separate step. If you are linking without a module-definition file, you can use a semicolon after your last entry to suppress LINK's prompt for the module-definition file name and other missing parameters. %@NL@% %@NL@% The segmented-executable linker is the only LINK program that recognizes module-definition files. Since it is backwards compatible, it should be the only linker in your path. The QuickC linker does not process these files. %@NL@% %@NL@% The following sections illustrate ways to use module-definition files. On-line help describes all of the commands and options available. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00140023 @%%@AB@%14.3.2 Creating Dynamic-Link Libraries (DLLs)%@AE@%%@EH@%%@NL@% %@NL@% You can build your own dynamic-link libraries. A simple module-definition file for such a library with one public function is shown below:%@CR:C6A00140024 @% %@NL@% %@NL@% %@AS@% LIBRARY Mylib INITINSTANCE %@AS@% %@AS@% DATA MULTIPLE %@AS@% %@AS@% EXPORTS %@AS@% MyProc%@AE@%%@NL@% %@NL@% You can use the same module-definition file you used to create the dynamic-link library as input to the IMPLIB utility. IMPLIB generates a library file with a .LIB extension for use by applications calling your dynamic-link routines. Section 14.3.5 describes the IMPLIB program. Chapter 16, "Dynamic Linking with OS/2," explains how to build a dynamic-link library. %@NL@% %@NL@% The %@AB@%LIBRARY%@AE@% statement tells the linker that this is a dynamic-link library rather than an application. (Applications use the %@AB@%NAME%@AE@% statement instead of the %@AB@%LIBRARY%@AE@% statement.) %@NL@% %@NL@% The %@AB@%EXPORTS%@AE@% statement gives the name of the public function. %@NL@% %@NL@% %@AU@% You can designate exported functions in a C source file.%@AE@% %@NL@% %@NL@% The C language keyword %@AB@%_export%@AE@% is an alternative to the %@AB@%EXPORTS%@AE@% statement. When %@AB@%_export%@AE@% appears in a function declaration or definition, the compiler puts the function and its parameter size in the object module's export record. Functions with the %@AB@%_export%@AE@% keyword that are not listed in the module-definition file cannot have input/output privileges or alias names. %@NL@% %@NL@% %@AU@% Using generic library names is dangerous.%@AE@% %@NL@% %@NL@% Since OS/2 systems have many dynamic-link libraries installed, try to pick a name that uniquely identifies your library. If you choose a generic name, such as CRT.DLL or WINDOWS.DLL, you run the risk of having your library overwritten by someone else's dynamic-link library with the same name. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00140025 @%%@AB@%14.3.3 Creating Programs with I/O Privileges%@AE@%%@EH@%%@NL@% %@NL@% OS/2 programs that must access hardware directly can designate a code segment with input/output privileges. This segment can then perform a limited set of I/O instructions but cannot make any calls to dynamic-link libraries. %@NL@% %@NL@% You cannot use the C run-time library functions %@AB@%inp%@AE@% and %@AB@%outp%@AE@% for input and output. Their use is limited to real-mode programs. You can, however, use in-line assembler code in your C source program to access a port. %@NL@% %@NL@% The sample module-definition file below shows two segments for a program: %@NL@% %@NL@% %@AS@% NAME IOPROG %@AS@% %@AS@% EXETYPE OS/2 %@AS@% %@AS@% SEGMENTS %@AS@% _IOSEG IOPL %@AS@% _TEXT NOIOPL %@AS@% %@AS@% EXPORTS %@AS@% CharIn 4 %@AS@% CharOut 4%@AE@%%@NL@% %@NL@% The first code segment contains the I/O portion of the program and has the %@AB@%IOPL %@AE@%keyword. The second segment is designated %@AB@%NOIOPL %@AE@%(the default). %@NL@% %@NL@% %@AU@% The EXPORT statement for IOPL functions must include parameter size.%@AE@% %@NL@% %@NL@% The %@AB@%EXPORTS %@AE@%section names two functions in the %@AB@%IOPL%@AE@% segment that can be called by procedures outside the segment. It also specifies the size of the function's parameters. Procedures with I/O privileges must specify the number of words needed for their parameters. %@NL@% %@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% NOTE %@AI@%Unless the user has specified IOPL=YES in the CONFIG.SYS file, the program %@AI@%will not load.%@AE@%%@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00140026 @%%@AB@%14.3.4 Creating Presentation Manager Applications%@AE@%%@EH@%%@NL@% %@NL@% The Presentation Manager calls window and dialog procedures inside a Presentation Manager application. The sample module-definition file below exports these procedures and gives the linker additional instructions for building the program. Module-definition files are optional for Presentation Manager applications. They can be used to control the way different segments of the program are loaded. %@NL@% %@NL@% %@AS@% NAME PMSAMPLE WINDOWAPI %@AS@% %@AS@% EXETYPE OS/2 %@AS@% STACKSIZE 4096 %@AS@% %@AS@% SEGMENTS %@AS@% _INIT PRELOAD %@AS@% _HELP LOADONCALL %@AS@% _TEXT LOADONCALL%@AE@%%@NL@% %@NL@% In the preceding example, the %@AB@%NAME %@AE@%statement identifies the program as an application named PMSAMPLE. The %@AB@%WINDOWAPI %@AE@%keyword tells the linker to mark the executable file as a Presentation Manager application. Only programs marked as windows applications or windows-compatible applications can share the Presentation Manager screen group. %@NL@% %@NL@% The %@AB@%EXETYPE %@AE@%statement tells the linker to build a program that runs only in protected mode and to produce the optimal executable file for OS/2. %@NL@% %@NL@% The %@AB@%STACKSIZE %@AE@%statement allocates 4096 bytes of local stack space. This is the minimum stack size recommended for Presentation Manager programs. %@NL@% %@NL@% %@AU@% You can reduce run-time memory requirements.%@AE@% %@NL@% %@NL@% The %@AB@%SEGMENTS %@AE@%statement controls the way code and data segments are handled. By default, segments are not brought into physical memory until needed. The %@AB@%PRELOAD %@AE@%keyword in the example tells the system loader to load the %@AS@% _INIT %@AE@% segment when the program starts. The %@AS@% _TEXT %@AE@% and %@AS@% _HELP %@AE@% segments are loaded on demand. You can use the compiler's /NT option to generate your own segment names, such as %@AS@% _INIT %@AE@% and %@AS@% _HELP%@AE@%. Separate segments are useful for code that is executed infrequently, such as a help subsystem. This reduces the amount of run-time memory required for your application, since each segment will be loaded when and if there is a request for it. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00140027 @%%@AB@%14.3.5 Creating Import Libraries with the IMPLIB Utility%@AE@%%@EH@%%@NL@% %@NL@% Applications that call dynamic-link library functions must use import definitions that specify the location of each dynamic-link function. The definitions consist of a function name and the name of the dynamic-link library file where it resides.%@CR:C6A00140028 @% %@NL@% %@NL@% Although the application can use a module-definition file to create the import definitions, it is easier to use import libraries built by the IMPLIB utility. %@NL@% %@NL@% IMPLIB creates an import library in the form of a file with a .LIB extension, which is read by the linker. At link time, the .LIB file is specified in the LINK command line, along with other libraries. %@NL@% %@NL@% IMPLIB accepts two types of sources: %@NL@% %@NL@% %@NL@% ■ The module-definition file used to create the dynamic-link library%@NL@% %@NL@% ■ The dynamic-link library itself%@NL@% %@NL@% %@NL@% The IMPLIB command has the syntax: %@NL@% %@NL@% %@AS@% IMPLIB «/c»libfile deffile «deffile ...»%@AE@%%@NL@% %@NL@% or %@NL@% %@NL@% %@AS@% IMPLIB «/c»libfile dynlib «dynlib ...»%@AE@%%@NL@% %@NL@% The /c option directs IMPLIB to be case sensitive. By default, it is case insensitive. %@NL@% %@NL@% The %@AI@%libfile %@AE@%field names the new import library file. The %@AI@%deffile %@AE@%or %@AI@%dynlib %@AI@%%@AE@%fields name the input files, which are dynamic-link library or module-definition files. %@NL@% %@NL@% The following example creates the import library file named MYLIB.LIB from the MYLIB.DLL dynamic-link library: %@NL@% %@NL@% %@AS@% IMPLIB mylib.lib mylib.dll%@AE@%%@NL@% %@NL@% For more information about import libraries and IMPLIB, consult on-line help. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00140029 @%%@AB@%14.4 Link Command-Line Options%@AE@%%@EH@%%@NL@% %@NL@% This section describes command-line options that control various aspects of the linker and the circumstances in which you will need to use them.%@CR:C6A00140030 @%%@CR:C6A00140031 @% %@NL@% %@NL@% %@NL@% %@4@%%@AB@%/NODEFAULTLIBRARYSEARCH (/NOD)%@AE@%%@EH@%%@NL@% %@NL@% %@AU@% If you did not compile with /MT, /MD, or /ML, suppress default library %@AU@%searching.%@AE@% %@NL@% %@NL@% The /NODEFAULTLIBRARYSEARCH option prevents the linker from searching any library specified in an object file. When you specify this option, you should also specify the name of the library to be linked. The minimum abbreviation for this option is /NOD. %@NL@% %@NL@% If you are using the multithread library, LLIBCMT, or the dynamic-link library, LLIBCDLL, you should use this option. Use it with dynamic-link libraries built with LLIBCDLL. This is mandatory if you did not compile with the /Zl, /MT, or /ML options. %@NL@% %@NL@% You can select a specific library by appending the library name to the /NOD option, as in %@NL@% %@NL@% %@AS@% /NOD:LLIBCMT.LIB%@AE@%%@NL@% %@NL@% %@NL@% %@4@%%@AB@%/NOEXTENDEDDICTSEARCH (/NOE)%@AE@%%@EH@%%@NL@% %@NL@% The /NOEXTENDEDDICTSEARCH option prevents the linker from searching the extended dictionary, which is an internal list of symbol locations maintained by the linker. You need to use this option if a library symbol (such as %@AB@%_setargv%@AE@%, %@AB@%_binmode%@AE@%, or %@AB@%_varstck%@AE@%) is redefined and you receive error L2044 from the linker. The minimum abbreviation for this option is /NOE.%@CR:C6A00140032 @%%@CR:C6A00140033 @% %@NL@% %@NL@% %@NL@% %@4@%%@AB@%/NOIGNORECASE (/NOI)%@AE@%%@EH@%%@NL@% %@NL@% The /NOIGNORECASE option preserves case sensitivity. By default, LINK maps all names to uppercase characters. Because many C function names are a mix of upper- and lowercase letters, it is important to use this option. The compile option /Zc causes any name declared with the %@AB@%_pascal%@AE@% keyword to be treated without regard to case at the source level. The minimum abbreviation is /NOI. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%/PMTYPE%@AE@%%@EH@%%@NL@% %@NL@% The /PMTYPE option is an alternative to specifying Presentation Manager compatibility with the %@AB@%NAME%@AE@% statement of a module-definition file. Use the following syntax: %@NL@% %@NL@% %@AS@% /PMTYPE:type%@AE@%%@NL@% %@NL@% Type must be one of the following: %@NL@% %@NL@% %@AB@%Type%@AE@% %@AB@%Effect%@AE@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@AB@%PM%@AE@% The application is an OS/2 Presentation Manager application using the Presentation Manager API and running in the Presentation Manager screen group. This type corresponds to specifying %@AB@%%@AE@% %@AB@%WINDOWAPI%@AE@% in the %@AB@%NAME%@AE@% statement of a module-definition file. %@AB@%VIO%@AE@% The application is compatible with the OS/2 Presentation Manager and can run in a window or in a separate screen group. This type corresponds to specifying %@AB@%WINDOWCOMPAT%@AE@% in the %@AB@%NAME %@AE@%statement of a module-definition file. %@AB@%NOVIO%@AE@% The application is not compatible with the OS/2 Presentation Manager. It must run in a separate screen group. This type corresponds to specifying%@AB@%%@AE@% %@AB@%NOTWINDOWCOMPAT%@AE@% in the %@AB@%NAME%@AE@% statement of a module-definition file. %@NL@% %@2@%%@CR:C6A00140034 @%%@AB@%14.5 The BIND Utility%@AE@%%@EH@%%@NL@% %@NL@% The BIND utility converts a protected-mode program into a program that runs in both OS/2 and DOS environments. It replaces Family API calls to dynamic-link library functions with DOS emulator routines from the API.LIB library. (See Section 14.1.3, "Creating Dual-Mode Programs as Family Applications," for a list of Family API calls.) BIND produces a stand-alone program file that can run under %@NL@% %@NL@% %@NL@% ■ OS/2 protected mode%@NL@% %@NL@% ■ OS/2 real mode%@NL@% %@NL@% ■ DOS 2.x and DOS 3.x%@NL@% %@NL@% %@NL@% BIND is an alternative to the C compiler's /Fb option described in Section 14.2.2, "Creating Bound Programs Option." You must use BIND instead of the /Fb option when you compile with the /c (compile without link) option or when your program includes functions that operate only in protected mode. %@NL@% %@NL@% %@AU@% You can include functions in a bound application that are not members of %@AU@%the Family API.%@AE@% %@NL@% %@NL@% To include functions available only in protected mode, you must run the BIND utility with the /n option. Your run-time code must call the Family API function %@AB@%DosGetMachineMode%@AE@% to determine whether it is running in real or protected mode. When your program executes in real mode, it will be aborted if it tries to call a function available only in protected mode. %@NL@% %@NL@% You might choose to design your application so it executes different sections of code, depending on the machine mode. For example, the application may need to keep track of the passage of elapsed time or to detect time-outs. In real mode, you might use polling or timing loops or perhaps intercept the timer interrupts. In protected mode, you should use the OS/2 semaphore and timer services, such as %@AB@%DosSetSem%@AE@% and %@AB@%DosTimerAsync%@AE@%, instead. %@NL@% %@NL@% Invoke BIND with the following syntax: %@NL@% %@NL@% %@AS@% BIND infile «implibs» «linklibs» «/o outfile» «/n @file» «/n names» %@AS@% «/m mapfile»%@AE@%%@NL@% %@NL@% The /n option provides a way to include protected-mode functions. It has two formats: %@NL@% %@NL@% %@NL@% ■ A list of one or more names, separated by spaces.%@NL@% %@NL@% ■ The name of a file, preceded by the at (@) sign. The file should consist of a list of functions, one name per line.%@NL@% %@NL@% %@NL@% The /o option specifies a name for the bound-executable file. If it is not present, the name of the input file is used. %@NL@% %@NL@% The /m option causes a link map to be generated for the real-mode version of the executable file. %@NL@% %@NL@% To bind a program named TIMER that uses %@AB@%DosTimerAsync%@AE@% to manage time-outs when running in protected mode, invoke BIND as follows: %@NL@% %@NL@% %@AS@% BIND TIMER /n DosTimerAsync%@AE@%%@NL@% %@NL@% For more information about BIND and other command-line options, consult on-line help. %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@CR:C6A00150001 @%%@1@%%@AB@%Chapter 15 Creating Multithread OS/2 Applications%@AE@%%@EH@%%@NL@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@NL@% Microsoft C, version 6.0, provides support for creating multithread applications under OS/2. You should consider using more than one thread if your application needs to manage multiple activities, such as simultaneous keyboard and mouse input. One thread can process keyboard input while a second thread filters mouse activities. A third thread could update the display screen based on data from the mouse and keyboard threads. At the same time, other threads can access disk files or get data from a communications port. %@NL@% %@NL@% This chapter explains the features in C 6.0 that support the creation of multithread programs. It also describes some important ways in which programming for OS/2 is different than programming for DOS. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00150002 @%%@AB@%15.1 Multithread Programs%@AE@%%@EH@%%@NL@% %@NL@% OS/2 performs the scheduling and allocation of real hardware resources to multiple programs, or "processes." It does not actually schedule the processes themselves; it schedules threads belonging to the processes. %@NL@% %@NL@% A thread is basically a path of execution through a program. It is also the smallest unit of execution that OS/2 schedules. A thread consists of a stack, the state of the CPU registers, and an entry in the execution list of the system scheduler. Each thread shares all of the process's resources. %@NL@% %@NL@% A process consists of one or more threads and the code, data, and other resources of a program in memory. Typical program resources are open files, semaphores, and dynamically allocated memory. A program executes when the system scheduler gives one of its threads execution control. The scheduler determines which threads should run and when they should run. Threads of lower priority may have to wait while higher priority threads complete their tasks. %@NL@% %@NL@% %@AU@% Threads operate independently and are unaware of other threads.%@AE@% %@NL@% %@NL@% All threads in a process operate independently of one another. Unless you take special steps to make them visible to each other, each thread executes while completely unaware of the existence of other threads in a process. Threads sharing common resources, however, must coordinate their work by using flags, semaphores or some other method of interprocess communication. See Section 15.3, "Writing a Multithread Program," for more information about synchronizing threads. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00150003 @%%@AB@%15.1.1 Library Support%@AE@%%@EH@%%@NL@% %@NL@% %@AU@% All shared functions in a multithread program must be re-entrant.%@AE@% %@NL@% %@NL@% If one thread is suspended by the OS/2 scheduler while executing the %@AB@%printf%@AE@% function, one of the program's other threads might start executing. If the second thread also calls %@AB@%printf%@AE@%, data might be corrupted. To avoid this, access to static data used by the function must be restricted to one thread at a time. This process of restricting access to certain data is called serialization. %@NL@% %@NL@% You do not need to serialize access to stack-based (automatic) variables because each thread has a different stack. Therefore, a function that uses only automatic (stack) variables is re-entrant. The standard C run-time libraries, such as SLIBCE, have a limited number of re-entrant functions. A multithread program needing to use C run-time library functions that are normally not re-entrant should be built with the multithread library LLIBCMT.LIB. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%The Multithread C Library LLIBCMT.LIB%@AE@%%@EH@%%@NL@% %@NL@% The support library LLIBCMT.LIB is a re-entrant large-model library for cre-ating multithread programs. %@NL@% %@NL@% %@AU@% A multithread program linked with LLIBCMT.LIB can use any memory model.%@AE@% %@NL@% %@NL@% All calls to library functions must use the large-model calling interface (far code pointers, far calls, and far data pointers). When your application calls functions in this library, %@NL@% %@NL@% %@NL@% ■ All library calls must be far calls.%@NL@% %@NL@% ■ All library calls must use the C calling convention; programs compiled using the /Gr (fastcall calling convention) or /Gc (Pascal calling convention) options must use the standard include files for the run-time library functions they call.%@NL@% %@NL@% ■ All data and code pointers must be far pointers.%@NL@% %@NL@% ■ Variables passed to library functions must either be passed by value or cast to a far address.%@NL@% %@NL@% ■ Your main function must be declared far if you are compiling with the small or compact memory models.%@NL@% %@NL@% %@NL@% You do not need to explicitly declare far pointers if you are using the compact, large, or huge memory models, since these models use far pointers as default. For the large and huge memory models, the function calls are also far by default. %@NL@% %@NL@% A small-model program calling a library function such as %@AB@%isupper%@AE@%, for example, must use declarations like the following: %@NL@% %@NL@% %@AS@% int _far _cdecl isupper( int _c );%@AE@%%@NL@% %@NL@% %@AU@% Programs built with LLIBCMT.LIB are entirely self-contained.%@AE@% %@NL@% %@NL@% Programs built with LLIBCMT.LIB do not share C run-time library code or data with any dynamic-link libraries they call. Chapter 16 explains how to build DLLs and how to share code and data between processes. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Alternatives to LLIBCMT.LIB%@AE@%%@EH@%%@NL@% %@NL@% If you choose to build a multithread program without using LLIBCMT.LIB, you must do the following: %@NL@% %@NL@% %@NL@% ■ Use the standard C libraries and limit library calls to the set of re-entrant functions.%@NL@% %@NL@% ■ Use the OS/2 API thread management functions, such as %@AB@%DosCreateThread%@AE@%.%@NL@% %@NL@% ■ Provide your own synchronization for functions that are not re-entrant by using OS/2 services such as semaphores and the %@AB@%DosEnterCritSec%@AE@% and %@AB@%DosExitCritSec%@AE@% functions.%@NL@% %@NL@% %@NL@% The C run-time library functions listed below are re-entrant and can be used in multithread programs linked with the standard libraries. %@NL@% %@NL@% %@AB@%abs%@AE@% %@AB@%atoi%@AE@% %@AB@%atol%@AE@% %@AB@%bsearch%@AE@% %@AB@%chdir%@AE@% %@AB@%getpid%@AE@% %@AB@%halloc%@AE@% %@AB@%hfree%@AE@% %@AB@%itoa%@AE@% %@AB@%labs%@AE@% %@AB@%lfind%@AE@% %@AB@%lsearch%@AE@% %@AB@%memccpy%@AE@% %@AB@%memchr%@AE@% %@AB@%memcmp%@AE@% %@AB@%memcpy%@AE@% %@AB@%memicmp%@AE@% %@AB@%memmove%@AE@% %@AB@%memset%@AE@% %@AB@%mkdir%@AE@% %@AB@%movedata%@AE@% %@AB@%putch%@AE@% %@AB@%rmdir%@AE@% %@AB@%segread%@AE@% %@AB@%strcat%@AE@% %@AB@%strchr%@AE@% %@AB@%strcmp%@AE@% %@AB@%strcmpi%@AE@% %@AB@%strcpy%@AE@% %@AB@%stricmp%@AE@% %@AB@%strlen%@AE@% %@AB@%strlwr%@AE@% %@AB@%strncat%@AE@% %@AB@%strncmp%@AE@% %@AB@%strncpy%@AE@% %@AB@%strnicmp%@AE@% %@AB@%strnset%@AE@% %@AB@%strrchr%@AE@% %@AB@%strrev%@AE@% %@AB@%strset%@AE@% %@AB@%strstr%@AE@% %@AB@%strupr%@AE@% %@AB@%swab%@AE@% %@AB@%tolower%@AE@% %@AB@%toupper%@AE@% %@AB@%──────────────────────────────────────────%@AE@% %@AU@%WARNING%@AE@%%@NL@% %@NL@% The multithread library LLIBCMT.LIB includes the %@AB@%%@AE@%%@AI@%_beginthread%@AE@% and %@AB@%%@AE@%%@AI@%_endthread%@AE@% functions. The %@AB@%%@AE@%%@AI@%_beginthread%@AE@% function performs initialization without which many C run-time functions will fail. You must use %@AB@%%@AE@%%@AI@%_beginthread%@AE@% instead of %@AB@%%@AE@%%@AI@%DosCreateThread%@AE@% in C programs built with LLIBCMT.LIB if you intend to call C run-time functions.%@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% %@NL@% %@NL@% %@4@%%@AB@%The Multithread Library Compile Option (/MT)%@AE@%%@EH@%%@NL@% %@NL@% The /MT option for the CL command is the best way to build a multithread program with LLIBCMT.LIB. The /MT option embeds the LLIBCMT library name in the object file. Using the /MT option automatically specifies the /ALw /FPi /G2 /D MT options. The following list describes what these options do. %@NL@% %@NL@% %@AB@%Switch%@AE@% %@AB@%Effect%@AE@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% /ALw Use the large memory model with separate stack segment; do not reload the DS register as part of the entry sequence for every function /FPi Generate in-line floating-point instructions and select the emulator math package /G2 Use the 80286 processor instruction set /D MT Use the multithread version of the include files These options can be combined with other options to specify different memory models and different relationships between the data segment and the stack. You can override the /G2 and /FPi options by specifying a different option later on the command line. The following example shows how to override the floating-point package option: %@NL@% %@NL@% %@AS@% CL /MT /FPa /Lp PROG.C%@AE@%%@NL@% %@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% NOTE %@AI@%You cannot replace the /MT option with /ALw /FPi /G2. You must use /MT to %@AI@%generate multithread programs.%@AE@%%@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00150004 @%%@AB@%15.1.2 Include Files%@AE@%%@EH@%%@NL@% %@NL@% The Microsoft C 6.0 include files contain conditional sections for multithread applications using LLIBCMT.LIB. To compile your application with the appropriate definitions, you can %@NL@% %@NL@% %@NL@% ■ Compile with the /MT option described in Section 15.1.1, "Library Support."%@NL@% %@NL@% ■ Define the symbolic constant %@AB@%MT%@AE@% in your source file or on the command line with the /D option.%@NL@% %@NL@% %@NL@% %@AU@% Always use the standard include files.%@AE@% %@NL@% %@NL@% Standard include files declare C run-time library functions as they are implemented in the libraries. If you used the Maximum Optimization (/Ox) or Register Calling Convention (/Gr) option, the compiler assumes that all functions should be called using the register calling convention. The run-time library functions were compiled using either the C or the FORTRAN/Pascal calling convention, and the declarations in the standard include files tell the compiler to generate correct external references to these functions. %@NL@% %@NL@% See Section 15.4, "Compiling and Linking," for examples of how to use the%@AB@% MT%@AE@% constant. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00150005 @%%@AB@%15.1.3 C Run-Time Library Functions for Thread Control%@AE@%%@EH@%%@NL@% %@NL@% All OS/2 programs have at least one thread. Any thread can create additional threads. A thread can complete its work very quickly and then terminate, or it can stay active for the life of the program. %@NL@% %@NL@% The LLIBCMT and LLIBCDLL C run-time libraries provide two functions for thread creation and termination: the %@AB@%_beginthread%@AE@% and %@AB@%_endthread%@AE@% functions. They also declare the global variable %@AB@%_threadid%@AE@%, which contains the address of an application's current thread identifier. %@NL@% %@NL@% The %@AB@%_beginthread%@AE@% function creates a new thread and returns a thread identifier if the operation is successful. The thread will terminate automatically if it completes execution, or it can terminate itself with a call to %@AB@%_endthread%@AE@%. %@NL@% %@NL@% The global variable %@AB@%_threadid%@AE@% holds the address of the identifier of the current thread. It is defined in the STDDEF.H file as shown below: %@NL@% %@NL@% %@AS@% /* define pointer to thread id value */ %@AS@% extern int far * _threadid;%@AE@%%@NL@% %@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% %@AU@%WARNING%@AE@%%@NL@% %@NL@% If you are going to call C run-time routines from a program built with LLIBCMT.LIB, you must start your threads with the %@AB@%%@AE@%%@AI@%_beginthread%@AE@% function. Do not use the OS/2 functions %@AB@%%@AE@%%@AI@%DosExit%@AE@% %@AB@% %@AE@%and %@AB@%DosCreateThread%@AE@%.%@AB@%%@AE@%%@AI@% %@AE@%Using %@AB@%%@AE@%%@AI@%DosSuspendThread%@AE@% can lead to a deadlock condition when more than one thread is blocked waiting for the suspended thread to complete its access to a C run-time data structure.%@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% %@NL@% The %@AB@%_beginthread%@AE@% and %@AB@%_endthread%@AE@% functions are described in detail below. Section 15.2 illustrates their use in a sample multithread program. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%The _beginthread Function%@AE@%%@EH@%%@NL@% %@NL@% %@AU@% All threads in a process can execute concurrently.%@AE@% %@NL@% %@NL@% The %@AB@%_beginthread%@AE@% function creates a new thread. A thread shares the code and data segments of a process with other threads in the process but has its own unique register values, stack space, and current instruction address. The system gives CPU time to each thread, so that all threads in a process can execute concurrently. You can find a complete description of %@AB@%_beginthread%@AE@% and its arguments in on-line help.%@CR:C6A00150006 @%%@CR:C6A00150007 @% %@NL@% %@NL@% The %@AB@%_beginthread%@AE@% function is similar to the %@AB@%DosCreateThread%@AE@% function in the OS/2 API with these differences: %@NL@% %@NL@% %@NL@% ■ The %@AB@%_beginthread%@AE@% function lets you pass arguments to the thread.%@NL@% %@NL@% ■ The stack address points to the bottom of the stack. It is the address of the start of an array or of the start of a block of dynamically allocated memory. When you use the %@AB@%DosCreateThread%@AE@% call, the stack address points to the top of the stack.%@NL@% %@NL@% ■ If you specify %@AB@%NULL%@AE@% for the stack address, %@AB@%_beginthread%@AE@% manages allocation and deallocation of the thread stack for you. This option is advantageous because it is difficult for your program to determine when a thread has terminated, so you cannot know when to deallocate the thread stack. However, %@AB@%_beginthread%@AE@% maintains enough information to know when a thread has terminated and deallocates the thread's stack the next time its thread ID is used.%@NL@% %@NL@% %@NL@% The %@AB@%_beginthread%@AE@% function returns the thread ID number of the new thread if successful or -1 if there was an error. Errors include specifying an odd-address stack or an odd- or zero-length stack (which is different than passing %@AB@%NULL%@AE@% for the stack address) or trying to create too many threads. The multithread library, LLIBCMT.LIB, supports the maximum number of threads allowed by OS/2. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%The _endthread Function%@AE@%%@EH@%%@NL@% %@NL@% The %@AB@%_endthread%@AE@% function terminates a thread created by %@AB@%_beginthread%@AE@%. Threads terminate automatically when they complete. The %@AB@%_endthread%@AE@% function is useful for conditional termination from within a thread. A thread dedicated to communications processing, for example, can quit if it is unable to get control of the communications port. You can find a complete description of %@AB@%_endthread%@AE@% in on-line help. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00150008 @%%@AB@%15.2 Sample Multithread C Program%@AE@%%@EH@%%@NL@% %@NL@% BOUNCE.C is a sample multithread program that creates a new thread each time the letter `a' or `A' is entered at the keyboard. Each thread bounces a "happy face" of a different color around the screen. Up to 32 threads can be created. The program's normal termination occurs when `q' or `Q' is entered. It will also terminate if it receives the CTRL+C or CTRL+BREAK signals. See Section 15.4, "Compiling and Linking," for details on compiling and linking BOUNCE.C. %@NL@% %@NL@% %@AS@% /* Bounce - Creates a new thread each time the letter 'a'is typed. %@AS@% * Each thread bounces a happy face of a different color around the %@AS@%screen. %@AS@% * All threads are terminated when the letter 'q' is entered or when %@AS@% * the CTRL+C/CTRL+BREAK signals are received. %@AS@% * %@AS@% * This program requires the multithread library. For example, compile %@AS@% * with the following command line: %@AS@% * CL /MT BOUNCE.C %@AS@% */ %@AS@% %@AS@% #define INCL_NOCOMMON /* Use only what we need */ %@AS@% #define INCL_NOPM /* Don't need PM */ %@AS@% #define INCL_DOSPROCESS /* DosBeep and DosSleep */ %@AS@% #define INCL_DOSSEMAPHORES /* OS/2 semaphore functions */ %@AS@% #define INCL_DOSSIGNALS /* OS/2 signal functions */ %@AS@% #define INCL_VIO %@AS@% #define INCL_KBD %@AS@% #include <os2.h> %@AS@% #include <stdlib.h> %@AS@% #include <string.h> %@AS@% #include <stdio.h> %@AS@% #include <process.h> %@AS@% %@AS@% #define STACK_SIZE 4096 %@AS@% #define MAX_THREADS 32 %@AS@% %@AS@% void main( void ); /* Thread 1: main */ %@AS@% void KbdThread( void ); /* Thread 2: keyboard input */ %@AS@% void BounceProc( char * MyID ); /* Threads 3 to n: display */ %@AS@% void VioClrScr( void ); /* Screen clear */ %@AS@% void ShutDown( void ); /* Program shutdown */ %@AS@% void VioWrtCStr( char *pchString, /* Write string to display */ %@AS@% unsigned usRow, unsigned usColumn ); %@AS@% void pascal far SigHandler( unsigned SigArg,/* Signal handler */ %@AS@% unsigned SigNum ); %@AS@% /* Screen clear macro */ %@AS@% #define VioClrScr() VioScrollDn( 0, 0, 50, 80, 50, BlankCell, 0 )%@AE@%%@NL@% %@NL@% %@AS@% struct tagCoords /* Display coordinates */ %@AS@% { %@AS@% int xLoc; %@AS@% int yLoc; %@AS@% int xInc; %@AS@% int yInc; %@AS@% }; %@AS@% %@AS@% unsigned long RunFlag = 0; /* "Keep Running" semaphore */ %@AS@% unsigned long ScreenLock = 0; /* Screen update semaphore */ %@AS@% %@AS@% char BlankCell[2] = { 0x20, 0x07 }; %@AS@% VIOMODEINFO vmi = { sizeof( VIOMODEINFO ) };/* Mode information */ %@AS@% %@AS@% PFNSIGHANDLER PrevHandler; /* for SetSigHandler call */ %@AS@% unsigned int PrevAction; /* for SetSigHandler call */ %@AS@% %@AS@% void main() /* Thread One */ %@AS@% { %@AS@% /* Get display screen's text row and column sizes & clear the %@AS@%screen.*/ %@AS@% VioGetMode( &vmi, 0 ); %@AS@% VioClrScr(); %@AS@% VioWrtCStr( "Threads running: 00. Press 'a' to start another thread", %@AS@% vmi.row - 1, 0 ); %@AS@% %@AS@% /* Set the "we are running" semaphore. */ %@AS@% DosSemSet( &RunFlag ); %@AS@% %@AS@% /* Start keyboard thread. Let _beginthread allocate memory %@AS@% * for the thread's stack. %@AS@% */ %@AS@% _beginthread( KbdThread, NULL, STACK_SIZE, NULL ); %@AS@% %@AS@% /* Install signal handler for CTRL+BREAK & CRTL+C. */ %@AS@% DosSetSigHandler( (PFNSIGHANDLER)SigHandler, &PrevHandler, %@AS@%&PrevAction, %@AS@% SIGA_ACCEPT, SIG_CTRLC ); %@AS@% %@AS@% /* Wait for "running" semaphore to clear (from signal or 'q' key). */ %@AS@% DosSemWait( &RunFlag, SEM_INDEFINITE_WAIT ); %@AS@% %@AS@% _endthread(); /* Kill all threads */ %@AS@% }%@AE@%%@NL@% %@NL@% %@AS@% void pascal far SigHandler( unsigned int SigArg, unsigned int SigNum ) %@AS@% { %@AS@% static char BreakMsg[] = "Signal Termination"; %@AS@% %@AS@% ShutDown(); %@AS@% VioWrtCStr( BreakMsg, vmi.row - 1, 0 ); %@AS@% /* Restore original signal handler for CTRL+BREAK & CRTL+C. */ %@AS@% DosSetSigHandler( (PFNSIGHANDLER)PrevHandler, &PrevHandler, %@AS@%&PrevAction, %@AS@% PrevAction, SIG_CTRLC ); %@AS@% } %@AS@% void ShutDown( void ) /* Clean up display when done %@AS@%*/ %@AS@% { %@AS@% /* Lock out screen updates from BounceProc & clear "running" semaphore %@AS@%*/ %@AS@% DosSemWait( &ScreenLock, SEM_INDEFINITE_WAIT ); %@AS@% DosSemSet( &ScreenLock ); %@AS@% VioClrScr(); %@AS@% DosSemClear( &RunFlag ); %@AS@% } %@AS@% %@AS@% void KbdThread( void ) /* Thread Two: keyboard */ %@AS@% { %@AS@% KBDKEYINFO KeyInfo; /* for KbdCharIn call */ %@AS@% char ThreadNr = 0; %@AS@% char NThreadMsg[4]; %@AS@% %@AS@% do %@AS@% { %@AS@% /* Block this thread by waiting for keyboard input. */ %@AS@% %@AS@% KbdCharIn( &KeyInfo, IO_WAIT, 0 ); %@AS@% if( tolower( KeyInfo.chChar ) == 'a' && ThreadNr < MAX_THREADS) %@AS@% { %@AS@% ThreadNr++; %@AS@% _beginthread( BounceProc, NULL, STACK_SIZE, &ThreadNr ); %@AS@% VioWrtCharStr( NThreadMsg, sprintf( NThreadMsg, "%02d", %@AS@%ThreadNr ), %@AS@% vmi.row - 1, 17, 0 ); %@AS@% } %@AS@% } while( tolower( KeyInfo.chChar ) != 'q' ); %@AS@% %@AS@% ShutDown(); %@AS@% } %@AS@% %@AS@% /* getrandom returns a random number between min and max, which must be in %@AS@% * integer range. %@AS@% */ %@AS@% #define getrandom( min, max ) ((rand() % (int)(((max) + 1) - (min))) + %@AS@%(min))%@AE@%%@NL@% %@NL@% %@AS@% void BounceProc( char * MyID ) /* Threads Three to n */ %@AS@% { %@AS@% int xOld, yOld; %@AS@% char MyCell[2]; %@AS@% char CurrentCell[2]; %@AS@% int CellLen = 2; %@AS@% struct tagCoords Coords;%@AE@%%@NL@% %@NL@% %@AS@% /* Generate update increments and initial display coordinates. */ %@AS@% srand( (unsigned) *MyID * 3 ); %@AS@% Coords.xLoc = getrandom( 0, vmi.col - 1 ); %@AS@% Coords.yLoc = getrandom( 0, vmi.row - 1 ); %@AS@% Coords.xInc = getrandom( -3, 3 ); %@AS@% Coords.yInc = getrandom( -3, 3 ); %@AS@% %@AS@% /* Set up "happy face" & generate color attribute from thread %@AS@%number.*/ %@AS@% if( *MyID > 16) %@AS@% MyCell[0] = 0x01; /* outline face */ %@AS@% else %@AS@% MyCell[0] = 0x02; /* solid face */ %@AS@% MyCell[1] = *MyID & 0x0F; /* force black background */ %@AS@% %@AS@% for( ;; ) %@AS@% { %@AS@% /* Wait for display to be available, then lock it. */ %@AS@% DosSemWait( &ScreenLock, SEM_INDEFINITE_WAIT ); %@AS@% DosSemSet( &ScreenLock ); %@AS@% %@AS@% /* If we still occupy the old screen position, blank it out. */ %@AS@% VioReadCellStr( CurrentCell, &CellLen, yOld, xOld, 0 ); %@AS@% if ( CurrentCell[0] == MyCell[0] && CurrentCell[1] == MyCell[1] ) %@AS@% VioWrtCellStr( BlankCell, CellLen, yOld, xOld, 0 ); %@AS@% %@AS@% /* Draw new face, then clear screen lock */ %@AS@% VioWrtCellStr( MyCell, CellLen, Coords.yLoc, Coords.xLoc, 0 ); %@AS@% DosSemClear( &ScreenLock ); %@AS@% %@AS@% /* Increment the coordinates for next placement of the block. */ %@AS@% xOld = Coords.xLoc; %@AS@% yOld = Coords.yLoc; %@AS@% Coords.xLoc += Coords.xInc; %@AS@% Coords.yLoc += Coords.yInc; %@AS@% %@AS@% %@AE@%%@NL@% %@NL@% %@AS@% /* If we are about to go off the screen, reverse direction */ %@AS@% if( Coords.xLoc < 0 || Coords.xLoc >= vmi.col ) %@AS@% { %@AS@% Coords.xInc = -Coords.xInc; %@AS@% DosBeep( 400, 50 ); %@AS@% } %@AS@% if( Coords.yLoc < 0 || Coords.yLoc >= vmi.row ) %@AS@% { %@AS@% Coords.yInc = -Coords.yInc; %@AS@% DosBeep( 600, 50 ); %@AS@% } %@AS@% %@AS@% /* Sleep to slow down screen update rate */ %@AS@% DosSleep( 75L ); %@AS@% } %@AS@% } %@AS@% %@AS@% void VioWrtCStr( char *pchString, unsigned usRow, unsigned usColumn ) %@AS@% { %@AS@% VioWrtCharStr( pchString, strlen( pchString ), usRow, usColumn, 0 ); %@AS@% }%@AE@%%@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00150009 @%%@AB@%15.3 Writing a Multithread Program%@AE@%%@EH@%%@NL@% %@NL@% When you write a program with multiple threads, you must coordinate their behavior and use of the program's resources. You must also make sure that each thread receives its own stack. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Sharing Common Resources%@AE@%%@EH@%%@NL@% %@NL@% Each thread has its own stack and its own copy of the CPU registers. Other resources, such as files, static data, and heap memory, are shared by all threads in the process. Threads using these common resources must coordinate their work. OS/2 provides semaphores and the %@AB@%DosEnterCritSec%@AE@% and %@AB@%DosExitCritSec%@AE@% system services for synchronizing resources. %@NL@% %@NL@% %@AU@% Your program must provide for resource conflicts.%@AE@% %@NL@% %@NL@% When multiple threads are accessing static data, your program must provide for possible resource conflicts. Consider a program where one thread updates a static data structure containing %@AI@%x%@AE@%,%@AI@%y%@AE@% coordinates for items to be displayed by another thread. If the update thread alters the %@AI@%x%@AE@% coordinate and is preempted before it can change the %@AI@%y%@AE@% coordinate, the display thread may be scheduled before the %@AI@%y%@AE@% coordinate is updated. The item would be displayed at the wrong location. You can avoid this type of problem by using semaphores to control access to the structure. %@NL@% %@NL@% Using semaphores is a way of communicating among threads or processes that are executing asynchronously of one another. This communication is usually used to coordinate the activities of multiple threads or processes, typically by controlling access to a shared resource by "locking" and "unlocking" the resource. To solve the %@AI@%x,y%@AE@% coordinate update problem described above, the update thread would set a semaphore indicating that the data structure is in use before performing the update. It would then clear the semaphore when both coordinates had been processed. The display thread must wait for the semaphore to be clear before updating the display. This process of waiting for a semaphore is often called "blocking" on a semaphore because the process is blocked and cannot continue until the semaphore clears. %@NL@% %@NL@% %@AU@% RAM semaphores are faster than system semaphores.%@AE@% %@NL@% %@NL@% OS/2 supports two types of semaphores: system and RAM semaphores. You must use a system semaphore if more than one process needs to access the semaphore. You can use the much faster RAM semaphores if their use is confined to the threads within a process. %@NL@% %@NL@% The BOUNCE.C program in Section 15.2 uses a RAM semaphore named %@AS@% ScreenLock %@AE@% to coordinate screen updates. Each time one of the display threads is ready to write to the screen, it calls %@AB@%DosSemWait%@AE@% with a pointer to %@AS@% ScreenLock %@AS@%%@AE@%and constant %@AB@%SEM_INDEFINITE_WAIT%@AE@% to indicate that the %@AB@%DosSemWait %@AE@%call should block on the semaphore and not time out. If the %@AS@%ScreenLock %@AE@%semaphore is clear, the wait function returns immediately. Otherwise, the thread blocks until the semaphore clears. When the thread receives control again, it calls %@AB@%DosSemSet%@AE@% to set the %@AS@%ScreenLock %@AE@%semaphore so other threads cannot interfere with the display. When the thread completes the display update, it releases the semaphore by calling %@AB@%DosSemClear%@AE@%.%@AS@% %@AE@%%@NL@% %@NL@% The %@AS@% ShutDown %@AE@% routine in BOUNCE.C is called from both the keyboard thread and the signal handler. The routine uses the %@AS@% ScreenLock %@AE@% semaphore to make sure other threads do not write to the screen after the screen has been cleared. %@NL@% %@NL@% Screen displays and static data are only two of the resources requiring careful management. For example, your program may have multiple threads accessing the same file. Since another thread may have moved the file pointer, each thread must reset the file pointer before reading or writing. In addition, each thread must make sure that it is not preempted between the time it positions the pointer and the time it accesses the file. These threads should use a semaphore to coordinate access to the file by bracketing each file access with %@AB@%DosSemRequest%@AE@% and %@AB@%DosSemClear%@AE@% calls. The following code fragment illustrates this technique: %@NL@% %@NL@% %@AS@% HSEM hsemIOSem; %@AS@% %@AS@% DosSemRequest( hsemIOSem, SEM_INDEFINITE_WAIT ); %@AS@% fseek( fp, desired_position, 0L ); %@AS@% fwrite( data, sizeof( data ), 1, fp ); %@AS@% DosSemClear( hsemIOSem );%@AE@%%@NL@% %@NL@% %@NL@% %@4@%%@AB@%Thread Stacks%@AE@%%@EH@%%@NL@% %@NL@% %@AU@% Stack checking is performed for each thread.%@AE@% %@NL@% %@NL@% All of an application's default stack space is allocated to the first thread of execution, which is known as thread 1. As a result, you must allocate memory to provide a separate stack for each additional thread your program needs. You must do this before creating the thread. Stack checking, if enabled, is performed for each thread. The keyboard thread in BOUNCE.C calls the %@AB@%malloc%@AE@% function each time the user wants to start a new display thread. If the allocation is successful, the %@AB@%_beginthread%@AE@% function is called. The first argument in the %@AB@%_beginthread%@AE@% call is a pointer to the %@AB@%BounceProc%@AE@% function, which will execute the threads. The last argument is an ID number that is passed to %@AB@%BounceProc%@AE@%. %@AB@%BounceProc%@AE@% uses the ID number to seed the random number generator and to select the thread's color attribute and display character. %@NL@% %@NL@% Threads that make calls to the C run-time library or to the OS/2 API must allow sufficient stack space for the library and API functions they call. The C %@AB@%printf%@AE@% function requires more than 500 bytes of stack space, and you should have 2K of stack space available when calling OS/2 API routines. To be safe, allocate at least 4K for each thread's stack. %@NL@% %@NL@% %@AU@% Use as little static data as possible.%@AE@% %@NL@% %@NL@% Since each thread has its own stack, you can avoid potential collisions over data items by using as little static data as possible. Design your program to use automatic stack variables for all data that can be private to a thread. The only global variables in the BOUNCE.C program are either RAM semaphores or variables that never change once they are initialized. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Signal Handling%@AE@%%@EH@%%@NL@% %@NL@% Signals are events that interrupt the normal flow of your program's execution. They are similar to hardware interrupts, but they come from the operating system or other programs and occur asynchronously. If you do not provide your own routines, OS/2 will take the default action for each signal, such as cancelling your program when the user enters CTRL+BREAK. You can install your own signal handler with the OS/2 API function %@AB@%DosSetSigHandler%@AE@%. %@NL@% %@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% %@AU@%WARNING%@AE@%%@NL@% %@NL@% The C run-time function signal is not supported in the multithread library LLIBCMT.LIB.%@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% %@NL@% When a signal occurs, OS/2 always suspends thread 1 and gives control to the signal handler, if installed. As a result, thread 1 must not be executing C run-time library code when the signal handler gets control or a potential deadlock condition can occur. In addition, the signal handler must not call C run-time library functions. Consider the following sequence of events: %@NL@% %@NL@% %@NL@% 1. Thread 2 is executing %@AB@%printf%@AE@% when the user interrupts it by pressing CTRL+C. The program has designated a CTRL+C signal handler, so OS/2 immediately transfers control to the signal handler in thread 1.%@NL@% %@NL@% 2. The signal handler in thread 1 tries to execute the statement: %@NL@% %@AS@% printf( "^C: Do you want to quit?" );%@AE@%%@NL@% %@NL@% %@NL@% 3. The %@AB@%printf%@AE@% call in thread 2 has already locked output to the console, so thread 1's %@AB@%printf%@AE@% must wait for release of that lock.%@NL@% %@NL@% 4. The thread 2 %@AB@%printf%@AE@% function never regains control because the signal handler must complete before other processing can continue. As a result, it is never able to release the lock on console output.%@NL@% %@NL@% %@NL@% If a situation like this happens, the program will wait indefinitely for resolution of the two mutually exclusive conditions. %@NL@% %@NL@% A multithread C program can process signals if it adheres to the following restrictions: %@NL@% %@NL@% %@NL@% ■ Thread 1 must be dedicated to signal handling and must not call the C run-time library once it identifies the signal handler to OS/2 using the API function %@AB@%DosSetSigHandler%@AE@%. When the signal handler gets control, it should set a semaphore or flag so other threads in the program can determine that the signal has occurred and is being processed.%@NL@% %@NL@% ■ The other threads in the process must check the status of semaphores set by thread 1 and respond accordingly. %@NL@% %@NL@% %@NL@% The BOUNCE.C sample program waits until thread 2, the keyboard handler, starts before installing the signal handler. It then dedicates thread 1 to signal handling by having the thread wait for a semaphore. Thread 1 blocks until either the keyboard thread or the signal handler clears the semaphore. It then calls %@AB@%_endthread%@AE@% to terminate the process, including all the other threads. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00150010 @%%@AB@%15.4 Compiling and Linking%@AE@%%@EH@%%@NL@% %@NL@% The steps for compiling and linking the multithread program BOUNCE.C are given below: %@NL@% %@NL@% %@NL@% 1. Ensure that the files LLIBCMT.LIB and OS2.LIB are in the directory specified in your LIB environment variable.%@NL@% %@NL@% %@STUB@% The file LLIBCMT.LIB takes the place of the regular C run-time library files. The file OS2.LIB provides support for OS/2 system calls made in the program, such as %@AB@%KbdCharIn%@AE@%.%@NL@% %@NL@% 2. Compile and link the program with the CL command-line option /MT.%@NL@% %@NL@% %@STUB@% The /Lp option instructs the compiler to create a protected-mode application. The /MT option implies the large memory model with a separate stack segment (/ALw). The multithread library functions have their own data segment but use the caller's stack. This option also sets the library search record to LLIBCMT.LIB and sets the %@AB@%MT%@AE@% symbolic constant for the multithread versions of the include files. The /link GRTEXTP option instructs the linker to search GRTEXTP.LIB, the character-graphics library for protected mode.%@NL@% %@NL@% %@STUB@% To compile and link in a single step, use this CL command line:%@NL@% %@NL@% %@AS@% CL /Lp /MT BOUNCE.C /link grtextp%@AE@%%@NL@% %@NL@% %@STUB@% For separate compile and link steps, you invoke the compiler and the linker with this code:%@NL@% %@NL@% %@AS@% CL /c /Lp /MT BOUNCE.C %@AS@% LINK BOUNCE;%@AE@%%@NL@% %@NL@% 3. If you choose not to use the /MT option, you must take these steps:%@NL@% %@NL@% %@NL@% %@NL@% ■ Ensure that the special multithread include file support is enabled. %@NL@% ■ Use the /Aw option. This is required because the functions in LLIBCMT.LIB have their own data segment but use the caller's stack. The /Aw option specifies a segment setup of SS not equal to DS with DS not reloaded on function entry.%@NL@% %@NL@% ■ Make sure that only far pointers are passed to library functions.%@NL@% %@NL@% ■ Make sure that all variables are either passed by value or cast to a far address (the large memory model).%@NL@% %@NL@% ■ Specify the multithread library and suppress default library selection.%@NL@% %@NL@% %@STUB@% The multithread include files are used when you define the symbolic constant %@AB@%MT%@AE@%. You can do this with the CL command line option /D MT or within the C source file before any include statements, as shown below:%@NL@% %@NL@% %@AS@% #define MT %@AS@% #include <stdlib.h>%@AE@%%@NL@% %@NL@% %@STUB@% To compile and link in a single step with the default libraries suppressed, this is the complete CL command line:%@NL@% %@NL@% %@AS@% CL /Lp /ALw /Zl /D MT BOUNCE.C /link LLIBCMT+OS2%@AE@%%@NL@% %@NL@% %@STUB@% To perform a two-step compile and link with the default libraries suppressed in the link step, use these commands:%@NL@% %@NL@% %@AS@% CL /c /Lp /ALw /D MT BOUNCE.C %@AS@% LINK /NOD BOUNCE,,,LLIBCMT+OS2;%@AE@%%@NL@% %@NL@% 1. Run the program under OS/2.%@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00150011 @%%@AB@%15.5 Avoiding Problem Areas%@AE@%%@EH@%%@NL@% %@NL@% There are several problems you can encounter in creating, linking, or executing a multithread C program. Some of the more common ones are described here. %@NL@% %@NL@% %@AB@%Problem%@AE@% %@AB@%Probable Cause%@AE@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% LINK searches for mLIBC%@AI@% f%@AE@%.LIB. If you omit the /NOD option from the LINK command, LINK searches for the default library. The default library should not be used with multithread programs. The /NOD option tells the computer not to search the default libraries. This problem can also be avoided by compiling with the /Zl option, which suppresses default library search records in the object files. You get error SYS1943. A program Many OS/2 programming errors cause caused a protection protection violations. A common cause of violation. protection violations is the indirect assignment of data to null pointers. This results in your program trying to access memory that does not "belong" to it, so a protection violation is issued. Protection violations also occur if your program gets a memory buffer from the operating system and then tries to read or write past the end of the buffer. Another cause of this error is failing to specify the condition "SS is not equal to DS" in the CL command invocation. Specify the correct conditions with the /ALw memory model option. An easy way to detect the cause of a protection violation is to compile your program with CodeView information, then run it in CodeView. When the protection fault occurs, OS/2 will transfer control to CodeView, and the cursor will be positioned on the line that caused the problem. See Chapter 9, "Debugging C Programs with CodeView," for more information about the CodeView debugger. Your program generates numerous If you attempt to compile and link a compile and link errors. multithread program without defining the symbolic constant%@AB@% MT%@AE@%, many of the definitions required for the multithread library will be missing. Define %@AB@%MT%@AE@% on the CL command line with /MT or /D MT, or use %@AS@% %@AE@% %@AS@%#define MT %@AE@%in your program. You can eliminate many potential problems by setting the compiler's warning level to one of its highest values and heeding the warning messages. By using the /W3 or /W4 warning level options, you can detect unintentional data conversions, missing function prototypes, and use of non-ANSI features. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00150012 @%%@AB@%15.6 Using the Protected-Mode CodeView Debugger%@AE@%%@EH@%%@NL@% %@NL@% The protected-mode version of CodeView (CVP) has special commands for debugging multiple processes and threads. It adds Thread and Process items to the standard Run Menu. Your CONFIG.SYS file must specify IOPL=YES for protected-mode CodeView to run.%@CR:C6A00150013 @%%@CR:C6A00150014 @%%@CR:C6A00150015 @% %@NL@% %@NL@% To enable multiple process debugging, invoke CodeView with the /O (offspring) option. Selecting the Process item from the Run Menu brings up a list box of child processes associated with the parent process. You choose the process to be debugged by selecting it with the list box. The Process item will be grey (unselectable) if you did not specify the /O option. The /O option applies only to debugging multiple processes. You do not need to use it to debug multiple threads. %@NL@% %@NL@% Selecting the Thread item from the Run Menu produces a list box showing the status of each thread associated with the current process. You can use the list box to designate a different current thread or to change a thread's status. There are equivalent keyboard commands for each option. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00150016 @%%@AB@%15.6.1 Compiling with the /Zi Option%@AE@%%@EH@%%@NL@% %@NL@% The compiler option /Zi causes the compiler to include symbolic information and line numbers in the object file for debugging with CodeView. If you run LINK in a separate step, you must invoke it with the /CODEVIEW option, which can be abbreviated as /CO. To compile and link the sample program BOUNCE.C in a single step, enter this code: %@NL@% %@NL@% %@AS@% CL /MT /Zi BOUNCE.C%@AE@%%@NL@% %@NL@% The following commands are for a two-step compile and link: %@NL@% %@NL@% %@AS@% CL /c /MT /Zi BOUNCE.C %@AS@% %@AS@% link /CO BOUNCE;%@AE@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00150017 @%%@AB@%15.6.2 Prompt for Thread Number%@AE@%%@EH@%%@NL@% %@NL@% When you debug a protected-mode program with CodeView, the command prompt is preceded by a three-digit number indicating the current thread. Thread 1 is always the current thread when you start a program. The prompt appears as %@NL@% %@NL@% %@AS@% 001>%@AE@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00150018 @%%@AB@%15.6.3 Thread Commands%@AE@%%@EH@%%@NL@% %@NL@% Protected-mode CodeView (CVP) has special commands to control the execution of threads. The CodeView Thread commands are accessed using the Thread command from the Run menu. Dialog commands for thread control start with the tilde character (%@AB@%~%@AE@%). Thread commands specify which thread(s) the command applies to, followed by the command. The syntax of the dialog version of the Thread command is %@NL@% %@NL@% %@AB@%~%@AE@%«%@AI@%specifier%@AE@%«%@AI@%command%@AE@%»» %@NL@% %@NL@% Entering the tilde character by itself displays the status of all threads. Enter the tilde and a specifier to see the status of particular threads. Legal values for the specifier field are listed below: %@NL@% %@NL@% %@AB@%Specifier%@AE@% %@AB@%Function%@AE@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% (blank) Displays the status of all threads # Specifies the last thread that executed . Specifies the current thread * Specifies all threads n Specifies the number of an existing thread The optional command field controls the way specified threads are executed. If it is omitted, status is displayed, but thread activity is not affected. Thread commands are summarized below, followed by examples. For more information about command execution and about how other threads in the process may be affected, consult on-line help. %@NL@% %@NL@% %@AB@%Command%@AE@% %@AB@%Function%@AE@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% (blank) Display status %@AB@%BP%@AE@% Set a breakpoint (used with the normal Breakpoint Set command syntax) %@AB@%E%@AE@% Execute in slow motion %@AB@%F%@AE@% Freeze the thread(s) %@AB@%G%@AE@% Pass control to a thread %@AB@%P%@AE@% Execute a program step %@AB@%S%@AE@% Select specified thread as the current thread %@AB@%T%@AE@% Trace a thread %@AB@%U%@AE@% Unfreeze thread(s) %@NL@% %@4@%%@AB@%Controlling a Thread Being Debugged%@AE@%%@EH@%%@NL@% %@NL@% If your program has multiple threads using the same functions, you may want to monitor the behavior of one particular thread. The standard Breakpoint Set command will affect every thread. The thread Breakpoint Set command lets you limit the breakpoint to one or more threads. The sample program BOUNCE.C has multiple threads executing the function %@AB@%BounceProc%@AE@%. This function erases the symbol at the thread's current screen position, writes it to a new location, computes the display coordinates to be used the next time the thread receives control, and then sleeps to slow down the rate at which the display is updated. %@NL@% %@NL@% Since thread-specific breakpoints can only be set for threads that are already running, you can set a breakpoint that will be executed after the target thread starts. In BOUNCE.C, the source line in thread 2 that tests each character received from the keyboard is a good location for such a breakpoint (line 113). Since thread 2 is not active when the program begins, you must first set a breakpoint in thread 1 after it has started thread 2 (line 73). The first breakpoint can be set by conventional methods or by using the thread breakpoint command: %@NL@% %@NL@% %@AS@% 001>~1BP .73%@AE@%%@NL@% %@NL@% Once you have reached the first breakpoint, you can set the keyboard test breakpoint for thread 2: %@NL@% %@NL@% %@AS@% 001>~2BP .113%@AE@%%@NL@% %@NL@% The BOUNCE.C program starts a new thread each time the letter `a' is typed. (`A' is also accepted.) Once you have started the desired number of threads, you can trigger the thread 2 breakpoint without starting a new thread by pressing another key, such as the space bar. When you reach the breakpoint in thread 2, you can set breakpoints for the other threads. To set a breakpoint in thread 3's %@AB@%BounceProc%@AE@% function immediately after it has updated the screen (source line 168), enter this code: %@NL@% %@NL@% %@AS@% 001>~3BP .168%@AE@%%@NL@% %@NL@% When this breakpoint is reached, the CodeView prompt will reflect the current thread number: %@NL@% %@NL@% %@AS@% 003>%@AE@%%@NL@% %@NL@% You can then set other breakpoints for the thread, execute it in slow motion without any other threads running in the background, or enter other CodeView commands, such as Breakpoint Clear. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Freezing and Unfreezing Threads%@AE@%%@EH@%%@NL@% %@NL@% %@AU@% Frozen threads do not execute.%@AE@% %@NL@% %@NL@% It can be useful to freeze one or more threads so they don't interfere with execution of a thread you are debugging. In the BOUNCE.C program, for example, you can monitor the path of a single bouncing ball by freezing all but one of the bounce threads. Frozen threads will not be scheduled for execution. %@NL@% %@NL@% If you have a large number of threads running, you can freeze all of them in a single command and then unfreeze the threads you want to monitor. Unfrozen threads continue to operate normally and will execute any breakpoints they encounter. The following example freezes all threads, enables threads 1 and 4, and then checks the status of all threads: %@NL@% %@NL@% %@AS@% 001>~*F %@AS@% 001>~1U %@AS@% 001>~4U %@AS@% 001>~%@AE@%%@NL@% %@NL@% If thread 1 is waiting for a semaphore when the status command is invoked, the report shows the following: %@NL@% %@NL@% %@AS@% 001 Blocked %@AS@% 002 Frozen %@AS@% 003 Frozen %@AS@% 004 Runnable%@AE@%%@NL@% %@NL@% %@NL@% %@4@%%@AB@%Switching to a Particular Thread%@AE@%%@EH@%%@NL@% %@NL@% The %@AB@%S%@AE@% (select) and %@AB@%E%@AE@% (execute) variations of the Thread command can be used to switch the current thread. However, when another thread causes the program to stop by hitting a breakpoint, the debugger will select the thread that encountered the breakpoint as the current thread. %@NL@% %@NL@% If you include %@AB@%~.S%@AE@% in the breakpoint command, CodeView stops the thread that encounters the breakpoint, then immediately switches back to the current thread. The following example selects thread 4, sets a breakpoint at line 168 in thread 3, and switches to thread 4 when the breakpoint is hit: %@NL@% %@NL@% %@AS@% 001>~4S %@AS@% 001>~3BP .168 "~.S" %@AS@% 001>G%@AE@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00150019 @%%@AB@%15.6.4 Screen Groups Used by CodeView%@AE@%%@EH@%%@NL@% %@NL@% Only one CodeView session at a time is supported in protected mode. You cannot run multiple copies in concurrent screen groups. %@NL@% %@NL@% The View Output Screen command ( %@AB@%\%@AE@% ) works differently in protected mode and in real mode. In protected mode, your application's output will be displayed for three seconds. The display will then revert to the CodeView display. To view the output window for a longer period, specify a different delay interval, measured in seconds, as follows: %@NL@% %@NL@% %@AS@% \10%@AE@%%@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@CR:C6A00160001 @%%@1@%%@AB@%Chapter 16 Dynamic Linking with OS/2%@AE@%%@EH@%%@NL@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@NL@% An OS/2 dynamic-link library (DLL) is an executable file containing functions that are available to other programs. In a statically linked program, you link the program with all its component functions when you build the executable file. In a dynamically linked program, the program-build step does not link all of the code. Instead, OS/2 links calls to functions in dynamic-link libraries at program load time or while the program is running. The DLL code and data become part of the address space of each program, even when the DLL is being accessed by several application programs. %@NL@% %@NL@% This chapter describes how to build your own dynamic-link libraries and how to build programs that use them. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00160002 @%%@AB@%16.1 Overview of Dynamic Linking%@AE@%%@EH@%%@NL@% %@NL@% Dynamic linking is the process of resolving external calls when a program runs, instead of at link time. It offers several benefits: %@NL@% %@NL@% %@NL@% ■ Multiple programs can use the same dynamic-link library simultaneously. Since only one copy of the DLL is in memory, there are fewer demands for physical memory and swap space.%@NL@% %@NL@% ■ Updates to dynamic-link libraries do not affect the programs that use them, since the only connection between DLLs and application programs is the function-calling sequence.%@NL@% %@NL@% ■ Application programs require less disk space and memory, since their executable program files contain the names of DLL functions but not the code for the functions.%@NL@% %@NL@% ■ Dynamic-link libraries can call other dynamic-link libraries.%@NL@% %@NL@% ■ DLLs can extend the OS/2 operating system to provide new or improved system services. This is possible because most of OS/2 consists of a set of dynamic-link libraries.%@NL@% %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00160003 @%%@AB@%16.1.1 Load-Time and Run-Time Linking%@AE@%%@EH@%%@NL@% %@NL@% Dynamic linking can take place both at program load time and while the program is running. A program can call functions in more than one DLL and combine both load-time and run-time linking. %@NL@% %@NL@% %@AU@% For load-time dynamic linking, build a program that calls DLL functions by %@AU@%name.%@AE@% %@NL@% %@NL@% The linker creates special records containing the name of each DLL subroutine and the name of its DLL file. It does not put any DLL code into the program's executable file. At load time, OS/2 dynamically links the program and its DLLs. It brings the program and the DLLs into memory and updates the program's DLL calls with the address of each DLL routine. If a DLL is already in memory, it is not reloaded. %@NL@% %@NL@% With run-time dynamic linking, the program creates the DLL file name and subroutine names during execution. The program then passes these names to OS/2 so the operating system can load the dynamic-link library. %@NL@% %@NL@% An example of a run-time dynamic link is an extension to the Programmer's WorkBench (PWB). PWB has no information about which extensions it needs until it reads the initialization file, TOOLS.INI. PWB then sends requests to OS/2 to demand-load the DLLs that it needs. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00160004 @%%@AB@%16.1.2 Application Programs and DLLs%@AE@%%@EH@%%@NL@% %@NL@% With static linking, all library code is bound into the executable program when you link the program. If the library changes, all programs using the library must be relinked. With the exception of some Microsoft Windows programs, all DOS programs use static linking. %@NL@% %@NL@% %@AU@% Updates to parts of a program are easier to deliver using DLLs.%@AE@% %@NL@% %@NL@% You can create loosely coupled applications and DLLs and modify the DLLs without relinking the program. For example, if your product has an underlying database access mechanism, you can package the database access routines into a DLL. You can then ship improvements or changes to the database code in a new dynamic-link library. The executable files for the program do not have to be relinked or redistributed. %@NL@% %@NL@% The programs calling a DLL are known as the DLL's "clients." %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00160005 @%%@AB@%16.1.3 DLLs and Microsoft C Run-Time Libraries%@AE@%%@EH@%%@NL@% %@NL@% You can construct three types of dynamic-link libraries with the Microsoft C Professional Development System. All of them can be multithreaded; they can support more than one client at a time. There are three types: %@NL@% %@NL@% %@NL@% ■ A stand-alone dynamic-link library that includes both your routines and code for the Microsoft C run-time library functions used by your DLL. This type of DLL is self-contained and completely independent of the programs that call it.%@NL@% %@NL@% ■ A dynamic-link library that does not use any functions from the Microsoft C run-time library. This type of DLL is also self-contained.%@NL@% %@NL@% ■ A private dynamic-link library that consists only of selected functions from the Microsoft C run-time library. This DLL is usually specific to one program or a closely tied group of programs. Application programs and dynamic-link libraries using this DLL do not contain any code for the C run-time library functions.%@NL@% %@NL@% %@NL@% The following sections provide more information about the differences between the various types of DLLs. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Stand-Alone Dynamic-Link Libraries%@AE@%%@EH@%%@NL@% %@NL@% %@AU@% Stand-alone DLLs include C run-time functions.%@AE@% %@NL@% %@NL@% If you want to call C run-time library functions in your DLL, you can include the functions you need. These run-time functions are statically linked in the DLL and the DLL does not rely on the client or any other DLL for run-time support. %@NL@% %@NL@% Figure 16.1 illustrates the relationships between this type of DLL, an application program, and C run-time library functions. Both the application program and the dynamic-link library have their own copies of functions from the C run-time library. This ensures that %@NL@% %@NL@% %@NL@% ■ The DLL always has access to the C run-time library routines it needs.%@NL@% %@NL@% ■ The DLL is not dependent on the calling application for any support code.%@NL@% %@NL@% ■ The programs using the DLL do not depend on the DLL for C run-time library functions.%@NL@% %@NL@% %@NL@% Section 16.3.1, "DLLs with Static C Run-Time Library Functions," describes the steps involved in creating this type of dynamic-link library using the special library LLIBCDLL.LIB. %@NL@% %@NL@% %@AU@%(This figure may be found in the printed book.)%@AE@%%@NL@% %@NL@% %@NL@% %@4@%%@AB@%DLLs without C Run-Time Library Functions%@AE@%%@EH@%%@NL@% %@NL@% You can write a dynamic-link library in C without calling any functions from the C run-time library. Section 16.3.2, "DLLs without C Run-Time Library Functions," shows how to set up this type of DLL. These DLLs contain only your code and require no run-time library support; they make no calls to run-time library functions. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Private C Run-Time DLLs%@AE@%%@EH@%%@NL@% %@NL@% %@AU@% You can create a custom C run-time DLL.%@AE@% %@NL@% %@NL@% A C run-time DLL can be shared by multiple programs and their DLLs. You generate the C run-time DLL in two steps. The first builds a module-definition file with a list of the C run-time library functions needed by your application and its DLLs; the second step links the module-definition file with the special library CDLLOBJS.LIB to create a C run-time DLL. %@NL@% %@NL@% The executable files for programs and DLLs linked with a customized C run-time DLL do not contain any code for the C run-time library functions. Figure 16.2 shows the relationships of the components. %@NL@% %@NL@% %@AU@% A private C run-time DLL must be closely tied to its programs and %@AU@%associated DLLs.%@AE@% %@NL@% %@NL@% Processes and DLLs that share a private run-time DLL share environment strings and global C run-time data (for example, file pointers for buffered I/O and memory allocated with the %@AB@%malloc%@AE@% function). Therefore, the program and the DLLs must cooperate on the use of this data. %@NL@% %@NL@% %@AU@%(This figure may be found in the printed book.)%@AE@%%@NL@% %@NL@% A closely tied structure is suitable for a complex application consisting of a set of application programs that act as front-end processors to several DLLs. A word processor, for example, might support one user interface for beginners, another for intermediate users, and a third for expert users. The different user interfaces could be implemented in three separate executable program files. All three programs would share the DLLs that do most of the real work. %@NL@% %@NL@% Section 16.3.3, "Programs and DLLs with a C Run-Time DLL," describes the procedures for building a C run-time library DLL and its associated programs and dynamic-link libraries. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00160006 @%%@AB@%16.2 Designing and Writing DLLs%@AE@%%@EH@%%@NL@% %@NL@% Before you write a DLL, you must determine some of the DLL's requirements. You need to know %@NL@% %@NL@% %@NL@% ■ Floating-point math requirements%@NL@% %@NL@% ■ Special initialization requirements such as allocation of buffers or registration of special termination routines%@NL@% %@NL@% ■ Termination requirements such as clearing semaphores or releasing allocated memory%@NL@% %@NL@% ■ Re-entrancy requirements; if the DLL is to be called by more than one process, it must be re-entrant%@NL@% %@NL@% %@NL@% This section explains how to design a DLL to take these requirements into account. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00160007 @%%@AB@%16.2.1 Floating-Point Math Requirements%@AE@%%@EH@%%@NL@% %@NL@% Stand-alone DLLs built with the LLIBCDLL library are independent of the programs calling them. They are "black boxes" that must operate without knowing anything about their client programs and without interfering with their clients.%@CR:C6A00160008 @% %@NL@% %@NL@% One area of potential conflict for stand-alone DLLs is control of the 80%@AI@%x%@AE@%87 math coprocessor. For a DLL to use the 80%@AI@%x%@AE@%87 coprocessor or the emulator floating-point library, the DLL and all of its client programs must agree on which process is going to handle floating-point exceptions and on which process is going to handle emulation if the machine does not have a coprocessor. %@NL@% %@NL@% Floating-point emulation is not possible with a genuinely independent DLL. A stand-alone DLL must use the alternate math library, which ignores the math coprocessor chip. The alternate math library provides the fastest processing available without a coprocessor, but results are not as accurate as those produced by the emulator floating-point library. Because the constraint applies only to the DLL and not to applications, clients of a stand-alone DLL can use any floating-point model. Since the DLL uses the alternate math library, it does not conflict with clients over control of the math coprocessor. %@NL@% %@NL@% In contrast, DLLs and programs using a private C run-time DLL are tightly coupled. This means that the floating-point math option is known when the program is built. Because these programs and DLLs all use the same C runtime functions (unlike the stand-alone DLL and its clients, which may incorporate different C run-time libraries), no contention can arise over control of the math coprocessor. The same floating-point math library is used for the entire application. %@NL@% %@NL@% %@AU@% The only way to use a math coprocessor within a DLL is with a private C %@AU@%run-time DLL.%@AE@% %@NL@% %@NL@% A private C run-time DLL uses the CDLLOBJS library and the emulator floating-point package. The emulator uses the 80%@AI@%x%@AE@%87 math coprocessor if one is installed; otherwise, it emulates the coprocessor. Floating-point emulation produces the most accurate results. There is no conflict over use of the coprocessor, since the C run-time DLL performs all floating-point math. The programs and DLLs calling the C run-time DLL do not have any C run-time library code of their own. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00160009 @%%@AB@%16.2.2 Initialization and Termination Requirements%@AE@%%@EH@%%@NL@% %@NL@% When you design a DLL, you must decide if it has special initialization or termination requirements. If the DLL needs to initialize variables or allocate memory buffers when it starts, it needs custom start-up procedures. If the DLL acquires system resources for a client program, the resources must be released when the program completes its processing. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Initialization%@AE@%%@EH@%%@NL@% %@NL@% All DLLs built with the Microsoft C run-time libraries must use per-process initialization to set up the C run-time data. Per-process initialization (also known as instance initialization) means that OS/2 calls the DLL's initialization code each time it loads a program linked with the DLL. For most DLLs, the default initialization routine is sufficient, and you do not need to take any other measures. %@NL@% %@NL@% %@AU@% If your DLL has special requirements, you must provide additional start-up %@AU@%processing.%@AE@% %@NL@% %@NL@% The C run-time library initialization function is called each time a new client is attached to the DLL. To override the default initialization, you must link your DLL with one of the following object modules, which are provided with the Microsoft C Professional Development System: %@NL@% %@NL@% %@AB@%File Name%@AE@% %@AB@%Description%@AE@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% DLLINIT.OBJ Initialization module for DLLs built with LLIBCDLL.LIB and using C run-time library code CRTDLL_I.OBJ Initialization module for DLLs using a C run-time DLL built with CDLLOBJS.LIB (replaces CRTDLL.OBJ) In addition, you must declare an entry point for your own DLL initialization function. Your function, or the application program calling your DLL, must initialize the C run-time data by calling the library function %@AB@%C_INIT%@AE@% before any other C run-time library functions are called. %@NL@% %@NL@% The prototype for %@AB@%C_INIT%@AE@% is %@NL@% %@NL@% %@AS@% void _far _pascal C_INIT( void );%@AE@%%@NL@% %@NL@% %@AU@% Designate your initialization function as the DLL's starting point.%@AE@% %@NL@% %@NL@% To have your custom function recognized as the DLL's default initialization routine, it must be the starting point for the DLL. This requires an assembly language file with an %@AB@%END%@AE@% statement naming your function. The sample file, SETENTRY.ASM, in the following example shows the minimum assembler code required for specifying a C language function named %@AB@%SampleInit%@AE@% as the DLL's entry point. %@NL@% %@NL@% %@AS@% ; SETENTRY.ASM %@AS@% extrn _SampleInit:FAR ;name of C start-up routine %@AS@% end _SampleInit%@AE@%%@NL@% %@NL@% The following example, SAMPLE.C, shows a simple custom initialization routine that maintains a count of how many clients it is currently serving. Since this example overrides the default dynamic-link library initialization, it must return a nonzero status code to OS/2 to show a successful start-up. If a DLL initialization function returns a status of 0, OS/2 will not load the program using the DLL. %@NL@% %@NL@% %@AS@% /* SAMPLE.C */ %@AS@% void _far _pascal C_INIT( void ); %@AS@% int UserCount = 0; %@AS@% %@AS@% int _export _loadds SampleInit() %@AS@% { %@AS@% UserCount++; /* increment number of users */ %@AS@% C_INIT(); /* initialize C run-time data */ %@AS@% return( 1 ); /* indicate successful start */ %@AS@% } %@AS@% %@AS@% /* code for other DLL functions belongs here */%@AE@%%@NL@% %@NL@% All DLLs must be linked with a module-definition file that contains a %@AB@%LIBRARY%@AE@% statement, such as the following: %@NL@% %@NL@% %@AS@% LIBRARY SAMPLE INITINSTANCE%@AE@%%@NL@% %@NL@% The following commands will create object files from the sample files and link them with DLLINIT.OBJ to make a stand-alone dynamic-link library named SAMPLE.DLL. The /ML compile option, explained in Section 16.2.6, "Compile Options for Dynamic-Link Libraries," sets the library search record to LLIBCDLL.LIB. %@NL@% %@NL@% %@AS@% MASM /Mx SETENTRY; %@AS@% CL /c /Gs /ML SAMPLE.C %@AS@% LINK /NOE DLLINIT+SETENTRY+SAMPLE,SAMPLE.DLL,,,SAMPLE.DEF;%@AE@%%@NL@% %@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% %@AU@%WARNING%@AE@%%@NL@% %@NL@% For DLLs linked with Microsoft C run-time libraries, the %@AI@%LIBRARY%@AE@% statement in the DLL's module-definition file must specify %@AI@%INITINSTANCE %@AE@%in the initialization field. If you omit this, the initialization routine is called only when the DLL is loaded into memory for the first client program, and the DLL will not function properly if it is called by additional programs.%@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% %@NL@% %@NL@% %@4@%%@AB@%Termination%@AE@%%@EH@%%@NL@% %@NL@% %@AU@% You may have to clean up before terminating.%@AE@% %@NL@% %@NL@% You may need to know when an application using your DLL is finished. If your DLL has created buffers, semaphores, or other resources for a particular application, they must be released when the application terminates. %@NL@% %@NL@% You can have an initialization routine in your DLL that calls the OS/2 API function %@AB@%DosExitList%@AE@% to register one or more exit subroutines for your DLL. OS/2 will call the exit routines when the client program finishes. The exit functions should free any resources your DLL acquired for the client program. %@NL@% %@NL@% %@AU@% DLLs built with LLIBCDLL.LIB have a default termination routine.%@AE@% %@NL@% %@NL@% The start-up routine for dynamic-link libraries built with the LLIBCDLL library calls %@AB@%DosExitList%@AE@% with a pointer to a default termination function. To replace the default processing with your own function, link the module DLLTERM.OBJ into the DLL. This suppresses the call to %@AB@%DosExitList%@AE@%. During initialization, your DLL must register its own routine by calling %@AB@%DosExitList%@AE@% unless you are sure the termination routine will be called explicitly. The termination processing must include a call to the library function %@AB@%C_TERM%@AE@%. %@NL@% %@NL@% The prototype for %@AB@%C_TERM%@AE@% is %@NL@% %@NL@% %@AS@% void _far _pascal C_TERM( void );%@AE@%%@NL@% %@NL@% There is no equivalent to DLLTERM.OBJ and %@AB@%C_TERM%@AE@% for DLLs using a private C run-time DLL built with the CDLLOBJS library. If special cleanup processing is required, these DLLs must provide their own termination function. The function is registered during initialization by calling either the C run-time library function %@AB@%atexit%@AE@% or the OS/2 API function %@AB@%DosExitList%@AE@%. %@NL@% %@NL@% %@AU@% Any DLL that calls %@AE@%%@AB@%DosExitList %@AE@%should also have a termination function. %@NL@% %@NL@% DLLs that set exit lists must provide termination functions that can be called by clients when they no longer need the DLL. If a program attaches itself to the DLL at run-time (using %@AB@%DosLoadModule%@AE@%), it cannot disconnect from the DLL as long as the exit list points to a function in the dynamic-link library. The DLL's termination function can perform any necessary cleanup and call %@AB@%DosExitList%@AE@% to remove itself from the exit list. %@NL@% %@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% NOTE %@AI@%There is no special termination procedure for DLLs build with CDLLOBJS.LIB %@AI@%because the C run-time termination code is called by the %@AB@%exit%@AE@%%@AI@% or %@AE@%%@AI@%%@AB@%_exit%@AE@%%@AE@%%@AI@% %@AI@%functions. If the process is terminated by a critical error or %@AE@%%@AI@%%@AB@%DosExit%@AE@%%@AE@%%@AI@%, C %@AI@%run-time termination does not occur.%@AE@%%@AE@%%@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00160010 @%%@AB@%16.2.3 Making the DLL Re-Entrant%@AE@%%@EH@%%@NL@% %@NL@% Re-entrant code is code that can be shared by multiple programs in a multitasking environment. DLLs that may be used by more than one program must be re-entrant. To do this, they must isolate each client program's data and resources. File handles belonging to one client, for example, must not be used for other clients. Re-entrancy also means that the DLL cannot allow itself to be switched to a different thread while it is performing certain operations. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Global Versus Instance Data%@AE@%%@EH@%%@NL@% %@NL@% %@AU@% A dynamic-link library can have separate data segments for each program %@AU@%that calls it.%@AE@% %@NL@% %@NL@% Separate data segments are known as "instance" data. With instance data segments, the DLL does not have to keep track of which resources belong to each client. OS/2 assigns a different data segment to each process calling the DLL, even though the selectors are the same. %@NL@% %@NL@% A dynamic-link library can also have a global data segment used for internal purposes or to support all of the programs using its services. %@NL@% %@NL@% A DLL providing time and date conversions might, for example, keep the current date in a global storage area. The same DLL might provide functions to compute elapsed time, such as the number of minutes between two clock readings. If static variables are used by the elapsed time functions, they should be in instance data segments, since the OS/2 scheduler might preempt the function and schedule another thread that calls the same function with different arguments before it has completed the first caller's task. %@NL@% %@NL@% Data sharing is controlled by %@AB@%DATA%@AE@% and %@AB@%SEGMENTS%@AE@% statements in a dynamic-link library's module-definition file. By default, a DLL's automatic data segment (the local stack and heap) is shared by all processes calling the DLL. You can specify a unique automatic data segment for each client process by specifying %@AB@%DATA MULTIPLE%@AE@%. %@NL@% %@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% %@AU@%WARNING%@AE@%%@NL@% %@NL@% DLLs built with the LLIBCDLL or CDLLOBJS C run-time libraries must use %@AI@%DATA %@AI@%MULTIPLE%@AE@% in the module-definition file.%@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% %@NL@% %@AU@% You can use %@AE@%%@AI@%SEGMENTS%@AE@% to specify attributes on a segment-by-segment basis. %@NL@% %@NL@% Using the %@AB@%SEGMENTS%@AE@% statement allows you to have both global and per-process (instance) data in the same DLL. The C run-time data segment must be per-process. The following is an example of a C program fragment and moduledefinition file that implement both instance and global data: %@NL@% %@NL@% %@AS@% /* Define static data in the shared segment SHR_SEG */ %@AS@% int _based(_segname("SHR_SEG")) intvar; %@AS@% char _based(_segname("SHR_SEG")) charvar;%@AE@%%@NL@% %@NL@% In the module-definition file, define all data segments as nonshareable, then override that default for %@AS@% SHR_SEG %@AE@% as follows: %@NL@% %@NL@% %@AS@% DATA MULTIPLE NONSHARED %@AS@% SEGMENTS %@AS@% SHR_SEG CLASS 'FAR_DATA' SHARED%@AE@%%@NL@% %@NL@% Global data segments are created when OS/2 brings the dynamic-link library into memory for its first client process. All of the processes calling the DLL share the same global variables. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Serializing Nonatomic References%@AE@%%@EH@%%@NL@% %@NL@% An atomic operation is an operation that can be completed in one machine language instruction. When writing a re-entrant procedure (in a multithread program or in a DLL), you must ensure that changes to static or global data are not preempted by the OS/2 scheduler before the update is complete. To prevent this, you must explicitly serialize nonatomic references to static or global data. The following code example is safe from preemption, because incrementing an integer requires only one machine instruction: %@NL@% %@NL@% %@AS@% int int_var; %@AS@% _export _loadds void _far _pascal dynlink_proc( void ) %@AS@% { %@AS@% int_var++; %@AS@% }%@AE@%%@NL@% %@NL@% The following variation on the same function is not safe because incrementing a %@AB@%long%@AE@% variable is not atomic; it requires two machine instructions. Between incrementing the least-significant word and the most-significant word, another thread could gain control of the processor. If that thread executes code in your DLL that uses %@AS@% long_var%@AE@%, that data would be in an indeterminate state. %@NL@% %@NL@% %@AS@% long long_var; %@AS@% _export _loadds void _far _pascal dynlink_proc( void ) %@AS@% { %@AS@% long_var++; %@AS@% }%@AE@%%@NL@% %@NL@% %@NL@% %@4@%%@AB@%Critical Code Sections%@AE@%%@EH@%%@NL@% %@NL@% A critical code section is a section of code that manipulates a resource (such as the long variable in the previous example) while blocking all other threads. When your program enters a critical section, it cannot be preempted until it performs a %@AB@%DosExitCritSec%@AE@% or until a signal is received. You don't usually just alter the value of a variable; you alter it and then use it later. In this case, you must isolate the smallest group of operations that must occur without interruption. You define these sections with the %@AB@%DosEnterCritSec%@AE@% and %@AB@%DosExitCritSec%@AE@% OS/2 API functions, as in the following example: %@NL@% %@NL@% %@AS@% _export _loadds void _far _pascal dynlink_proc( void ) %@AS@% { static int_var;%@AE@%%@NL@% %@NL@% %@AS@% DosEnterCritSec(); %@AS@% int_var += 7; %@AS@% SetLeftCorner( int_var, int_var ); %@AS@% DosExitCritSec();%@AE@%%@NL@% %@NL@% %@AS@% /* Code that does not reference int_var */ %@AS@% }%@AE@%%@NL@% %@NL@% %@AU@% Keep your critical sections as short as possible.%@AE@% %@NL@% %@NL@% While in a critical section, all other threads in the process are blocked from execution. Writing extremely long critical sections can make your program inefficient and can degrade system performance. %@NL@% %@NL@% Although other threads are blocked from execution by %@AB@%DosEnterCritSec%@AE@% and %@AB@%DosExitCritSec%@AE@%, these functions do not block signal handling. %@NL@% %@NL@% Note that static variables in DLLs are protected from interference from other processes if they are in an instance data segment designated as %@AB@%MULTIPLE%@AE@% in the %@AB@%DATA%@AE@% statement of the DLL's module-definition file. Memory is "owned" by a process and, unless specifically allocated as shareable, cannot be altered by any other process. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00160011 @%%@AB@%16.2.4 Signal Handling%@AE@%%@EH@%%@NL@% %@NL@% The C library function %@AB@%signal%@AE@% is not supported for multithread programs or for DLLs. If you need to process signals, use the OS/2 API signal functions, such as %@AB@%DosSetSigHandler%@AE@%. %@NL@% %@NL@% See Chapter 15, "Creating Multithread OS/2 Applications," for more information about signal handling in OS/2 programs. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00160012 @%%@AB@%16.2.5 Using Microsoft C Keywords%@AE@%%@EH@%%@NL@% %@NL@% The %@AB@%_export%@AE@% and %@AB@%_loadds%@AE@% keywords simplify writing DLLs. They are used to define or declare functions or pointers to functions. In the DLL, an exported function with a single argument might be defined as %@NL@% %@NL@% %@AS@% int _export _loadds sample( int )%@AE@%%@NL@% %@NL@% %@NL@% %@4@%%@AB@%The _export Keyword%@AE@%%@EH@%%@NL@% %@NL@% %@AU@% All DLL functions that will be called from outside the library must be %@AU@%exported.%@AE@% %@NL@% %@NL@% The %@AB@%_export%@AE@% keyword gives a function the export attribute. Stack checking must be disabled for exported entry points. You can use the /Gs compile option or the %@AB@%check_stack%@AE@% pragma to accomplish this. %@NL@% %@NL@% Using the %@AB@%_export%@AE@% keyword is an alternative to declaring the name of the function in the %@AB@%EXPORTS%@AE@% section of a module-definition file. It assigns certain default attributes: no I/O privilege, shared data, load on demand, and no alias name. If the defaults are not acceptable, you must specify the proper attributes in the module-definition file. %@NL@% %@NL@% Not all functions in a DLL are for external use. A DLL can have any number of utility subroutines supporting the work of the exported functions. Functions that are private to the DLL should not have the %@AB@%_export%@AE@% keyword. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%The _loadds Keyword%@AE@%%@EH@%%@NL@% %@NL@% At entry to a DLL, the DS (data segment) register points to the calling program's data segment. To access the DLL's data, the DS register has to be loaded with the DLL's segment selector. The %@AB@%_loadds%@AE@% keyword causes the compiler to add prolog and epilog code to the function. The prolog code initializes the DS register to point to the function's data group. The epilog code restores the caller's DS register when the function terminates. %@NL@% %@NL@% Since loading the DS register is a high overhead operation, you should limit the use of %@AB@%_loadds%@AE@% to the exported functions in your DLL. %@NL@% %@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% %@AU@%WARNING%@AE@%%@NL@% %@NL@% Do not use the %@AB@%_loadds%@AE@% keyword in a function definition if the function uses only stack variables. If you specify %@AB@%_loadds%@AE@% in a DLL that does not have any static data, the linker will issue a segment fix-up error.%@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00160013 @%%@AB@%16.2.6 Compile Options for Dynamic-Link Libraries%@AE@%%@EH@%%@NL@% %@NL@% Dynamic-link libraries must be compiled with specific options that control linking, memory models, and library selection. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Compile without Linking (/c)%@AE@%%@EH@%%@NL@% %@NL@% You must use the /c option to build your DLL in separate compile and link steps. This is necessary because the DLL must be linked with a module-definition file specifying that the output file is a dynamic-link library. (The compiler does not pass module-definition file names to the linker.) The /c option is automatically specified in the makefile generated by the Programmer's WorkBench. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Large Memory Model with Separate Stack (/ALw)%@AE@%%@EH@%%@NL@% %@NL@% The /ALw option instructs the compiler to use the large memory model with a separate stack segment. Because all DLLs use the caller's stack, you must use /Aw or /Au. The /Aw option sets up separate stack and data segments but does not cause the DS register to be reloaded at the entry to each function. This allows you to call private functions (functions that you do not export) without incurring the overhead of loading the DS register. Functions that you do export must also be declared using the %@AB@%_loadds%@AE@% keyword, described above, which sets up the proper DS register handling. If you use the /Au option, the DS register will be reloaded on entry to every function, which can cause the function calls in your DLLs to execute more slowly. %@NL@% %@NL@% All DLL functions are reached using far calls. Pointers passed to and from the DLL must be far pointers. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Remove Stack Probes (/Gs)%@AE@%%@EH@%%@NL@% %@NL@% Since the DLL uses the caller's stack, you should usually use the /Gs option to disable stack checking within the DLL. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Specify 80286 Code (/G2)%@AE@%%@EH@%%@NL@% %@NL@% Use the /G2 option to designate code generation for the 80286 processor instruction set, since OS/2 runs only on 80286 and higher model processors. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Link C Run-Time into Stand-Alone DLL (/ML)%@AE@%%@EH@%%@NL@% %@NL@% Use the /ML option to build a stand-alone dynamic-link library that includes static code for C run-time library functions. This option has the same effect as using the /ALw, /FPa, /G2, and /D MT options. It changes the library search record to LLIBCDLL.LIB. See Section 16.3.1, "DLLs with Static C Run-Time Library Functions" for more information about these options. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Link Executable or DLL with C Run-Time DLL (/MD)%@AE@%%@EH@%%@NL@% %@NL@% Use the /MD option to build an executable file or a dynamic-link library that calls a C run-time DLL. This option has the same effect as using the /ALw, /FPi, /G2, /D DLL, and /D MT options. It inhibits library search records. See Section 16.3.3, "Programs and DLLs with a C Run-Time DLL," for more information about these options. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Suppress Default Library Selection (/Zl)%@AE@%%@EH@%%@NL@% %@NL@% If you do not compile with the /MD or /ML options described above, compile with the /Zl option or use the /NOD option when you link in order to inhibit searches for default libraries. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00160014 @%%@AB@%16.3 Building DLLs with Microsoft C%@AE@%%@EH@%%@NL@% %@NL@% %@AU@% Building a DLL for OS/2 is like building an executable program file.%@AE@% %@NL@% %@NL@% To build a DLL, compile and link the dynamic-link library like any other executable file, but add a module-definition file. This module-definition file tells the linker that the output is a dynamic-link library. %@NL@% %@NL@% When you build applications that use a dynamic-link library, you must tell the linker where to find the library's dynamically linked functions. You use import libraries and module-definition files for this purpose. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00160015 @%%@AB@%16.3.1 DLLs with Static C Run-Time Library Functions%@AE@%%@EH@%%@NL@% %@NL@% The LLIBCDLL library is used to create stand-alone DLLs. The library functions are re-entrant and can be called by multiple threads within a program as well as by multiple programs. The code for the stand-alone DLL's C run-time library functions is contained within the DLL. Programs that call stand-alone DLLs have their own run-time library code. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Building the DLL%@AE@%%@EH@%%@NL@% %@NL@% The files required to build a stand-alone DLL with the LLIBCDLL library are listed below: %@NL@% %@NL@% %@AB@%File Name%@AE@% %@AB@%Description%@AE@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% OS2.LIB OS/2 kernel import library LLIBCDLL.LIB Large-model multithread C run-time library for DLLs DLLINIT.OBJ Optional initialization module for DLLs requiring custom initialization DLLTERM.OBJ Optional termination module for DLLs requiring custom exit processing %@AI@%userdll%@AE@%.C Source code for the DLL you create %@AI@%userdll%@AE@%.DEF Module-definition file for the DLL you create The module JUSTIFY.C, below, is an example of source code for a simple dynamic-link library. The %@AB@%RightJustify%@AE@% routine calls the %@AB@%strlen%@AE@% function from the C run-time library and right-justifies a caller's buffer. The function definition includes the %@AB@%_export%@AE@% keyword. The %@AB@%_loadds%@AE@% keyword is omitted, since this function does not need any static data. If it did, you would need to specify %@AB@%_loadds%@AE@%. %@NL@% %@NL@% For simplicity, JUSTIFY.C below shows a DLL with a single function. In actual practice, you would usually package a group of similar utilities into one DLL. %@NL@% %@NL@% %@AS@% /* JUSTIFY.C -- Sample Dynamic-Link Library */ %@AS@% %@AS@% #include <string.h> %@AS@% %@AS@% /* Right justifies the string in TargetBuff to TargetSize %@AS@% * and inserts necessary number of FillChars on the left. %@AS@% */%@AE@%%@NL@% %@NL@% %@AS@% #pragma stack_check(off) %@AS@% %@AS@% int _export RightJustify( char *TargetBuff, int TargetSize, %@AS@% char FillChar) %@AS@% { %@AS@% char *s, *d; %@AS@% s = TargetBuff + strlen( TargetBuff ); %@AS@% d = TargetBuff + TargetSize; %@AS@% while ( s = TargetBuff ) %@AS@% *d-- = *s--; %@AS@% while ( d = TargetBuff ) %@AS@% *d-- = FillChar; %@AS@% %@AS@% return( 0 ); %@AS@% }%@AE@%%@NL@% %@NL@% The steps for creating a stand-alone dynamic-link library with JUSTIFY.C are given below. The DLL in the example is named JUSTLIB1.DLL. %@NL@% %@NL@% %@NL@% ■ Compile with the /ML Option.%@NL@% %@NL@% %@STUB@% Compile the source file without linking. Dynamic-link libraries linked with LLIBCDLL must be compiled with specific options.%@NL@% %@NL@% %@STUB@% Use the /ML option to set the library search record to LLIBCDLL.LIB and to indicate that C run-time code is to be included in the DLL. When you use /ML, the following options take effect:%@NL@% %@NL@% %@AB@%Option%@AE@% %@AB@%Effect%@AE@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@NL@% /ALw Use large memory model with separate stack segment /G2 Use 80286 processor instruction set /D MT Use the multithread version of the include files /FPa Generate floating-point calls and select the alternate math library The /G2 and the /ALw options can be overridden.%@NL@% %@NL@% %@STUB@% You should also use the /Gs option to suppress stack checking and the /c option to compile without linking. The complete command to compile the sample file JUSTIFY.C is%@NL@% %@NL@% %@AS@% CL /ML /Gs /c JUSTIFY.C%@AE@%%@NL@% %@NL@% ■ Create a module-definition file.%@NL@% %@NL@% %@STUB@% Create a module-definition file, JUSTLIB1.DEF, which includes the following lines:%@NL@% %@NL@% %@AS@% LIBRARY JUSTLIB1 INITINSTANCE %@AS@% DATA MULTIPLE%@AE@%%@NL@% %@NL@% %@STUB@% The %@AB@%LIBRARY%@AE@% statement identifies the executable file, JUSTLIB1.DLL, as a dynamic-link library. DLLs linked with the LLIBCDLL library must specify %@AB@%INITINSTANCE%@AE@% in the initialization field. You could add an %@AB@%EXPORTS%@AE@% statement for the %@AB@%RightJustify%@AE@% function in JUSTIFY.C, but it is optional since the %@AB@%_export%@AE@% keyword was used in the source code.%@NL@% %@NL@% %@STUB@% See Chapter 14, "Building OS/2 Applications," for more information about module-definition files.%@NL@% %@NL@% ■ Link with LLIBCDLL.LIB.%@NL@% %@NL@% %@STUB@% Ensure that the file LLIBCDLL.LIB, which takes the place of the regular C run-time library, is available.%@NL@% %@NL@% %@STUB@% Create JUSTLIB1.DLL with a command such as%@NL@% %@NL@% %@AS@% LINK justify,justlib1.dll,,,justlib1.def/NOI%@AE@%%@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% %@AU@%WARNING%@AE@%%@NL@% %@NL@% When you link with LLIBCDLL, you cannot have any other C run-time libraries in the link.%@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% %@NL@% %@NL@% ■ Create an import library.%@NL@% %@NL@% %@STUB@% Applications that call DLLs use import libraries to identify DLL functions to the linker. The following example uses JUSTLIB1.DLL and the IMPLIB utility to create an import library named JUSTLIB1.LIB.%@NL@% %@NL@% %@AS@% IMPLIB justlib1.lib justlib1.dll%@AE@%%@NL@% %@NL@% %@STUB@% For more information about import libraries, see Chapter 14, "Building OS/2 Applications."%@NL@% %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Building Programs that Call the DLL%@AE@%%@EH@%%@NL@% %@NL@% To link a dynamic-link library with an application, you must have one of the following: %@NL@% %@NL@% %@NL@% ■ A module-definition file with an %@AB@%IMPORTS%@AE@% statement for each DLL function called by your program%@NL@% %@NL@% ■ An import library created from the DLL itself or from a module-definition file%@NL@% %@NL@% %@NL@% All calls to DLLs must be far calls; all pointers passed must be far data pointers. If you do not compile with the large memory model option (/AL), you must cast the DLL function calls and pointers yourself. %@NL@% %@NL@% The sample file below, TESTJUST.C, is compiled and linked into a small-model program named SAMPLE1.EXE. TESTJUST.C includes a function prototype that declares %@AB@%RightJustify%@AE@% as a far function expecting a far pointer as its first argument. Because of the prototype, the compiler will generate a far call to %@AB@%RightJustify%@AE@% and coerce the pointer argument to the proper value. %@NL@% %@NL@% %@AS@% /* TESTJUST.C. Call sample DLL library */%@AE@%%@NL@% %@NL@% %@AS@% #include <stdio.h> %@AS@% #include <string.h>%@AE@%%@NL@% %@NL@% %@AS@% /* DLL function prototype */ %@AS@% %@AS@% int _far RightJustify( char _far *, int, char ); %@AS@% %@AS@% void main( void ) %@AS@% { %@AS@% char buff[12]; %@AS@% %@AS@% strcpy( buff, "ABCD" ); %@AS@% %@AS@% /* Right justify to 8 characters and zero fill. */ %@AS@% RightJustify( buff, 8, '0' ); %@AS@% printf( "Result: %s\n", buff ); %@AS@% }%@AE@%%@NL@% %@NL@% You need several files to link an application with a stand-alone DLL: %@NL@% %@NL@% %@AB@%File Name%@AE@% %@AB@%Description%@AE@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@AI@%userdll%@AE@%.LIB Import library file for the DLL %@AI@%userapp%@AE@%.DEF Optional module-definition file for your application that contains an %@AB@%IMPORTS%@AE@% statement for each DLL function called (required if not using an import library) OS2.LIB Optional import library file for the OS/2 kernel (required if your application calls the kernel directly or via a C run-time library function) %@AI@%userapp%@AE@%.OBJ Object module(s) for your application %@AI@%m%@AE@%LIBC %@AI@%f%@AE@% P.LIB Regular C run-time library for protected mode, where %@AI@%m%@AE@% indicates memory model (S, C, M, L) and%@AI@%%@AE@% %@AI@%f%@AE@% indicates math package (A, E, 7) The following command lines illustrate how TESTJUST.C can be compiled and linked with the standard libraries, plus the sample dynamic-link library, JUSTLIB1.DLL. The example uses the small memory model library and the JUSTLIB1.LIB import library created from JUSTLIB1.DLL to create SAMPLE1.EXE. %@NL@% %@NL@% %@AS@% CL /AS /G2 /c TESTJUST.C %@AS@% LINK TESTJUST,SAMPLE1.EXE,,JUSTLIB1;%@AE@%%@NL@% %@NL@% Make sure that the JUSTLIB1.DLL file is in a directory on your LIBPATH before executing SAMPLE1.EXE. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00160016 @%%@AB@%16.3.2 DLLs without C Run-Time Library Functions%@AE@%%@EH@%%@NL@% %@NL@% Building a DLL that does not call any of the C run-time library functions is similar to creating a stand-alone DLL. %@NL@% %@NL@% To use the JUSTIFY.C sample program shown in Section 16.3.1, "DLLs with Static C Run-Time Library Functions," without calling C run-time functions, one change must be made. You must remove the call to the C run-time library function %@AB@%strlen%@AE@%. The %@AB@%strlen%@AE@% function was used in the sample program to calculate a pointer to the end of the caller's buffer. Remove the following line in the program JUSTIFY.C: %@NL@% %@NL@% %@AS@% s = TargetBuff + strlen( TargetBuff ); %@AE@%%@NL@% %@NL@% Replace the line above with the following code fragment, which does the same thing without calling %@AB@%strlen%@AE@%: %@NL@% %@NL@% %@AS@% s = TargetBuff; %@AS@% while ( *s ) %@AS@% s++;%@AE@%%@NL@% %@NL@% After making this change, you can use the following commands to create a DLL named JUSTLIB2.DLL and its import library: %@NL@% %@NL@% %@AS@% CL /c /ALw /G2s /Zl JUSTIFY.C %@AS@% LINK JUSTIFY,JUSTLIB2.DLL,,,JUSTLIB2.DEF/NOI %@AS@% IMPLIB JUSTLIB2.LIB JUSTLIB2.DLL%@AE@%%@NL@% %@NL@% Note that object modules compiled with releases of Microsoft C prior to Version 6.0 refer to the C run-time library variable %@AB@%_acrtused%@AE@%. C 6.0 defines this variable if the %@AB@%main%@AE@% function is present. This causes the linker to automatically add the C run-time start-up module to the DLL. To suppress the start-up module, your source file must include a line defining %@AB@%_acrtused%@AE@% as follows: %@NL@% %@NL@% %@AS@% int _acrtused = 0;%@AE@%%@NL@% %@NL@% This is required only if you do not use a C run-time library and if the link includes object modules built with earlier versions of the compiler. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00160017 @%%@AB@%16.3.3 Programs and DLLs with a C Run-Time DLL%@AE@%%@EH@%%@NL@% %@NL@% The CDLLOBJS.LIB and CDLLOBJS.DEF files are the foundation for building a DLL that consists only of C run-time library functions. The application programs and optional dynamic-link libraries linked with this DLL do not contain any C run-time library code. %@NL@% %@NL@% You create an application to use the C run-time DLL in either two or three phases, depending on whether or not the application has additional DLLs: %@NL@% %@NL@% %@NL@% ■ Build a C run-time DLL.%@NL@% %@NL@% ■ Build any optional DLLs that use the C run-time DLL.%@NL@% %@NL@% ■ Compile and link the application.%@NL@% %@NL@% %@NL@% The examples in this section use the JUSTIFY.C and TESTJUST.C source files shown in Section 16.3.1, "DLLs with Static C Run-Time Library Functions." %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Building a C Run-Time DLL%@AE@%%@EH@%%@NL@% %@NL@% The C run-time DLL is derived from the CDLLOBJS.LIB and CDLLOBJS.DEF files provided with the Microsoft C Professional Development System. The CDLLOBJS.DEF file includes export definitions for all of the C run-time library functions. %@NL@% %@NL@% The steps for creating a C run-time DLL are given below. The C run-time DLL in the example is named CEXAMPLE.DLL. %@NL@% %@NL@% %@NL@% 1. Create a module-definition file.%@NL@% %@NL@% %@STUB@% You can use CDLLOBJS.DEF as the basis for your own module-definition file by copying and editing it. This allows you to create a customized DLL that contains only the functions your application requires. If you use the CDLLOBJS.DEF file without modification, every program that links to your C run-time DLL will get the entire C run-time library.%@NL@% %@NL@% %@STUB@% The following examples create the sample file CEXAMPLE.DEF to define the custom dynamic link library CEXAMPLE.DLL. The CEXAMPLE.DEF file, shown below, exports the three C run-time library functions called from JUSTIFY.C and TESTJUST.C. It also exports functions required by the C run-time library start-up modules.%@NL@% %@NL@% %@AS@% LIBRARY CEXAMPLE INITINSTANCE %@AS@% DESCRIPTION 'Sample Dynamic-link C Run-Time Library' %@AS@% DATA MULTIPLE %@AS@% PROTMODE %@AS@% EXPORTS %@AS@% _printf %@AS@% _strlen %@AS@% _strcpy %@AS@% __CRT_INIT %@AS@% __aFchkstk %@AS@% _exit%@AE@%%@NL@% %@NL@% 2. Create the C run-time DLL.%@NL@% %@NL@% %@STUB@% The files for creating a C run-time DLL are listed below:%@NL@% %@NL@% %@AB@%File Name%@AE@% %@AB@%Description%@AE@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@NL@% OS2.LIB Import library for the OS/2 kernel CDLLOBJS.LIB Dynamic link C run-time library CRTLIB.OBJ Start-up code for C run-time DLL %@AI@%yourclib%@AE@%.DEF Module-definition file specifying C run-time library functions for the DLL The command to create the sample CEXAMPLE.DLL file is%@NL@% %@NL@% %@AS@% %@AS@% LINK /NOD /NOE /NOI crtlib.obj,cexample.dll,,cdllobjs+os2,cexample.def%@AE@%%@NL@% %@NL@% 3. Create an import library.%@NL@% %@NL@% %@STUB@% You need to create a library file of import definitions that can be used by programs that will be linked with your custom DLL. This is a two-step process. The first phase uses the module-definition file and the IMPLIB utility to create an interim version of the library, as in this example:%@NL@% %@NL@% %@AS@% IMPLIB cexample.lib cexample.def%@AE@%%@NL@% %@NL@% %@STUB@% Note that the IMPLIB utility accepts either a module-definition file or a DLL as input.%@NL@% %@NL@% %@STUB@% The second step uses the LIB utility to append the file CDLLSUPP.LIB to the import library. You must append CDLLSUPP.LIB because it contains some routines that cannot be dynamically linked. The LIB utility requires the full path name for CDLLSUPP.LIB. If it is in a directory named C:\ LIB, the command to complete the library build for CEXAMPLE.LIB is%@NL@% %@NL@% %@AS@% LIB CEXAMPLE.LIB+C:\LIB\CDLLSUPP.LIB;%@AE@%%@NL@% %@NL@% %@STUB@% When you have finished building the custom DLL, be sure to copy it to a directory specified in the %@AB@%LIBPATH%@AE@% statement of the CONFIG.SYS file.%@NL@% %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Building an Application-Specific DLL%@AE@%%@EH@%%@NL@% %@NL@% You must compile a DLL that calls a C run-time DLL with specific options and link it with the C run-time DLL's import library. The steps for building an application-specific DLL named JUSTLIB3.DLL are given below. %@NL@% %@NL@% %@NL@% 1. Compile with the /MD option.%@NL@% %@NL@% %@STUB@% The easiest way to be sure you choose the proper options is to use the /MD switch, which indicates that the DLL will be used with a C run-time DLL. When you use /MD, library search records are suppressed and the following options are in effect:%@NL@% %@NL@% %@AB@%Option%@AE@% %@AB@%Effect%@AE@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@NL@% /ALw Use large memory model with separate stack segment /G2 Use 80286 processor instruction set /D MT Use the multithread version of the include files /D DLL Use a C run-time dynamic-link library /FPi Generate in-line floating-point instructions and select the emulator math package The /G2 and /ALw options can be overridden. The FPi option can be replaced with /FPi87 or /FPc, but not with /FPa. See Chapter 4, "Controlling Floating-Point Math Operations," for more information about compatible floating-point options.%@NL@% %@NL@% %@STUB@% You should also use the /c option to compile without linking. The command line to compile the sample file JUSTIFY.C is%@NL@% %@NL@% %@AS@% CL /MD /c JUSTIFY.C%@AE@%%@NL@% %@NL@% 2. Create a module-definition file.%@NL@% %@NL@% %@STUB@% Create a module-definition file named JUSTLIB3.DEF that includes the following line:%@NL@% %@NL@% %@AS@% LIBRARY JUSTLIB3 INITINSTANCE%@AE@%%@NL@% %@NL@% 3. Link the DLL with the C run-time and OS/2 import libraries.%@NL@% %@NL@% %@STUB@% To create a DLL that will call a C run-time DLL, the following files must be linked together:%@NL@% %@NL@% %@AB@%File Name%@AE@% %@AB@%Description%@AE@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@NL@% OS2.LIB Import library for the OS/2 kernel %@AI@%yourclib%@AE@%.LIB Import library for your C run-time DLL CRTDLL.OBJ Start-up code for DLLs using a C run-time DLL CRTDLL_I.OBJ Optional initialization module for DLLs requiring custom initialization (replaces CRTDLL.OBJ) %@AI@%yourdll%@AE@%.OBJ Object file for your DLL %@AI@%yourdll%@AE@%.DEF Module-definition file for your DLL The command for linking these files to create JUSTLIB3.DLL is%@NL@% %@NL@% %@AS@% %@AS@% LINK justify+crtdll,justlib3.dll,,cexample+os2,justlib3.def%@AE@%%@NL@% %@NL@% 4. Create an import library.%@NL@% %@NL@% %@STUB@% Use JUSTLIB3.DLL and the IMPLIB utility to create an import library file, JUSTLIB3.LIB, for use by applications calling JUSTLIB3.DLL:%@NL@% %@NL@% %@AS@% IMPLIB JUSTLIB3.LIB JUSTLIB3.DLL%@AE@%%@NL@% %@NL@% %@STUB@% Remember to copy JUSTLIB3.DLL to a directory named in the %@AB@%LIBPATH%@AE@% statement in the CONFIG.SYS file.%@NL@% %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Using C Run-Time and Application-Specific DLLs%@AE@%%@EH@%%@NL@% %@NL@% Application programs using a C run-time DLL, such as the sample program CEXAMPLE.DLL (described earilier in this section), must define the symbolic constants %@AB@%MT%@AE@% and %@AB@%DLL%@AE@%. These constants cause the compiler to use the multithread and DLL sections of the include files. You can define the constants in your source code or with the compiler's /D command-line option. Since the C run-time DLL uses the large memory model, your program must either use the same model or declare all C run-time functions and pointers passed to them as %@AB@%_far%@AE@%. If you use the standard include files for the C run-time functions in your program, all these declarations are made for you. %@NL@% %@NL@% The following files are required to link an application that calls a C runtime DLL: %@NL@% %@NL@% %@AB@%File Name%@AE@% %@AB@%Description%@AE@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% OS2.LIB Import library for the OS/2 kernel %@AI@%yourclib%@AE@%.LIB Import library for your C run-time DLL %@AI@%yourdll%@AE@%.LIB Import library for each optional application DLL CRTEXE.OBJ Start-up code for executable files calling a C run-time DLL %@AI@%yourapp%@AE@%.OBJ Object file(s) for your application %@AI@%yourapp%@AE@%.DEF Optional module-definition file for your application The following commands compile and link the TESTJUST.C file from Section 16.3.1 for use with the dynamic-link libraries CEXAMPLE.DLL and JUSTLIB3.DLL. The link command uses the /NOD option to suppress selection of the standard large-model library. The result is a program named SAMPLE2.EXE. %@NL@% %@NL@% %@AS@% CL /AL /D MT /D DLL /G2 /c TESTJUST.C %@AS@% LINK /NOD TESTJUST+CRTEXE,SAMPLE2.EXE,,CEXAMPLE+OS2+JUSTLIB3;%@AE@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00160018 @%%@AB@%16.3.4 Using CodeView to Debug Dynamic-Link Libraries%@AE@%%@EH@%%@NL@% %@NL@% The protected-mode version of CodeView (CVP) supports debugging of dynamic-link libraries. The /L option lets you name one or more DLLs to be debugged with your application. %@NL@% %@NL@% To enable full symbolic debugging, use the CodeView options /Zi when compiling and /CO when linking. Do this for both the DLL to be debugged and for the program that calls the DLL. %@NL@% %@NL@% The syntax for the /L CodeView option is %@NL@% %@NL@% %@AS@% /L file%@AE@%%@NL@% %@NL@% At least one space must separate /L from the file name(s). You can enter multiple DLL names. To debug the JUSTLIB3.DLL dynamic-link library and the SAMPLE2.EXE program discussed in the previous section, use this command line:%@CR:C6A00160019 @% %@NL@% %@NL@% %@AS@% CVP /L JUSTLIB3.DLL SAMPLE2.EXE%@AE@%%@NL@% %@NL@% %@AU@% Use the CodeView Trace com%@AE@%%@AB@%mand (F8) to enter an%@AE@%d view DLL code. %@NL@% %@NL@% A simple way to use CodeView is to place a breakpoint at the instruction that calls the DLL function you want to debug. When you reach the breakpoint, press F8 to execute the current source line. CodeView will then display the DLL function's source code, allowing you to set additional breakpoints and enter other CodeView commands. %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@CR:C6A-A0001 @%%@1@%%@AB@%Appendix A Using Exit Codes%@AE@%%@EH@%%@NL@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@NL@% When C programs terminate, they return values to the process that started them. These values are called "exit codes." The process that starts a C program can be either an operating system, such as DOS or OS/2, or another program. The process that starts the C program is referred to as the "parent process"; the program started is referred to as the "child process." The parent process can interpret return values as an error code sent to the operating system or use those return values as a form of interprocess communication (communication between two separate processes).%@CR:C6A-A0002 @% %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A-A0003 @%%@AB@%A.1 The exit Function%@AE@%%@EH@%%@NL@% %@NL@% The %@AB@%exit%@AE@% function terminates execution of your C program and returns an exit code (an integer value) to the parent process. The parent process can be the operating system or another program, depending on how the child process was executed. Note that a C program always returns an integer, regardless of how you declare the %@AB@%main%@AE@% function. %@NL@% %@NL@% Most programs use exit codes to communicate errors to the parent process; these are called "error codes." By convention, programs return zero if they complete normally and a nonzero value if they are exiting because of an error. This error code (the nonzero value) can then be used by the operating system to control the execution of other programs (for example, from inside a batch file). %@NL@% %@NL@% The Microsoft C compiler is a good example of a program that returns an exit code. It returns 0 if no errors occur in your compile and a positive value if an error occurs during compilation. %@NL@% %@NL@% The following program attempts to open a file for reading. If the file cannot be opened, %@AB@%exit%@AE@% returns 1 to the calling program. Therefore, 1 and 0 are both exit codes. %@NL@% %@NL@% %@AS@% #include <stdio.h> %@AS@% %@AS@% int main(void) %@AS@% { %@AS@% FILE * fp; %@AS@% %@AS@% if( !(fp = fopen( filename, "rb" )) ) %@AS@% { %@AS@% printf("Error %d: Could not open file\n", errno); %@AS@% exit(1); %@AS@% } %@AS@% %@AS@% do_file_access(fp); %@AS@% }%@AE@%%@NL@% %@NL@% In the preceding example, the exit code is unpredictable because the %@AB@%exit %@AB@%%@AE@%function is not used. The value actually returned to the parent process (or to the operating system shell) is whatever happens to be in the AX register when the program terminates─in this case, whatever %@AS@% do_file_access %@AE@% returned. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A-A0004 @%%@AB@%A.2 Testing Exit Codes from Command and Batch Files%@AE@%%@EH@%%@NL@% %@NL@% Using the IF ERRORLEVEL command, you can test to see if a program has executed successfully by checking its exit code. The IF ERRORLEVEL command is an OS/2 command file or DOS batch file command that tests the exit code of the most recently executed program. %@NL@% %@NL@% IF ERRORLEVEL can help you organize program execution. For example, you can define program execution to be dependent on the successful exit code testing of earlier programs by IF ERRORLEVEL. You can also use the value of the exit code to branch to different commands in a batch or command file. %@NL@% %@NL@% When placed in a batch or command file, the following commands will execute REPORTS.EXE only if FILEMNG.EXE does not return an error: %@NL@% %@NL@% %@AS@% echo Running file manager.... %@AS@% FILEMNG.EXE %@AS@% IF NOT ERRORLEVEL 1 REPORTS.EXE%@AE@%%@NL@% %@NL@% Despite the name %@AS@% ERRORLEVEL%@AE@%, the exit code does not always denote an error. You can define error codes to communicate any information useful to you. %@NL@% %@NL@% Refer to the %@AI@%Microsoft Operating System/2 User's Guide%@AE@% or the %@AI@%Microsoft %@AI@%MS-DOS User's Guide and User's Reference %@AE@%for more information about the IF ERRORLEVEL command. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A-A0005 @%%@AB@%A.3 Accessing Exit Codes from Other Programs%@AE@%%@EH@%%@NL@% %@NL@% When you use any of the %@AB@%spawn%@AE@% family of functions to run a program as the child of another program, the return value of %@AB@%spawn %@AE@%is the exit code of the function. The following code performs the same function as the batch file in Section A.2: %@NL@% %@NL@% %@AS@% void main( void ) %@AS@% { %@AS@% if( !spawnl( P_WAIT, "filemng.exe", "filemng.exe", %@AS@% NULL ) ) %@AS@% spawnl( P_WAIT, "reports.exe", "reports.exe", %@AS@% NULL ); %@AS@% }%@AE@%%@NL@% %@NL@% The program %@AS@% reports.exe %@AE@% is executed only if the program %@AS@% filemng.exe %@AS@%%@AE@%terminates with an exit code of 0. %@NL@% %@NL@% The following code uses the exit code as part of a simple menu system: %@NL@% %@NL@% %@AS@% void main(void) %@AS@% { %@AS@% int option; %@AS@% int menu_num = 0; /* Initialize for first execution */ %@AS@% %@AS@% while( (option = spawnl( P_WAIT, "menu.exe", %@AS@% "menu.exe", menu_num, NULL )) ) %@AS@% { %@AS@% switch( option ) %@AS@% { %@AS@% case 1 : %@AS@% menu_num = spawnl( P_WAIT, "program1.exe", %@AS@% "program1.exe", NULL ); %@AS@% break; %@AS@% case 2 : %@AS@% menu_num = spawnl( P_WAIT, "program2.exe", %@AS@% "program2.exe", NULL ); %@AS@% break; %@AS@% case 3 : %@AS@% menu_num = spawnl( P_WAIT, "program3.exe", %@AS@% "program3.exe", NULL ); %@AS@% break; %@AS@% default: /* Guard against a bad option */ %@AS@% break; %@AS@% } %@AS@% } %@AS@% }%@AE@%%@NL@% %@NL@% The preceding example demonstrates how you could have a program, %@AS@% menu.exe%@AE@%, that solicits input from a menu of choices. This input is interpreted and passed back to the main program in the form of an exit code. (The %@AB@%spawnl%@AE@% function returns the value of the child process's exit code.) This exit code value is stored in %@AS@% option%@AE@%, which is used as a selector variable in a switch statement. %@NL@% %@NL@% Based on the value returned from %@AS@% menu.exe%@AE@%, the main program executes %@AS@%program1.exe%@AE@%, %@AS@% program2.exe%@AE@%, or %@AS@% program3.exe%@AE@%. Finally, %@AS@% menu_num%@AE@%, the exit code of the program selected, is used as a parameter to the next execution of %@AS@% menu.exe%@AE@%. %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@CR:C6A-B0001 @%%@1@%%@AB@%Appendix B Differences between C Versions 5.1 and 6.0%@AE@%%@EH@%%@NL@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@NL@% This appendix describes the differences between versions 5.1 and 6.0 of Microsoft C, including additions, deletions, and changes. Some of the changes are required by the American National Standards Institute (ANSI) draft standard for the C programming language. Other changes improve or augment the existing capabilities of the compiler. %@NL@% %@NL@% Many of the changes will have no effect on code that was written and compiled with previous versions of Microsoft C. In some cases, however, you may have to modify or correct existing code before compiling with version 6.0. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A-B0002 @%%@AB@%B.1 Modifications for ANSI Compatibility%@AE@%%@EH@%%@NL@% %@NL@% A number of changes have been made to the compiler to support the ANSI draft standard. These include new features (Section B.1.1) and changes (Sections B.1.2 - B.1.8). %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-B0003 @%%@AB@%B.1.1 ANSI-Mandated New Features%@AE@%%@EH@%%@NL@% %@NL@% The following ANSI-mandated features are new to version 6.0: %@NL@% %@NL@% %@NL@% ■ The semantics for %@AB@%volatile%@AE@% have been implemented.%@NL@% %@NL@% ■ Both %@AB@%long %@AE@%and %@AB@%unsigned long%@AE@% values are allowed in switch expressions and case constants.%@NL@% %@NL@% ■ The compiler supports %@AB@%unsigned long%@AE@% decimal constants. It is now possible to initialize %@AB@%unsigned long%@AE@% variables with values larger than %@AB@%MAX_LONG%@AE@% using decimal (rather than hexadecimal or octal) constants.%@NL@% %@NL@% ■ Bit fields are permitted in unions.%@NL@% %@NL@% ■ The address-of operator (%@AB@%&%@AE@%) works correctly on arrays and functions.%@NL@% %@NL@% ■ Storage classes or types (or both) are now required on variable declarations. The compiler previously assumed that untyped variables (such as %@AS@% a;%@AE@%) were integers. This declaration now generates a warning.%@NL@% %@NL@% ■ The LOCALE.H header file is new to version 6.0. It declares functions and structures for describing conventions that vary from one country to the next, such as the currency symbol and the way calendar dates are printed.%@NL@% %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-B0004 @%%@AB@%B.1.2 Integer Promotion Rules%@AE@%%@EH@%%@NL@% %@NL@% The ANSI draft standard requires a change in the evaluation of some expressions that mix signed and unsigned integers. Earlier versions of the compiler attempted to preserve an expression's unsigned nature as much as possible. Version 6.0 attempts to preserve the expression's value. %@NL@% %@NL@% In version 5.1, an %@AB@%unsigned char%@AE@% promotes to an %@AB@%unsigned int%@AE@%; an %@AB@%unsigned %@AB@%int%@AE@% promotes to an %@AB@%unsigned long%@AE@%. %@NL@% %@NL@% In version 6.0, an %@AB@%unsigned char%@AE@% promotes to a %@AB@%signed int%@AE@%; an %@AB@%unsigned int%@AE@% promotes to a %@AB@%signed long%@AE@%. %@NL@% %@NL@% For example, %@NL@% %@NL@% %@AS@% main() %@AS@% { %@AS@% long int li = -256L; %@AS@% test( li ); %@AS@% } %@AS@% %@AS@% test( long li) %@AS@% { %@AS@% if( li < 0xffff ) %@AS@% puts( "C 6.0 does a signed compare" ); %@AS@% else puts( "C 5.1 does an unsigned compare" ); %@AS@% }%@AE@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-B0005 @%%@AB@%B.1.3 Defining NULL as a Pointer%@AE@%%@EH@%%@NL@% %@NL@% The constant %@AB@%NULL %@AE@%is now defined as %@AS@% ((void *)0)%@AE@%. Previous versions of Microsoft C defined %@AB@%NULL%@AE@% as 0x0000 in small and medium models and 0x00000000L in compact and large models. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-B0006 @%%@AB@%B.1.4 Shift Operators%@AE@%%@EH@%%@NL@% %@NL@% Shift operators now give a result that is of the same type as the left side. For example, %@NL@% %@NL@% %@AS@% short si; %@AS@% long li; %@AS@% si = 0x0001; %@AS@% li = si << 16L;%@AE@%%@NL@% %@NL@% The compiler previously yielded a result that was the size of the largest of the two values. In the example above, the short value would be automatically cast to a long because 16L is long. The value assigned to %@AS@% li %@AE@% would be 0x00010000L in Microsoft C 5.1. %@NL@% %@NL@% To adhere to the ANSI draft standard, Microsoft C 6.0 maintains the size of the left operand. The variable %@AS@% si %@AE@% has 16 bits. Shifting left 16 times produces a value of 0, which is then assigned to %@AS@% li%@AE@%. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-B0007 @%%@AB@%B.1.5 Pointers to Typedefs%@AE@%%@EH@%%@NL@% %@NL@% The rules for handling pointers to typedefs have changed subtly. For example, C 5.1 interprets %@NL@% %@NL@% %@AS@% typedef int far f_int; %@AS@% f_int *fp_i;%@AE@%%@NL@% %@NL@% as being equivalent to %@NL@% %@NL@% %@AS@% int *far fp_i;%@AE@%%@NL@% %@NL@% which means %@AS@% fp_i %@AE@% is a distant pointer to an integer. The address of %@AS@% fp_i %@AE@% contains 32 bits. The size of the integer's address is indeterminate. %@NL@% %@NL@% C 6.0 interprets it as %@NL@% %@NL@% %@AS@% int far *fp_i;%@AE@%%@NL@% %@NL@% This means %@AS@% fp_i %@AE@% is a far pointer to an integer. The address of the integer contains 32 bits. The size of the address of %@AS@% fp_i %@AE@% is indeterminate. %@AS@% %@AE@%%@NL@% %@NL@% This affects typedefs containing %@AB@%_near%@AE@%, %@AB@%_far%@AE@%, %@AB@%_based%@AE@%, and other modifiers. Although these are Microsoft-specific keywords, their new behavior is consistent with what the ANSI draft standard requires for the %@AB@%const %@AE@%and %@AB@%volatile %@AE@%keywords. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-B0008 @%%@AB@%B.1.6 Identifying Nonstandard Keywords%@AE@%%@EH@%%@NL@% %@NL@% The following modifiers are specific to Microsoft C; they are not described in the ANSI draft standard. To identify these implementation-defined keywords as non-ANSI, an initial underscore has been added.%@CR:C6A-B0009 @% %@NL@% %@NL@% %@AB@%C 5.1 Keyword%@AE@% %@AB@%C 6.0 Keyword%@AE@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@AB@%far%@AE@% %@AB@%_far%@AE@% %@AB@%huge%@AE@% %@AB@%_huge%@AE@% %@AB@%near%@AE@% %@AB@%_near%@AE@% %@AB@%cdecl%@AE@% %@AB@%_cdecl%@AE@% %@AB@%fortran%@AE@% %@AB@%_fortran%@AE@% %@AB@%interrupt%@AE@% %@AB@%_interrupt%@AE@% %@AB@%pascal%@AE@% %@AB@%_pascal%@AE@% The compiler still accepts the obsolescent versions of these keywords, unless the /Za option is used. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-B0010 @%%@AB@%B.1.7 Trigraphs%@AE@%%@EH@%%@NL@% %@NL@% To maintain compatibility with and portability to other systems, Microsoft C 6.0 supports the following trigraphs: %@NL@% %@NL@% %@AB@%Trigraph%@AE@% %@AB@%Character%@AE@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@AB@%??=%@AE@% %@AB@%#%@AE@% %@AB@%??(%@AE@% %@AB@%[%@AE@% %@AB@%??/%@AE@% %@AB@%\%@AE@% %@AB@%??)%@AE@% %@AB@%]%@AE@% %@AB@%??'%@AE@% %@AB@%^%@AE@% %@AB@%??<%@AE@% %@AB@%{%@AE@% %@AB@%??!%@AE@% %@AB@%|%@AE@% %@AB@%??>%@AE@% %@AB@%}%@AE@% %@AB@%??-%@AE@% %@AB@%~%@AE@% %@NL@% %@3@%%@CR:C6A-B0011 @%%@AB@%B.1.8 ANSI Nonconformance%@AE@%%@EH@%%@NL@% %@NL@% This section lists the areas where Microsoft C 6.0 does not conform to the ANSI draft standard. %@NL@% %@NL@% %@NL@% ■ Microsoft C does not support multibyte characters, wide-character and string constants, and the related library functions and types.%@NL@% %@NL@% ■ Microsoft C contains some name-space violations in the language (extended keywords, such as %@AB@%near%@AE@% and %@AB@%far%@AE@%) and in the library (non-ANSI macros and types in header files and extended library function names, such as %@AB@%read %@AE@%and %@AB@%write%@AE@%).%@NL@% %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A-B0012 @%%@AB@%B.2 New Keywords and Functions%@AE@%%@EH@%%@NL@% %@NL@% This section describes keywords and functions that did not exist in previous versions of Microsoft C. Details about how to use these features can be found elsewhere in the documentation. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-B0013 @%%@AB@%B.2.1 In-Line Assembler%@AE@%%@EH@%%@NL@% %@NL@% The new %@AB@%_asm%@AE@% keyword allows you to mix assembly instructions with C source code. This feature includes the %@AB@%_emit%@AE@% function, which lets you enter arbitrary values into the code stream. %@NL@% %@NL@% See Chapter 3, "Using the In-Line Assembler." %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-B0014 @%%@AB@%B.2.2 Based Pointers and Objects%@AE@%%@EH@%%@NL@% %@NL@% A based pointer is a special, compact form of pointer. It is always represented as a short offset. The address represented by such a pointer is calculated by adding the based pointer to its base. The base must be supplied each time the pointer is dereferenced, either explicitly using a special operator or implicitly by associating the base value with the pointer when it is declared. The base can be a far pointer, a near pointer, or a new type that represents a segment. %@NL@% %@NL@% Based pointers and objects are declared using the new keyword, %@AB@%_based%@AE@%. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Segment Types%@AE@%%@EH@%%@NL@% %@NL@% The new type specifier, %@AB@%_segment%@AE@%, specifies a segment. %@NL@% %@NL@% Any pointer or address can be cast to %@AB@%_segment%@AE@%. If the operand is a near pointer, the result is the current value of the data segment register (DS). If the operand is a far pointer, the result is the segment part of the far pointer. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Segment Names%@AE@%%@EH@%%@NL@% %@NL@% Segment names are declared using the built-in function %@AB@%_segname%@AE@%. The compiler recognizes four predefined segment names: %@AB@%_CODE%@AE@%, %@AB@%_CONST%@AE@%, %@AB@%_DATA%@AE@%, and %@AB@%_STACK%@AE@%. %@NL@% %@NL@% Each segment name represents a constant of type %@AB@%_segment%@AE@%. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Base Operator%@AE@%%@EH@%%@NL@% %@NL@% The base operator%@AB@% %@AE@%(%@AB@%:>%@AE@%) associates a base expression (usually a segment) with a based pointer, to form a far pointer value. For example, %@NL@% %@NL@% %@AS@% 0x0F01:>0x0015%@AE@%%@NL@% %@NL@% combines the segment 0x0F01 with the offset 0x0015 to form the effective address 0x0F025. The base operator's precedence falls between ( ) and [ ]. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Casting Based Pointers%@AE@%%@EH@%%@NL@% %@NL@% A based pointer can be cast to a pointer, a long integer, a short integer, or another based pointer. When a based pointer is converted to a far pointer, a long integer, a near pointer, or another based pointer having a different base expression, it is first normalized to a far pointer (including adding the offset in the base, if present, to the based pointer); then any additional conversions are applied. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Operations on Based Pointers%@AE@%%@EH@%%@NL@% %@NL@% Based pointers, for the purpose of arithmetic and dereferencing, are treated as semantically equivalent to far pointers. When a based pointer mixes with another integral type (%@AB@%int%@AE@%, %@AB@%long%@AE@%, near pointer, far pointer, or based pointer), implicit casting is done. In some cases, the compiler can optimize these references and treat the pointer as an offset. %@NL@% %@NL@% The value of 0 is treated specially, as it is for near and far pointers. No conversions are applied to the constant 0 because it is assumed to be a null pointer. %@NL@% %@NL@% See Chapter 2, "Managing Memory." %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-B0015 @%%@AB@%B.2.3 Based Heap Allocation Support%@AE@%%@EH@%%@NL@% %@NL@% The functions listed below provide support for allocating, expanding, and freeing memory for based heaps, which dynamically allocate memory for based items. The functions are prototyped in the MALLOC.H include file. %@NL@% %@NL@% %@TH: 6 421 01 11 12 53 @%%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%_bcalloc%@AE@% %@AB@%_bheapchk%@AE@% %@AB@%_bmalloc%@AE@%%@AB@%_bexpand%@AE@% %@AB@%_bheapmin%@AE@% %@AB@%_bmsize%@AE@%%@AB@%_bfree%@AE@% %@AB@%_bheapseg%@AE@% %@AB@%_brealloc%@AE@%%@AB@%_bfreeseg%@AE@% %@AB@%_bheapset%@AE@%%@AB@%_bheapadd%@AE@% %@AB@%_bheapwalk%@AE@%%@TE: 6 421 01 11 12 53 @% See Chapter 2, "Managing Memory." %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-B0016 @%%@AB@%B.2.4 Releasing Unused Heap Memory%@AE@%%@EH@%%@NL@% %@NL@% The following routines release unused heap memory by shortening data segments. MALLOC.H contains the function prototypes. %@NL@% %@NL@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@AB@%_fheapmin%@AE@% %@AB@%_heapmin%@AE@% %@AB@%_nheapmin%@AE@% %@NL@% %@3@%%@CR:C6A-B0017 @%%@AB@%B.2.5 Making Static Data Available to the Heap%@AE@%%@EH@%%@NL@% %@NL@% The %@AB@%_heapadd%@AE@% function is new. It allows the user to make unused static data available to the heap. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-B0018 @%%@AB@%B.2.6 Long Doubles%@AE@%%@EH@%%@NL@% %@NL@% Microsoft C version 5.1 treated %@AB@%double%@AE@% and %@AB@%long double%@AE@% as syntactically different types that were semantically equal. Both types were stored in memory as 64-bit quantities. For purposes of type-checking, %@AB@%long double%@AE@% and %@AB@%double%@AE@% have always been different types. %@NL@% %@NL@% Because the 80%@AI@%x%@AE@%87 family of math coprocessors supports an 80-bit floating-point type, Microsoft C version 6.0 stores %@AB@%long double%@AE@% variables in the 80%@AI@%x%@AE@%87 10-byte (80-bit) form. %@NL@% %@NL@% Certain functions have been modified to handle the %@AB@%long double%@AE@% type. The %@AB@%printf%@AE@% and %@AB@%scanf%@AE@% family of functions supports %@AB@%long double%@AE@% values with the trailing %@AB@%l%@AE@%. The library contains new versions of the transcendental functions as well as intrinsic forms that accept %@AB@%long double%@AE@% arguments. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-B0019 @%%@AB@%B.2.7 Long Double Functions%@AE@%%@EH@%%@NL@% %@NL@% All the functions below are defined in the standard include file MATH.H. They return %@AB@%long double%@AE@% values and results and error codes analogous to the double versions. %@NL@% %@NL@% %@TH: 10 630 01 08 08 60 @%%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%acosl%@AE@% %@AB@%expl%@AE@% %@AB@%_matherrl%@AE@%%@AB@%asinl%@AE@% %@AB@%fabsl%@AE@% %@AB@%modfl%@AE@%%@AB@%atanl%@AE@% %@AB@%floorl%@AE@% %@AB@%powl%@AE@%%@AB@%atan2l%@AE@% %@AB@%fmodl%@AE@% %@AB@%sinl%@AE@%%@AB@%_atold%@AE@% %@AB@%frexpl%@AE@% %@AB@%sinhl%@AE@%%@AB@%cabsl%@AE@% %@AB@%hypotl%@AE@% %@AB@%sqrtl%@AE@%%@AB@%ceill%@AE@% %@AB@%ldexpl%@AE@% %@AB@%tanl%@AE@%%@AB@%cosl%@AE@% %@AB@%logl%@AE@% %@AB@%tanhl%@AE@%%@AB@%coshl%@AE@% %@AB@%log10l%@AE@%%@TE: 10 630 01 08 08 60 @% %@NL@% %@3@%%@CR:C6A-B0020 @%%@AB@%B.2.8 Model-Independent String and Memory Functions%@AE@%%@EH@%%@NL@% %@NL@% The following functions make it easier to write mixed-model programs by providing model-independent (large model) forms for most of the standard string and memory functions. These functions can be called from any point in any program, no matter which memory model has been selected. These functions take only far pointers as arguments. Thus, any data item, near or far, in any combination, can be handled. %@NL@% %@NL@% The names of these functions are the same as the model-dependent forms, except they include an %@AB@%_f %@AE@%prefix. For example, %@AB@%_fstrlen %@AE@%is the model-independent version of the %@AB@%strlen %@AE@%function. %@NL@% %@NL@% The functions listed below are defined in the standard include file STRING.H. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Memory Functions%@AE@%%@EH@%%@NL@% %@NL@% %@TH: 5 340 01 29 47 @%%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%_fmemccpy %@AE@% %@AB@%_fmemcpy%@AE@%%@AB@%_fmemchr%@AE@% %@AB@%_fmemmove%@AE@%%@AB@%_fmemcmp%@AE@% _fmemset%@AB@%_fmemicmp%@AE@% %@TE: 5 340 01 29 47 @% %@NL@% %@4@%%@AB@%String Functions%@AE@%%@EH@%%@NL@% %@NL@% %@TH: 8 520 01 11 12 53 @%%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%_fstrcat%@AE@% _fstrlwr %@AB@%_fstrrchr%@AE@%%@AB@%_fstrchr%@AE@% %@AB@%_fstrncat%@AE@% _fstrrev%@AB@%_fstrcmp%@AE@% _fstrncmp %@AB@%_fstrset%@AE@%%@AB@%_fstricmp%@AE@% _fstrnicmp %@AB@%_fstrspn%@AE@%%@AB@%_fstrcpy%@AE@% _fstrncpy %@AB@%_fstrstr%@AE@%%@AB@%_fstrcspn%@AE@% %@AB@%_fstrnset%@AE@% _fstrtok%@AB@%_fstrlen%@AE@% _fstrpbrk %@AB@%_fstrupr %@AE@%%@TE: 8 520 01 11 12 53 @% %@NL@% %@4@%%@AB@%String Duplication Functions%@AE@%%@EH@%%@NL@% %@NL@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@AB@%_fstrdup%@AE@% %@AB@%_nstrdup%@AE@% %@NL@% %@3@%%@CR:C6A-B0021 @%%@AB@%B.2.9 Mixed-Model Memory Allocation Support%@AE@%%@EH@%%@NL@% %@NL@% The following functions are based on %@AB@%realloc%@AE@%, %@AB@%calloc%@AE@%, and %@AB@%expand%@AE@%, but they affect only near memory or far memory. MALLOC.H contains the function prototypes. %@NL@% %@NL@% %@TH: 4 271 01 28 48 @%%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%_fcalloc%@AE@% _ncalloc%@AB@%_fexpand%@AE@% _nexpand%@AB@%_frealloc%@AE@% _nrealloc%@TE: 4 271 01 28 48 @% %@NL@% %@3@%%@CR:C6A-B0022 @%%@AB@%B.2.10 The _fastcall Attribute (/Gr Option)%@AE@%%@EH@%%@NL@% %@NL@% Individual function prototypes can be declared with the new attribute %@AB@%_fastcall%@AE@%. %@NL@% %@NL@% The /Gr option enables the fastcall function-calling convention for all functions that are not explicitly prototyped with the %@AB@%_cdecl%@AE@%, %@AB@%_pascal%@AE@%, or %@AB@%_fortran %@AE@%attributes. Using /Gr on the command line causes each function in the module to compile as %@AB@%_fastcall%@AE@% unless the function is declared with a conflicting attribute, or the name of the function is %@AB@%main%@AE@%. %@NL@% %@NL@% When you use the /Gr option, all functions are assumed to use the %@AB@%_fastcall %@AB@%%@AE@%convention. As a result, to use any run-time library functions, you must either include the standard include files or explicitly prototype the function you want to call. %@NL@% %@NL@% A fastcall function receives up to three 16-bit arguments, passed in registers rather than on the stack. Arguments are passed in the AX, BX, and DX registers. This may change in future versions of the compiler. %@NL@% %@NL@% The argument types and their potential register assignments are %@NL@% %@NL@% %@AB@%Argument%@AE@% %@AB@%Registers%@AE@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% character (3) AL, DL, BL short integer (3) AX, DX, BX near pointer (3) BX, AX, DX long integer (1) DX:AX far pointer (1) ES:BX If the registers for a particular class have already been used, or if an argument is not one of the five types listed above, it is pushed on the stack as usual. An argument list of types %@AB@%long%@AE@%, %@AB@%float%@AE@%, %@AB@%short %@AE@%would pass the %@AB@%long %@AE@%in DX:AX, push the %@AB@%float%@AE@%, and pass the %@AB@%short %@AE@%in BX. %@NL@% %@NL@% The treatment of character arguments depends further on prototypes. If there is no prototype, the argument is promoted to %@AB@%short %@AE@%and the rules for short integers apply. Only if the argument is prototyped as a %@AB@%char %@AE@%do the character rules apply. %@NL@% %@NL@% The %@AB@%_fastcall %@AE@%convention is not compatible with any of the following attributes: %@AB@%_interrupt%@AE@%, %@AB@%_saveregs%@AE@%, %@AB@%_export%@AE@%, %@AB@%_cdecl%@AE@%, %@AB@%_fortran%@AE@%, or %@AB@%_pascal%@AE@%. %@NL@% %@NL@% See Chapter 1, "Optimizing C Programs." %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-B0023 @%%@AB@%B.2.11 Drive and Directory Functions%@AE@%%@EH@%%@NL@% %@NL@% Several new functions make it easier to get and set the current drive and the current directory. The prototypes for the following routines are in DIRECT.H:%@CR:C6A-B0024 @% %@NL@% %@NL@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@AB@%_chdrive%@AE@% %@AB@%_fullpath%@AE@% %@AB@%_getdrive%@AE@% %@AB@%_getdcwd%@AE@% %@NL@% %@3@%%@CR:C6A-B0025 @%%@AB@%B.2.12 Text Output Functions for OS/2%@AE@%%@EH@%%@NL@% %@NL@% Several text-mode screen functions have been added to Microsoft C 6.0 for OS/2. With the exception of the new %@AB@%_scrolltextwindow %@AE@%function, they are identical to what is defined in real mode, except for any references to behavior in graphics modes. The following routines are located in GRTEXT.LIB, and the prototypes are in GRAPH.H: %@NL@% %@NL@% %@TH: 7 561 01 18 18 40 @%%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%_clearscreen%@AE@% _getvideoconfig %@AB@%_settextrows%@AE@%%@AB@%_displaycursor%@AE@% _outtext %@AB@%_settextwindow%@AE@%%@AB@%_getbkcolor%@AE@% _setbkcolor %@AB@%_setvideomode%@AE@%%@AB@%_gettextcolor%@AE@% _settextcolor %@AB@%_setvideomoderows%@AE@%%@AB@%_gettextcursor%@AE@% _settextcursor _scrolltextwindow%@AB@%_gettextposition%@AE@% _settextposition %@AB@%_wrapon %@AE@%%@TE: 7 561 01 18 18 40 @% See Part 4 of this manual, "OS/2 Support." %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A-B0026 @%%@AB@%B.3 New Features%@AE@%%@EH@%%@NL@% %@NL@% The features described in Sections B.3.1-B.3.10 are new to version 6.0. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-B0027 @%%@AB@%B.3.1 Strings and Macros%@AE@%%@EH@%%@NL@% %@NL@% The compiler now allows longer string literals (up to 4K) and longer macro expansions (up to 6K). %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-B0028 @%%@AB@%B.3.2 CL Options%@AE@%%@EH@%%@NL@% %@NL@% The following options are new to Microsoft C 6.0:%@CR:C6A-B0029 @% %@NL@% %@NL@% %@AB@%Option%@AE@% %@AB@%Action%@AE@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% /AT Compiles in tiny model (.COM files). /Fr« %@AI@%filename%@AE@%» Outputs source browser information file. /FR«%@AI@% filename%@AE@%» Outputs extended source browser information file. /Gd Forces %@AB@%_cdecl %@AE@%calling conventions. /Gr Enables register (%@AB@%_fastcall%@AE@%) function-calling conventions. /MA%@AI@%masmoption%@AE@% Supports invocation of the assembler using the CL driver. All MASM-supported options are accepted. In addition, the compiler recognizes file names with .ASM suffixes and passes them directly to MASM. /MD- Uses C run-time as DLL option. Defaults to /ALw /FPi /G2 /DDLL /DMT and inhibits library search records. /ML Links C run-time as part of a dynamic-link library (DLL). Defaults to /ALw /FPa /G2 /DMT and changes library search record to LLIBCDLL.LIB. /MT Enables multithread option. Defaults to /ALw /FPi /G2 /DMT and changes library search record to LLIBCMT.LIB. /Oe Enables global register allocation. /Og Enables global optimizations and global common subexpressions (CSEs). /Ox Is now equivalent to /Ocegilt /Gs. Note that this implies that maximum optimization includes the %@AB@%_fastcall%@AE@% function-calling convention. /Oz Enables aggressive optimizations. /Ta %@AI@%name%@AE@% Specifies that%@AI@% name %@AE@%is to be treated as an assembler input file. /W4 Turns on extra warning level which supports more detailed (LINT-like) warnings and recognition of ANSI violations. /WX Causes warnings to be treated as errors. If a warning occurs, the .OBJ file is not created. %@NL@% %@3@%%@CR:C6A-B0030 @%%@AB@%B.3.3 Tiny Memory Model (.COM Files)%@AE@%%@EH@%%@NL@% %@NL@% Microsoft C 6.0 now supports the tiny memory model, which produces .COM rather than .EXE files (for DOS only). %@NL@% %@NL@% The /AT option selects the tiny model. This forces the linker to use options /NOE and /TINY. Within the linker, /TINY turns on /FARCALLTRANSLATION to help eliminate far segment relocations. If you link your own .OBJ files, link with CRTCOM.OBJ. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-B0031 @%%@AB@%B.3.4 The Optimize Pragma%@AE@%%@EH@%%@NL@% %@NL@% The %@AB@%optimize %@AE@%pragma turns optimizing options on or off: %@NL@% %@NL@% %@AS@% #pragma optimize("<optimization switch list>",{off|on})%@AE@%%@NL@% %@NL@% where %@AI@%<optimization switch list>%@AE@% can be an empty list or one or more of the following: a, c, e, g, l, w, n, p, t, and z. For example, %@NL@% %@NL@% %@AS@% #pragma optimize("lp",on) /* equivalent to /Olp */ %@AS@% #pragma optimize("",off) /* turns off all optimization */ %@AS@% #pragma optimize("",on) /* restores default settings */%@AE@%%@NL@% %@NL@% See Chapter 1, "Optimizing C Programs." %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-B0032 @%%@AB@%B.3.5 Nameless Structures and Unions%@AE@%%@EH@%%@NL@% %@NL@% Both %@AB@%struct %@AE@%and %@AB@%union %@AE@%declarations can now be specified without a declarator when they are members of another structure or union. %@NL@% %@NL@% A nameless union would look like this: %@NL@% %@NL@% %@AS@% struct str %@AS@% { %@AS@% int a,b; %@AS@% union /* unnamed union */ %@AS@% { %@AS@% char c[4]; %@AS@% long l; %@AS@% float f; %@AS@% }; %@AS@% char c_array[10]; %@AS@% } my_str; %@AS@% . %@AS@% . %@AS@% . %@AS@% my_str.l == 0L;%@AE@%%@NL@% %@NL@% A nameless structure would look like this: %@NL@% %@NL@% %@AS@% struct s1 %@AS@% { %@AS@% int a,b,c; %@AS@% }; %@AS@% %@AS@% struct s2 %@AS@% { %@AS@% float y; %@AS@% struct s1; %@AS@% char str[10]; %@AS@% } *p_s2; %@AS@% . %@AS@% . %@AS@% . %@AS@% %@AS@% p_s2->b = 100;%@AE@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-B0033 @%%@AB@%B.3.6 Unsized Arrays as the Last Member of a Structure%@AE@%%@EH@%%@NL@% %@NL@% The compiler now allows an unsized or zero-sized array as the last member of a structure. The declaration of such a structure would look like this: %@NL@% %@NL@% %@AS@% struct var_length %@AS@% { %@AS@% <set of declarations>; %@AS@% <type> array[]; %@AS@% };%@AE@%%@NL@% %@NL@% Unsized arrays can appear only as the last member of a structure. Structures containing unsized array declarations can be nested within other structures as long as no further members are declared in any enclosing structures. Arrays of such structures are not allowed. %@NL@% %@NL@% The %@AB@%sizeof %@AE@%operator, when applied to a variable of this type or to the type itself, assumes 0 for the size of the array. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-B0034 @%%@AB@%B.3.7 Improved Warnings%@AE@%%@EH@%%@NL@% %@NL@% A new warning level four (CL option /W4) has been added for the following warnings: %@NL@% %@NL@% %@NL@% ■ Detection of unused global variables%@NL@% %@NL@% ■ Expressions without side effects%@NL@% %@NL@% ■ Nonportable (non-ANSI) constructs%@NL@% %@NL@% ■ Local variable referenced before being initialized%@NL@% %@NL@% ■ Undefined or implementation-defined constructs%@NL@% %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-B0035 @%%@AB@%B.3.8 Macros%@AE@%%@EH@%%@NL@% %@NL@% The number of macros definable with /D options has increased from 20 to 30. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-B0036 @%%@AB@%B.3.9 Improved Multithread Support in OS/2%@AE@%%@EH@%%@NL@% %@NL@% The number of OS/2 threads supported at run time has increased from 32 to the operating system limit. Three new options aid development of multithread applications and dynamic-link libraries: %@NL@% %@NL@% %@NL@% 1. /MT for building multithread programs. It implies /ALw /FPi /G2 /D MT, and changes the library search record emitted in the object file to reference LLIBCMT.%@NL@% %@NL@% 2. /ML for building a DLL that uses the C run-time library. It implies /ALw /FPa /G2 /D MT, and changes the library search record emitted in the object file to reference LLIBCDLL.%@NL@% %@NL@% 3. /MD for building .EXE files and DLLs that share a C run-time DLL. It implies /ALw /FPi /G2 /DDLL /D MT, and no library search records are emitted in the object file.%@NL@% %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-B0037 @%%@AB@%B.3.10 Pipe Support in OS/2%@AE@%%@EH@%%@NL@% %@NL@% Microsoft C 6.0 supports pipes as part of the file I/O system. The functions listed below are defined in the standard include file IO.H: %@NL@% %@NL@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@AB@%_pipe%@AE@% %@AB@%_popen%@AE@% %@AB@%_pclose%@AE@% %@NL@% %@2@%%@CR:C6A-B0038 @%%@AB@%B.4 Differences in Code Generation%@AE@%%@EH@%%@NL@% %@NL@% This section lists ways in which the executable files produced by Microsoft C 6.0 may differ from the files produced by previous versions of the compiler. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-B0039 @%%@AB@%B.4.1 Speed and Space Improvements%@AE@%%@EH@%%@NL@% %@NL@% Executable files are smaller and faster. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-B0040 @%%@AB@%B.4.2 Code Quality%@AE@%%@EH@%%@NL@% %@NL@% Microsoft C 6.0 generates improved local code in default optimization cases and, under full optimization, supports global (function level) register allocation and common subexpressions (CSEs), loop optimizations, parameter passing through registers, and generation of in-line code for certain intrinsic functions. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-B0041 @%%@AB@%B.4.3 Floating-Point Code Generation%@AE@%%@EH@%%@NL@% %@NL@% In Microsoft C 6.0, the /FPi87 option suppresses the fixups previously used for emulation. Pure coprocessor instructions are now emitted. This makes object files smaller and speeds up linking, in addition to making in-line assembly easier to use. %@NL@% %@NL@% In version 5.1, /FPi and /FPi87 generated the same code; the only difference was the library. In C 6.0, the two options generate different code. It is no longer possible to force /FPi87 to act like /FPi. If you use /FPi87, the math coprocessor must be in the computer on which the program is running. %@NL@% %@NL@% Note that if you use /FPi87 you must link with mLIB7, not mLIBCE. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-B0042 @%%@AB@%B.4.4 Intrinsic Functions%@AE@%%@EH@%%@NL@% %@NL@% The intrinsic function optimization option (/Oi) causes the compiler to generate in-line code for the following functions: %@NL@% %@NL@% %@TH: 8 467 01 10 08 58 @%%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%abs%@AE@% _lrotl %@AB@%_rotl%@AE@%%@AB@%_disable%@AE@% _lrotr %@AB@%_rotr%@AE@%%@AB@%_enable%@AE@% memcmp %@AB@%strcat%@AE@%%@AB@%ffabs%@AE@% memcpy %@AB@%strcmp%@AE@%%@AB@%inp%@AE@% memset %@AB@%strcpy%@AE@%%@AB@%inpw%@AE@% outp %@AB@%strlen%@AE@%%@AB@%labs%@AE@% outpw %@AB@%strset%@AE@%%@TE: 8 467 01 10 08 58 @% The compiler does not generate in-line code for the following functions, although it will modify the calling convention to pass the arguments on the floating-point chip: %@NL@% %@NL@% %@TH: 13 759 01 07 08 61 @%%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%acos%@AE@% %@AB@%pow%@AE@% %@AB@%coshl%@AE@%%@AB@%asin%@AE@% %@AB@%sin%@AE@% %@AB@%expl%@AE@%%@AB@%atan%@AE@% %@AB@%sinh%@AE@% %@AB@%floorl%@AE@%%@AB@%atan2%@AE@% %@AB@%sqrt%@AE@% %@AB@%fmodl%@AE@%%@AB@%ceil%@AE@% %@AB@%tan%@AE@% logl%@AB@%cos%@AE@% %@AB@%tanh%@AE@% %@AB@%log10l%@AE@%%@AB@%cosh%@AE@% %@AB@%acosl%@AE@% %@AB@%powl%@AE@%%@AB@%exp%@AE@% %@AB@%asinl%@AE@% sinl%@AB@%floor%@AE@% %@AB@%atanl%@AE@% %@AB@%sinhl%@AE@%%@AB@%fmod%@AE@% atan2l %@AB@%sqrtl%@AE@%%@AB@%log%@AE@% %@AB@%ceill%@AE@% %@AB@%tanl%@AE@%%@AB@%log10%@AE@% cosl %@AB@%tanhl%@AE@%%@TE: 13 759 01 07 08 61 @% %@NL@% %@2@%%@CR:C6A-B0043 @%%@AB@%B.5 Changes and Deletions%@AE@%%@EH@%%@NL@% %@NL@% The changes and deletions listed in this section have a high probability of affecting existing programs. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-B0044 @%%@AB@%B.5.1 Deleted Features%@AE@%%@EH@%%@NL@% %@NL@% The %@AB@%data_seg%@AE@% pragma has been deleted. %@NL@% %@NL@% The memory management routine %@AB@%sbrk%@AE@% has been deleted. %@NL@% %@NL@% The compiler and tools do not run under DOS 2.1. The run-time files produced by the compiler and linker will continue to run under DOS 2.1. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-B0045 @%%@AB@%B.5.2 Evaluation of Real Expressions%@AE@%%@EH@%%@NL@% %@NL@% Real expressions inside parentheses are now evaluated according to the semantics of the parentheses. For example, in the expression %@NL@% %@NL@% %@AS@% ((r1 / r2) * r3)%@AE@%%@NL@% %@NL@% the division is performed before the multiplication. Previous versions of the compiler might have reordered the operations. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-B0046 @%%@AB@%B.5.3 Default Optimizations%@AE@%%@EH@%%@NL@% %@NL@% Version 6.0 performs more extensive optimizations than version 5.1. This implies that code that had aliasing but worked with the /Oa option in 5.1 might not work with version 6.0 and /Oa. Also, because of the improved optimizations, the /Od option should be used to turn off all optimizing before you begin debugging with CodeView. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-B0047 @%%@AB@%B.5.4 Sign Extension of char Arguments%@AE@%%@EH@%%@NL@% %@NL@% Previous versions of Microsoft C would sign-extend %@AB@%char %@AE@%arguments to %@AB@%int %@AB@%%@AE@%size before passing them to a second function. Version 6.0 does not extend the sign if the function is prototyped and the prototype includes a %@AB@%char%@AE@% argument. The most-significant byte is considered undefined. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-B0048 @%%@AB@%B.5.5 Conditional Compilation and Signed Values%@AE@%%@EH@%%@NL@% %@NL@% Version 5.1 of Microsoft C treated conditional compilation expressions as %@AB@%signed long%@AE@% values. Version 6.0 evaluates these expressions using the same rules as expressions in C. For example, %@NL@% %@NL@% %@AS@% #if 0xFFFFFFFFL > 1UL %@AS@% . %@AS@% . %@AS@% . %@AS@% #endif%@AE@%%@NL@% %@NL@% The expression evaluates to be true. It was evaluated as false in version 5.1. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-B0049 @%%@AB@%B.5.6 The const and volatile Qualifiers%@AE@%%@EH@%%@NL@% %@NL@% The %@AB@%const %@AE@% and %@AB@%volatile %@AE@%qualifiers must be placed after the type they qualify. The declaration %@NL@% %@NL@% %@AS@% int (const *p);%@AE@%%@NL@% %@NL@% is now treated as a syntax error. Previous versions of the compiler would accept such a construction. %@NL@% %@NL@% The following declarations are legal: %@NL@% %@NL@% %@AS@% int const *p_ci; /* pointer to constant int */ %@AS@% int const (*p_ci); /* pointer to constant int */ %@AS@% int *const cp_i; /* constant pointer to int */ %@AS@% int (*const cp_i); /* constant pointer to int */%@AE@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-B0050 @%%@AB@%B.5.7 Memory Allocation%@AE@%%@EH@%%@NL@% %@NL@% The %@AB@%_fmalloc %@AE@%function attempts to allocate far memory. It previously called %@AB@%_nmalloc %@AE@%if far memory was not available. Now it returns a null pointer if far memory isn't available, even if near memory is available. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-B0051 @%%@AB@%B.5.8 Memory Used by Command-Line Arguments%@AE@%%@EH@%%@NL@% %@NL@% Previous versions of the compiler placed the command-line argument strings and environment strings in the near heap. Now they are allocated though %@AB@%malloc%@AE@%, which means that they will be in far memory in compact and large models. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-B0052 @%%@AB@%B.5.9 Format Specifiers in printf%@AE@%%@EH@%%@NL@% %@NL@% The %@AB@%printf%@AE@% format specifier modifiers %@AB@%N%@AE@%, %@AB@%F%@AE@%, %@AB@%h%@AE@%, and%@AB@% l%@AE@% have changed. %@NL@% %@NL@% The specifier %@AB@%%Np%@AE@% is a synonym for %@AB@%%hp%@AE@%, but the latter is preferred. Likewise, %@AB@%%Fp%@AE@% is a synonym for %@AB@%%lp%@AE@%. %@NL@% %@NL@% For %@AB@%scanf%@AE@%, %@AB@%N%@AE@% and %@AB@%F%@AE@% refer to the distance to the object being read in; that is, whether the pointer itself is allocated near or far. The modifiers %@AB@%h%@AE@% and%@AB@% %@AB@%l%@AE@% refer to the size of the object (16-bit near pointer or 32-bit far pointer). In these examples, %@NL@% %@NL@% %@AS@% scanf("%Nlp", n_fp); %@AS@% scanf("%Fhp", f_np);%@AE@%%@NL@% %@NL@% the first line reads in an address that resides in near memory (%@AS@%N%@AE@%) but holds a 32-bit far pointer variable (%@AS@%lp%@AE@%). The second line reads in a near pointer value (%@AS@%hp%@AE@%) into a pointer variable that resides in far memory (%@AS@%F%@AE@%). %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-B0053 @%%@AB@%B.5.10 Functions that Return Float Values%@AE@%%@EH@%%@NL@% %@NL@% In Microsoft C 5.1, a prototype or definition such as %@NL@% %@NL@% %@AS@% float funcname();%@AE@%%@NL@% %@NL@% was interpreted as %@AS@% %@AE@%%@NL@% %@NL@% %@AS@% double funcname()%@AE@%%@NL@% %@NL@% Version 6.0 interprets it as %@AS@% %@AE@%%@NL@% %@NL@% %@AS@% float %@AE@%%@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@CR:C6A-C0001 @%%@1@%%@AB@%Appendix C Implementation-Defined Behavior%@AE@%%@EH@%%@NL@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@NL@% The American National Standards Institute (ANSI) Standard for the C programming language contains an appendix called "Portability Issues." The ANSI appendix lists areas of the C language that ANSI leaves open to each particular implementation. This appendix describes how Microsoft C handles these implementation-defined areas of the C language. %@NL@% %@NL@% This appendix follows the same order as the ANSI Standard appendix. Each item covered includes references to the ANSI chapter and section that explains the implementation-defined behavior. %@NL@% %@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% NOTE %@AI@%This appendix describes the U.S. English-language version of the C compiler %@AI@%only. Foreign-language implementations of Microsoft C may differ slightly.%@AE@%%@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@%%@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A-C0002 @%%@AB@%C.1 Translation%@AE@%%@EH@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-C0003 @%%@AB@%C.1.1 Diagnostics%@AE@%%@EH@%%@NL@% %@NL@% %@AB@%How a diagnostic is identified (2.1.1.3)%@AE@% %@NL@% %@NL@% Microsoft C produces error messages in the form: %@NL@% %@NL@% %@AS@% filename(line-number) : diagnostic Cnumber message%@AE@%%@NL@% %@NL@% where %@AI@%filename%@AE@% is the name of the source file in which the error was encountered; %@AI@%line-number%@AE@% is the line number at which the compiler detected the error; %@AI@%diagnostic%@AE@% is either "error" or "warning"; %@AI@%number%@AE@% is a unique four-digit number (preceded by a %@AB@%C%@AE@%) that identifies the error or warning; %@AI@%message%@AE@% is an explanatory message. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A-C0004 @%%@AB@%C.2 Environment%@AE@%%@EH@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-C0005 @%%@AB@%C.2.1 Arguments to main%@AE@%%@EH@%%@NL@% %@NL@% %@AB@%The semantics of the arguments to main (2.1.2.2)%@AE@% %@NL@% %@NL@% In Microsoft C, the function called at program start-up is called %@AB@%main%@AE@%. There is no prototype declared for %@AB@%main%@AE@%, and it can be defined with zero, two, or three parameters: %@NL@% %@NL@% %@AS@% int main( void ) %@AS@% int main( int argc, char *argv[] ) %@AS@% int main( int argc, char *argv[], char *envp[] )%@AE@%%@NL@% %@NL@% The third line above, where %@AB@%main %@AE@%accepts three parameters, is a Microsoft extension to the ANSI Standard. The third parameter, %@AB@%envp%@AE@%, is an array of pointers to environment variables. The %@AB@%envp %@AE@%array is terminated by a null pointer. See on-line help for more information about %@AB@%main %@AE@%and %@AB@%envp%@AE@%. %@NL@% %@NL@% The variable %@AB@%argc%@AE@% never holds a negative value. %@NL@% %@NL@% The array of strings ends with %@AB@%argv[argc]%@AE@%, which contains a null pointer. %@NL@% %@NL@% All elements of the %@AB@%argv %@AE@%array are pointers to strings. %@NL@% %@NL@% A program invoked with no command-line arguments will receive a value of one for %@AB@%argc%@AE@%, as the name of the executable file is placed in %@AB@%argv[0]%@AE@%. (In DOS versions prior to 3.0, the executable file name is not available. The letter "C" is placed in %@AB@%argv[0]%@AE@%.) Strings pointed to by %@AB@%argv[1] %@AE@%through %@AB@%argv[argc - %@AB@%1] %@AE@%represent program parameters. %@NL@% %@NL@% The parameters %@AB@%argc %@AE@%and %@AB@%argv %@AE@%are modifiable and retain their last-stored values between program start-up and program termination. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-C0006 @%%@AB@%C.2.2 Interactive Devices%@AE@%%@EH@%%@NL@% %@NL@% %@AB@%What constitutes an interactive device (2.1.2.3)%@AE@% %@NL@% %@NL@% Microsoft C defines the keyboard and the display as interactive devices. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A-C0007 @%%@AB@%C.3 Identifiers%@AE@%%@EH@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-C0008 @%%@AB@%C.3.1 Significant Characters without External Linkage%@AE@%%@EH@%%@NL@% %@NL@% %@AB@%The number of significant characters without external linkage (3.1.2)%@AE@% %@NL@% %@NL@% Identifiers are significant to 31 characters. The compiler does not restrict the number of characters you can use in an identifier; it simply ignores any characters beyond the limit. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-C0009 @%%@AB@%C.3.2 Significant Characters with External Linkage%@AE@%%@EH@%%@NL@% %@NL@% %@AB@%The number of significant characters with external linkage (3.1.2)%@AE@% %@NL@% %@NL@% Identifiers declared %@AB@%extern %@AE@%in programs compiled with Microsoft C are significant to 31 characters. You can modify this default to a smaller number using the /H (restrict length of external names) option. See on-line help for more information on the syntax of the /H option. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-C0010 @%%@AB@%C.3.3 Upper- and Lowercase%@AE@%%@EH@%%@NL@% %@NL@% %@AB@%Whether case distinctions are significant (3.1.2)%@AE@% %@NL@% %@NL@% Microsoft C treats identifiers within a compilation unit as case sensitive. Externally linked identifiers may or may not be case sensitive, depending on whether you use /NOIGNORECASE option when you invoke the linker. The default for the linker is to ignore case, making externally linked identifiers case insensitive. %@NL@% %@NL@% Thus, symbols in source files are sensitive to case. By default, symbols in object files are not. %@NL@% %@NL@% Two CL command-line options affect case sensitivity: %@NL@% %@NL@% %@NL@% 1. The /Gc (generate Pascal-style function calls) command-line option converts all external identifiers (including function names) to uppercase.%@NL@% %@NL@% %@STUB@% The %@AB@%_pascal%@AE@% declarator performs the same operation on a function-byfunction basis.%@NL@% %@NL@% 2. The /Zc (compile case insensitive) converts all identifiers (excluding function names) to uppercase.%@NL@% %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A-C0011 @%%@AB@%C.4 Characters%@AE@%%@EH@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-C0012 @%%@AB@%C.4.1 The ASCII Character Set%@AE@%%@EH@%%@NL@% %@NL@% %@AB@%Members of source and execution character sets (2.2.1)%@AE@% %@NL@% %@NL@% The source character set is the set of legal characters that can appear in source files. For Microsoft C, the source character set is the standard ASCII character set. Figure C.1 contains an ASCII table. %@NL@% %@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% %@AU@%WARNING%@AE@%%@NL@% %@NL@% Because keyboard and console drivers can remap the character set, programs intended for international distribution should check the country code.%@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-C0013 @%%@AB@%C.4.2 Multibyte Characters%@AE@%%@EH@%%@NL@% %@NL@% %@AB@%Shift states for multibyte characters (2.2.1)%@AE@% %@NL@% %@NL@% Multibyte characters are used by some implementations to represent foreignlanguage characters not represented in the base character set. Microsoft C 6.0 does not support multibyte characters. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-C0014 @%%@AB@%C.4.3 Bits per Character%@AE@%%@EH@%%@NL@% %@NL@% %@AB@%Number of bits in a character (2.2.4.2)%@AE@% %@NL@% %@NL@% The number of bits in a character is represented by the manifest constant %@AB@%CHAR_BIT%@AE@%. The LIMITS.H file defines %@AB@%CHAR_BIT%@AE@% as 8. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-C0015 @%%@AB@%C.4.4 Character Sets%@AE@%%@EH@%%@NL@% %@NL@% %@AB@%Mapping members of the source character set (3.1.3.4)%@AE@% %@NL@% %@NL@% The source character set and execution character set include the ANSI ASCII characters listed in Table C.1. Escape sequences are also shown in Table C.1. %@NL@% %@NL@% %@AB@%Table %@AB@%C.1%@AE@%%@AE@% %@TH: 13 657 02 17 18 41 @%Escape Sequence Character ASCII Value%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%\a Alert/bell 7\b Backspace 8\f Form feed 12\n Newline 10\r Carriage return 13\t Horizontal tab 9\v Vertical tab 11\" Double quotation 34\%@AS@%'%@AE@% Single quotation 39\\ Backslash 92%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@TE: 13 657 02 17 18 41 @% %@NL@% %@3@%%@CR:C6A-C0016 @%%@AB@%C.4.5 Unrepresented Character Constants%@AE@%%@EH@%%@NL@% %@NL@% %@AB@%The value of an integer character constant that contains a character or %@AB@%escape sequence not represented in the basic execution character set or the %@AB@%extended character set for a wide character constant (3.1.3.4)%@AE@% %@NL@% %@NL@% Microsoft C does not support wide characters. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-C0017 @%%@AB@%C.4.6 Wide Characters%@AE@%%@EH@%%@NL@% %@NL@% %@AB@%The value of an integer character constant that contains more than one %@AB@%character or a wide character constant that contains more than one multibyte %@AB@%character (3.1.3.4)%@AE@% %@NL@% %@NL@% Microsoft C does not support wide characters or multibyte characters. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-C0018 @%%@AB@%C.4.7 Converting Multibyte Characters%@AE@%%@EH@%%@NL@% %@NL@% %@AB@%The current locale used to convert multibyte characters into corresponding %@AB@%wide characters (codes) for a wide character constant (3.1.3.4) %@AE@%%@NL@% %@NL@% Microsoft C does not support multibyte characters. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-C0019 @%%@AB@%C.4.8 Range of char Values%@AE@%%@EH@%%@NL@% %@NL@% %@AB@%Whether a "plain" char has the same range of values as a signed char or an %@AB@%unsigned char (3.2.1.1)%@AE@% %@NL@% %@NL@% All character values range from 0x00 to 0xFF, signed or unsigned. If a %@AB@%char%@AE@% is not explicitly marked as %@AB@%signed%@AE@% or %@AB@%unsigned%@AE@%, it defaults to the %@AB@%signed%@AE@% type. %@NL@% %@NL@% The CL option /J changes the default from %@AB@%signed%@AE@% to %@AB@%unsigned%@AE@%. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A-C0020 @%%@AB@%C.5 Integers%@AE@%%@EH@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-C0021 @%%@AB@%C.5.1 Range of Integer Values%@AE@%%@EH@%%@NL@% %@NL@% %@AB@%The representations and sets of values of the various types of integers %@AB@%(3.1.2.5)%@AE@% %@NL@% %@NL@% Short integers contain 16 bits (two bytes). Long integers contain 32 bits (four bytes). Signed integers are represented in two's-complement form. The mostsignificant bit holds the sign: 1 for negative, 0 for positive and zero. The values are listed below: %@NL@% %@NL@% %@AB@%Type%@AE@% %@AB@%Minimum and Maximum%@AE@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@AB@%unsigned short%@AE@% 0 to 65535 %@AB@%signed short%@AE@% -32768 to 32767 %@AB@%unsigned long%@AE@% 0 to 4294967295 %@AB@%signed long%@AE@% -2147483648 to 2147483647 %@NL@% %@3@%%@CR:C6A-C0022 @%%@AB@%C.5.2 Demotion of Integers%@AE@%%@EH@%%@NL@% %@NL@% %@AB@%The result of converting an integer to a shorter signed integer, or the %@AB@%result of converting an unsigned integer to a signed integer of equal %@AB@%length, if the value cannot be represented (3.2.1.2)%@AE@% %@NL@% %@NL@% When a %@AB@%long%@AE@% integer is cast to a %@AB@%short%@AE@%, or a %@AB@%short%@AE@% is cast to a %@AB@%char%@AE@%, the least significant bytes are retained. %@NL@% %@NL@% For example, this line %@NL@% %@NL@% %@AS@% short x = (short)0x12345678L;%@AE@%%@NL@% %@NL@% assigns the value 0x5678 to %@AS@% x%@AE@%, and this line %@NL@% %@NL@% %@AS@% char y = (char)0x1234;%@AE@%%@NL@% %@NL@% assigns the value 0x34 to %@AS@% y%@AE@%. %@NL@% %@NL@% When signed variables are converted to unsigned and vice versa, the bit patterns remain the same. For example, casting -2 (0xFE) to an unsigned value yields 254 (also 0xFE). %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-C0023 @%%@AB@%C.5.3 Signed Bitwise Operations%@AE@%%@EH@%%@NL@% %@NL@% %@AB@%The results of bitwise operations on signed integers (3.3)%@AE@% %@NL@% %@NL@% Bitwise operations on signed integers work the same as bitwise operations on unsigned integers. For example, %@AS@% -16 & 99 %@AE@% can be expressed in binary as %@NL@% %@NL@% %@AS@% 11111111 11110000 %@AS@% & 00000000 01100011 %@AS@% ----------------- %@AS@% 00000000 01100000%@AE@%%@NL@% %@NL@% The result of the bitwise AND is 96. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-C0024 @%%@AB@%C.5.4 Remainders%@AE@%%@EH@%%@NL@% %@NL@% %@AB@%The sign of the remainder on integer division (3.3.5)%@AE@% %@NL@% %@NL@% The sign of the remainder is the same as the sign of the dividend. For example, %@NL@% %@NL@% %@AS@% 50 / -6 == -8 %@AS@% 50 % -6 == 2 %@AS@% -50 / 6 == -8 %@AS@% -50 % 6 == -2%@AE@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-C0025 @%%@AB@%C.5.5 Right Shifts%@AE@%%@EH@%%@NL@% %@NL@% %@AB@%The result of a right shift of a negative-value signed integral type %@AB@%(3.3.7)%@AE@% %@NL@% %@NL@% Shifting a negative value to the right yields half the absolute value, rounded down. For example, -253 (binary 11111111 00000011) shifted right one bit produces -127 (binary 11111111 10000001). A %@AI@%positive%@AE@% 253 shifts right to produce +126. %@NL@% %@NL@% Right shifts preserve the sign bit. When a signed integer shifts right, the mostsignificant bit remains set. When an unsigned integer shifts right, the mostsignificant bit is cleared. Thus, if 0xF000 is signed, a right shift produces 0xF800. If 0xF000 is unsigned, the result is 0x7800. %@NL@% %@NL@% Shifting a positive number right sixteen times produces 0x0000. Shifting a negative number right sixteen times produces 0xFFFF. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A-C0026 @%%@AB@%C.6 Floating-Point Math%@AE@%%@EH@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-C0027 @%%@AB@%C.6.1 Values%@AE@%%@EH@%%@NL@% %@NL@% %@AB@%The representations and sets of values of the various types of %@AB@%floating-point numbers (3.1.2.5)%@AE@% %@NL@% %@NL@% The %@AB@%float%@AE@% type contains 32 bits: 1 for the sign, 8 for the exponent, and 23 for the mantissa. Its range is +/- 3.4E38 with at least 7 digits of precision. %@NL@% %@NL@% The %@AB@%double%@AE@% type contains 64 bits: 1 for the sign, 11 for the exponent, and 52 for the mantissa. Its range is +/- 1.7E308 with at least 15 digits of precision. %@NL@% %@NL@% The %@AB@%long double%@AE@% type is new to Version 6.0 of Microsoft C. It contains 80 bits: 1 for the sign, 15 for the exponent, and 64 for the mantissa. Its range is +/- 1.2E4932 with at least 17 digits of precision. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-C0028 @%%@AB@%C.6.2 Casting Integers to Floating-Point Values%@AE@%%@EH@%%@NL@% %@NL@% %@AB@%The direction of truncation when an integral number is converted to a %@AB@%floating-point number that cannot exactly represent the original value %@AB@%(3.2.1.3)%@AE@% %@NL@% %@NL@% When an integral number is cast to a floating-point value that cannot exactly represent the value, the value is rounded (up or down) to the nearest suitable value. %@NL@% %@NL@% For example, casting an %@AB@%unsigned long%@AE@% (with 32 bits of precision) to a %@AB@%float%@AE@% (whose mantissa has 23 bits of precision) rounds the number to the nearest multiple of 256. The %@AB@%long%@AE@% values 4294966913 - 4294967167 are all rounded to the %@AB@%float%@AE@% value 4294967040. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-C0029 @%%@AB@%C.6.3 Truncation of Floating-Point Values%@AE@%%@EH@%%@NL@% %@NL@% %@AB@%The direction of truncation or rounding when a floating-point number is %@AB@%converted to a narrower floating-point number (3.2.1.4)%@AE@% %@NL@% %@NL@% When an underflow occurs, the value of a floating-point variable is rounded down to zero. An overflow causes a run-time math error. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A-C0030 @%%@AB@%C.7 Arrays and Pointers%@AE@%%@EH@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-C0031 @%%@AB@%C.7.1 Largest Array Size%@AE@%%@EH@%%@NL@% %@NL@% %@AB@%The type of integer required to hold the maximum size of an array─that is, %@AB@%the size of size_t (3.3.3.4, 4.1.1)%@AE@% %@NL@% %@NL@% The %@AB@%size_t%@AE@% typedef is an %@AB@%unsigned short%@AE@%, with the range 0x0000 to 0xFFFF. Huge arrays can exceed this limit if they contain more than 65,535 elements. Arithmetic operations on huge arrays should therefore cast %@AB@%size_t%@AE@% and the results of an arithmetic operations on pointers to %@AB@%unsigned long%@AE@%. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-C0032 @%%@AB@%C.7.2 Casting Pointers%@AE@%%@EH@%%@NL@% %@NL@% %@AB@%The result of casting a pointer to an integer or vice versa (3.3.4)%@AE@% %@NL@% %@NL@% Near pointers are the same size as short integers; casting near to short (or short to near) has no immediate effect on the value. %@NL@% %@NL@% Far pointers and huge pointers are the same size as long integers. Casting far/huge to long (or long to far/huge) has no immediate effect on the value. %@NL@% %@NL@% When a near pointer is cast to a long, the 16-bit value is "normalized," which means the segment (usually DS) and offset are combined to produce a 32-bit memory location. %@NL@% %@NL@% When a far or huge pointer is cast to a short, the long value is truncated to a short. %@NL@% %@NL@% The compiler normalizes based pointers when necessary, unless the based pointer is a constant zero, in which case it is assumed to be a null pointer. See Chapter 13, "Writing Portable Programs," for more information about based pointers. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-C0033 @%%@AB@%C.7.3 Pointer Subtraction%@AE@%%@EH@%%@NL@% %@NL@% %@AB@%The type of integer required to hold the difference between two pointers to %@AB@%elements of the same array, ptrdiff_t (3.3.6, 4.1.1)%@AE@% %@NL@% %@NL@% A %@AB@%ptrdiff_t%@AE@% is a signed integer in the range -32768 to 32767, with one exception. Because huge pointers can address more than 64K of memory, subtracting one huge pointer from another can yield a result that is a long integer. The result of subtracting two huge pointers should be cast to a long. %@NL@% %@NL@% The compiler normalizes based pointers when necessary. In most cases, based pointers are treated as far pointers. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A-C0034 @%%@AB@%C.8 Registers%@AE@%%@EH@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-C0035 @%%@AB@%C.8.1 Availability of Registers%@AE@%%@EH@%%@NL@% %@NL@% %@AB@%The extent to which objects can actually be placed in registers by use of %@AB@%the register storage-class specifier (3.5.1)%@AE@% %@NL@% %@NL@% Two registers, SI and DI, are available in Microsoft C. Register variables with a type that has 16 bits may be allocated in these registers. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A-C0036 @%%@AB@%C.9 Structures, Unions, Enumerations, and Bit Fields%@AE@%%@EH@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-C0037 @%%@AB@%C.9.1 Improper Access to a Union%@AE@%%@EH@%%@NL@% %@NL@% %@AB@%A member of a union object is accessed using a member of a different type %@AB@%(3.3.2.3)%@AE@% %@NL@% %@NL@% If a union of two types is declared and one value is stored, but the union is accessed with the other type, the results are unreliable. %@NL@% %@NL@% For example, a union of %@AB@%float%@AE@% and %@AB@%int%@AE@% is declared. A %@AB@%float%@AE@% value is stored, but the program later accesses the value as an %@AB@%int%@AE@%. In such a situation, the value would depend on the internal storage of %@AB@%float%@AE@% values. The integer value would not be reliable. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-C0038 @%%@AB@%C.9.2 Sign of Bit Fields%@AE@%%@EH@%%@NL@% %@NL@% %@AB@%Whether a "plain" int field is treated as a signed int bit field or as an %@AB@%unsigned int bit field (3.5.2.1)%@AE@% %@NL@% %@NL@% Bit fields can be signed or unsigned. Plain bit fields are treated as signed. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-C0039 @%%@AB@%C.9.3 Storage of Bit Fields%@AE@%%@EH@%%@NL@% %@NL@% %@AB@%The order of allocation of bit fields within an int (3.5.2.1)%@AE@% %@NL@% %@NL@% Bit fields are allocated within a 16-bit integer from least-significant to mostsignificant bit. In the following code, %@NL@% %@NL@% %@AS@% struct mybitfields %@AS@% { %@AS@% unsigned a : 4; %@AS@% unsigned b : 5; %@AS@% unsigned c : 7; %@AS@% } test; %@AS@% %@AS@% void main( void ) %@AS@% { %@AS@% test.a = 2; %@AS@% test.b = 31; %@AS@% test.c = 0; %@AS@% }%@AE@%%@NL@% %@NL@% the bits would be arranged as follows: %@NL@% %@NL@% %@AS@% 00000001 11110010 %@AS@% cccccccb bbbbaaaa%@AE@%%@NL@% %@NL@% Since the 80%@AI@%x%@AE@%86 processors store the low byte of integer values before the high byte, the integer 0x01F2 above would be stored in physical memory as 0xF2 followed by 0x01. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-C0040 @%%@AB@%C.9.4 Alignment of Bit Fields%@AE@%%@EH@%%@NL@% %@NL@% %@AB@%Whether a bit field can straddle a storage-unit boundary (3.5.2.1)%@AE@% %@NL@% %@NL@% Bit fields default to size %@AB@%short%@AE@%, which can cross a byte boundary (see Section C.9.3 above) but not a 16-bit boundary. If the size and location of a bit field would cause it to overflow the current integer, the field is moved to the beginning of the next available integer. %@NL@% %@NL@% If a bit field is declared as a %@AB@%long%@AE@%, it can hold up to 32 bits. %@NL@% %@NL@% In either case, an individual field cannot cross a 16- or 32-bit boundary. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-C0041 @%%@AB@%C.9.5 The enum Type%@AE@%%@EH@%%@NL@% %@NL@% %@AB@%The integer type chosen to represent the values of an enumeration type %@AB@%(3.5.2.2)%@AE@% %@NL@% %@NL@% A variable declared as %@AB@%enum%@AE@% is a signed short integer. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A-C0042 @%%@AB@%C.10 Qualifiers%@AE@%%@EH@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-C0043 @%%@AB@%C.10.1 Access to Volatile Objects%@AE@%%@EH@%%@NL@% %@NL@% %@AB@%What constitutes an access to an object that has volatile-qualified type %@AB@%(3.5.3)%@AE@% %@NL@% %@NL@% Any reference to a volatile-qualified type is an access. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A-C0044 @%%@AB@%C.11 Declarators%@AE@%%@EH@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-C0045 @%%@AB@%C.11.1 Maximum Number%@AE@%%@EH@%%@NL@% %@NL@% %@AB@%The maximum number of declarators that can modify an arithmetic, structure, %@AB@%or union type (3.5.4)%@AE@% %@NL@% %@NL@% Microsoft C does not limit the number of declarators. The number is limited only by available memory. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A-C0046 @%%@AB@%C.12 Statements%@AE@%%@EH@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-C0047 @%%@AB@%C.12.1 Limits on Switch Statements%@AE@%%@EH@%%@NL@% %@NL@% %@AB@%The maximum number of case values in a switch statement (3.6.4.2)%@AE@% %@NL@% %@NL@% Microsoft C does not limit the number of %@AB@%case%@AE@% values in a %@AB@%switch%@AE@% statement. The number is limited only by available memory. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A-C0048 @%%@AB@%C.13 Preprocessing Directives%@AE@%%@EH@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-C0049 @%%@AB@%C.13.1 Character Constants and Conditional Inclusion%@AE@%%@EH@%%@NL@% %@NL@% %@AB@%Whether the value of a single-character character constant in a constant %@AB@%expression that controls conditional inclusion matches the value of the same %@AB@%character constant in the execution character set. Whether such a character %@AB@%constant can have a negative value (3.8.1)%@AE@% %@NL@% %@NL@% The character set used in preprocessor statements is the same as the execution character set. The preprocessor recognizes negative character values. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-C0050 @%%@AB@%C.13.2 Including Bracketed File Names%@AE@%%@EH@%%@NL@% %@NL@% %@AB@%The method for locating includable source files (3.8.2)%@AE@% %@NL@% %@NL@% The preprocessor first searches the directories specified by the CL option /I. If the /I option is not present or if it fails, the preprocessor uses the INCLUDE environment variable to find any include files within angle brackets. If more than one directory appears as part of the /I option or within the INCLUDE variable, the preprocessor searches them in the order they appear. %@NL@% %@NL@% For example, the command %@NL@% %@NL@% %@AS@% CL /ID:\MSC\INCLUDE MYPROG.C%@AE@%%@NL@% %@NL@% causes the preprocessor to search the directory D:\MSC\INCLUDE for include files such as STDIO.H. %@NL@% %@NL@% The commands %@NL@% %@NL@% %@AS@% SET INCLUDE = D:\MSC\INCLUDE %@AS@% CL MYPROG.C%@AE@%%@NL@% %@NL@% have a similar effect. %@NL@% %@NL@% If both sets of searches fail, a fatal error is generated. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-C0051 @%%@AB@%C.13.3 Including Quoted File Names%@AE@%%@EH@%%@NL@% %@NL@% %@AB@%The support for quoted names for includable source files (3.8.2)%@AE@% %@NL@% %@NL@% If the file name is fully specified, with a path that includes a colon (for example, F:\C6\SPECIAL\INCL\ORANGE.H), the preprocessor follows the path. %@NL@% %@NL@% If the file name is not fully specified, the preprocessor searches the directory of the file that included it. If the file is not found there, the preprocessor searches the parent directory, the parent's parent, and so on, terminating with the root directory. %@NL@% %@NL@% If the include file is not found in any of those directories, the rules for bracketed file names apply. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-C0052 @%%@AB@%C.13.4 Character Sequences%@AE@%%@EH@%%@NL@% %@NL@% %@AB@%The mapping of source file character sequences (3.8.2)%@AE@% %@NL@% %@NL@% Preprocessor statements use the same character set as source file statements with the exception that escape sequences are not supported. %@NL@% %@NL@% Thus, to specify a path for an include file, use only one backslash: %@NL@% %@NL@% %@AS@% #include "path1\path2\myfile"%@AE@%%@NL@% %@NL@% Within source code, two backslashes are necessary: %@NL@% %@NL@% %@AS@% fil = fopen( "path1\\path2\\myfile", "rt" );%@AE@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-C0053 @%%@AB@%C.13.5 Pragmas%@AE@%%@EH@%%@NL@% %@NL@% %@AB@%The behavior on each recognized #pragma directive (3.8.6)%@AE@% %@NL@% %@NL@% The following pragmas are defined in the %@AI@%Microsoft C Reference%@AE@%: %@NL@% %@NL@% %@AB@%#pragma alloc_text%@AE@% %@AB@%#pragma optimize%@AE@% %@AB@%#pragma check_pointer%@AE@% %@AB@%#pragma pack%@AE@% %@AB@%#pragma check_stack%@AE@% %@AB@%#pragma page%@AE@% %@AB@%#pragma comment%@AE@% %@AB@%#pragma pagesize%@AE@% %@AB@%#pragma function%@AE@% %@AB@%#pragma same_seg%@AE@% %@AB@%#pragma intrinsic%@AE@% %@AB@%#pragma skip%@AE@% %@AB@%#pragma linesize%@AE@% %@AB@%#pragma subtitle%@AE@% %@AB@%#pragma loop_opt%@AE@% %@AB@%#pragma title%@AE@% %@AB@%#pragma message%@AE@% %@NL@% %@3@%%@CR:C6A-C0054 @%%@AB@%C.13.6 Default Date and Time%@AE@%%@EH@%%@NL@% %@NL@% %@AB@%The definitions for _DATE_ and _TIME_ when, respectively, the date and time %@AB@%of translation are not available (3.8.8)%@AE@% %@NL@% %@NL@% When a hardware clock is not accessible, the default values for _DATE_ and _TIME_ are Friday, May 3, 1957 and 5:00 PM. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A-C0055 @%%@AB@%C.14 Library Functions%@AE@%%@EH@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-C0056 @%%@AB@%C.14.1 NULL Macro%@AE@%%@EH@%%@NL@% %@NL@% %@AB@%The null pointer constant to which the macro NULL expands (4.1.5)%@AE@% %@NL@% %@NL@% Several include files define the NULL macro as %@AS@% ((void *)0)%@AE@%. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-C0057 @%%@AB@%C.14.2 Diagnostic Printed by the assert Function%@AE@%%@EH@%%@NL@% %@NL@% %@AB@%The diagnostic printed by and the termination behavior of the assert %@AB@%function (4.2)%@AE@% %@NL@% %@NL@% The%@AB@% assert %@AE@%function prints a diagnostic message and calls the abort routine if the expression is false (0). The diagnostic message has the form %@NL@% %@NL@% Assertion failed: [%@AI@%expression%@AE@%], file [%@AI@%filename%@AE@%], line [%@AI@%linenumber%@AE@%] %@NL@% %@NL@% where %@AI@%filename %@AE@%is the name of the source file and %@AI@%linenumber %@AE@%is the line number of the assertion that failed in the source file. No action is taken if%@AI@% expression%@AE@% is true (nonzero). %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-C0058 @%%@AB@%C.14.3 Character Testing%@AE@%%@EH@%%@NL@% %@NL@% %@AB@%The sets of characters tested for by the isalnum, isalpha, iscntrl, islower, %@AB@%isprint, and isupper functions (4.3.1)%@AE@% %@NL@% %@NL@% %@AB@%Function%@AE@% %@AB@%Tests For%@AE@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@AB@%isalnum%@AE@% Characters 0 - 9, A-Z, a-z ASCII 48-57, 65-90, 97-122 %@AB@%isalpha%@AE@% Characters A-Z, a-z ASCII 65-90, 97-122 %@AB@%iscntrl%@AE@% ASCII 0 -31, 127 %@AB@%islower%@AE@% Characters a-z ASCII 97-122 %@AB@%isprint%@AE@% Characters A-Z, a-z, 0 - 9, punctuation, space ASCII 32-126 %@AB@%isupper%@AE@% Characters A-Z ASCII 65-90 %@NL@% %@3@%%@CR:C6A-C0059 @%%@AB@%C.14.4 Domain Errors%@AE@%%@EH@%%@NL@% %@NL@% %@AB@%The values returned by the mathematics functions on domain errors (4.5.1)%@AE@% %@NL@% %@NL@% The ERRNO.H file defines the domain error constant EDOM as 33. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-C0060 @%%@AB@%C.14.5 Underflow of Floating-Point Values%@AE@%%@EH@%%@NL@% %@NL@% %@AB@%Whether the mathematics functions set the integer expression errno to the %@AB@%value of the macro ERANGE on underflow range errors (4.5.1)%@AE@% %@NL@% %@NL@% A floating-point underflow does not set the expression %@AB@%errno%@AE@% to ERANGE. When a value approaches zero and eventually underflows, the value is set to zero. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-C0061 @%%@AB@%C.14.6 The fmod Function%@AE@%%@EH@%%@NL@% %@NL@% %@AB@%Whether a domain error occurs or zero is returned when the fmod function has %@AB@%a second argument of zero (4.5.6.4)%@AE@% %@NL@% %@NL@% When the %@AB@%fmod%@AE@% function has a second argument of zero, the function returns zero. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-C0062 @%%@AB@%C.14.7 The signal Function%@AE@%%@EH@%%@NL@% %@NL@% %@AB@%The set of signals for the signal function (4.7.1.1)%@AE@% %@NL@% %@NL@% The first argument passed to %@AB@%signal%@AE@% must be one of the symbolic constants listed below. The constants are defined in SIGNAL.H. Also listed is the operating mode support for each signal. %@NL@% %@NL@% %@AB@%Signal Argument%@AE@% %@AB@%Description%@AE@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% SIGABRT Abnormal termination (real and protected mode). SIGBREAK CTRL+BREAK signal. Terminates the calling program (protected mode only). SIGFPE Floating-point error, such as overflow, division by zero, or invalid operation. Terminates the calling program (real and protected mode). SIGILL Illegal instruction. Terminates the calling program (protected mode only). SIGINT CTRL+C interrupt. Issues INT 23H (real and protected mode). SIGSEGV Illegal storage access. Not generated by DOS or OS/2, but supported for ANSI compatibility. Terminates the calling program (real and protected mode). SIGTERM Termination request sent to the program. Not generated by DOS or OS/2, but supported for ANSI compatibility. Terminates the calling program (real and protected mode). SIGUSR1 OS/2 process flag A (protected mode only). SIGUSR2 OS/2 process flag B (protected mode only). SIGUSR3 OS/2 process flag C (protected mode only). %@NL@% %@3@%%@CR:C6A-C0063 @%%@AB@%C.14.8 Default Signals%@AE@%%@EH@%%@NL@% %@NL@% %@AB@%If the equivalent of signal (sig, SIG_DFL) is not executed prior to the call %@AB@%of a signal handler, the blocking of the signal that is performed (4.7.1.1)%@AE@% %@NL@% %@NL@% Signals are set to their default status when a program begins running. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-C0064 @%%@AB@%C.14.9 The SIGILL Signal%@AE@%%@EH@%%@NL@% %@NL@% %@AB@%Whether the default handling is reset if the SIGILL signal is received by a %@AB@%handler specified to the signal function (4.7.1.1)%@AE@% %@NL@% %@NL@% The SIGILL signal applies to OS/2 applications only. When SIGILL is received, the signal handling is not reset to the default SIG_DFL. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-C0065 @%%@AB@%C.14.10 Terminating Newline Characters%@AE@%%@EH@%%@NL@% %@NL@% %@AB@%Whether the last line of a text stream requires a terminating newline %@AB@%character (4.9.2)%@AE@% %@NL@% %@NL@% Stream functions recognize either newline or end-of-file as the terminating character for a line. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-C0066 @%%@AB@%C.14.11 Blank Lines%@AE@%%@EH@%%@NL@% %@NL@% %@AB@%Whether space characters that are written out to a text stream immediately %@AB@%before a newline character appear when read in (4.9.2)%@AE@% %@NL@% %@NL@% Space characters are preserved. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-C0067 @%%@AB@%C.14.12 Null Characters%@AE@%%@EH@%%@NL@% %@NL@% %@AB@%The number of null characters that can be appended to data written to a %@AB@%binary stream (4.9.2)%@AE@% %@NL@% %@NL@% Any number of null characters can be appended to a binary stream. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-C0068 @%%@AB@%C.14.13 File Position in Append Mode%@AE@%%@EH@%%@NL@% %@NL@% %@AB@%Whether the file position indicator of an append mode stream is initially %@AB@%positioned at the beginning or end of the file (4.9.3)%@AE@% %@NL@% %@NL@% When a file is opened in append mode, the file position indicator initially points to the end of the file. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-C0069 @%%@AB@%C.14.14 Truncation of Text Files%@AE@%%@EH@%%@NL@% %@NL@% %@AB@%Whether a write on a text stream causes the associated file to be truncated %@AB@%beyond that point (4.9.3)%@AE@% %@NL@% %@NL@% Writing to a text stream does not truncate the file beyond that point. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-C0070 @%%@AB@%C.14.15 File Buffering%@AE@%%@EH@%%@NL@% %@NL@% %@AB@%The characteristics of file buffering (4.9.3)%@AE@% %@NL@% %@NL@% Disk files accessed through standard I/O functions are fully buffered. By default, the buffer holds 512 bytes. Some of the low-level DOS and BIOS functions (all of which are non-ANSI) are unbuffered. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-C0071 @%%@AB@%C.14.16 Zero-Length Files%@AE@%%@EH@%%@NL@% %@NL@% %@AB@%Whether a zero-length file actually exists (4.9.3)%@AE@% %@NL@% %@NL@% Files with a length of zero are permitted. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-C0072 @%%@AB@%C.14.17 File Names%@AE@%%@EH@%%@NL@% %@NL@% %@AB@%The rules for composing valid file names (4.9.3)%@AE@% %@NL@% %@NL@% A file specification can include an optional drive letter (always followed by a colon), a series of optional directory names (separated by backslashes), and a file name. %@NL@% %@NL@% File names and directory names can contain up to eight characters followed by a period and a three-character extension. Case is ignored. The wild-card characters * and ? are not permitted within the name or extension. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-C0073 @%%@AB@%C.14.18 File Access Limits%@AE@%%@EH@%%@NL@% %@NL@% %@AB@%Whether the same file can be open multiple times (4.9.3)%@AE@% %@NL@% %@NL@% Opening a file that is already open is not permitted. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-C0074 @%%@AB@%C.14.19 Deleting Open Files%@AE@%%@EH@%%@NL@% %@NL@% %@AB@%The effect of the remove function on an open file (4.9.4.1)%@AE@% %@NL@% %@NL@% The %@AB@%remove%@AE@% function deletes a file, even if the file is open. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-C0075 @%%@AB@%C.14.20 Renaming with a Name that Exists%@AE@%%@EH@%%@NL@% %@NL@% %@AB@%The effect if a file with the new name exists prior to a call to the rename %@AB@%function (4.9.4.2)%@AE@% %@NL@% %@NL@% If you attempt to rename a file using a name that exists, the %@AB@%rename%@AE@% function fails and returns an error code. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-C0076 @%%@AB@%C.14.21 Printing Pointer Values%@AE@%%@EH@%%@NL@% %@NL@% %@AB@%The output for %p conversion in the fprintf function (4.9.6.1)%@AE@% %@NL@% %@NL@% Microsoft C supports three types of pointer conversions: %@AB@%%p %@AE@%(a pointer),%@AB@% %lp%@AE@% (a 32-bit far pointer), and %@AB@%%hp %@AE@%(a 16-bit near pointer). %@NL@% %@NL@% The %@AB@%fprintf%@AE@% function produces hexadecimal values of the form %@AI@%XXXX%@AE@% (an offset) for near pointers or %@AI@%XXXX:XXXX%@AE@% (a segment plus an offset, separated by a colon) for far pointers. The output for%@AB@% %p%@AE@% depends on the memory model in use. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-C0077 @%%@AB@%C.14.22 Reading Pointer Values%@AE@%%@EH@%%@NL@% %@NL@% %@AB@%The input for %p conversion in the fscanf function (4.9.6.2)%@AE@% %@NL@% %@NL@% When the %@AB@%%p%@AE@% format character is specified, the %@AB@%fscanf%@AE@% function converts pointers from hexadecimal ASCII values into the correct address. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-C0078 @%%@AB@%C.14.23 Reading Ranges%@AE@%%@EH@%%@NL@% %@NL@% %@AB@%The interpretation of a dash (-) character that is neither the first nor the %@AB@%last character in the scanlist for % [ conversion in the fscanf function %@AB@%(4.9.6.2)%@AE@% %@NL@% %@NL@% The following line %@NL@% %@NL@% %@AS@% fscanf( fileptr, "%[A-Z]", strptr);%@AE@%%@NL@% %@NL@% reads any number of characters in the range A-Z into the string to which %@AS@% %@AS@%strptr %@AE@% points. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-C0079 @%%@AB@%C.14.24 File Position Errors%@AE@%%@EH@%%@NL@% %@NL@% %@AB@%The value to which the macro errno is set by the fgetpos or ftell function %@AB@%on failure (4.9.9.1, 4.9.9.4)%@AE@% %@NL@% %@NL@% When %@AB@%fgetpos%@AE@% or %@AB@%ftell%@AE@% fails, %@AB@%errno%@AE@% is set to the manifest constant %@AB@%EINVAL%@AE@% if the position is invalid or %@AB@%EBADF%@AE@% if the file number is bad. The constants are defined in ERRNO.H. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-C0080 @%%@AB@%C.14.25 Messages Generated by the perror Function%@AE@%%@EH@%%@NL@% %@NL@% %@AB@%The messages generated by the perror function (4.9.10.4)%@AE@% %@NL@% %@NL@% The %@AB@%perror%@AE@% function generates these messages: %@NL@% %@NL@% %@AS@% 0 Error 0 %@AS@% 1 %@AS@% 2 No such file or directory %@AS@% 3 %@AS@% 4 %@AS@% 5 %@AS@% 6 %@AS@% 7 Arg list too long %@AS@% 8 Exec format error %@AS@% 9 Bad file number %@AS@% 10 %@AS@% 11 %@AS@% 12 Not enough core %@AS@% 13 Permission denied %@AS@% 14 %@AS@% 15 %@AS@% 16 %@AS@% 17 File exists %@AS@% 18 Cross-device link %@AS@% 19 %@AS@% 20 %@AS@% 21 %@AS@% 22 Invalid argument %@AS@% 23 %@AS@% 24 Too many open files %@AS@% 25 %@AS@% 26 %@AS@% 27 %@AS@% 28 No space left on device %@AS@% 29 %@AS@% 30 %@AS@% 31 %@AS@% 32 %@AS@% 33 Math argument %@AS@% 34 Result too large %@AS@% 35 %@AS@% 36 Resource deadlock would occur%@AE@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-C0081 @%%@AB@%C.14.26 Allocating Zero Memory%@AE@%%@EH@%%@NL@% %@NL@% %@AB@%The behavior of the calloc, malloc, or realloc function if the size %@AB@%requested is zero (4.10.3)%@AE@% %@NL@% %@NL@% The %@AB@%calloc%@AE@%, %@AB@%malloc%@AE@%, and %@AB@%realloc %@AE@%functions accept zero as an argument. No actual memory is allocated, but the memory size can be modified later by %@AB@%realloc%@AE@%. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-C0082 @%%@AB@%C.14.27 The abort Function%@AE@%%@EH@%%@NL@% %@NL@% %@AB@%The behavior of the abort function with regard to open and temporary files %@AB@%(4.10.4.1)%@AE@% %@NL@% %@NL@% The %@AB@%abort%@AE@% function does not close files that are open or temporary. It does not flush stream buffers. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-C0083 @%%@AB@%C.14.28 The atexit Function%@AE@%%@EH@%%@NL@% %@NL@% %@AB@%The status returned by the atexit function if the value of the argument is %@AB@%other than zero, EXIT_SUCCESS, or EXIT_FAILURE (4.10.4.3r)%@AE@% %@NL@% %@NL@% The %@AB@%atexit %@AE@%function returns zero if successful, or a nonzero value if unsuccessful. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-C0084 @%%@AB@%C.14.29 Environment Names%@AE@%%@EH@%%@NL@% %@NL@% %@AB@%The set of environment names and the method for altering the environment %@AB@%list used by the getenv function (4.10.4.4)%@AE@% %@NL@% %@NL@% The set of environment names is unlimited. %@NL@% %@NL@% To change environment variables from within a C program, call the %@AB@%putenv%@AE@% function. To change environment variables from the DOS command line, use the SET command (for example, SET LIB = D:\ LIBS). %@NL@% %@NL@% Environment variables exist only as long as their host copy of DOS is running. For example, the line %@NL@% %@NL@% %@AS@% system( "SET LIB = D:\LIBS" );%@AE@%%@NL@% %@NL@% would run a copy of DOS, set the environment variable LIB, and return to the C program, exiting the secondary copy of DOS. Exiting that copy of DOS removes the temporary environment variable LIB. %@NL@% %@NL@% Likewise, changes made by the %@AB@%putenv%@AE@% function last only until the program ends. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-C0085 @%%@AB@%C.14.30 The system Function%@AE@%%@EH@%%@NL@% %@NL@% %@AB@%The contents and mode of execution of the string by the system function %@AB@%(4.10.4.5)%@AE@% %@NL@% %@NL@% The %@AB@%system%@AE@% function executes an internal DOS or OS/2 command, or an EXE, COM, or BAT file from within a C program rather than from the command line. %@NL@% %@NL@% It examines the COMSPEC environment variable to find the command interpreter, which is typically COMMAND.COM in DOS or CMD.EXE in OS/2. The %@AB@%system%@AE@% function then passes the argument string to the command interpreter. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-C0086 @%%@AB@%C.14.31 The strerror Function%@AE@%%@EH@%%@NL@% %@NL@% %@AB@%The contents of the error message strings returned by the strerror function %@AB@%(4.11.6.2)%@AE@% %@NL@% %@NL@% The %@AB@%strerror%@AE@% function generates these messages: %@NL@% %@NL@% %@AS@% 0 Error 0 %@AS@% 1 %@AS@% 2 No such file or directory %@AS@% 3 %@AS@% 4 %@AS@% 5 %@AS@% 6 %@AS@% 7 Arg list too long %@AS@% 8 Exec format error %@AS@% 9 Bad file number %@AS@% 10 %@AS@% 11 %@AS@% 12 Not enough core %@AS@% 13 Permission denied %@AS@% 14 %@AS@% 15 %@AS@% 16 %@AS@% 17 File exists %@AS@% 18 Cross-device link %@AS@% 19 %@AS@% 20 %@AS@% 21 %@AS@% 22 Invalid argument %@AS@% 23 %@AS@% 24 Too many open files %@AS@% 25 %@AS@% 26 %@AS@% 27 %@AS@% 28 No space left on device %@AS@% 29 %@AS@% 30 %@AS@% 31 %@AS@% 32 %@AS@% 33 Math argument %@AS@% 34 Result too large %@AS@% 35 %@AS@% 36 Resource deadlock would occur%@AE@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-C0087 @%%@AB@%C.14.32 The Time Zone%@AE@%%@EH@%%@NL@% %@NL@% %@AB@%The local time zone and Daylight Saving Time (4.12.1)%@AE@% %@NL@% %@NL@% The local time zone is Pacific Standard Time. Microsoft C supports Daylight Saving Time. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-C0088 @%%@AB@%C.14.33 The clock Function%@AE@%%@EH@%%@NL@% %@NL@% %@AB@%The era for the clock function (4.12.2.1)%@AE@% %@NL@% %@NL@% The %@AB@%clock %@AE@%function's era begins (with a value of 0) when the C program starts to execute. It returns times measured in 1/1000th seconds. %@NL@% %@NL@% %@NL@% %@NL@% %@CR:GeneralIndex@% %@1@%%@AB@%INDEX%@AE@%%@EH@%%@NL@% %@AB@%────────────────────────────────────────────────────────────────────────── 80x87 coprocessor%@BO: 309cd@%%@BO: 370f9@%%@BO: 39bde@% 80x87 Detection of%@BO: 339af@% %@2@%%@AB@% A%@AE@%%@EH@%%@NL@% Alternate math package%@BO: 341c5@%%@BO: 3826d@% %@2@%%@AB@% B%@AE@%%@EH@%%@NL@% _based keyword%@BO: 1fe23@%%@BO: 2117b@%%@BO: 21caa@% %@2@%%@AB@% C%@AE@%%@EH@%%@NL@% C extensions, PWB building protected-mode%@BO: 66d22@% building real-mode%@BO: 65d11@%%@BO: 66532@% calling C library functions%@BO: 6c61c@% calling C library routines%@BO: 6cb47@% calling PWB functions%@BO: 6a499@%%@BO: 6a9d3@%%@BO: 6b0c7@%%@BO: 6bab9@%%@BO: 6c441@% describing functions and switches%@BO: 67324@%%@BO: 67619@%%@BO: 67de2@%%@BO: 6866c@% initializing functions%@BO: 68b44@% prototyping functions%@BO: 69257@% receiving parameters%@BO: 69257@%%@BO: 699b4@%%@BO: 6a499@% sample%@BO: 650a9@%%@BO: 65b31@% versus executable files%@BO: 64e30@% C extentions, PWB building protected-mode%@BO: 66876@% Calls Emulator math package%@BO: 3737c@% Emulator package%@BO: 39396@%%@BO: 39bde@% Floating-point%@BO: 3494a@%%@BO: 38cfd@% Math coprocessor package%@BO: 37927@% CODEVIEW.LST file%@BO: 77d77@% CodeView debugging DLLs with%@BO: e3f22@% CONFIG.SYS file%@BO: 7890b@% CONFIG.SYS files%@BO: d390b@% _control87%@BO: 33ec0@% Coordinates overview%@BO: 806a5@% physical%@BO: 80b01@%%@BO: 80f5d@%%@BO: 8141f@% screen location%@BO: 81fcd@% viewport%@BO: 8141f@%%@BO: 83d1f@% window%@BO: 81a8a@%%@BO: 81fcd@%%@BO: 82fc7@%%@BO: 83d1f@%%@BO: 845b2@%%@BO: 84b29@%%@BO: 85aa5@%%@BO: 86287@%%@BO: 86c8b@% Coprocessor%@BO: 309cd@% CURRENT.STS%@BO: 6e5cb@% %@2@%%@AB@% D%@AE@%%@EH@%%@NL@% Default math package%@BO: 339af@% Denormalized numbers%@BO: 31b6f@%%@BO: 33ec0@%%@BO: 34416@% Dot commands%@BO: 59bb9@%%@BO: 59efd@%%@BO: 5ac14@%%@BO: 5ba95@% double%@BO: 30ed4@%%@BO: 32a89@% %@2@%%@AB@% E%@AE@%%@EH@%%@NL@% 80x87 coprocessor%@BO: 309cd@%%@BO: 370f9@%%@BO: 39bde@% 80x87 Detection of%@BO: 339af@% EMOEM.ASM%@BO: 3a8c0@% Emulator math package%@BO: 33170@%%@BO: 3376a@% Emulator package In-line%@BO: 366b7@%%@BO: 39bde@% With dynamic-link libraries%@BO: 36ed5@% Environment NO87 variable%@BO: 309cd@%%@BO: 39a6a@% %@2@%%@AB@% F%@AE@%%@EH@%%@NL@% _far keyword%@BO: 1fe23@%%@BO: 2117b@%%@BO: 21caa@%%@BO: 9f33e@%%@BO: a0b7f@%%@BO: b7e65@% _fastcall keyword%@BO: 9d859@% Files .FON%@BO: 87899@%%@BO: 87d60@%%@BO: 8a479@% CODEVIEW.LST%@BO: 77d77@% CONFIG.SYS%@BO: 7890b@%%@BO: d390b@% CURRENT.STS%@BO: 6e5cb@% TOOLS.INI See TOOLS.INI%@BO: 460ef@% Fill patterns%@BO: 91bc1@%%@BO: 922bf@%%@BO: 92bf4@% float%@BO: 30ed4@%%@BO: 32a89@% Floating-point accumulator%@BO: 32a89@% Floating-point math requirements, DLLs%@BO: d8678@% Floating-point Alternate math package%@BO: 341c5@%%@BO: 3826d@% Biased exponent%@BO: 316fc@% Compatibility between options%@BO: 3913f@% Floating-Point Controlling%@BO: 308f3@% Floating-point Default math package%@BO: 36898@% Default package%@BO: 339af@% Denormalized numbers%@BO: 31b6f@%%@BO: 33ec0@%%@BO: 34416@% Effect of calls on code size%@BO: 37cb2@%%@BO: 38491@% Effect of calls on speed%@BO: 37d4f@%%@BO: 38491@%%@BO: 38feb@% Effect on optimization%@BO: 36063@% Emulator package%@BO: 33170@%%@BO: 3376a@% Exception masking%@BO: 33ec0@% Exceptions%@BO: 33d51@%%@BO: 3a5d8@% exponent%@BO: 3123f@% Fastest programs%@BO: 372f4@% In libraries%@BO: 3768f@% Infinities%@BO: 34416@% Interrupt-enable%@BO: 33ec0@% Library considerations for%@BO: 386a4@% Mantissa%@BO: 3123f@% Math coprocessor package%@BO: 33212@%%@BO: 33f87@% Maximizing accuracy%@BO: 33a98@% NaNs%@BO: 34416@% On non-IBM compatible computers%@BO: 3a2a8@% Packages%@BO: 33116@%%@BO: 3353d@% Precision%@BO: 3210e@% Program size%@BO: 34143@%%@BO: 341c5@% Program speed%@BO: 34143@%%@BO: 341c5@% Sign bit%@BO: 31380@% Smallest programs%@BO: 372f4@% Transcendental function results%@BO: 33cce@% Underflow%@BO: 33ec0@% Using in dynamic-link libraries%@BO: 345ba@% With libraries not provided by Microsoft%@BO: 37728@% .FON files%@BO: 87899@%%@BO: 87d60@%%@BO: 8a479@% /FPa%@BO: 3826d@% /FPc%@BO: 3737c@%%@BO: 39396@%%@BO: 39bde@% /FPc87%@BO: 37927@% /FPi%@BO: 366b7@%%@BO: 39bde@% /FPi87%@BO: 36f6a@% Function calls near call%@BO: 16856@% C calling convention%@BO: 19198@% FORTRAN/Pascal calling convention%@BO: 19198@%%@BO: 19c0f@% register calling convention%@BO: 19c0f@% _fastcall calling convention%@BO: 19c0f@%%@BO: 1a9ca@%%@BO: 1b06e@%%@BO: 1b6f2@% Functions drive and directory (list)%@BO: eafe2@% graphics (list)%@BO: 82c5e@% initializing%@BO: 68b44@% prototyping%@BO: 69257@% Returning floating-point types%@BO: 32643@% WhenLoaded%@BO: 68b44@% %@2@%%@AB@% G%@AE@%%@EH@%%@NL@% /Gd option%@BO: eb7e9@% Gd option%@BO: 19198@% Graphics video modes default mode%@BO: 7b01e@% graphics mode, defined%@BO: 7b01e@% text mode, defined%@BO: 7b01e@% %@2@%%@AB@% H%@AE@%%@EH@%%@NL@% Help files local help context%@BO: 568ec@% HIMEM.SYS driver%@BO: 7890b@% _huge keyword%@BO: e7371@% _huge Keyword%@BO: 1dce4@% _huge keyword%@BO: 1fe23@%%@BO: 2117b@%%@BO: 21caa@%%@BO: b7caa@%%@BO: b7e65@% %@2@%%@AB@% I%@AE@%%@EH@%%@NL@% IEEE%@BO: 30b59@%%@BO: 34416@%%@BO: 36063@% In-line assembly advantages%@BO: 28854@% In-line Floating-point emulator package%@BO: 366b7@% Floating-point emulator%@BO: 39bde@% Floating-point instructions%@BO: 38cfd@% Floating-point math coprocessor package%@BO: 36f6a@% Floating-point%@BO: 3494a@% Institute of Electrical and Electronics Engineers %@AI@%see%@AE@% IEEE%@NL@%; %@AI@%see%@AE@% %@NL@% %@2@%%@AB@% L%@AE@%%@EH@%%@NL@% Language conventions calling conventions%@BO: 9d0ff@%%@BO: 9d859@% naming conventions%@BO: 9bde5@%%@BO: 9c6f1@%%@BO: 9cf4d@% parameter-passing conventions%@BO: 9e336@%%@BO: 9f33e@% Libraries dynamic-link See DLLs%@BO: c58c8@% import%@BO: c7173@%%@BO: c77ce@% special%@BO: c2ecf@%%@BO: c39de@% LINK /EXEPACK option%@BO: 184e3@% /FARCALLTRANSLATION option%@BO: 16856@% /NODEFAULTLIBRARYSEARCH (/NOD) option%@BO: c1915@%%@BO: c247b@%%@BO: c77ce@% /NOEXTENDEDDICTSEARCH (/NOE) option%@BO: c7d3e@% /NOIGNORECASE (/NOI) option%@BO: c7d3e@% /PACKCODE option%@BO: 17100@% /PACKDATA option%@BO: 1812a@%%@BO: 18322@% /PADCODE option%@BO: 3c4e6@% /PADDATA option%@BO: 3c4e6@%%@BO: 3c641@% /TINY option%@BO: 1df3d@% compatibility (/Lc)%@BO: c1915@% PACKCODE option%@BO: 17bab@% protected-mode (/Lp)%@BO: c1915@%%@BO: c247b@% real-mode (/Lr)%@BO: c1915@%%@BO: c247b@% LLIBCDLL.LIB%@BO: 345ba@% long double%@BO: 30ed4@%%@BO: 32a89@%%@BO: 32d2a@% %@2@%%@AB@% M%@AE@%%@EH@%%@NL@% Macros inherited%@BO: 454a5@% Math coprocessor package%@BO: 33212@%%@BO: 33f87@% In-line%@BO: 36f6a@% %@2@%%@AB@% N%@AE@%%@EH@%%@NL@% _near keyword%@BO: 1fe23@%%@BO: 2117b@%%@BO: 21caa@%%@BO: 9f33e@%%@BO: a0b7f@%%@BO: b7e65@% NO87%@BO: 309cd@%%@BO: 39a6a@% %@2@%%@AB@% O%@AE@%%@EH@%%@NL@% optimise pragma%@BO: 14ce4@%%@BO: 1546c@% Optimization Effect of floating-point math on%@BO: 36063@%%@BO: 381c4@% optimize pragma%@BO: 11ff2@%%@BO: 14815@% OS/2 calling%@BO: bede0@% %@2@%%@AB@% P%@AE@%%@EH@%%@NL@% Process child%@BO: e4420@% debugging multiple processes%@BO: d390b@% Programmer's WorkBench %@AI@%see%@AE@% PWB%@NL@%; %@AI@%see%@AE@% %@NL@% Pseudotargets%@BO: 48ea4@%%@BO: 4922a@% PWB 80x87 option%@BO: 363c0@% Debug Build Options%@BO: 36200@% Emulation calls option%@BO: 36305@% extensions.See C extensions, PWB%@BO: 650a9@% Fast alternate math option%@BO: 3646a@% Global Compile Options%@BO: 36200@% Inline 80x87 Instructions option%@BO: 36658@% Inline Emulation option%@BO: 36526@% Release Build Options%@BO: 36200@% Selecting floating-point options from%@BO: 3494a@% %@2@%%@AB@% R%@AE@%%@EH@%%@NL@% Run-time support of type long double%@BO: 32d2a@% %@2@%%@AB@% S%@AE@%%@EH@%%@NL@% SETUP%@BO: 333b8@% SLLs data segments%@BO: 253a7@% %@2@%%@AB@% T%@AE@%%@EH@%%@NL@% Threads _beginthread function%@BO: cc91d@% _endthread function%@BO: cc91d@% /TINY option%@BO: 1df3d@% Type double%@BO: 30ed4@% float%@BO: 30ed4@% long double%@BO: 30ed4@% Promotion of floating point%@BO: 3234a@% Range of floating-point%@BO: 31d97@% Significance of floating-point%@BO: 30ed4@% Storage requirements for floating-point%@BO: 30ed4@% Widening for floating-point types%@BO: 32170@% Types double%@BO: 32a89@% float%@BO: 32a89@% long double%@BO: 32a89@%%@BO: 32d2a@% %@2@%%@AB@% V%@AE@%%@EH@%%@NL@% Variables Declaring as floating-point types%@BO: 30d03@% Precision with floating-point%@BO: 3210e@% Promotion of floating-point%@BO: 3234a@% Range of floating-point%@BO: 31d97@% Significance of%@BO: 30ed4@% Storage requirements for%@BO: 30ed4@%