home *** CD-ROM | disk | FTP | other *** search
/ Programming Tool Box / SIMS_2.iso / bp_6_93 / bonus / winer / chap5.txt < prev    next >
Text File  |  1994-09-03  |  130KB  |  2,382 lines

  1.                                  CHAPTER 5
  2.  
  3.                            COMPILING AND LINKING
  4.  
  5.  
  6. The final step in the creation of any program is compiling and linking, to
  7. produce a stand-alone .EXE file.  Although you can run a program in the
  8. BASIC editing environment, it cannot be used by others unless they also
  9. have their own copy of BASIC.  In preceding chapters I explained the
  10. fundamental role of the BASIC compiler, and how it translates BASIC source
  11. statements to assembly language.  However, that is only an intermediate
  12. action.  Before a final executable program can be created, the compiled
  13. code in the object file must be joined to routines in the BASIC language
  14. library.  This process is called linking, and it is performed by the LINK
  15. program that comes with BASIC.
  16.      In this chapter you will learn about the many options and features
  17. available with the BASIC compiler and LINK.  By thoroughly understanding
  18. all of the capabilities these programs offer, you will be able to create
  19. applications that are as small and fast as possible.  Many programmers are
  20. content to let the BASIC editor create the final program using the pulldown
  21. menu selections.  And indeed, it is possible to create a program without
  22. invoking BC and LINK manually--many programmers never advance beyond
  23. BASIC's "Make .EXE" menu.  But only by understanding fully the many options
  24. that are available will you achieve the highest performance possible from
  25. your programs.
  26.      I'll begin with a brief summary of the compiling and linking process,
  27. and explain how the two processes interact.  I will then move on to more
  28. advanced aspects of compiling and linking.  BC and LINK are very complex
  29. programs which possess many features and capabilities, and all of their
  30. many options will be described throughout this chapter.  You may also refer
  31. back to Chapter 1, which describes compiling in more detail.
  32.  
  33.  
  34. AN OVERVIEW OF COMPILING AND LINKING
  35. ====================================
  36.  
  37. When you run the BC.EXE compiler, it reads your BASIC source code and
  38. translates some statements directly into the equivalent assembly language
  39. commands.  In particular, integer math and comparisons are converted
  40. directly, as well as integer-controlled DO, WHILE, and FOR loops.  Floating
  41. point arithmetic and comparisons, and string operations and comparisons are
  42. instead translated to calls to existing routines written by the programmers
  43. at Microsoft.  These routines are in the BCOM and BRUN libraries that come
  44. with BASIC.
  45.      As BC compiles your program, it creates an object file (having an .OBJ
  46. extension) that contains both the translated code as well as header
  47. information that LINK needs to create a final executable program.  Some
  48. examples of the information in an object file header are the name of the
  49. original source file, copyright notices, offsets within the file that
  50. specify external procedures whose addresses are not known at compile time,
  51. and code and data segment names.  In truth, most of this header information
  52. is of little or no relevance to the BASIC programmer; however, it is useful
  53. to know that it exists.  All Microsoft-compatible object files use the same
  54. header structure, regardless of the original source language they were
  55. written in.
  56.      The LINK program is responsible for combining the object code that BC
  57. produces with the routines in the BASIC libraries.  A library (any file
  58. with a .LIB extension) is merely a collection of individual object files,
  59. combined one after the other in an organized manner.  A header portion of
  60. the .LIB file holds the name of each object file and the procedure names
  61. contained therein, as well as the offset within the library where each
  62. object module is located.  Therefore, LINK identifies which routines are
  63. being accessed by the BASIC program, and searches the library file for the
  64. procedures with those names.  Once found, a copy of that portion of the
  65. library is then appended to the .EXE file being created.
  66.      LINK can also join multiple object files compiled by BC to create a
  67. single executable program, and it can produce a Quick Library comprised of
  68. one or more object files.  Quick Libraries are used only in the editing
  69. environment, primarily to let BASIC access non-BASIC procedures.  Because
  70. the BASIC editor is really an interpreter and not a true compiler, Quick
  71. Libraries were devised as a way to let you call compiled (or assembled)
  72. subroutines during the development of a program.
  73.      When LINK is invoked it reads the header information in each object
  74. file compiled by BC, and uses that to know which routines in the specified
  75. library or libraries must be added to your program.  Since every external
  76. routine is listed by name, LINK simply examines the library header for the
  77. same name.  It is worth mentioning that BASIC places the name of the
  78. default library in the object file, so you don't have to specify it when
  79. linking.  For example, when you compile a stand-alone program (with the /o)
  80. switch) using BC version 4.5, it places the name BCOM45.LIB in the header.
  81.      BASIC is not responsible for determining where external routines are
  82. located.  If your program uses a PRINT statement, the compiler generates
  83. the instruction CALL 0000:0000, and identifies where in the object file
  84. that instruction is located.  BASIC knows that the print routine will be
  85. located in another segment, and so leaves room for both a segment and
  86. address in the Call instruction.  But it doesn't know where in the final
  87. executable file the print routine will end up.  The absolute address
  88. depends on how many other modules will be linked with the current object
  89. file, and the size of the main program.
  90.      In fact, LINK does not even know in which segment a given routine will
  91. ultimately reside.  While it can resolve all of the code and data addresses
  92. among modules, the absolute segment in which the program will be loaded
  93. depends on whether there are TSR programs in memory, the version of DOS
  94. (and thus its size), and the number of buffers specified in the host PC's
  95. CONFIG.SYS file, among other factors.  Therefore, all .EXE files also have
  96. a header portion to identify segment references.  DOS actually modifies the
  97. program, assigning the final segment values as it loads the program into
  98. memory.  Figure 5.1 shows how DOS, file buffers, and device drivers are
  99. loaded in memory, before any executable programs.
  100.  
  101. ┌─────────────────────┐
  102. │  ROM BIOS routines  │
  103. ├─────────────────────┤
  104. │    Video memory     │
  105. ╞═════════════════════╡ <-- top of DOS memory (640K boundary)
  106. │                     │
  107.  
  108. │   Far heap storage  │
  109.    for dynamic arrays
  110. │                     │
  111.  
  112. ├─────────────────────┤
  113. │    String memory    │
  114. ├─────────────────────┤
  115. │      The stack      │
  116. ├─────────────────────┤
  117. │    Variable data    │
  118. ├─────────────────────┤
  119. │ Compiled BASIC code │
  120. ╞═════════════════════╡ <-- this address is changeable
  121. │     TSR programs    │
  122. ├─────────────────────┤
  123. │    Device drivers   │
  124. ├─────────────────────┤
  125. │ File control blocks │
  126. ├─────────────────────┤
  127. │    File buffers     │
  128. ├─────────────────────┤
  129. │     DOS program     │
  130. ├─────────────────────┤ <-- address 0000:0600
  131. │   BIOS work area    │
  132. ├─────────────────────┤ <-- address 0000:0400
  133. │  Interrupt vectors  │
  134. └─────────────────────┘ <-- bottom of memory
  135.  
  136. Figure 5-1: DOS and BASIC memory organization.
  137.  
  138. It is important to understand that library routines are added to your
  139. program only once, regardless of how many times they are called.  Even if
  140. you use PRINT three hundred times in a program, only one instance of the
  141. PRINT routine is included in the final .EXE file.  LINK simply modifies
  142. each use of PRINT to call the same memory address.  Further, LINK is
  143. generally smart enough to not add all of the routines in the library. 
  144. Rather, it just includes those that are actually called. 
  145.      However, LINK can extract only entire object files from a library.  If
  146. a single object module contains, say, four routines, all of them will be
  147. added, even if only one is called.  For BASIC modules that you write, you
  148. can control which procedures are in which object files, and thus how they
  149. are combined.  But you have no control over how the object modules provided
  150. with BASIC were written.  If the routines that handle POS(0), CSRLIN, and
  151. SCREEN are contained in a single assembly language source file (and they
  152. are), all of them are added to your program even if you use only one of
  153. those BASIC statements.
  154.      Now that you understand what compiling and linking are all about, you
  155. may wonder why it is necessary to know this, or why you would ever want to
  156. compile manually from the DOS command line.  The most important reason is
  157. to control fully the many available compile and link options.  For example,
  158. when you let the BASIC editor compile for you, there is no way to override
  159. BC's default size for the communications receive buffer.  Likewise, the
  160. QuickBASIC editor does not let you specify the /s (string) option that in
  161. many cases will reduce the size of your programs.
  162.      LINK offers many powerful options as well, such as the ability to
  163. combine code segments to achieve faster performance during procedure calls. 
  164. Another important LINK option lets you create an .EXE file that can be run
  165. under CodeView.  Again, these options are not selectable from within the
  166. QuickBASIC environment [but PDS and VB/DOS Pro Edition let you select more
  167. options than QuickBASIC], and they can be specified only by compiling and
  168. linking manually.  All of these options are established via command line
  169. switches, and each will be discussed in turn momentarily.
  170.      Finally, BASIC PDS includes a number of *stub files* which reduce the
  171. size of your programs, although at the expense of decreased functionality. 
  172. For example, if your program does not use the SCREEN statement to enable
  173. graphics mode, a stub file is provided to eliminate graphics support for
  174. the PRINT statement.  BASIC PDS [and the VB/DOS Pro Edition] also support
  175. program overlays, and to use those requires linking manually from DOS.
  176.  
  177.  
  178. COMPILING
  179. =========
  180.  
  181. To compile a program you run BC.EXE specifying the name of the BASIC
  182. program source file.  BC accepts several optional parameters, as well as
  183. many optional command line switches.  The general syntax for BC is as
  184. follows, with brackets used to indicate optional information.
  185.  
  186.      bc program [/options] [, object] [, listfile] [;]
  187.  
  188. In most cases you will simply give the name of the BASIC source file, any
  189. option switches, and a terminating semicolon.  A typical BC command is as
  190. follows:
  191.  
  192.      bc program /o;
  193.  
  194. Here, a BASIC source file named PROGRAM.BAS is being compiled, and the
  195. output object file will be called PROGRAM.OBJ.  The /o option indicates
  196. that the program will be a stand-alone .EXE file that does not require the
  197. BRUN library to be present at runtime.  If the semicolon is omitted, the
  198. compiler will prompt for each of the file name parameters it needs.  For
  199. example, entering bc program /o invokes the compiler, which then prompts
  200. you for the output and listing file names.  Pressing Enter in response to
  201. any prompt tells BC to use the source file's first name.  You may also
  202. start BC with no source file name, and let it prompt for that as well.
  203.      In most cases the default file names are acceptable; however, it is
  204. not uncommon to want the output file placed into a different directory. 
  205. This is done as follows:
  206.  
  207.      bc program, \objdir\ /o;
  208.  
  209. [Note that if the trailing backslash were omitted from \objdir\ above, BC
  210. would create an output file named OBJDIR.OBJ in the root directory.  Of
  211. course, that is not what is intended.  Therefore, a trailing backslash is
  212. added to tell BC to use the default name of PROGRAM.OBJ, and to place that
  213. file in the directory named \OBJDIR.]
  214.      If you are letting BC prompt you for the file names, you would enter
  215. the output path name at that prompt position.  You may also include a drive
  216. letter as part of the path, or a drive letter only to use the default
  217. directory on the specified drive.  The listing that follows shows a typical
  218. BC session that uses prompting.
  219.  
  220.  
  221.      C>bc program /o
  222.  
  223.      Microsoft (R) QuickBASIC Compiler Version 4.50
  224.      (C) Copyright Microsoft Corporation 1982-1988.
  225.      All rights reserved.
  226.      Simultaneously published in the U.S. and Canada.
  227.  
  228.      Object Filename [PROGRAM.OBJ]: d:\objects\ <Enter>
  229.      Source Listing [NUL.LST]: <Enter>
  230.  
  231.      43965 Bytes Free
  232.      43751 Bytes Available
  233.  
  234.          0 Warning Error(s)
  235.          0 Severe Error(s)
  236.      C>
  237.  
  238.  
  239. Although you can override the default file extensions, this is not common
  240. and you shouldn't do that unless you have a good reason to.  For example,
  241. the command BC source.txt , output.out; will compile a BASIC source file
  242. named SOURCE.TXT and create an object module named OUTPUT.OUT.  Since there
  243. are already standard default file extension conventions, I recommend
  244. against using any others you devise.
  245.      The optional list file contains a source listing of the BASIC program
  246. showing the addresses of each program statement, and uses a .LST extension
  247. by default.  There are a number of undocumented options you can specify to
  248. control how the list file is formatted, and these are described later in
  249. this chapter in the section *Compiler Metacommands*.  A list file may also
  250. include the compiler-generated assembly language instructions, and you
  251. specify that with the /a option switch.  All of the various command options
  252. will be discussed in the section following.
  253.      Notice that the positioning of the file name delimiting commas must be
  254. maintained when the object file name is omitted.  If you plan to accept the
  255. default file name but also want to specify a listing file, you must use two
  256. commas like this:
  257.  
  258.      bc source , , listfile;
  259.  
  260. The Bytes Available and Bytes Free messages indicate how much working
  261. memory the compiler has at its disposal, and how much of it remained free
  262. while compiling your program.  BC must keep track of many different kind of
  263. information as it processes your source code, and it uses its own internal
  264. DGROUP memory for that.  For example, every variable that you use must be
  265. remembered, as well as its address.
  266.      When BASIC sees a statement such as X = 100, it must look in its
  267. *symbol table* to see if it has already encountered that variable.  If so,
  268. it creates an assembly language instruction to store the value 100 at the
  269. corresponding address.  Otherwise, it adds the variable X to the table,
  270. assigns a new address for it, and then adds code to assign the value 100 to
  271. that address.  When you use PRINT X later on, BASIC will again search its
  272. table, find the address, and use that when it creates the code that calls
  273. the PRINT routine.
  274.      Other data that BASIC must remember as it works includes the number
  275. and type of arguments for each SUB or FUNCTION that is declared, line label
  276. names and their corresponding addresses, and quoted string constants.  As
  277. you may recall, in Chapter 2 I explained that BC maintains a table of
  278. string constants, and stores each in the final program only once.  Even
  279. when the same quoted string is used in different places in a program, BC
  280. remembers that they are the same and stores only a single copy.  Therefore,
  281. an array is used by BC to store these strings while your program is being
  282. compiled.
  283.      In most cases you can simply ignore the Bytes Available and Bytes Free
  284. messages, since how much memory BASIC used or had available is of no
  285. consequence.  The only exception, of course, is when your program is so
  286. large that BC needed more than was available.  But again, you will receive
  287. an error message when that occurs.  However, if you notice that the Bytes
  288. Free value is approaching zero, you should consider splitting your program
  289. into separate modules.
  290.      The error message display indicates any errors that occurred during
  291. compilation, and if so how many.  This display is mostly a throw-back to
  292. the earlier versions of the BASIC compiler, because they had no development
  293. environment.  These days, most people get their program working correctly
  294. in the BASIC editor, before attempting to compile it.  Of course, there
  295. must still be a facility for reporting errors.
  296.      In most cases, any errors that BC reports will be severe errors. 
  297. These include a mismatched number of parentheses, using a reserved word as
  298. a variable name (for example, PRINT = 12), and so forth.  One example of a
  299. warning error is referencing an array that has not been dimensioned.  When
  300. this happens, BASIC creates the array with a default 11 elements (0 through
  301. 10), and then reports that it did this as a warning.
  302.      One interesting quirk worth mentioning is that BASIC will not let you
  303. compile a program named USER.BAS.  If you enter BC USER, BC assumes that
  304. you intend to enter the entire program manually, statement by statement! 
  305. This too must be a holdover from earlier versions of the compiler; however,
  306. when USER.BAS is specified it will appear that the compiler has crashed,
  307. because nothing happens and no prompt is displayed.  In my testing with
  308. BASIC 7.1, any statements I entered were also ignored, and no object file
  309. was created.
  310.  
  311.  
  312. COMPILER OPTIONS
  313.  
  314. All of the options available for use with the BASIC compiler are described
  315. in this section in alphabetical order.  Some options pertain only to BASIC
  316. 7 PDS, and these are noted in the accompanying discussion.  Each option is
  317. specified by listing it on the BC command line, along with a preceding
  318. forward slash (/).  Also, these options apply to the BC compiler only, and
  319. not necessarily to the QB and QBX editing environments.
  320.  
  321.  
  322. /A
  323.  
  324. The /a (assembly) switch tells BC to include the assembly language source
  325. code it creates in the listing file.  The format of the file was described
  326. in detail in Chapter 4, so I won't belabor that here.  Note, however, that
  327. a file name must be given in the list file position of the BC command line. 
  328. Otherwise, a list file will not be written.
  329.  
  330.  
  331. /Ah
  332.  
  333. Using /ah (array huge) tells BASIC that you plan to create dynamic arrays
  334. that may exceed 64K in total data size.  This option affects numeric, TYPE,
  335. and fixed-length string arrays only, and not conventional string arrays. 
  336. Normally, BASIC calculates the element addresses for array references
  337. directly, based on the segment and other information in the array
  338. descriptor.  This is the most direct method, and thus provides the fastest
  339. performance and smallest code.
  340.      When /ah is used, all access to non-string dynamic arrays is instead
  341. made through a called routine.  This called routine calculates the segment
  342. and address of a single array element, and because it must also manipulate
  343. segment values, increases the size of your programs.  Therefore, /ah should
  344. be avoided unless you truly need the ability to create huge arrays.  Even
  345. if a particular array does not currently exceed the 64K segment limit,
  346. BASIC has no way to know that when it compiles your program.
  347.      To minimize the size and speed penalty /ah imposes, it may be used
  348. selectively on only some of the source modules in a program.  If you have
  349. one subprogram that needs to manipulate huge arrays but the rest of program
  350. does not, you should create a separate file containing only that subprogram
  351. and compile it using /ah.  When the program is linked, only that module's
  352. array accesses will be slower.
  353.      Note that the /ah switch is also needed if you plan to create huge
  354. arrays when running programs in the BASIC editor.  However, with the BASIC
  355. editor, using /ah does not impinge on available memory or make the program
  356. run slower.  Rather, it merely tells BASIC not to display an error message
  357. when an array is dimensioned to a size greater than 64K.  [The BASIC editor
  358. always uses the slower code that checks for illegal array elements anyway,
  359. so it can report an error rather than lock up your computer.]
  360.      One limitation that /ah will not overcome is BASIC's limit of 32,767
  361. elements in a single dimension.  That is, the statement REDIM Array%(1 to
  362. 32768) will fail, regardless of whether /ah is used.  There are two ways to
  363. exceed this limit: one is to create a TYPE array in which each element is
  364. comprised of two or more variables.  The other is to create an array that
  365. has more than one dimension.  The brief program below shows how to access a
  366. 2-dimensional array as if it had only a single dimension.
  367.  
  368.  
  369. DEFINT A-Z
  370.  
  371. '----- pick an arbitrary group size, and number of groups (in this
  372. '      case 100,000 elements)
  373. GroupSize = 1000: NumGroups = 100
  374.  
  375. '----- dimension the array
  376. REDIM Array(1 TO GroupSize, 1 TO NumGroups)
  377.  
  378. '----- pick an element number to assign (note use of a long integer)
  379. Element& = 50000
  380.  
  381. '----- calculate the first and second subscripts
  382. First = ((Element& - 1) MOD GroupSize) + 1
  383. Second = (Element& - 1) \ GroupSize + 1
  384.  
  385. '----- assign the appropriate array element 
  386. Array(First, Second) = 123
  387.  
  388. '----- show how to derive the original element based on First and 
  389. '      Second (CLNG is needed to prevent an Overflow error)
  390. CalcEl& = First + (Second - 1) * CLNG(GroupSize)
  391.  
  392.  
  393.  
  394. /C
  395.  
  396. The /c (communications) option lets you specify the size of the receive
  397. buffer when writing programs that open the COM port.  The value specified
  398. represents the total buffer size in bytes, and is shared when two ports are
  399. open at once.  For example, if two ports are open and the total buffer size
  400. is 4096 bytes, then each port has 2048 bytes available for itself.
  401.      A receive buffer is needed when performing communications, and it
  402. accumulates the incoming characters as they are received.  Each time a
  403. character is accepted by the serial port, it is placed into the receive
  404. buffer automatically.  When your program subsequently uses INPUT or INPUT$
  405. or GET to read the data, it is actually reading the characters from the
  406. buffer and not from the hardware port.  Without this buffering, your
  407. program would have to wait in a loop constantly looking for each character,
  408. which would preclude it from doing anything else!
  409.      Communications data is received in a continuous stream, and each byte
  410. must be processed before the next one arrives, otherwise the data will be
  411. lost.  The communications port hardware generates an interrupt as each
  412. character is received, and the communications routines within BASIC act on
  413. that interrupt.  The byte is retrieved from the hardware port using an
  414. assembly language IN instruction, which is equivalent to BASIC's INP
  415. function.  This allows the characters to accumulate in the background,
  416. without any additional effort on your part.
  417.      As each byte is received it is placed into the buffer, and a pointer
  418. is updated showing the current ending address within the buffer.  As your
  419. program reads those bytes, another pointer is updated to show the new
  420. starting address within the buffer.  This type of buffer is called a
  421. *circular buffer*, because the starting and ending buffer addresses are
  422. constantly changing.  That is, the buffer's end point "wraps" around to the
  423. beginning when it becomes full.
  424.      The receive buffer whose size is specified with /c is located in far
  425. memory.  However, BASIC also maintains a second buffer in near memory, and
  426. its size is dictated by the optional LEN= argument used with the OPEN
  427. statement.  Because near memory can be accessed more quickly than far
  428. memory, it is sensible for BASIC to copy a group of characters from the far
  429. receive buffer to the near buffer all at once, rather than individually
  430. each time you use GET or INPUT$.
  431.      When /c is not specified, the buffer size defaults to 512 bytes.  This
  432. means that up to 512 characters can be received with no intervention on
  433. your part.  If more than 512 bytes arrive and your program still hasn't
  434. removed them using INPUT$ or GET, new characters that come later will be
  435. lost.  It is also possible to stipulate hardware handshaking when you open
  436. the communications port.  This means that the sender and receiver use
  437. physical control wires to indicate when the buffer is full, and when it is
  438. okay to resume transmitting.
  439.      In many programming situations, the 512 byte default will be more than
  440. adequate.  However, if many characters are being received at a high baud
  441. rate (9600 or greater) and your program is unable to accept and process
  442. those characters quickly enough, you should consider using a larger buffer. 
  443. Fortunately, the buffer is located in far memory, so increasing its size
  444. will not impinge on available string and data stored in DGROUP.
  445.  
  446.  
  447. /D
  448.  
  449. The /d (debug) option switch is intended solely to help you find problems
  450. in a program while it is being developed.  Because /d causes BC to generate
  451. additional code and thus bloat your executable program, it should be used
  452. only during development.
  453.      When /d is specified, four different types of tests are added to your
  454. program.  The first is a call to a routine that checks if Ctrl-Break has
  455. been pressed.  One call is added for every BASIC source statement, and each
  456. adds five bytes of code to your final executable program.  The second
  457. addition is a one-byte assembly language INTO instruction following each
  458. integer and long integer math operation, to detect overflow errors.
  459.      The third is a call to a routine that calculates array element
  460. addresses, to ensure that the element number is in fact legal.  Normally,
  461. element addresses are computed directly without checking the upper and
  462. lower bounds, unless you are using huge (greater than 64K) arrays.  Without
  463. /d, it is therefore possible to corrupt memory by assigning an element that
  464. doesn't exist.
  465.       The final code addition implements GOSUB and RETURN statements using
  466. a library routine, rather than calling and returning from the target line
  467. directly.  Normally, a GOSUB statement is translated into a three-byte
  468. assembly language *near call* instruction, and a RETURN is implemented
  469. using a one-byte *near return*.  But when /d is used, the library routines
  470. ensure that each RETURN did in fact result from a corresponding GOSUB, to
  471. detect RETURN without GOSUB errors.  This is accomplished by incrementing
  472. an internal variable each time GOSUB is used, and decrementing it at each
  473. RETURN.  If that variable is decremented below 0 during a RETURN statement,
  474. then BASIC knows that there was no corresponding GOSUB.  These library
  475. routines are added to your program only once by LINK, and comprise only a
  476. few bytes of code.  However, a separate five-byte call is generated for
  477. each GOSUB and RETURN statement.
  478.      Many aspects of the /d option were described in detail in Chapters 1
  479. and 4, and there is no need to repeat that information here.  But it is
  480. important to remember that /d always makes your programs larger and run
  481. more slowly.  Therefore, it should be avoided once a program is running
  482. correctly.
  483.  
  484.  
  485. /E
  486.  
  487. The /e (error) option is necessary for any program that uses ON ERROR or
  488. RESUME with a line label or number.  In most cases using /e adds little or
  489. no extra code to your final .EXE program, unless ON ERROR and RESUME are
  490. actually used, or unless you are using line numbers.  For each line number,
  491. four bytes are added to remember the number itself as well as its position
  492. in the file [two bytes each].  As with /d, every GOSUB and RETURN statement
  493. is implemented through a far call to a library routine, rather than by
  494. calling the target line directly.  Without this added protection it would
  495. not be possible to trap "RETURN without GOSUB" errors correctly, or recover
  496. from them in an ON ERROR handler.
  497.      Also see the /x option which is needed when RESUME is used alone, or
  498. with a 0 or NEXT argument.  The /x switch is closely related to /e, and is
  499. described separately below.
  500.  
  501.  
  502. /Fpa and /Fpi (BASIC PDS and later)
  503.  
  504. When Microsoft introduced their BASIC compiler version 6.0, they included
  505. an alternate method for performing floating point math.  This Floating
  506. Point Alternate library (hence the /fpa) offered a meaningful speed
  507. improvement over the IEEE standard, though at a cost of slightly reduced
  508. accuracy.  This optional math library has been continued with BASIC 7 PDS,
  509. and is specified using the /fpa command switch.
  510.      By default, two parallel sets of floating point math routines are
  511. added to every program.  When the program runs, code in BASIC's runtime
  512. startup module detects the presence of a math coprocessor chip, and selects
  513. which set of math routines will be used.  The coprocessor version is called
  514. the Inline Library, and it merely serves as an interface to the 80x87 math
  515. coprocessor that does the real work in its hardware.  (Note that inline is
  516. really a misnomer, because that term implies that the compiler generates
  517. coprocessor instructions directly.  It doesn't.)  The second version is
  518. called the Emulator Library, because it imitates the behavior of the
  519. coprocessor using assembly language subroutines.
  520.      Although the ability to take advantage of a coprocessor automatically
  521. is certainly beneficial, there are two problems with this dual approach:
  522. code size and execution speed.  The coprocessor version is much smaller
  523. than the routines that perform the calculations manually, since it serves
  524. only as an interface to the coprocessor chip itself.  When a coprocessor is
  525. in fact present, the entire emulator library is still loaded into memory. 
  526. And when a coprocessor is not installed in the host PC, the library code to
  527. support it is still loaded.  The real issue, however, is that each BASIC
  528. math operation requires additional time to route execution to the
  529. appropriate routines.
  530.      Since BC has no way to know if a coprocessor will be present when the
  531. program eventually runs, it cannot know which routine names to call. 
  532. Therefore, BASIC uses a system of software interrupts that route execution
  533. to one library or the other.  That is, instead of using, say, CALL
  534. MultSingle, it instead creates code such as INT 39h.  The Interrupt 39h
  535. vector is set when the program starts to point to the correct library
  536. routine.  Unfortunately, the extra level of indirection to first read the
  537. interrupt address and then call that address impacts the program's speed.
  538.      Recall that Chapter 1 explained how the library routines in a BRUN-
  539. style program modify the caller's code the first time they are invoked. 
  540. The compiler creates code that uses an interrupt to access the library
  541. routines, and those routines actually rewrite that code to produce a direct
  542. call.  Although this code modification increases the time needed to call a
  543. library routine initially, subsequent calls will be noticeably faster. 
  544. BASIC statements executed many times within a FOR or DO loop will show the
  545. greatest improvement, but statements executed only once will be much slower
  546. than usual.
  547.      In a similar fashion, the coprocessor routines that are in BASIC's
  548. runtime library alter the caller's code, replacing the interrupt commands
  549. with equivalent coprocessor instructions.  Each floating point interrupt
  550. that BC generates includes the necessary variable addresses and other
  551. arguments within the caller's code.  These arguments are in the same format
  552. as a coprocessor instruction.  The first time an interrupt is invoked, it
  553. subtracts the "magic value" &H5C32 from the bytes that comprise the
  554. interrupt instruction, thus converting the instruction into a coprocessor
  555. command.  This will be covered in Chapter 12 and I won't belabor it here.
  556.      Since the alternate floating point math routines do not use a
  557. coprocessor even if one is present, the interrupt method is not necessary. 
  558. BC simply hardcodes the library subroutine names into the generated code,
  559. and the program is linked with the alternate math library.  Besides the
  560. speed improvement achieved by avoiding the indirection of interrupts, the
  561. alternate math library is also inherently faster than the emulator library
  562. when a coprocessor is not present.
  563.      The /fpi switch tells BASIC to use its normal method of including both
  564. the coprocessor and emulator math libraries in the program, and determining
  565. which to use at runtime.  (See the discussion of /fpa above.)  Using /fpi
  566. is actually redundant and unnecessary, because this is the default that is
  567. used if no math option is specified.
  568.  
  569.  
  570. /Fs  (BASIC PDS only)
  571.  
  572. BASIC PDS offers an option to use far strings, and this is specified with
  573. the /fs (far strings) switch.  Without /fs, all conventional (not fixed-
  574. length) string variables and string arrays are stored in the same 64K
  575. DGROUP memory that holds numeric variables, DATA items, file buffers, and
  576. static numeric and TYPE arrays.  Using the /fs option tells BASIC to
  577. instead store strings and file buffers in a separate segment in far memory.
  578.      Although a program using far strings can subsequently hold more data,
  579. the capability comes at the expense of speed and code size.  Obviously,
  580. more code is required to access strings that are stored in a separate data
  581. segment.  Furthermore, the string descriptors are more complex than when
  582. near strings are used, and the code that acts on those descriptors requires
  583. more steps.  Therefore, you should use /fs only when truly necessary, for
  584. example when BASIC reports an Out of string space error.
  585.      Far versus near strings were discussed in depth in Chapter 2, and you
  586. should refer to that chapter for additional information.
  587.      [One very unfortunate limitation of VB/DOS is that only far strings
  588. are supported.  The decision makers at Microsoft apparently decided it was
  589. too much work to also write a near-strings version of the forms library. 
  590. So users of VB/DOS are stuck with the additional size and speed overhead of
  591. far strings, even for small programs that would have been better served
  592. with near strings.]
  593.  
  594.  
  595. /G2  (BASIC PDS and later)
  596.  
  597. The /g2 option tells BASIC to create code that takes advantage of an 80286
  598. or later CPU.  Each new generation of Intel microprocessors has offered
  599. additional instructions, as well as performance optimizations to the
  600. internal microcode that interprets and executes the original instructions. 
  601. When an existing instruction is recoded and improved within the CPU, anyone
  602. who owns a PC using the newer CPU will benefit from the performance
  603. increase.  For example, the original 8086/8088 had several instructions
  604. that performed poorly.  These include Push and Pop, and Mul and Div.  When
  605. Intel released the 80186, they rewrote the microcode that performs those
  606. instructions, increasing their speed noticeably.  The 80286 is an offshoot
  607. of the 80186, and of course includes the same optimizations.  The 80386 and
  608. 80486 offer even more improvements and additions to the original 8086
  609. instruction set.
  610.      Besides the enhancements to existing instructions, newer CPU types
  611. also include additional instructions not present in the original 8086.  For
  612. example, the 80286 offers the Enter and Leave commands, each of which can
  613. replace a lengthy sequence of instructions on the earlier microprocessors. 
  614. Another useful enhancement offered in the 80286 is the ability to push
  615. numbers directly onto the stack.  Where the 8086 can use only registers as
  616. arguments to Push, the instructions Push 1234 and Push Offset Variable are
  617. legal with 80186 and later CPUs.  Likewise, the 80386 offers several new
  618. commands to directly perform long integer operations.  For example, adding
  619. two long integer values using the 8086 instruction set requires a number of
  620. separate steps.  The 80386 and later CPUs can do this using only one
  621. instruction.
  622.      If you are absolutely certain that your program will be run only on
  623. PCs with an 80286 or later microprocessor, the /g2 option can provide a
  624. modest improvement in code size and performance.  In particular, programs
  625. that use /g2 can save one byte each time a variable address is passed to a
  626. routine.  When /g2 is not used, the command PRINT Work$ results in the code
  627. shown below.
  628.  
  629.  
  630. PRINT Work$
  631.   Mov  AX,Offset Work$    'this requires 3 bytes
  632.   Push AX                 'this requires 1 byte
  633.   Call B$PESD             'a far call is 5 bytes
  634.  
  635.  
  636.  
  637. When /g2 is used, the address is pushed directly rather than first being
  638. loaded into AX, as shown following.
  639.  
  640.  
  641. PRINT Work$
  642.   Push Offset Work$       'this requires 3 bytes
  643.   Call B$PESD             'this call is 5 bytes
  644.  
  645.  
  646. With the rapid proliferation of 80386 and 80486 [and Pentium] computers,
  647. Microsoft should certainly consider adding a /g3 switch.  Taking advantage
  648. of 80386 instructions could provide substantially more improvement over
  649. 80286 instructions than the 80286 provides beyond the 8086.
  650.      [In fact, Microsoft has added a /g3 switch to VB/DOS.  Unfortunately,
  651. it does little more than the /g2 switch.  Most of a program's execution is
  652. spent running code inside the Microsoft-supplied runtime libraries.  But
  653. those libraries contain only 8088 code!  Using /g2 and /g3 affect only the
  654. compiler-generated code, which has little impact on a program's overall
  655. performance.  Until Microsoft writes additional versions of their runtime
  656. libraries using 80386 instructions (yeah, right), using /g2 or /g3 will
  657. offer very little practical improvement.]
  658.  
  659.  
  660. /Ix  (BASIC PDS and later)
  661.  
  662. Another important addition to BASIC 7 PDS is its integral ISAM data file
  663. handler.  Microsoft's ISAM (Indexed Sequential Access Method) offers three
  664. key features: The first is indexing, which lets you search a data file very
  665. quickly.  A simple sequential search reads each record from the disk in
  666. order until the desired information is found.  That is, to find the record
  667. for customer David Eagle you would start at the beginning of the file, and
  668. read each record until you found the one containing that name.  An index
  669. system, on the other hand, keeps as many names in memory as will fit, and
  670. searches memory instead of the disk.  This is many time faster than reading
  671. the disk repeatedly.  If Mr. Eagle is found in, say, the 1200th position,
  672. the index manager can go directly to the corresponding record on disk and
  673. return the data it contains.
  674.      The second ISAM feature is its ability to maintain the data file in
  675. sorted order.  In most situations, records are stored in a data file in the
  676. order they were originally entered.  For example, with a sales database,
  677. each time a customer purchases a product a new record is added holding the
  678. item and price for the item.  When you subsequently step through the data
  679. file, the entries will most likely be ordered by the date and time they
  680. were entered.  ISAM lets you access records in sorted order--for example,
  681. alphabetically by the customer's last name--regardless of the order in
  682. which the data was actually entered.
  683.      The last important ISAM feature is its ability to establish
  684. relationships between files, based on the information they contain.  Many
  685. business applications require at least two data files: one to hold names
  686. and addresses of each customer which rarely changes, and another to hold
  687. the products or other items that are ordered periodically.  It would be
  688. impractical and wasteful to duplicate the name and address information
  689. repeatedly in each product detail record.  Instead, many database programs
  690. store a unique customer number in each record.  Then, it is possible to
  691. determine which sales record goes with which customer based on the matching
  692. numbers in both files.  A program that uses this technique is called a
  693. *relational database*.
  694.      To help the BASIC ISAM routines operate efficiently, you are required
  695. to provide some information when compiling your program.  Each of the /i
  696. switches requires a letter indicating which option is being specified, and
  697. a numeric value.  For each field in the file that requires fast (indexed)
  698. access, ISAM must reserve a block of memory for file buffers.  This is the
  699. purpose of the /ii: switch.  Notice that /ii: is needed only if more than
  700. 30 indexes will be active at one time.
  701.      The /ie: option tells ISAM how much EMS memory to reserve for buffers,
  702. and is specified in kilobytes.  This allows other applications to use the
  703. remaining EMS for their own use.
  704.      The /ib: option switch tells ISAM how many 2K (2048-byte) *page
  705. buffers* to create in memory.  In general, the more memory that is reserved
  706. for buffers, the faster the ISAM program can work.  Of course, each buffer
  707. that you specify reduces the amount of memory that is available for other
  708. uses in your program.
  709.      An entire chapter in the BASIC PDS manual is devoted to explaining the
  710. ISAM file system, and there is little point in duplicating that information
  711. here.  Please refer to your BASIC documentation for more examples and
  712. tutorial information on using ISAM.  In particular, advice and formulas are
  713. given that show how to calculate the numeric values these options require.
  714.      In Chapter 6 I will cover file handling and indexing techniques in
  715. detail, with accompanying code examples showing how you can create your own
  716. indexing methods.
  717.  
  718.  
  719. /Lp And /Lr  (BASIC PDS only)
  720.  
  721. BASIC 7 PDS includes an option to write programs that operate under OS/2,
  722. as well as MS-DOS.  Although OS/2 has yet to be accepted by most PC users,
  723. many programmers agree that it offers a number of interesting and powerful
  724. capabilities.  By default, BC compiles a program for the operating system
  725. that is currently running.  If you are using DOS when the program is
  726. compiled and linked, the resultant program will also be for use with DOS. 
  727. Similarly, if you are currently running OS/2, then the program will be
  728. compiled and linked for use with that operating system.
  729.      The /lp (protected) switch lets you override the assumption that BC
  730. makes, and tell it to create OS/2 instructions that will run in protected
  731. mode.  The /lr (real) option tells BC that even though you are currently
  732. running under OS/2, the program will really be run with DOS.  Again, these
  733. switches are needed only when you need to compile for the operating system
  734. that is not currently in use.
  735.  
  736.  
  737. /Mbf
  738.  
  739. With the introduction of QuickBASIC 4.0, Microsoft standardized on the IEEE
  740. format for floating point data storage.  Earlier versions of QuickBASIC and
  741. GW-BASIC used a faster, but non-standard proprietary numeric format that is
  742. incompatible with other compilers and languages.  In many cases, the
  743. internal numeric format a compiler uses is of little consequence to the
  744. programmer.  After all, the whole point of a high-level language is to
  745. shield the programmer from machine-specific details.
  746.      One important exception is when numeric data is stored in a disk file. 
  747. While it is certainly possible to store numbers as a string of ASCII
  748. characters, this is not efficient.  As I described in Chapter 2, converting
  749. between binary and decimal formats is time consuming, and also wastes disk
  750. space.  Therefore, BASIC (and most other languages) write numeric data to a
  751. file using its native fixed-length format.  That is, integers are stored in
  752. two bytes, and double-precision data in eight.
  753.      Although QuickBASIC 4 and later compilers use the IEEE format for
  754. numeric data storage, earlier version of the compiler do not.  This means
  755. that values written to disk by programs compiled using earlier version of
  756. QuickBASIC or even GW-BASIC cannot be read correctly by programs built
  757. using the newer compilers.  The /mbf option tells BASIC that it is to
  758. convert to the original Microsoft Binary Format (hence the MBF) prior to
  759. writing those values to disk.  Likewise, floating point numbers read from
  760. disk will be converted from MBF to IEEE before being stored in memory. 
  761. [Even when /mbf is used, all floating point numbers are still stored in
  762. memory and manipulated using the IEEE method.  It is only when numbers are
  763. read from or written to disk that a conversion between MBF and IEEE format
  764. is performed.]
  765.      Notice that current versions of Microsoft BASIC also include functions
  766. to convert between the MBF and IEEE formats manually.  For example, the
  767. statement Value# = CVDMBF(Fielded$) converts the MBF-format number held in
  768. Fielded$, and assigns an IEEE-format result to Value#.  When /mbf is used,
  769. however, you do not have to perform this conversion explicitly, and using
  770. Value# = CVD(Fielded$) provides the identical result.
  771.      Also see the data format discussion in Chapter 2, that compares the
  772. IEEE and MBF storage methods in detail.
  773.  
  774.  
  775. /O
  776.  
  777. BASIC can create two fundamentally different types of .EXE programs:  One
  778. type is a stand-alone program that is completely self-contained.  The other
  779. type requires the presence of a special runtime .EXE library file when it
  780. runs, which contains the routines that handle all of BASIC's commands.  By
  781. default, BASIC creates a program that requires the runtime .EXE library,
  782. which produces smaller program files.  However, the runtime library is also
  783. needed, and is loaded along with the program into memory.  The differences
  784. between the BRUN and BCOM programs were described in detail in Chapter 1.
  785.      The /o switch tells BASIC to create a stand-alone program that does
  786. not require the BRUN library to be present.  Notice that when /o is used,
  787. the CHAIN command is treated as if you had used RUN, and COMMON variables
  788. may not be passed to a subsequently executed program.
  789.  
  790.  
  791. /Ot  (BASIC PDS and later)
  792.  
  793. Each time you invoke a BASIC subprogram, function, or DEF FN function, code
  794. BC adds to the subprogram or function creates a stack frame that remembers
  795. the caller's segment and address.  Normally, Call and Return statements in
  796. assembly language are handled directly by the microprocessor.  DEF FN
  797. functions and GOSUB statements are translated by the compiler into near
  798. calls, which means that the target address is located in the same segment. 
  799. Invoking a formal function or subprogram is instead treated as a far call,
  800. to support multiple segments and thus larger programs.  Therefore, a RETURN
  801. or EXIT DEF statement assumes that a single address word is on the stack,
  802. where EXIT SUB or EXIT FUNCTION expect both a segment and address to be
  803. present (two words).
  804.      A problem can arise if you invoke a GOSUB routine within a SUB or
  805. FUNCTION procedure, and then attempt to exit the procedure from inside that
  806. subroutine with EXIT SUB or EXIT FUNCTION.  If a GOSUB is active, EXIT SUB
  807. will incorrectly return to the segment and address that are currently on
  808. the stack.  Unfortunately, the address is that of the statement following
  809. the GOSUB, and the "segment" is in fact the address portion of the original
  810. caller's return location.  This is shown in Figure 5-2.
  811.  
  812.  
  813. ┌── This is the original caller's segment and address to return to.
  814. │   │                         │
  815. │   ├─────────────────────────┤
  816. ├─> │ Caller's return segment │
  817. │   ├─────────────────────────┤
  818. └─> │ Caller's return address │ <─┐
  819.     ├─────────────────────────┤   │
  820.     │ GOSUB's return address  │ <─┤
  821.     ├─────────────────────────┤   │
  822.     │(next available location)│   │
  823.     ├─────────────────────────┤   │
  824.                                   │
  825.     │                         │   │
  826.                                   │
  827.                                   │
  828. These addresses will incorrectly ─┘
  829. be used as a segment and address.
  830.  
  831.  
  832. Figure 5.2: The stack frame within a procedure while a GOSUB is pending.
  833.  
  834. To avoid this potential problem, the original caller's segment and address
  835. are saved when a subprogram or function is first invoked.  The current
  836. stack pointer is also saved, so it can be restored to the correct value, no
  837. matter how deeply nested GOSUB calls may become.  Then when the procedure
  838. is exited, another library routine is called that forces the originally
  839. saved segment and address to be on the stack in the correct position.
  840.      Because this process reduces the speed of procedure calls and adds to
  841. the resultant code size, the /ot option was introduced with BASIC 7 PDS. 
  842. Using /ot tells BASIC not to employ the larger and slower method, unless
  843. you are in fact using a GOSUB statement within a procedure.  Since this
  844. optimization is disabled automatically anyway in that case, it is curious
  845. that Microsoft requires a switch at all.  That is, BC should simply
  846. optimize procedure calls where it can, and use the older method only when
  847. it has to.
  848.  
  849.  
  850. /R
  851.  
  852. The /r switch tells BASIC to store multi-dimensioned arrays in row, rather
  853. than column order.  All arrays, regardless of their type, are stored in a
  854. contiguous block of memory.  Even though string data can be scattered in
  855. different places, the table of descriptors that comprise a string array is
  856. contiguous.  When you dimension an array using two or more subscripts, each
  857. group of rows and columns is placed immediately after the preceding one. 
  858. By default, BASIC stores multi-dimensioned arrays in column order, as shown
  859. in Figure 5-3.
  860.  
  861.  
  862. ┌─────────────┐
  863. │ Array(5, 2) │   ^
  864. ├─────────────┤   │
  865. │ Array(4, 2) │   │
  866. ├─────────────┤   │
  867. │ Array(3, 2) │   └── toward higher addresses
  868. ├─────────────┤
  869. │ Array(2, 2) │
  870. ├─────────────┤
  871. │ Array(1, 2) │
  872. ├─────────────┤
  873. │ Array(5, 1) │
  874. ├─────────────┤
  875. │ Array(4, 1) │
  876. ├─────────────┤
  877. │ Array(3, 1) │
  878. ├─────────────┤
  879. │ Array(2, 1) │
  880. ├─────────────┤
  881. │ Array(1, 1) │
  882. └─────────────┘
  883.  
  884. Figure 5.3: How BASIC stores a 2-dimensional array dimensioned created
  885. using DIM Array(1 TO 5, 1 TO 2).
  886.  
  887. As you can see, each of the elements in the first subscript are stored in
  888. successive memory locations, followed each of the elements in the second
  889. subscript.  In some situations it may be necessary to maintain arrays in
  890. row order, for example when interfacing with another language that expects
  891. array data to be organized that way [notably FORTRAN].  When an array is
  892. stored in row order, the elements are arranged such that Array(1, 1) is
  893. followed by Array(1, 2), which is then followed by Array(2, 1), Array(2,
  894. 2), Array(3, 1), and so forth.
  895.      Although many of the BC option switches described here are also
  896. available for use with the QB editing environment, /r is not one of them.
  897.  
  898.  
  899. /S
  900.  
  901. The /s switch has been included with BASIC since the first BASCOM 1.0
  902. compiler, and it remains perhaps the least understood of all the BC
  903. options.  Using /s affects your programs in two ways.  The first is
  904. partially described in the BASIC manuals, which is to tell BC not to
  905. combine like string constants as it compiles your program.  As you learned
  906. in Chapter 2, BASIC makes available as much string memory as possible in
  907. your programs, by consolidating identical constant string data.  For
  908. example, if you have the statement PRINT "Insert disk in drive A" seven
  909. times in your program, the message is stored only once, and used for each
  910. instance of PRINT.
  911.      In order to combine like data the BC compiler examines each string as
  912. it is encountered, and then searches its own memory to see if that string
  913. is already present.  Having to store all of the strings your program uses
  914. just to check for duplicates impinges on BC's own working memory.  At some
  915. point it will run out of memory, since it also has to remember variable and
  916. procedure names, line labels and their corresponding addresses, and so on.
  917. When this happens, BC has no recourse but to give up and display an "Out of
  918. memory" error message.
  919.      The /s switch is intended to overcome this problem, because it tells
  920. the compiler not to store your program's string constants.  Instead of
  921. retaining the strings in memory for comparison, each is simply added to the
  922. object file as it is encountered.  However, strings four characters long or
  923. shorter are always combined, since short strings are very common and doing
  924. that does not require much of BC's memory.
  925.      The second [undocumented] thing /s does is to add two short (eight
  926. bytes each) assembly language subroutines to the very beginning of your
  927. program.  Two of the most common string operations are assignments and
  928. concatenations, which are handled by routines in the runtime library. 
  929. Normally, a call to either of these routines generates thirteen bytes of
  930. code, including the statements that pass the appropriate string addresses.
  931.      The subroutines that /s adds are accessed using a near rather than a
  932. far call, and they receive the string addresses in CPU registers rather
  933. than through the stack.  Therefore, they can be called using between three
  934. and nine bytes, depending on whether the necessary addresses are already in
  935. the correct registers at the time.  The inevitable trade-off, however, is
  936. that calling one subroutine that in turn calls another reduces the speed of
  937. your programs slightly.
  938.      In many cases--especially when there are few or no duplicated string
  939. constants--using /s will reduce the size of your programs.  This is
  940. contrary to the Microsoft documentation which implies that /s will make
  941. your programs larger because the duplicate strings are not combined.  I
  942. would like to see Microsoft include this second feature of /s as a separate
  943. option, perhaps using /ss (string subroutine) as a designator.
  944.  
  945.  
  946. /T
  947.  
  948. The /t (terse) switch tells BC not to display its copyright notice or any
  949. warning (non-fatal) error messages.  This option was not documented until
  950. BASIC PDS, even though it has been available since at least QuickBASIC 4.0. 
  951. The only practical use I can see for /t is to reduce screen clutter, which
  952. is probably why QB and QBX use it when they shell to DOS to create an .EXE
  953. program.
  954.  
  955.  
  956. /V and /W
  957.  
  958. Any programs that use event handling such as ON KEY, ON COM, ON PLAY, or
  959. the like [but not ON GOTO or ON GOSUB] require that you compile using
  960. either the /v or /w option switches.  These options do similar things,
  961. adding extra code to call a central handler that determines if action is
  962. needed to process an event.  However, the /v switch checks for events at
  963. every program statement while /w checks only at numbered or labeled lines.
  964.      In Chapter 1 I described how event handling works in BASIC, using
  965. polling rather than true interrupt handling.  There you saw how a five-byte
  966. call is required each time BASIC needs to see if an event has occurred. 
  967. Because of this added overhead, many programmers prefer to avoid BASIC's
  968. event trapping statements in favor of manually polling when needed. 
  969. However, it is important to point out that by using line numbers and labels
  970. sparingly in conjunction with /w, you can reduce the amount of extra code
  971. BASIC creates thus controlling where such checking is performed.
  972.  
  973.  
  974. /X
  975.  
  976. Like the /e switch, /x is used with ON ERROR and RESUME; however, /x
  977. increases substantially the size of your final .EXE program file.  When
  978. RESUME, RESUME 0, or RESUME NEXT are used, BASIC needs a way to find where
  979. execution is to resume in your program.  Unfortunately, this is not a
  980. simple task.  Since a single BASIC source statement can create a long
  981. series of assembly language commands, there is no direct correlation
  982. between the two.  When an error occurs and you use RESUME with no argument
  983. telling BASIC to execute the same statement again, it can't know directly
  984. how many bytes earlier that statement begins.
  985.      Therefore, when /x is specified, a numbered line marker is added in
  986. the object code to identify the start of every BASIC source statement. 
  987. These markers comprise a linked list of statement addresses, and the RESUME
  988. statement walks through this list looking for the address that most closely
  989. precedes the offending BASIC statement.  Because of the overhead to store
  990. these addresses--four bytes for each BASIC source statement--many
  991. professional programmers avoid using /x unless absolutely necessary. 
  992. However, the table of addresses is stored within the code segment, and does
  993. not take away from DGROUP memory.
  994.  
  995.  
  996. /Z  (BASIC PDS and later)
  997.  
  998. The /z switch is meant to be used in conjunction with the Microsoft editor. 
  999. This editor is included with BASIC PDS, and allows editing programs that
  1000. are too large to be contained within the QB and QBX editing environments. 
  1001. When a program is compiled with /z, BASIC includes line number information
  1002. in the object file.  The Microsoft editor can then read these numbers after
  1003. an unsuccessful compile, to help you identify which lines were in error. 
  1004. Because the addition of these line number identifiers increases a program's
  1005. size, /z should be used only for debugging and not in a final production.
  1006.      In general, the Microsoft editor has not been widely accepted by BASIC
  1007. programmers, primarily because it is large, slow, and complicated to use. 
  1008. Microsoft also includes a newer editing environment called the Programmer's
  1009. Workbench with BASIC PDS; however, that too is generally shunned by serious
  1010. developers for the same reasons.
  1011.  
  1012.  
  1013. /Zd
  1014.  
  1015. Like /z, the /zd switch tells BC to include line number information in the
  1016. object file it creates.  Unlike /zi which works with CodeView (see the /zi
  1017. switch below), /zd is intended for use with the earlier SYMDEB debugger
  1018. included with MASM 4.0.  It is extremely unlikely that you will ever need
  1019. to use /zd in your programming.
  1020.  
  1021.  
  1022. /Zi
  1023.  
  1024. The /zi option is used when you will execute your program in the Microsoft
  1025. CodeView debugger.  CodeView was described in Chapter 4, and there is no
  1026. reason to repeat that information here.  Like /z and /zd, /zi tells BC to
  1027. include additional information about your program in the object file. 
  1028. Besides indicating which assembler statements correspond to which BASIC
  1029. source lines, /zi also adds variable and procedure names and addresses to
  1030. the file.  This allows CodeView to display meaningful names as you step
  1031. through the assembly language compiled code, instead of addresses only.
  1032.      In order to create a CodeView-compatible program, you must also link
  1033. with the /co LINK option.  All of the options that LINK supports are listed
  1034. elsewhere in this chapter, along with a complete explanation of what each
  1035. does.
  1036.      Note that CodeView cannot process a BASIC source file that has been
  1037. saved in the Fast Load format.  This type of file is created by default in
  1038. QuickBASIC, when you save a newly created program.  Therefore, you must be
  1039. sure to select the ASCII option button manually from the Save File dialog
  1040. box.  In fact, there are so many bugs in the Fast Load method that you
  1041. should never use it.  Problems range from QuickBASIC hanging during the
  1042. loading process to completely destroying your source file!
  1043.      If a program that has been saved as ASCII is accidentally damaged, it
  1044. is at least possible to reconstruct it or salvage most of it using a DOS
  1045. tool such as the Norton Utilities.  But a Fast Load file is compressed and
  1046. encrypted; if even a single byte is corrupted, QB will refuse to load it. 
  1047. Since a Fast Load file doesn't really load that much faster than a plain
  1048. ASCII file anyway, there is no compelling reason to use it.
  1049.      [Rather than fix the Fast Load bug, which Microsoft claims they cannot
  1050. reproduce, beginning with PDS version 7 BASIC now defaults to storing
  1051. programs as plain ASCII files.]
  1052.  
  1053.  
  1054. COMPILER METACOMMANDS
  1055.  
  1056. There are a number of compiler metacommands that you can use to control how
  1057. your program is formatted in the listing file that BC optionally creates. 
  1058. Although these list file formatting options have been available since the
  1059. original IBM BASCOM 1.0 compiler [which Microsoft wrote], they are not
  1060. documented in the current versions.  As with '$INCLUDE and '$DYNAMIC and
  1061. the other documented metacommands, each list formatting option is preceded
  1062. by a REM or apostrophe, and a dollar sign.  The requirement to imbed
  1063. metacommands within remarks was originally to let programs run under the
  1064. GW-BASIC interpreter without error.
  1065.      Each of the available options is listed below, along with an
  1066. explanation and range of acceptable values.  Many options require a numeric
  1067. parameter as well; in those cases the number is preceded by a colon.  For
  1068. example, a line width of 132 columns is specified using '$LINESIZE: 132. 
  1069. Other options such as '$PAGE do not require or accept parameters.  Notice
  1070. that variables may not be used for metacommand parameters, and you must use
  1071. numbers.  CONST values are also not allowed.
  1072.      Understand that the list file that BASIC creates is of dubious value,
  1073. except when debugging a program to determine the address at which a runtime
  1074. error occurred.  While a list file could be considered as part of the
  1075. documentation for a finished program, it conveys no useful information. 
  1076. These formatting options are given here in the interest of completeness,
  1077. and because they are not documented anywhere else.  [In order to use any of
  1078. these list options you must specify a list file name when compiling.]
  1079.  
  1080.  
  1081. '$LINESIZE
  1082.  
  1083. The '$LINESIZE option lets you control the width of the list file, to
  1084. prevent or force line wrapping at a given column.  The default list width
  1085. is 80 columns, and any text that would have extended beyond that is instead
  1086. continued on the next line.  Many printers offer a 132-column mode, which
  1087. you can take advantage of by using '$LINESIZE: 132.  [Of course, it's up to
  1088. you to send the correct codes to your printer before printing such a wide
  1089. listing.]  Note that the minimum legal width is 40, and the maximum is 255.
  1090.  
  1091.  
  1092. '$LIST
  1093.  
  1094. The '$LIST metacommand accepts either a minus (-) or plus (+) argument, to
  1095. indicate that the listing should be turned off and on respectively.  That
  1096. is, using '$LIST - suspends the listing at that point in the program, and
  1097. '$LIST + turns it back on.  This option is useful to reduce the size of the
  1098. list file and to save paper when a listing is not needed for the entire
  1099. program.
  1100.  
  1101.  
  1102. '$PAGE
  1103.  
  1104. To afford control over the list file format, the '$PAGE metacommand forces
  1105. subsequent printing to begin on the next page.  Typically '$PAGE would be
  1106. used prior to the start of a new section of code; for example, just before
  1107. each new SUB or FUNCTION procedure.  This tells BC to begin the procedure
  1108. listing on a new page, to avoid starting it near the bottom of a page.
  1109.  
  1110.  
  1111. 'PAGEIF
  1112.  
  1113. '$PAGEIF is related to '$PAGE, except it lets you specify that a new page
  1114. is to be started only if a certain minimum number of lines remain on the
  1115. current page.   For example, '$PAGEIF: 6 tells BC to advance to the next
  1116. page only if there are six or less printable lines remaining.
  1117.  
  1118.  
  1119. '$PAGESIZE 
  1120.  
  1121. You can specify the length of each page with the '$PAGESIZE metacommand, to
  1122. override the 66-line default.  This would be useful with laser printers, if
  1123. you are using a small font that supports more than that many lines on each
  1124. page.  Notice that a 6-line bottom margin is added automatically, so
  1125. specifying a page size of 66 results in only 60 actual lines of text on
  1126. each page.  The largest value that can be used with '$PAGESIZE is 255, and
  1127. the smallest is 15.  To set the page length to 100 lines you would use
  1128. '$PAGESIZE: 100.  There is no way to disable the page numbering altogether,
  1129. and using values outside this range result in a warning error message.
  1130.  
  1131.  
  1132. '$OCODE
  1133.  
  1134. Using '$OCODE (object code) allows you to turn the assembly language source
  1135. listing on or off, using "+" or "-" arguments.  Normally, the /a switch is
  1136. needed to tell BC to include the assembly language code in the list file. 
  1137. But you can optionally begin a listing at any place in the program with
  1138. '$OCODE +, and then turn it off again using '$OCODE -.
  1139.  
  1140.  
  1141. '$SKIP
  1142.  
  1143. Like '$PAGE and '$PAGEIF, the '$SKIP option lets you control the appearance
  1144. of the source listing.  '$SKIP accepts a colon and a numeric argument that
  1145. tells BC to print that many blank lines in the list file or skip to the end
  1146. of the page, whichever comes first.
  1147.  
  1148.  
  1149. '$TITLE and '$SUBTITLE
  1150.  
  1151. By default, each page of the list file has a header that shows the current
  1152. page number, and date and time of compilation.  The '$TITLE and '$SUBTITLE
  1153. metacommands let you also specify one or two additional strings, which are
  1154. listed at the start of each page.  Using '$TITLE: 'My program' tells BASIC
  1155. to print the text between the single quotes on the first line of each page. 
  1156. If a subtitle is also specified, it will be printed on the second line. 
  1157. Note that the title will be printed on the first page of the list file only
  1158. if the '$TITLE metacommand is the very first line in the BASIC source file.
  1159.  
  1160.  
  1161. LINKING
  1162. =======
  1163.  
  1164. Once a program has been compiled to an object file, it must be linked with
  1165. the routines in the BASIC library before it can be run.  LINK combines one
  1166. or more object files with routines in a library, and produces an executable
  1167. program file having an .EXE extension.  LINK is also used to create Quick
  1168. Libraries for use in the QB editing environment, and that is discussed
  1169. later in this chapter.
  1170.      LINK can combine multiple BASIC object files, as well as object files
  1171. created with other Microsoft-compatible languages.  In the section that
  1172. follows you will learn how the LINK command line is structured, what each
  1173. parameter is for, and how the many available options may be used.  Using
  1174. the various LINK options can reduce the size of your programs, and help
  1175. them run faster as well.
  1176.      I should mention here it is imperative that you use the correct
  1177. version of LINK.  DOS comes with an old version of LINK.EXE that is not
  1178. suitable for use with QuickBASIC or BASIC PDS.  Therefore, you should
  1179. always use the LINK.EXE program that came with your compiler.  I also
  1180. suggest that you remove or rename the copy of LINK that came with DOS if it
  1181. is still on your hard disk.  More than once I have seen programmers receive
  1182. inexplicable LINK error messages because their PATH setting included the
  1183. \DOS directory.  In particular, many of the switches that current versions
  1184. of LINK support cause an "Unrecognized option" message from older versions. 
  1185. If the correct version of LINK is not in the current directory, then DOS
  1186. will use its PATH variable to see where else to look, possibly running an
  1187. older version.
  1188.      The LINK command line is structured as follows, using brackets to
  1189. indicate optional information.  The example below is intended to be entered
  1190. all on one line.
  1191.  
  1192.  
  1193. link [/options] objfile [objfile] [libfile.lib], [exefile], [mapfile],
  1194.   [libfile] [libfile] [;]
  1195.  
  1196.  
  1197. As with the BC compiler, you may either enter all of the information on a
  1198. single command, let LINK prompt you for the file names, or use a
  1199. combination of the two.  That is, you could enter LINK [filename] and let
  1200. LINK prompt you for the remaining information.  Default choices are
  1201. displayed by LINK, and these are used if Enter alone is pressed.  Typing a
  1202. semicolon on a prompt line by itself or after a file name tells LINK to
  1203. assume the default responses for the remaining fields.  LINK also lets you
  1204. use a *response file* to hold the file names and options.  When there are
  1205. dozens or even hundreds of files being specified, this is the only
  1206. practical method.  Response files are described later in this section.
  1207.      Also like BC, the separating commas are required as place holders when
  1208. successive fields are omitted.  For example, the command:
  1209.  
  1210.      link program , , mapfile;
  1211.  
  1212. links PROGRAM.OBJ to produce PROGRAM.EXE, and creates a map file with the
  1213. name MAPFILE.MAP.  If the second comma had not been included, the output
  1214. file would be named MAPFILE.EXE and a map file would not be written at all.
  1215.      The first LINK argument is one or more optional command switches,
  1216. which let you control some of the ways in which link works.  For example,
  1217. the /co switch tells LINK to add line number and other information needed
  1218. when debugging the resultant EXE program with CodeView.  Another option,
  1219. /ex, tells LINK to reduce the size of the program using a primitive form of
  1220. data compression.  Each LINK option will be discussed in the section that
  1221. follows, and we won't belabor them here.
  1222.      The second argument is the name of the main program object module,
  1223. which contains the code that will be executed when the program is run from
  1224. the DOS command line.  Many programs use only a single object file;
  1225. however, in a multi-module program you must list the main module first. 
  1226. That is then followed by the other modules that contain additional
  1227. subprograms and functions.  Of course, you can precede any file name with a
  1228. drive letter and/or directory name as necessary.
  1229.      You may also specify that all of the object modules in an entire
  1230. library be included in the executable program by entering the library name
  1231. where the object name would be given.  Since LINK assumes an .OBJ file
  1232. extension, you must explicitly include the .LIB extension when linking an
  1233. entire library.  For example, the command
  1234.  
  1235.      link mainprog subs.lib;
  1236.  
  1237. creates a program named MAINPROG.EXE which is comprised of the code in
  1238. MAINPROG.OBJ and all of the routines in SUBS.LIB.  Normally, a library is
  1239. specified at the end of the LINK command line.  However, in that case only
  1240. the routines that are actually called will be added to the program. 
  1241. Placing a library name in the object name field tells LINK to add all of
  1242. the routines it contains, regardless of whether they are actually needed. 
  1243. Normally you do not want LINK to include unused routines, but that is often
  1244. needed when creating Quick Libraries which will be discussed in a moment.
  1245.      Notice that when more than one object file is given, the first listed
  1246. is the one that is run initially.  Its name is also used for the executable
  1247. file name if an output file name is not otherwise given.  Like the BC
  1248. compiler, LINK assumes that you are using certain file naming conventions
  1249. but lets you override those assumptions with explicit extensions.  I
  1250. recommend that you use the standard extensions, and avoid any unnecessary
  1251. heartache and confusion.  In particular, using non-standard names is a poor
  1252. practice when more than one programmer is working on a project.  Also
  1253. notice that either spaces or plus signs (+) may be used to separate each
  1254. object and library file name.  Which you use is a matter of personal
  1255. preference.
  1256.      The third LINK field is the optional executable output file name.  If
  1257. omitted, the program will use the base name of the first object file
  1258. listed.  Otherwise, the specified name will be used, and given an .EXE
  1259. extension.  Again, you can override the .EXE extension, but this is not
  1260. recommended.
  1261.      Following the output file name field is the map file entry.  A map
  1262. file contains information about the executable program, such as segment
  1263. names and sizes, the size of the stack, and so forth.  The /map option,
  1264. which is described later, tells LINK to include additional information in
  1265. the map file.  In general, a map file is not useful in high-level language
  1266. programming.
  1267.      One interesting LINK quirk is that it will create a map file if empty
  1268. commas are used, but not if a semicolon is used prior to that field.  You
  1269. can specify the reserved DOS device name nul to avoid creating a map file. 
  1270. For example, the command
  1271.  
  1272.      link program, , nul, library;
  1273.  
  1274. links PROGRAM.OBJ to create PROGRAM.EXE, but not does not create the file
  1275. PROGRAM.MAP.  I use a similar line in the batch files I use for compiling
  1276. and linking, to avoid cluttering my hard disk with these useless files.
  1277.      The last field specifies one or more libraries that hold additional
  1278. routines needed for the program.  In purely BASIC programming you do not
  1279. need to specify a library name, because the compiler specifies a default
  1280. library in the object file header.  If you are linking with assembly or
  1281. other language subroutines that are in a library, you would list the
  1282. library names here.  You can list any number of library names, and LINK
  1283. will search each of them in turn looking for any routines it does not find
  1284. in the object files.
  1285.      The version of LINK that comes with BASIC 7 also accepts a definitions
  1286. file as an optional last argument.  But that is used only for OS/2 and
  1287. Windows programming, and is not otherwise needed with BASIC.
  1288.  
  1289.  
  1290. LINK OPTIONS
  1291.  
  1292. All of the available LINK options that are useful with BASIC running under
  1293. DOS are shown following in alphabetical order.  As with the switches
  1294. supported by BC, each is specified on the LINK command line by preceding it
  1295. forward slash (/).  Many of the options may be abbreviated by entering just
  1296. the first few letters of their name.  For example, what I refer to as the
  1297. /co option is actually named /codeview; however, the first two letters are
  1298. sufficient for LINK to know what you mean.
  1299.      Each option is described using only enough letters to understand the
  1300. meaning of its name.  You can see the full name for those options in the
  1301. section headers below, or run LINK with the /help switch.  Any switch may
  1302. be specified using only as many characters as needed to distinguish it from
  1303. other options.  That is, /e is sufficient to indicate /exepack because it
  1304. is the only one that starts with that letter.  But you must use at least
  1305. the first three characters of the /nologo switch, since /no could mean
  1306. either /nologo or /nodefaultlibrary.  The details section for each option
  1307. shows the minimum letters that are actually needed.
  1308.  
  1309.  
  1310. /BATCH
  1311.  
  1312. Using /ba tells LINK that you are running it from a batch file, and that it
  1313. is not to pause and prompt for library names it is unable to find.  When
  1314. /ba is used and external routines are not found, a warning message is
  1315. issued rather than the usual prompt.  The /ba option is not generally very
  1316. useful--even if you are linking with a batch file--since it offers no
  1317. chance to fix an incorrect file or directory name.
  1318.      One interesting LINK quirk worth noting is when it is unable to find a
  1319. library you must include a trailing backslash (\) after the path name when
  1320. reentering it manually.  If LINK displays the prompt "Enter new file spec:"
  1321. and you type \pathname, you are telling LINK to use the library named
  1322. PATHNAME.LIB and look for it in the root directory.  What is really needed
  1323. is to enter \pathname\, which tells it to look in that directory for the
  1324. library.  Furthermore, if you initially enter the directory incorrectly,
  1325. you must then specify both the directory and library name.  If you are not
  1326. sure of the default library name it is often easier to simply press Ctrl-C
  1327. and start again.
  1328.  
  1329.  
  1330. /CODEVIEW
  1331.  
  1332. The /co switch is necessary when preparing a program for debugging with
  1333. CodeView.  Because of the extra information that LINK adds to the resultant
  1334. executable file, /co should be used only for debugging purposes.  However,
  1335. the added data is stored at the end of the file, and is not actually loaded
  1336. into memory if the program is run from the DOS command line.  The program
  1337. will therefore have the same amount of memory available to it as if /co had
  1338. not been used.
  1339.  
  1340.  
  1341. /EXEPACK
  1342.  
  1343. When /e is used, LINK compresses repeated character strings to reduce the
  1344. executable file size.  Because variables and static arrays are initialized
  1345. to zero by the compiler, they are normally stored in the file as a group of
  1346. CHR$(0) zero bytes.  The /e switch tells LINK to replace these groups of
  1347. zero bytes with a group count.  Then when the program is run, the first
  1348. code that actually executes is the unpacking code that LINK adds to your
  1349. program.  This is not unlike the various self-extracting archive utilities
  1350. that are available commercially and as shareware.
  1351.      Notice that the compression algorithm LINK employs is not particularly
  1352. sophisticated.  For example, SLR System's OptLink is an alternate linker
  1353. that reduces a program to a much smaller file size than Microsoft's LINK. 
  1354. PKWare and SEA Associates are two other third-party companies that produce
  1355. utilities to create smaller executable files that unpack and run themselves
  1356. automatically.
  1357.  
  1358.  
  1359. /FARCALLTRANSLATE
  1360.  
  1361. By default, all calls from BASIC to its runtime library routines are far
  1362. calls, which means that both a segment and address are needed to specify
  1363. the location of the routine being accessed.  Assembly language and C
  1364. routines meant to be used with BASIC are also designed as far calls, as are
  1365. BASIC subprograms and functions.  This affords the most flexibility, and
  1366. also lets you create programs larger than could fit into a single 64K
  1367. segment.
  1368.      Within the BASIC runtime library there are both near and far calls to
  1369. other library routines.  Which is used depends on the routines involved,
  1370. and how the various segments were named by the programmers at Microsoft. 
  1371. Because a far call is a five-byte instruction compared to a near call which
  1372. is only three, a near call requires less code and can execute more quickly. 
  1373. In many cases, separate code segments that are less than 64K in size can be
  1374. combined by LINK to form a single segment.  The routines in those segments
  1375. could then be accessed using near calls.  However, BASIC always generates
  1376. far calls as it compiles your programs.
  1377.      The /f option tells LINK to replace the far calls it encounters with
  1378. near calls, if the target address is indeed close enough to be accessed
  1379. with a near call.  The improvement /f affords is further increased by also
  1380. using the /packcode switch (see below).  Although the far call is replaced
  1381. with a near call, LINK can't actually reduce the size of the original
  1382. instruction.  Instead it inserts a Nop (no operation) assembly language
  1383. command where part of the far call had been.  But since a near call does
  1384. not require segment relocation information in the .EXE file header, the
  1385. file size may be reduced slightly.  See the text that accompanies Figure 5-
  1386. 1 earlier in this chapter for an explanation of DOS' loading and relocation
  1387. process.
  1388.      There is one condition under which the /f option can cause your
  1389. program to fail.  The machine code for a far call is a byte with the value
  1390. of &H9A, which is what LINK searches for as it converts the far calls to
  1391. near ones.  Most high-level languages, store all data in a separate
  1392. segment, which is ignored by LINK when servicing /f.  BASIC, however,
  1393. stores line label addresses in the program's code segment when ON GOTO and
  1394. the other ON commands are used.  If one of those addresses happens to be
  1395. &H9A, then LINK may incorrectly change it.  In my personal experience, I
  1396. have never seen this happen.  I recommend that you try /f in conjunction
  1397. with /packc, and then test your program thoroughly.  You could also examine
  1398. any ON statements with CodeView if you are using them, to determine if an
  1399. address happens to contain the byte &H9A.
  1400.  
  1401.  
  1402. /HELP
  1403.  
  1404. Starting LINK with the /he option tells it to display a list of all the
  1405. command options it recognizes.  This is useful both as a reminder, and to
  1406. see what new features may have been added when upgrading to a newer
  1407. compiler.  In many cases, new compilers also include a new version of LINK.
  1408.  
  1409.  
  1410. /INFO
  1411.  
  1412. The /inf switch tells LINK to display a log of its activity on the screen
  1413. as it processes your file.  The name of each object file being linked is
  1414. displayed, as are the routines being read from the libraries.  It is
  1415. extremely unlikely that you will find /inf very informative.
  1416.  
  1417.  
  1418. /LINENUM
  1419.  
  1420. If you have compiled with the /zd switch to create SYMDEB information, you
  1421. will also need to specify the /li LINK switch.  This tells LINK to read the
  1422. line number information in the object file, and include it in the resultant
  1423. executable program.  SYMDEB is an awkward predecessor to CodeView that is
  1424. also hard to use, and you are not likely to find /li useful.
  1425.  
  1426.  
  1427. /MAP
  1428.  
  1429. If you give a map file name when linking, LINK creates a file showing the
  1430. names of every segment in your program.  The /m switch tells LINK to also
  1431. include all of the public symbol names.  A public symbol is any procedure
  1432. or data in the object file whose address must be determined by LINK.  This
  1433. information is not particularly useful in purely BASIC programming, but it
  1434. is occasionally helpful when writing subroutines in assembly language. 
  1435. Segment naming and grouping will be discussed in Chapter 13.
  1436.  
  1437.  
  1438. /NODEFAULTLIB
  1439.  
  1440. When BC compiles your program, it places the default runtime library name
  1441. into the created object file's header.  This way you can simply run LINK,
  1442. without having to specify the correct library manually.  Before BASIC PDS
  1443. there were only two runtime library names you had to deal with--QuickBASIC
  1444. 4.5 uses BCOM45.LIB and BRUN45.LIB.  But PDS version 7.1 comes with 16
  1445. different libraries, each intended for a different use.
  1446.      For example, there are BRUN and BCOM libraries for every combination
  1447. of near and far strings, IEEE and /fpa (alternate) math, and DOS and OS/2. 
  1448. That is, BRT71EFR.LIB stands for BASIC Runtime 7.1 Emulator Far strings
  1449. Real mode.  Likewise, BCL71ANP is for use with a BCOM stand-along program
  1450. using Alternate math and Near strings under OS/2 Protected mode.
  1451.      Using /nod tells LINK not to use the library name imbedded within the
  1452. object file, which of course means that you must specify a library name
  1453. manually.  The /nod switch also accepts an optional colon and explicit
  1454. library name to exclude.  That is, /nod:libname means use all of the
  1455. default libraries listed in the object file except libname.
  1456.      In general, /nod is not useful with BASIC, unless you are using an
  1457. alternate library such as Crescent Software's P.D.Q.  Another possible use
  1458. for /nod is if you have renamed the BASIC libraries.
  1459.  
  1460.  
  1461. /NOEXTDICT
  1462.  
  1463. As LINK combines the various object files that comprise your program with
  1464. routines in the runtime library, it maintains a table of all the procedure
  1465. and data names it encounters.  Some of these names are in the object
  1466. modules, such as the names of your BASIC subprograms and functions.  Other
  1467. procedure names are those in the library.
  1468.      In some situations the same procedure or data name may be encountered
  1469. more than once.  For example, when you are linking with a stub file it will
  1470. contain a routine with the same name as the one it replaces in BASIC's
  1471. library.  Usually, LINK will issue an error message when it finds more than
  1472. one occurrence of a public name.  If you use /noe (No Extended Dictionary)
  1473. LINK knows to use the routine or data item it finds first, and not to issue
  1474. an error message.
  1475.      The /noe option should be used only when necessary, because it causes
  1476. LINK to run more slowly.  Linking with stub files is described separately
  1477. later in this chapter.
  1478.  
  1479.  
  1480. /NOFARCALL
  1481.  
  1482. The /nof switch is usually not needed, since by default LINK does not
  1483. translate far calls to near ones (see /farcalltranslate earlier in this
  1484. section).  But since you can set an environment variable to tell LINK to
  1485. assume /far automatically, /nof would be used to override that behavior. 
  1486. Setting LINK options through the use of environment variables is described
  1487. later in this chapter.
  1488.  
  1489.  
  1490. /NOLOGO
  1491.  
  1492. The /nol switch tells LINK not to display its copyright notice, and, like
  1493. the /t BC switch may be used to minimize screen clutter.
  1494.  
  1495.  
  1496. /NOPACKCODE
  1497.  
  1498. As with the /nof switch, /nop is not necessary unless you have established
  1499. /packc as the default behavior using an environment variable.
  1500.  
  1501.  
  1502. /OVERLAYINT
  1503.  
  1504. When you have written a program that uses overlays, BASIC uses an *overlay
  1505. manager* to handle loading subprograms and functions in pieces as they are
  1506. needed.  Instead of simply calling the overlay manager directly, it uses an
  1507. interrupt.  This is similar to how the routines in a BRUN library are
  1508. accessed.
  1509.      BASIC by default uses Interrupt &H3F, which normally will not conflict
  1510. with the interrupts used by DOS, the BIOS, or network adapter cards.  If an
  1511. interrupt conflict is occurring, you can use the /o switch to specify that
  1512. a different interrupt number be used to invoke the overlay manager.  This
  1513. might be necessary in certain situations, perhaps when data acquisition or
  1514. other special hardware is installed in the host PC.
  1515.  
  1516.  
  1517. /PACKCODE
  1518.  
  1519. The /packc switch is meant to be used with /far, and it combines multiple
  1520. adjacent code segments into as few larger ones as possible.  This enable
  1521. the routines within those segments to call each other using near, rather
  1522. than far calls.  When combined with /f, /packc will make your programs
  1523. slightly faster and possibly reduce their size.
  1524.  
  1525.  
  1526. /PAUSE
  1527.  
  1528. Using /pau tells link to pause after reading and processing the object and
  1529. library files, but before writing the final executable program to disk. 
  1530. This is useful only when no hard drive is available, and all of the files
  1531. will not fit onto a single floppy disk.
  1532.  
  1533.  
  1534. /QUICKLIB
  1535.  
  1536. The /q switch tells LINK that you are creating a Quick Library having a
  1537. .QLB extension, rather than an .EXE program file.  A Quick Library is a
  1538. special file comprised of one or more object modules, that is loaded into
  1539. the QB editing environment.  Although BASIC can call routines written in
  1540. non-BASIC languages, they must already be compiled or assembled.  Since the
  1541. BASIC editor can interpret only BASIC source code, Quick Libraries provide
  1542. a way to access routines written in other languages.  Creating and using
  1543. Quick Libraries is discussed separately later in this chapter.
  1544.  
  1545.  
  1546. /SEGMENTS
  1547.  
  1548. The /seg: switch tells LINK to reserve memory for the specified number of
  1549. segment names.  When LINK begins, it allocates enough memory to hold 128
  1550. different segment names.  This is not unlike using DIM in a BASIC program
  1551. you might write to create a 128-element string array.  If LINK encounters
  1552. more than 128 names as it processes your program, it will terminate with a
  1553. "Too many segments" error.  When that happens, you must start LINK again
  1554. using the /seg switch.
  1555.      All of the segments in an object module that contain code or data are
  1556. named according to a convention developed by Microsoft.  Segment naming
  1557. allows routines in separate files to ultimately reside in the same memory
  1558. segment.  Routines in the same segment can access each other using near
  1559. calls instead of far calls, which results in smaller and faster programs. 
  1560. Also, all data in a BASIC program is combined into a single segment, even
  1561. when the data is brought in from different modules.  LINK knows which
  1562. segments are to be combined by looking for identical names.
  1563.      The routines in BASIC's runtime library use only a few different
  1564. names, and it is not likely that you will need to use /seg in most
  1565. situations.  But when writing a large program that also incorporates many
  1566. non-BASIC routines, it is possible to exceed the 128-name limit.  It is
  1567. also possible to exceed 128 segments when creating a very large Quick
  1568. Library comprised of many individual routines.
  1569.      The /seg switch requires a trailing colon, followed by a number that
  1570. indicates the number of segment names to reserve memory for.  For example,
  1571. to specify 250 segments you would use this command line:
  1572.  
  1573.      link /seg:250 program, , nul, library;
  1574.  
  1575. In most cases, there is no harm in specifying a number that is too large,
  1576. unless that takes memory LINK needs for other purposes.  Besides the
  1577. segment names, LINK must also remember object file names, procedure names,
  1578. data variables that are shared among programs, and so forth.  But if LINK
  1579. runs out of memory while it is processing your program, it simply creates a
  1580. temporary work file to hold the additional information.  
  1581.  
  1582. /STACK
  1583.  
  1584. The /st: option lets you control the size of BASIC's stack.  One situation
  1585. where you might need to do this is if your program has deeply nested calls
  1586. to non-static procedures.  Likewise, calling a recursive subprogram or
  1587. function that requires many levels of invocation will quickly consume stack
  1588. space.
  1589.      You can increase the stack size in a QuickBASIC program by using the
  1590. CLEAR command:
  1591.  
  1592.      CLEAR , , stacksize
  1593.  
  1594. where stacksize specifies the number of bytes needed.  However, CLEAR also
  1595. clears all of your variables, closes all open files, and erases any arrays. 
  1596. Therefore, CLEAR is suitable only when used at the very beginning of a
  1597. program.  Unfortunately, this precludes you from using it in a chained-to
  1598. program, since any variables being passed are destroyed.  Using /stack:
  1599. avoids this by letting you specify how much memory is to be set aside for
  1600. the stack when you link the chained-to program.
  1601.      The /stack: option accepts a numeric argument, and can be used to
  1602. specify the stack size selectively for each program module.  For example,
  1603. /stack:4096 specifies that a 4K block be set aside in DGROUP for use as a
  1604. stack.  Furthermore, you do not need to use the same value for each module. 
  1605. Since setting aside more stack memory than necessary impinges on available
  1606. string space, you can override BASIC's default for only those modules that
  1607. actually need it.
  1608.      Note that this switch is not needed or recommended if you have BASIC
  1609. PDS, since that version includes the STACK statement for this purpose.
  1610.  
  1611.  
  1612. STUB FILES (PDS and later)
  1613.  
  1614. A stub file is an object module that contains an alternate version of a
  1615. BASIC language statement.  A stub file could also be an alternate library
  1616. containing multiple object files.  The primary purpose of a stub file is to
  1617. let you replace one or more BASIC statements with an alternate version
  1618. having reduced capability and hence smaller code.  Some stub files
  1619. completely remove a particular feature or language statement.  Others offer
  1620. increased functionality at the expense of additional code.
  1621.      Several stub files are included with BASIC PDS, to reduce the size of
  1622. your programs.  For example, NOCOM.OBJ removes the routines that handle
  1623. serial communications, replacing them with code that prints the message
  1624. "Feature stubbed out" in case you attempt to open a communications port.
  1625.      When BASIC compiles your program and sees a statement such as OPEN
  1626. Some$ FOR OUTPUT AS #1, it has no way to know what the contents of Some$
  1627. will be when the program runs.  That is, Some$ could hold a file name, a
  1628. device name such as "CON" or "LPT1:", or a communications argument like
  1629. "COM1:2400,N,8,1,RS,DS".  Therefore, BASIC instructs LINK to include code
  1630. to support all of those possibilities.  It does this by placing all of the
  1631. library routine names in the object file header.  When the program runs,
  1632. the code that handles OPEN examines Some$ and determines which routine to
  1633. actually call.
  1634.      Within BASIC's runtime library are a number of individual object
  1635. modules, each of which contains code to handle one or more BASIC
  1636. statements.  In chapter 1 you learned that how finely LINK can extract
  1637. individual routines from BASIC's libraries depends on how the routines were
  1638. combined in the original assembly language source files.  In BASIC 7.1,
  1639. using the SCREEN function in a program also causes LINK to add the routines
  1640. that handle CSRLIN and POS(0), even if those statements are not used.  This
  1641. is because all three routines are in the same object module.  The manner in
  1642. which these routines are combined is called *granularity*, and a library's
  1643. granularity dictates which routines can be replaced by a stub file.  That
  1644. is, a stub file that eliminated the code to support SCREEN would also
  1645. remove CSRLIN and POS(0).
  1646.      Some of the stub files included with BASIC 7 PDS are NOGRAPH.OBJ,
  1647. NOLPT.OBJ, and SMALLERR.OBJ.  NOGRAPH.OBJ removes all support for graphics,
  1648. NOLPT.OBJ eliminates the code needed to send data to a printer, and
  1649. SMALLERR.OBJ contains a small subset of the many runtime error messages
  1650. that a BASIC program normally contains.  Other stub files selectively
  1651. eliminate VGA or CGA graphics support, and another, OVLDOS21.OBJ, adds the
  1652. extra code necessary for the BASIC overlay manager to operate with DOS 2.1.
  1653.      When linking with a stub file, it is essential that you use the /noe
  1654. LINK switch, so LINK will not be confused by the presence of two routines
  1655. with the same name.  The general syntax for linking with a stub file is as
  1656. follows:
  1657.  
  1658.      link /noe basfile stubfile;
  1659.  
  1660. Of course, you could add other LINK options, such as /ex and /packc, and
  1661. specify other object and library files that are needed as well.
  1662.      You can also create your own BASIC stub files, perhaps to produce a
  1663. demo version of a program that has all features except the ability to save
  1664. data to disk.  In order for this to work, you must organize your
  1665. subprograms and functions such that all of the routines that are to be
  1666. stubbed out are in separate source files, or combined together in one file.
  1667.      In the example above, you would place the routines that save the data
  1668. in a separate file.  Then, simply create an empty subprogram that has the
  1669. same name and the same number and type of parameters, and compile that
  1670. separately.  Finally, you would link the BASIC stub file with the rest of
  1671. the program.  Note that such a replacement file is not technically a stub,
  1672. unless the BASIC routines being replaced have been compiled and placed into
  1673. a library.  But the idea is generally the same.
  1674.  
  1675.  
  1676. QUICK LIBRARIES
  1677.  
  1678. For many programmers, one of the most confusing aspects of Microsoft BASIC
  1679. is creating and managing Quick Libraries.  The concept is quite simple,
  1680. however, and there are only a few rules you must follow.
  1681.      The primary purpose of a Quick Library is to let you access non-BASIC
  1682. procedures from within the BASIC editor.  For example, BASIC comes with a
  1683. Quick Library that contains the Interrupt routine, to let you call DOS and
  1684. BIOS system services.  A Quick Library can contain routines written in any
  1685. language, including BASIC.
  1686.      Although the BASIC editor provides a menu option to create a Quick
  1687. Library, that will not be addressed here.  Rather, I will show the steps
  1688. necessary to invoke LINK manually from the DOS command line.  There are
  1689. several problems and limitations imposed by BASIC's automated menus, which
  1690. can be overcome only by creating the library manually.
  1691.      One limitation is that the automated method adds all of the programs
  1692. currently loaded into memory into the Quick Library, including the main
  1693. program.  Unfortunately, only subprograms and functions should be included. 
  1694. Code in the main module will never be executed, and its presence merely
  1695. wastes the memory it occupies.  Another, more serious problem is there's no
  1696. way to specify a /seg parameter, which is needed when many routines are to
  1697. be included in the library.
  1698.      [Actually, you can set a DOS environment variable that tells LINK to
  1699. default to a given number of segments.  But that too has problems when
  1700. using VB/DOS, because the VB/DOS editor specifies a /seg: value manually,
  1701. and incorrectly.  Unfortunately, LINK honors the value passed to it by
  1702. VB/DOS, rather than the value you assigned to the environment variable.]
  1703.      Quick Libraries are built from one or more object files using LINK
  1704. with the /q switch, and once created may not be altered.  Unlike the
  1705. LIB.EXE library manager that lets you add and remove object files from an
  1706. existing .LIB library, there is no way to modify a Quick Library.
  1707.      When LINK combines the various components of an executable file, it
  1708. resolves the data and procedure addresses in each object module header. 
  1709. The header contains relocation information that shows the names of all
  1710. external routines being called, as well as where in the object file the
  1711. final address is to be placed.  Since the address of an external routine is
  1712. not known when the source file is compiled or assembled, the actual CALL
  1713. instruction is left blank.  This was described earlier in this chapter in
  1714. the section *Overview of Compiling and Linking*.
  1715.      Resolving these data and procedure addresses is one of the jobs that
  1716. LINK performs.  Because the external names that had been in each object
  1717. file are removed by LINK and replaced with numeric addresses, there is no
  1718. way to reconstruct them later.  Similarly, when LINK creates a Quick
  1719. Library it resolves all incomplete addresses, and removes the information
  1720. that shows where in the object module they were located.  Thus, it is
  1721. impossible to extract an object module from a Quick Library, or to modify
  1722. it by adding or removing modules.
  1723.      Understand that the names of the procedures within the Quick Library
  1724. are still present, so QuickBASIC can find them and know the addresses to
  1725. call.  But if a routine in a Quick Library in turn calls another routine in
  1726. the library, the name of the called routine is lost.
  1727.  
  1728.  
  1729. Creating a Quick Library
  1730.  
  1731. Quick Libraries are created using the version of LINK that came with your
  1732. compiler, and the general syntax is as follows:
  1733.  
  1734.      link /q obj1 [obj2] [library.lib] , , nul , support;
  1735.  
  1736. The support library file shown above is included with BASIC, and its name
  1737. will vary depending on your compiler version.  The library that comes with
  1738. QuickBASIC version 4.5 is named BQLB45.LIB; BASIC 7 instead includes
  1739. QBXQLB.LIB for the same purpose.  You must specify the appropriate support
  1740. library name when creating a Quick Library.
  1741.      Notice that LINK also lets you include all of the routines in one or
  1742. more conventional (.LIB) libraries.  Simply list the library names where
  1743. the object file names would go.  The .LIB extension must be given, because
  1744. .OBJ is the default extension that LINK assumes.  You can also combine
  1745. object files and multiple libraries in the same Quick Library like this:
  1746.  
  1747.      link /q obj1 obj2 lib1.lib lib2.lib , , nul , support;
  1748.      
  1749. Although Quick Libraries are necessary for accessing non-BASIC subroutines,
  1750. you can include compiled BASIC object files.  In general, I recommend
  1751. against doing that; however, there are some advantages.  One advantage is
  1752. that a compiled subprogram or function will usually require less memory,
  1753. because comments are not included in the compiled code and long variable
  1754. names are replaced with equivalent 2-byte addresses.  Another advantage is
  1755. that compiled code in a Quick Library can be loaded very quickly, thus
  1756. avoiding the loading and parsing process needed when BASIC source code is
  1757. loaded.
  1758.      But there are several disadvantages to storing BASIC procedures in a
  1759. Quick Library.  One problem is that you cannot trace into them to determine
  1760. the cause of an error.  Another is that all of the routines in a Quick
  1761. Library must be loaded together.  If the files are retained in their
  1762. original BASIC source form, you can selectively load and unload them as
  1763. necessary.  The last disadvantage affects BASIC 7 [and VB/DOS] users only.
  1764.      The QBX [and VB/DOS] editors places certain subprogram and function
  1765. procedures into expanded memory if any is available.  Understand that all
  1766. procedures are not placed there; only those whose BASIC source code size is
  1767. between 1K and 16K.  But Quick Libraries are always stored in conventional
  1768. DOS memory.  Therefore, more memory will be available to your programs if
  1769. the procedures are still in source form, because they can be placed into
  1770. EMS memory.
  1771.      Note that when compiling BASIC PDS programs for placement in a Quick
  1772. Library, it is essential that you compile using the /fs (far strings)
  1773. option.  Near strings are not supported within the QBX editor, and failing
  1774. to use /fs will cause your program to fail spectacularly.
  1775.  
  1776.  
  1777. RESPONSE FILES
  1778.  
  1779. A response file contains information that LINK requires, and it can
  1780. completely or partially replace the commands that would normally be given
  1781. from the DOS command line.  The most common use for a LINK response file is
  1782. to specify a large number of object files.  If you are creating a Quick
  1783. Library that contains dozens or even hundreds of separate object files, it
  1784. is far easier to maintain the names in a file than to enter them each time
  1785. manually.
  1786.      To tell LINK that it is to read its input from a response file enter
  1787. an at sign (@) followed by the response file name, as shown below.
  1788.  
  1789.      link /q @quicklib.rsp
  1790.  
  1791. Since the /q switch was already given, the response file need only contain
  1792. the remaining information.  A typical response is shown in the listing
  1793. below.
  1794.  
  1795.  
  1796.      object1 +
  1797.      object2 +
  1798.      object3 +
  1799.      object4 +
  1800.      object5 
  1801.      qlbname
  1802.      nul
  1803.      support
  1804.  
  1805.  
  1806. Even though this example lists only five object files, there could be as
  1807. many as necessary.  Each object file name except the last one is followed
  1808. by a plus sign (+), so LINK will know that another object file name input
  1809. line follows.  The qlbname line indicates the output file name.  If it is
  1810. omitted and replaced with a blank line, the library will assume the name of
  1811. the first object file but with a .QLB extension.  In this case, the name
  1812. would be OBJECT1.QLB.  The nul entry could also be replaced with a blank
  1813. line, in which case LINK would create a map file named OBJECT1.MAP.  As
  1814. shown in the earlier examples, the support library will actually be named
  1815. BQLB45 or QBXQLB, depending on which version of BASIC you are using.
  1816.      LINK recognizes several variations on the structure of a response
  1817. file.  For example, several object names could be placed on each line, up
  1818. to the 126-character line length limit imposed by DOS.  That is, you could
  1819. have a response file like this:
  1820.  
  1821.      object1 object2 object3 +
  1822.      object4 object5 object6 +
  1823.      ...
  1824.  
  1825. I have found that placing only one name on each line makes it easier to
  1826. maintain a large response file.  That also lends itself to keeping the
  1827. names in alphabetical order.
  1828.      You may also place the various option switches in a response file, by
  1829. listing them on the first line with the object files:
  1830.  
  1831.      /ex /seg:250 object1 +
  1832.      object2 +
  1833.      ...
  1834.  
  1835. Response files can be used for conventional linking, and not just for
  1836. creating Quick Libraries.  This is useful when you are developing a very
  1837. large project comprised of many different modules.  Regardless of what you
  1838. are linking, however, understanding how response files are used is a
  1839. valuable skill.
  1840.  
  1841.  
  1842. LINKING WITH BATCH FILES
  1843.  
  1844. Because so many options are needed to fully control the compiling and
  1845. linking process, many programmers use a batch file to create their
  1846. programs.  The C.BAT batch file below compiles and links a single BASIC
  1847. program module, and exploits DOS' replaceable batch parameter feature.
  1848.  
  1849.      bc /o /s /t %1;
  1850.      link /e /packc /far /seg:250 %1, , nul, mylib;
  1851.  
  1852. Like many programs, a batch file can also accept command line arguments. 
  1853. The first argument is known within the batch file as %1, the second is %2,
  1854. and so forth, up to the ninth parameter.  Therefore, when this file is
  1855. started using this command:
  1856.  
  1857.      c myprog
  1858.  
  1859. the compiler is actually invoked with the command
  1860.  
  1861.      bc /o /s /t myprog;
  1862.  
  1863. The second line becomes
  1864.  
  1865.      link /e /far /packc /seg:250 myprog, , nul, mylib;
  1866.  
  1867. That is, every occurrence of the replaceable parameter %1 is replaced by
  1868. the first (and in this case only) argument: myprog.
  1869.      I often create a separate batch file for each new project I begin, to
  1870. avoid having to type even the file name.  I generally use the name C.BAT
  1871. because its purpose is obvious, and it requires typing only one letter! 
  1872. Once the project is complete, I rename the batch file to have the same
  1873. first name as the main BASIC program.  This lets me see exactly how the
  1874. program was created if I have to come back to it again months later.  An
  1875. example of a batch file that compiles and links three BASIC source files is
  1876. shown below.
  1877.  
  1878.      bc /o /s /t mainprog;
  1879.      bc /o /s /t module1;
  1880.      bc /o /s /t module2;
  1881.      link /e /packc /far mainprog module1 module2, , nul, mylib;
  1882.  
  1883. Of course, you'd use the compiler and link switches that are appropriate to
  1884. your particular project.  You could also specify a LINK response file
  1885. within a batch file.  In the example above you would replace the last line
  1886. with a command such as this:
  1887.  
  1888.      link @mainprog.rsp;
  1889.  
  1890.  
  1891. LINKING WITH OVERLAYS (PDS and VB/DOS PRO EDITION ONLY)
  1892.  
  1893. At one time or another, most programmers face the problem of having an
  1894. executable program become too large to fit into memory when run.  With
  1895. QuickBASIC your only recourse is to divide the program into separate .EXE
  1896. files, and use CHAIN to go back and forth between them.  This method
  1897. requires a lot of planning, and doesn't lend itself to structured
  1898. programming methods.  Each program is a stand-alone main module, rather
  1899. than a subprogram or function.
  1900.      Worse, chaining often requires the same subroutine code to be
  1901. duplicated in each program, since only one program can be loaded into
  1902. memory at a time.  If both PROGRAM1.EXE and PROGRAM2.EXE make calls to the
  1903. same subprogram, that subprogram will have to be added to each program. 
  1904. Obviously, this wastes disk space.  BASIC 6.0 included the BUILDRTM program
  1905. to create custom runtime program files that combines common subroutine code
  1906. with the BASIC runtime library.  But that program is complicated to use and
  1907. often buggy in operation.
  1908.      Therefore, one of the most useful features introduced with BASIC 7 is
  1909. support for program overlays.  An overlay is a module that contains one or
  1910. more subprograms or functions that is loaded into memory only when needed. 
  1911. All overlaid modules are contained in a single .EXE file along with the
  1912. main program, as opposed to the separate files needed when programs use
  1913. CHAIN.  The loading and unloading of modules is handled for you
  1914. automatically by the overlay manager contained in the BASIC runtime
  1915. library.
  1916.      Consider, as an example, a large accounting program comprised of three
  1917. modules.  The main module would consist of a menu that controls the
  1918. remaining modules, and perhaps also contains some ancillary subprograms and
  1919. functions.  The second module would handle data entry, and the third would
  1920. print all of the reports.  In this case, the data entry and reporting
  1921. modules are not both required at the same time; only the module currently
  1922. selected from the menu is necessary.  Therefore, you would link those
  1923. modules as overlays, and let BASIC's overlay manager load and unload them
  1924. automatically when they are called.
  1925.      The overall structure of an overlaid program is shown in Figure 5-4.
  1926.  
  1927. ┌────────────────────────────┐
  1928. │ '**** MAINPROG.BAS         │
  1929. │ CALL Menu(Choice)          │
  1930. │ IF Choice = 1 THEN         │
  1931. │   CALL EnterData           │
  1932. │ ELSEIF Choice = 2 THEN     │
  1933. │   CALL DoReports           │
  1934. │ END IF                     │
  1935. ├────────────────────────────┤
  1936. │ SUB Menu(Choice)           │
  1937. │   ...                      │
  1938. │   CALL GetChoice(Choice)   │
  1939. │   ...                      │
  1940. │ END SUB                    │
  1941. ├────────────────────────────┤
  1942. │ SUB GetChoice(ChoiceNum)   │
  1943. │   ...                      │
  1944. │   ...                      │
  1945. │ END SUB                    │
  1946. └────────────────────────────┘
  1947. ┌────────────────────────────┐
  1948. │ '*** ENTERDAT.BAS          │
  1949. │ SUB EnterData              │
  1950. │   ...                      │
  1951. │   CALL GetChoice(Choice)   │
  1952. │   ...                      │
  1953. │ END SUB                    │
  1954. └────────────────────────────┘
  1955. ┌────────────────────────────┐
  1956. │ '*** REPORTS.BAS           │
  1957. │ SUB DoReports              │
  1958. │   PRINT "Which report? ";  │
  1959. │   CALL GetChoice(Choice)   │
  1960. │   ...                      │
  1961. │   ...                      │
  1962. │ END SUB                    │
  1963. └────────────────────────────┘
  1964.  
  1965. Figure 5-4: The structure of a program that uses overlays.
  1966.  
  1967. Here, the main program is loaded into memory when the program is first run. 
  1968. Since the main program also contains the Menu and GetChoice subprograms,
  1969. they too are initially loaded into memory.  Understand that the main
  1970. program is always present in memory, and only the overlaid modules are
  1971. swapped in and out.  Thus, EnterData and DoReports can both freely call the
  1972. GetChoice subprogram which is always in memory, without incurring any delay
  1973. to load it into memory from disk.
  1974.      If the host computer has expanded memory, BASIC will use that to hold
  1975. the overlaid modules.  Since EMS can be accessed much more quickly than a
  1976. disk, this reduces the load time to virtually instantaneous.  You should be
  1977. aware, however, that BASIC PDS contains a bug in the EMS portion of its
  1978. overlay manager.  If EMS is present but less than 64K is available, your
  1979. program will terminate with the error message "Insufficient EMS to load
  1980. overlay."
  1981.      If no expanded memory is available, BASIC simply reads the overlaid
  1982. modules from the original disk file each time they are called.  It should
  1983. also use the disk if it determines that there isn't enough EMS to handle
  1984. the overlay requirements, but it doesn't.  Therefore, it is up to your
  1985. users to determine how much expanded memory is present, and disable the EMS
  1986. driver in their PC if there isn't at least 64K.
  1987.      To specify that a module is to be overlaid, simply surround its name
  1988. with parentheses when linking.  Using the earlier example shown in Figure
  1989. 5-4, you would link MAINPROG.OBJ with ENTERDAT.OBJ and REPORTS.OBJ as
  1990. follows:
  1991.  
  1992.      link mainprog (enterdat) (reports);
  1993.  
  1994. Of course, you may include any link switches that are needed, and also
  1995. include any non-overlaid object files.  Any object file names that are not
  1996. surrounded by parentheses will be kept in memory at all times.  Therefore,
  1997. you should organize your programs such that subprograms and functions that
  1998. are common to the entire application are always loaded.  Otherwise, the
  1999. program could become very slow if those procedures are swapped in and out
  2000. of memory each time they are called.
  2001.  
  2002.  
  2003. OTHER LINK DETAILS
  2004.  
  2005. The BASIC PDS documentation lists no less than 143 different LINK error
  2006. messages, and at one time or another you are bound to see at least some of
  2007. those.  LINK errors are divided into two general categories: warning errors
  2008. and fatal errors.  Warning errors can sometimes be ignored.  For example,
  2009. failing to use the /noe switch when linking with a stub file produces the
  2010. message "Symbol multiply defined", because LINK encountered the same
  2011. procedure name in the stub file and in the runtime library.  In this case
  2012. LINK simply uses the first procedure it encountered.  In general, however,
  2013. you should not run a program whose linking resulted in any error messages.
  2014.      Fatal errors are exactly that--an indication that LINK was unable to
  2015. create the program successfully.  Even if an .EXE file is produced, running
  2016. it is almost certain to cause your PC to lock up.  One example of a fatal
  2017. error is "Unresolved external."  This means that your program made a call
  2018. to a procedure, but LINK wasn't able to find its name in the list of object
  2019. and library files you gave it.  Another fatal error is "Too many segments." 
  2020. You might think that LINK would be smart enough to finish reading the
  2021. files, count the number of segment names it needs, and then restart itself
  2022. again reserving enough memory.  Unfortunately, it isn't.
  2023.      Regardless of the type of error messages you receive, it is impossible
  2024. to read all of them if there are so many that they scroll off the screen. 
  2025. Although you can press Ctrl-P to tell DOS to echo the messages to your
  2026. printer, there is an even better method.  You can use the DOS redirection
  2027. feature to send the message to a disk file.  This lets you load the file
  2028. into a text editor for later perusal.  To send all of LINK's output to a
  2029. file simply use the "greater than" symbol (>) specifying a file name as
  2030. follows:
  2031.  
  2032.      link [/options] [object files]; > error.log
  2033.  
  2034. Instead of displaying the messages on the screen, DOS intercepts and routes
  2035. them to the ERROR.LOG file.  It is important to understand that this is a
  2036. DOS issue, and has nothing to do with LINK.  Therefore, you can use this
  2037. same general technique to redirect the output of most programs to a file. 
  2038. Note that using redirection causes *all* of the program's output to go to
  2039. the file, not just the error messages.  Therefore, nothing will appear to
  2040. happen on the screen, since the copyright and sign-on notices are also
  2041. redirected.
  2042.      Another LINK detail you should be aware of is that numeric arguments
  2043. may be given in either decimal or hexadecimal form.  Any LINK option that
  2044. expects a number--for example, the /seg: switch--may be given as a
  2045. Hexadecimal value by preceding the digits with 0x.  That is, /seg:0x100 is
  2046. equivalent to /seg:256.  The use of 0x is a C notation convention, and the
  2047. "x" character is used because it sounds like "hex".
  2048.      Finally, if you are using QuickBASIC 4.0 there is a nasty bug you
  2049. should be aware of.  All versions of QuickBASIC let you create an
  2050. executable program from within the editing environment.  And if a Quick
  2051. Library is currently loaded, QB knows to link your program with a parallel
  2052. .LIB library having the same name.  But instead of specifying that library
  2053. in the proper LINK field, QB 4.0 puts its name in the object file position. 
  2054. This causes LINK to add every routine in the library to your program,
  2055. rather than only those routines that are actually called.  There is no way
  2056. to avoid this bug, and QB 4.0 users must compile and link manually from
  2057. DOS.
  2058.  
  2059.  
  2060. MAINTAINING LIBRARIES
  2061. =====================
  2062.  
  2063. As you already know, multiple object files may be stored in a single
  2064. library.  A library has a .LIB extension, and LINK can extract from it only
  2065. those object modules actually needed as it creates an executable file.  All
  2066. current versions of Microsoft compiled BASIC include the LIB.EXE program,
  2067. which lets you manage a library file.  With LIB.EXE you can add and remove
  2068. objects, extract a copy of a single object without actually deleting it
  2069. from the library, and create a cross-referenced list of all the procedures
  2070. contained therein.
  2071.      It is important to understand that a .LIB library is very different
  2072. from a Quick Library.  A .LIB library is simply a collection of individual
  2073. object files, with a header portion that tells which objects are present,
  2074. and where in the library they are located.  A Quick Library, on the other
  2075. hand, contains the raw code and data only.  The routines in a Quick Library
  2076. do not contain any of the relocation and address information that was
  2077. present in the original object module.
  2078.      The runtime libraries that Microsoft includes with BASIC are .LIB
  2079. libraries, as are third-party support libraries you might purchase.  You
  2080. can also create your own libraries from both compiled BASIC code and
  2081. assembly language subroutines.  The primary purpose of using a library is
  2082. to avoid having to list every object file needed manually.  Another
  2083. important use is to let LINK add only those routines actually necessary to
  2084. your final .EXE program.
  2085.      Like BC and LINK, you can invoke LIB giving all of the necessary
  2086. parameters on a single command line, or wait for it to prompt you for the
  2087. information.  LIB can also read file names and options from a response
  2088. file, which avoids having to enter many object names manually.  A LIB
  2089. response file is similar--but not identical--to a LINK response file. 
  2090. Using LIB response files will be described later in this section.
  2091.      The general syntax of the LIB command line is shown below, with
  2092. brackets indicating optional information.
  2093.  
  2094.      lib [/options] libname [commands] , [listfile] , [newlib] [;]
  2095.  
  2096. After any optional switches, the first parameter is the name of the library
  2097. being manipulated, and that is followed by one or more commands that tell
  2098. LIB what you want to do.  A list file can also be created, and it contains
  2099. the names of every object file in the library along with the procedure
  2100. names each object contains.  The last argument indicates an optional new
  2101. library; if present LIB will leave the original library intact, and copy it
  2102. to a new one applying the changes you have asked for.
  2103.      There are three commands that can be used with LIB, and each is
  2104. represented using a punctuation character.  However, LIB lets you combine
  2105. some of these commands, for a total of five separate actions.  This is
  2106. shown in Table 5-1.
  2107.  
  2108.  
  2109. Command                  Action
  2110. =======    =========================================
  2111.    +       Add an object module or entire library.
  2112.    -       Remove an object module from the library.
  2113.    *       Extract a copy of an object module.
  2114.    -+      Replace an object module with a new one.
  2115.    -*      Extract and then remove an object module.
  2116.  
  2117. Table 5-1: The LIB commands for managing libraries.
  2118.  
  2119.  
  2120. To add the file NEWOBJ.OBJ to the existing library MYLIB.LIB you would use
  2121. the plus sign (+) as follows:
  2122.  
  2123.      lib mylib +newobj;
  2124.  
  2125. And to update the library using a newer version of an object already
  2126. present in the library you would instead use this:
  2127.  
  2128.      lib mylib -+d:\newstuff\anyobj;
  2129.  
  2130. As you can see, the combination operators use a sensible syntax.  Here, you
  2131. are instructing LIB to first remove ANYOBJ.OBJ from MYLIB.LIB, and then add
  2132. a newer version in its place.  A drive and directory are given just to show
  2133. that it is possible, and how that would be specified.
  2134.      To extract a copy of an object file from a library, use the asterisk
  2135. (*) command.  Again, you can specify a directory in which the extracted
  2136. file is to be placed, as follows:
  2137.  
  2138.      lib mylib *\objdir\thisobj;
  2139.  
  2140. You should understand that LIB never actually modifies an existing library. 
  2141. Rather, it first renames the original library to have a .BAK extension, and
  2142. then creates and modifies a new file using the original name.  It is up to
  2143. you to delete the backup copy once you are certain that the new library is
  2144. correct.  [But this backup is made only if you do not specify a new output
  2145. library name--NEWLIB in the earlier syntax example.]
  2146.      If the named library does not exist, LIB asks if you want to create
  2147. it.  This gives you a chance to abort the process if you accidentally typed
  2148. the wrong name.  If you really do want to create a new library, simply
  2149. answer Y (Yes) at the prompt.  Of course, the only thing you can do to a
  2150. non-existent library is add new objects to it with the plus (+) command.
  2151.      One important LIB feature is its ability to create a list file showing
  2152. what routines are present in the library.  This is particularly valuable if
  2153. you are managing a library you did not create, such as a library purchased
  2154. from a third-party vendor.  Many vendors use the same name for the object
  2155. file as the routine it contains when possible, but there are exceptions. 
  2156. For example, an object file name is limited to eight characters, even
  2157. though procedure names can be as long as 40.  If you want to know which
  2158. object file contains the procedure ReadDirectories, you will need to create
  2159. a list file.  Also, one object file can hold multiple procedures, and it is
  2160. not always obvious which procedure is in which file.  Individual procedures
  2161. cannot necessarily be extracted from a library--only entire object files.
  2162.      To create a library list file you will run LIB giving the name of the
  2163. library, as well as the name of a list file to create.  The example below
  2164. creates a list file named MYLIST.LST for the library named MYLIB.LIB:
  2165.  
  2166.      lib mylib , mylist.lst;
  2167.  
  2168. The list file that is created contains two cross-referenced tables; one
  2169. shows each object name and the procedures it contains, and the other shows
  2170. the procedure names and which object they are in.  A typical list file is
  2171. shown in the Figure 5-5, using the QB.LIB file that comes with QuickBASIC
  2172. 4.5 as an example.
  2173.  
  2174.  
  2175. ABSOLUTE..........absolute          INT86OLD..........int86old 
  2176. INT86XOLD.........int86old          INTERRUPT.........intrpt 
  2177. INTERRUPTX........intrpt             
  2178.  
  2179. absolute          Offset: 00000010H  Code and data size: cH 
  2180.   ABSOLUTE         
  2181.  
  2182. intrpt            Offset: 000000e0H  Code and data size: 107H 
  2183.   INTERRUPT         INTERRUPTX       
  2184.  
  2185. int86old          Offset: 000002a0H  Code and data size: 11eH 
  2186.   INT86OLD          INT86XOLD        
  2187.  
  2188. Figure 5-5: The format of a LIB list file.
  2189.  
  2190.  
  2191. In this list file, each object module contains only one procedure.  The
  2192. first section shows each procedure name in upper case, followed by the
  2193. object name in lower case.  The second section shows each object file name,
  2194. its offset within the library and size in bytes, and the routine names
  2195. within that object file.
  2196.      Just for fun, you should create a list file from one of the libraries
  2197. that came with your compiler.  Besides showing how a large listing is
  2198. structured, you will also be able to see which statements are combined with
  2199. others in the same object file.  Thus, you can determine the granularity of
  2200. these libraries.  In many cases the names of the procedures are similar to
  2201. the corresponding BASIC keywords.
  2202.      For example, if you create a list file for the BCOM45.LIB library that
  2203. comes with QuickBASIC 4.5, you will see an object file named STRFCN.OBJ
  2204. (string function) that contains the procedures B$FASC, B$FLEN, B$FMID,
  2205. B$INS2, B$INS3, B$LCAS, B$LEFT, and several other string functions.  Most
  2206. of the library routines start with the characters B$, which ensures that
  2207. the names will not conflict with procedure names you are using.  (A dollar
  2208. sign is illegal in a BASIC procedure name.)  Other procedures (and data
  2209. items) use an imbedded underscore (_) which is also illegal in BASIC.
  2210.      FASC stands for Function ASC, FLEN is for Function LEN, and so forth. 
  2211. INS2 and INS3 contain the code to handle BASIC's INSTR function, with the
  2212. first being the two-argument version and the second the three-argument
  2213. version.  That is, using INSTR(Work$, Substring$) calls B$INS2, and
  2214. INSTR(Start, Work$, Substring$) instead calls B$INS3.  As you can see, most
  2215. of the internal procedure names are sensible, albeit somewhat abbreviated.
  2216.  
  2217.  
  2218. LIB OPTIONS
  2219.  
  2220. Many LIB options are frankly not that useful to purely BASIC programming. 
  2221. However, I will list them here in the interest of completeness.  Note that
  2222. none of these option switches are available in versions of LIB prior to the
  2223. one that comes with BASIC 7.0.
  2224.  
  2225.  
  2226. /HELP
  2227.  
  2228. As with the LINK switch of the same name, using /help (or /?) tells LIB to
  2229. display its command syntax, and a list of all the available options.
  2230.  
  2231.  
  2232. /I
  2233.  
  2234. Using /i means that LIB should ignore capitalization when searching the
  2235. library for procedure names.  This is the default for LIB, and is not
  2236. necessary unless you are manipulating an existing library that was created
  2237. with /noi (see below).
  2238.  
  2239.  
  2240. /NOE
  2241.  
  2242. The /noe option has a similar meaning as its LINK counterpart, and should
  2243. be used if LIB reports an Out of memory error.  Creating an extended
  2244. dictionary requires memory, and using /noe will avoid that.
  2245.  
  2246.  
  2247. /NOI
  2248.  
  2249. The /noi switch tells LIB not to ignore capitalization, and it should not
  2250. be used with BASIC programs.
  2251.  
  2252.  
  2253. /NOLOGO
  2254.  
  2255. Like the LINK option, /nologo reduces screen clutter by eliminating the
  2256. sign-on logo and copyright display.
  2257.  
  2258.  
  2259. /PA
  2260.  
  2261. The /pa: option lets you change the default library page size of 16 bytes. 
  2262. Larger values waste memory, because each object file will always occupy the
  2263. next higher multiple number of bytes.  For example, with a page size of 200
  2264. bytes, a 50 byte object file will require an entire 200-byte page.  Since a
  2265. library can hold no more than 65,536 pages, a larger page size is useful
  2266. only when you need to create a library larger than 1 megabyte.  The /pa:
  2267. switch requires a colon, followed by an integer value between 16 and 32768. 
  2268. For example, using /pa:256 sets a page size of 256 bytes.
  2269.  
  2270.  
  2271. USING RESPONSE FILES WITH LIB.EXE
  2272.  
  2273. A LIB response file is similar to a LINK response file, in that it lets you
  2274. specify a large number of operations by entering them on separate lines of
  2275. a text file.  The syntax is similar to a LINK response file, but it is not
  2276. identical.  Since the plus sign continuation character that LINK uses
  2277. serves as a command character to LIB, an ampersand (&) is used instead.  A
  2278. typical LIB response file is shown below.
  2279.  
  2280.      + object1 &
  2281.      + \subdir\object2 &
  2282.      + c:\subdir2\object3 &
  2283.      + object4 ;
  2284.  
  2285. As with LINK, you will use an at sign (@) to tell LIB to look in the file
  2286. for its input, as opposed to reading the names from the command line:
  2287.  
  2288.      lib @filename.rsp
  2289.      
  2290.  
  2291. USEFUL BC, LINK, AND LIB ENVIRONMENT PARAMETERS
  2292. ===============================================
  2293.  
  2294. Most programmers are familiar with the DOS environment as a way to
  2295. establish PATH and PROMPT variables.  The PATH environment variable tells
  2296. DOS where to search for executable program files it doesn't find in the
  2297. current directory.  The PROMPT variable specifies a new prompt that DOS
  2298. displays at the command line.  For example, many people use the command
  2299.  
  2300.      SET PROMPT=$P$G
  2301.  
  2302. to show the current drive and directory.  However, the DOS environment can
  2303. be used to hold other, more general information as well.
  2304.      The environment is simply an area of memory that DOS maintains to hold
  2305. variables you have assigned.  Some of these variables are used by DOS, such
  2306. as the PATH and PROMPT settings.  Other variables may be defined by you or
  2307. your programs, to hold any type of information.  For example, you could
  2308. enter SET USERNAME=TAMI in the AUTOEXEC.BAT file, and a program could read
  2309. that to know the name of the person who is using it.  The contents of this
  2310. variable (TAMI) could then be used as a file or directory name, or for any
  2311. other purpose.
  2312.      LINK looks at the DOS environment to see if you have specified LINK=
  2313. or LIB= or TMP= variables.  The first is used to specify default option
  2314. switches.  For example, if you set LINK=/SEG:450 from the DOS command line
  2315. or a batch file, you do not need to use that option each time LINK is run. 
  2316. Multiple options may be included in a single SET statement, by listing each
  2317. in succession.  The command SET LINK=/NOE/NOD/EX establishes those three
  2318. options shown as the default.  Additional separating spaces may also be
  2319. included; however, that is unnecessary and wastes environment memory.
  2320.      Likewise, setting LIB=D:\LIBDIR\ tells LINK to look in the LIBDIR
  2321. directory of drive D: for any libraries it cannot find it the current
  2322. directory.  In this case, LIB= acts as a sort of PATH command.  Like PATH,
  2323. the LIB= variable accepts multiple path names with or without drive
  2324. letters, and each is separated by a semicolon.  The command
  2325.  
  2326.      SET LIB=C:\LIBS\;D:\WORKDIR\
  2327.  
  2328. sets a library path to both C:\LIBS and D:\WORKDIR, and even more
  2329. directories could be added if needed.  To remove an environment variable
  2330. simply assign it to a null value; in this case you would use SET LIB=.
  2331.      The TMP= variable also specifies a path that tells LINK where to write
  2332. any temporary files.  When a very large program or Quick Library is being
  2333. created, it is possible for LINK to run out of memory.  Rather than abort
  2334. with an error message, LINK will open a temporary disk file and spool the
  2335. excess data to that file.  If no TMP= variable has been defined, that file
  2336. is created in the current directory.  However, if you have a RAM disk you
  2337. can specify that as the TMP parameter, to speed up the linking process. 
  2338. For example, SET TMP=F:\ establishes the root directory of drive F as the
  2339. temporary directory.
  2340.      The INCLUDE= variable is recognized by both BC and MASM (the Microsoft
  2341. Macro Assembler program), to specify where they should look for Include
  2342. files.  In my own programming, I prefer to give an explicit directory name
  2343. as part of the $INCLUDE metacommand.  This avoids unpleasant surprises when
  2344. an obsolete version of a file is accidentally included.  But you may also
  2345. store all $INCLUDE files in a single directory, and then set the INCLUDE
  2346. variable to show where that directory is.  Like LIB and PATH, the INCLUDE
  2347. variable accepts one or more directory names separated by semicolons.
  2348.  
  2349.  
  2350. SUMMARY
  2351. =======
  2352.  
  2353. In this chapter you have learned about compiling and linking manually from
  2354. the DOS command line, to avoid the limitations imposed by the automated
  2355. menus in the BASIC editor.  You have also learned how to create and
  2356. maintain both Quick Libraries and conventional .LIB libraries.  Besides
  2357. accepting information you enter at the DOS command line, LINK and LIB can
  2358. also process instructions and file names contained in a response file.
  2359.      All of the commands and option switches available with BC, LINK, and
  2360. LIB were described in detail, along with a listing of the undocumented BC
  2361. metacommands for controlling the format of a compiler list file.  Library
  2362. list files were also discussed, and a sample printout was given showing how
  2363. LIB shows all the procedure and object names in a library cross-referenced
  2364. alphabetically.
  2365.      The discussion about stub files explained what they are and how to use
  2366. them, to reduce the size of your programs.  Overlays were also covered,
  2367. accompanied by some reasons you will find them useful along with specific
  2368. linking instructions.
  2369.      Finally, I explained some of the details of the linking process. 
  2370. Information in each object file header tells LINK the names of external
  2371. procedures being called, and where in the object file the incomplete
  2372. addresses are located.  Besides the segment and address fixups that LINK
  2373. performs, DOS also makes some last-minute patches to your program as it is
  2374. loaded into memory.
  2375.      In the next chapter I will cover file handling in similar detail,
  2376. explaining how files are manipulated at a low level, and also offering
  2377. numerous tips for achieving high performance and small program size.
  2378.