Page 277 - Introduction to Microcontrollers Architecture, Programming, and Interfacing of The Motorola 68HC12
P. 277

254                                Chapter 9 Implementation of C Procedures

         9,1 Global and Local Variables


         This section shows how a variable is allocated and accessed in C. The first part of this
         section shows how to write a constant into a variable, which highlights the allocation
         mechanism, and the addressing mode and instruction data width used with each variable.
         The shorter second part describes what is done before the main procedure is executed, and
         a short third part discusses access to I/O ports, which are treated as global variables in C,
            In the first part of this section, we will use a short procedure main as an example
         that we briefly show first. The names of the variables are abbreviations of their
         characteristics; guc represents a global unsigned char, and gsi represents a global
         signed int.  The C program in Figure 9.la, which writes some constants into these
         variables, is compiled into the assembly-language program in Figure 9.1b. Global
         variables, which are declared outside a procedure, can be allocated by the compiler by the
         equivalent of assembly-language ORG statement and DS statements. For instance, a
         possible global declaration for Figure 9.1b is shown in Figure 9.1c.

                       unsigned char guc; int gsi;
                       roain(){ char Isc; unsigned int lui;
                           guc = 0; gsi = 5; Isc = 0; lui = 7;
                       }
                                      a. A C Program

                  4: main(){ char Isc; unsigned int lui;
              0000095B 1B9D              LEAS ~3,SP
                  5s     guc = 0;
              0000095D 790800            CLR    $0800
                  6:     gsi = 5;
              00000960 C605              LDAB #5
              00000962 87                CLRA
              00000963 7C0801            STD    $0801
                  7:     Isc = 0;
              00000966 6A82              STAA 2,SP
                  8:     lui = 7;
              00000968 C607              LDAB #7
              0000096A 6C80              STD    0,SP
                 10: }
              0000096C 1B83              LEAS 3,SP
              0000096E 3D                RTS
                         b. Assembly Language Developed From Part (a)
                     ORG 2048 ; put global data at the beginning of RAM ($800)
               guc: DS. B 1    ; allocate a byte for scalar char variable guc
               gsi: DS. W 1    ; allocate two bytes for scalar int variable gsi
                                  c. Declarations for Part (b)
                                Figure 9.1. A Simple Program
   272   273   274   275   276   277   278   279   280   281   282