ZiLOG, Inc. makes no warranty, express, statutory, implied or by description, regarding the
information set forth herein or regarding the freedom of the described devices from intellectual property
infringement. ZiLOG, Inc. makes no warranty of merchantability or fitness for any purpose.
The software described herein is provided on an as-is basis and without warranty. ZiLOG accepts no
liability for incidental or consequential damages arising from use of the software.
ZiLOG, Inc. shall not be responsible for any errors that may appear in this document. ZiLOG, Inc.
makes no commitment to update or keep current the information contained in this docum ent.
ZiLOG's products are not authorized for use as critical components in life support devices or systems
unless a specific written agreement pertaining to such intended use is executed between the customer
and ZiLOG prior to use. Life support devices or systems are those which are intended for surgical
implantation into the body, or which sustains life whose failure to perform, when properly used in
accordance with instructions for use provided in the labeling, can be reasonably expected to result in
significant injury to the user.
ZiLOG, Inc.
532 Race.Street,
San Jose, CA 95126-3432
Telephone: (408) 558-8500
FAX: (408) 558-8300
Internet: http://www.zilog.com
iiUM004001-COR1103
Page 3
380 C-COMPILER USER’S MANUAL
PREFACE
ABOUT THIS MANUAL
W e recommend that you read and understand everything in this manual before setting up and
using the product. However, we recognize that users have different styles of learning. There
fore, we have designed this manual to be used either as a how-to procedural manual or a reference guide to important data.
The following conventions have been adopted to provide clarity and ease of use:
•Universe Medium 10-pointall-caps is used to highlight to the following items:
– commands , displayed messages
– menu selections, pop-up lists, button, fields, or dialog boxes
–modes
– pins and ports
– program or application name
– instructions, registers, signals and subroutines
– an action performed by the software
–icons
-
•Courier Regular 10-point is used to highlight the following items
–bit
– software code
– file names and paths
– hexadecimal value
•Grouping of Actions Within A Procedure Step
Actions in a procedure step are all performed on the same window or dialog box.
Actions performed on different windows or dialog boxes appear in separate steps.
The 380 C-Compiler conforms to the ANSI’s definition of a “freestanding implementation”,
with the exception that doubles are 32 bits. In accordance with the definition of a freestand
ing implementation, the compiler accepts programs which confine the use of the features of
the ANSI standard library to the contents of the standard headers <float.h>, <limits.h>,
<stdarg.h> and <stddef.h>. This release supports more of the standard library than is required
of a freestanding implementation, as described in
There are several language extensions supported in this version, including interrupt functions
and memory space accesses.
Chapter 4, Run Time Environment.
-
UM004001-COR11031–1
Page 14
IntroductionIntroduction
Linker Command
Files
FIGURE 1-1. DEVELOPMENTFLOW
ZDS ENVIRONMENT
ZiLOG Developer Studio is an integrated development environment with a standard Windows 95/98/NT user interface that allows access to all of ZiLOG’s development tools without having to alternate from one program to another. These development tools include a
language sensitive editor, project manager, assembler , linker, and a symbolic debugger. ZDS
supports the 380 line of ZiLOG processors.
ZDS allows the user to:
•Create project files and add or remove files to and from the project
•Create and edit a source file.
•Download, execute, debug, and analyze code
1–2UM004001-COR1103
Page 15
IntroductionMinimum Requirements
•Build and link a project file
•Compile, assemble and link files
•Prepare code for ROM release (one-time programming)
RUN-TIMEMODEL
The compiler assumes that the processor is running in the long-word extended mode. Ints
are 32 bits and addresses are 24 bits. A startup program named z380boot.s is
included on the installation diskette. This program clears the .bss section, sets the proces
sor mode, and calls the main function.
NOTE: The startup program does not copy initialized data.
MINIMUM REQUIREMENTS
For the C-Compiler to run properly with ZDS, the host system must meet the following minimum requirements:
•The380 C-Compiler requires Windows 95 or Windows/NT. The compiler generates
assembler language source, which can be assembled and linked using the UNIX, DOS
or Windows versions of the ZiLOG assembler, archiver and linker.
-
• IBM PC (or 100-percent compatible) Pentium-based machine
• 75MHz,16MB Memory
• VGA Video Adapter
• Hard Disk Drive (12 MB free space)
• CD-ROM drive
• Mouse or Pointing Device
• Microsoft Windows 95/98/NT
•To use the ZDS debugger, an emulator is needed that corresponds to the processor
required for configuration
UM004001-COR11031–3
Page 16
Installing the 380 C-compilerIntroduction
INSTALLING THE 380 C-COMPILER
To install the 380 C-Compiler, insert the 380 C-Compiler CD ROM and follow the onscreen
prompts
After installing the380 C-Compiler the compiler’s installation path is set in the Window’s
registry. When installing ZDS 3.00 or later, ZDS automatically looks for the c-compilers
installation path and loads the corresponding DLL from that path.
This is effective for the following compiler versions:
•Z380 10.00 or later
•Z3xx B0.00 or later
•Z8 C1.00 or later
NOTE: Older compiler versions require the user to copy the compiler’s DLLs to the ZDS installation
directory.
REGISTRY KEYS
The following keys are written to the window’s registry during the C-compiler installation:
•For Z380 Installation
– + HKEY_LOCAL_MACHINE\Software\ZiLOG\C Compiler\Z380
– + Z380 Key has Path value which tells where the Z380
is located
•For Z3xx Installation
– + HKEY_LOCAL_MACHINE\Software\ZiLOG\C Compiler\Z3xx
– + Z3xx Key has Path value which tells where the Z3xx is
located
•For Z8/Z8Plus Installation
– + HKEY_LOCAL_MACHINE\Software\ZiLOG\C Compiler\Z8
– + Z8 Key has Path value which tells where the Z8 is
located
1–4UM004001-COR1103
Page 17
INSTALLING ZDS
Perform the following steps to install ZDS:
1. Insert the ZiLOG Developer Studio CD-ROM into the host CD ROM drive. The Emulator
Software Setup window appears.
2. In the Select Components dialog box check ZiLOG Developer Studio.
3. Click Next. The ZiLOG Developer Studio window appears.
4. Click Next to accept the licensing agreement. Immediately after the agreement is accepted,
the Choose Destination Location dialog box appears.
5. Click Next to install ZDS in the default directory. Click Browse to change the ZDS install
directory.
6. After selecting the appropriate install directory, click next. The Select Program Folder
dialog box appears.
7. Click Next to add the ZDS program icon to the ZiLOG Developer Studio program folder.
To create a personalized folder, type the folders name in the Program Folders field.
8. Click Next. The Installing ZDS Program Files progress bar appears.
9. After installation the Setup Complete dialog box appears. Check View README File to
view the read me file containing the ZDS release notes. Check Launch ZiLOG Developer
Studio to start ZDS at the end of the installation.
10. Click Finish to complete the ZDS installation.
Page 18
Sample SessionIntroduction
SAMPLE SESSION
The 380 C-Compiler is a modular component that is part of the ZDS development environment. Users should become familiar with ZDS and configure the settings before programming or downloading files. This chapter orients the user on using ZDS and configuring the
compiler for the 380 family of processors. For more information on installing ZDS, consult
the ZDS Quick Start Guide or the ZDS on-line help.
CREATEAPROJECTAND SELECTA PROCESSOR
The user must create a project and select a processor before creating or opening a C-file. Perform the following steps to create a new project and select a processor:
1. Open ZDS by selecting Start>Programs>Zilog Developer Studio> ZDS.
2. Choose New Project from the File menu. The New Project dialog box appears. See
Figure 1-2.
FIGURE 1-2. NEW PROJECTDIALOGBOX
3. Select Family in the Selection by field.
4. Select Z380 from the Master pop-up list.
5. Select the processor from the Project Target pop-up list.
6. Select an emulator or simulator from the Emulator pop-up list.
7. Click on the browse button (...) in the Projec t Name field. The New Project Browse dialog
box appears.
8. Enter the file name and select a path in the New Project Browse dialog box.
1–6UM004001-COR1103
Page 19
IntroductionSample Session
9. Click Save. The file name appears in the Project Name field in the New Project dialog box.
10. Select Application from the Project type field. This selection enables the linker.
11.Check Include default startup files for C Compiler. This option must be checked to enable
the Wizard. To manually add the necessary files for the C-Compiler, see
Manually
Configuring the Compiler on page 1-9.
12.Click on Chip Data to view specifications for the selected Project Target.
NOTE: Fields in the Chip Data page are read-only and can not be modified .
13.Click OK. The new project is saved with the file name specified in the New Project Browse
dialog box.
CONFIGURINGTHE COMPILERUSINGTHE WIZARD
The Wizard is enabled when the Include default startup files for C Compiler option is
checked in the New Project dialog box.
NOTE: The Wizard is only available for ZDS version 3.5 and later. To configure the compiler to run
with static frames you must use the small model.
Perform the following steps after clicking OK in the New Project Browse dialog box.
1. In the ZDS New Project dialog box select all the files in the Check the files you wish to
include window. See
Figure 1-3. For more information on which files to include see
Installed files on page 3-4.
FIGURE 1-3. ZDS NEW PROJECTDIALOGBOX
UM004001-COR11031–7
Page 20
Sample SessionIntroduction
2. Select Set default include path to compiler settings in the Settings window. Selecting this
option sets the path of the include files in the Additional include directories field in the CCompiler preprocessor page.
3. Select Set default linker settings for compiler.
4. Click OK. The initialization files for the selected model appears in the project viewer
window. See
Perform the following steps to create a new C file:
1. Select Add to Project>New from the Project menu. The Insert New Files Into Project dialog
box appears.
2. Select C Files from the Files of type pop-up menu.
3. Type a file name in the File Name field.
4. Click Open. The new file name appears in the Project Viewer window with a .c suffix,
and a blank Edit window also appears.
1–8UM004001-COR1103
Page 21
IntroductionSample Session
5. Type the following code in the edit window:
#include <stdlib.h>
int randnum;
int main()
{
srand(10);
randnum=rand();
randnum=rand();
}
6. Close and save the file.
NOTE: Skip the Manually Configuring the Compiler section if you configured the compiler using the
wizard.
MANUALLY CONFIGURINGTHE COMPILER
The user can manually add files and configure the settings for the C-Compiler.
After creating a project the user must add or create new files. A previously created project
has the following attributes saved with it:
•Target settings
•Assembler and Linker settings for the specified target
•Source files (including header files)
The user must first add the necessary files for the compiler to function properly. The following examples are based on using a small model.
Perform the following steps to add files:
1. Select Open Project from the File menu. The Open Project dialog box appears.
2. In the Open Project dialog box, select the project that was created in the previous exercise.
The project appears in the Project Viewer window.
3. Select Add to Project>Files from the Project menu. The Insert Files into Project dialog box
appears.
4. Browse to the directory where the C-Compiler was installed.
5. Select the Lib directory.
6. Select all files from the Files of type pop-up menu.
UM004001-COR11031–9
Page 22
Sample SessionIntroduction
7. Hold the Control key and select the following files:
– libc.lib(standard C library)
– lhf.lib(library helper functions)
8. Click Open. The files appear in the Project Viewer window. See Figure 1-5.
9. Repeat steps 1 to 4 and select the sample directory.
10.Hold the Control key and select the following files:
– Z8380eval.c(example of ZiLOG language extensions)
– Z380boot.s(example C startup module)
11. Click Open. The files appear in the Project Viewer window. See Figure 1-5.
FIGURE 1-5. PROJECT VIEWERWINDOWWITHFILES
12. S elect Add to Project>New from the Project menu. The Insert New Files Into Project
dialog box appears.
13. S elect C Files from the Files of type pop-up menu.
14. T ype a file name in the File Name field.
15. Click Open. The new file name appears in the Project Viewer window with a .c suffix,
and a blank Edit window also appears.
1–10UM004001-COR1103
Page 23
IntroductionSample Session
16.Type the following code in the edit window:
#include <stdlib.h>
int randnum;
int main()
{
srand(10);
randnum=rand();
randnum=rand();
}
17. C lose and save the file.
18.Select Update All Dependencies from the Build menu. The Dependencies folder list in the
Project Viewer window is updated.
Configure Settings
The Z8/Z8Plus C-Compiler can be configured through the Settings Option dialog box in
ZDS. The Settings Option dialog box allows the user to configure:
•General options
•Optimization levels
•Preprocessor symbol definitions
•C-Compiler memory locations
•Section names
Perform the following steps to open the C-Compiler Settings Option dialog box:
1. Open the project.
2. Select Settings from the Project menu. The Settings Options dialog box appears.
3. Click the C-Compiler tab. The C-Compiler Settings Option dialog box appears.
4.
CONFIGURE SETTINGS
The 380 C-compiler can be configured through the Settings Option dialog box in ZDS. The
Settings Option dialog box allows the user to configure:
•General options
UM004001-COR11031–11
Page 24
Sample SessionIntroduction
•Warnings
•Optimization levels
•Preprocessor symbol definitions
•Code generation configuration
Perform the following steps to open the C-compiler Settings Option dialog box:
1. Open the project.
2. Select Settings from the Project menu. The Settings Options dialog box appears.
3. Click the C-Compiler tab. The C-Compiler Settings Option dialog box appears.
General Configuration
The C-compiler General page allows the user to enable or disable settings for the C-Compiler.
Perform the following steps to configure the General Page .
1. Select General from the Category pop-up list in the C-Compiler Settings dialog box. The
C-Compiler General page appears.
2. Click the Set Default button.
3. Click Apply.
FIGURE 1-6. C-COMPILER GENERALPAGE
The following options are available in the C-compiler General page.
1–12UM004001-COR1103
Page 25
IntroductionSample Session
•The Generate debug information option generates symbolic debug information in the
output object module. If a relocatable object file is being generated, symbols and other
debugging information are embedded in the output relocatable object file. If this option
is not checked, no symbolic debug information is generated. If this option is checked,
optimizations are not performed.
•The Display compiler version number option causes a two-line message to display in
the Output window that shows the C-Compiler copyright notice and version number.
•The Enable ZiLOG extensions causes the C-Compiler to automatically recognize
language extensions for the target device. These language extensions allow the
microcontroller to communicate with external devices.
•The Set Default button automatically configures the linker for use by the C-Compiler.
UM004001-COR11031–13
Page 26
Sample SessionIntroduction
Configuring Warnings
The C-Compiler Optimizations page allows the user to control the informational and warning
messages that are generated in the ZDS output window.
Perform the following steps to configure the Warnings page .
1. Select Warnings from the Category pop-up list in the C-Compiler Settings Options dialog
box. The Optimizations page appears.
2. Select the warnings you wish to apply.
3. Click Apply.
FIGURE 1-7. C-COMPILER WARNINGSPAGE
1–14UM004001-COR1103
Page 27
IntroductionSample Session
Configuring Optimization Levels
The C-Compiler Optimizations page allows the user to select an optimization level for the Ccompiler. See
Optimization Levels on page 2-9 for a detailed description of the different opti-
mization levels.
Perform the following steps to configure the Optimizations page .
1. Select Optimizations from the Category pop-up list in the C-Compiler Settings Options
dialog box. The Optimizations page appears.
2. Select Level 4 optimization.
3. Click Apply.
FIGURE 1-8. C-COMPILER OPTIMIZATIONSPAGE
The following optimization levels are available in the C-Compiler Optimizations page.
•The No optimization option disables all optimizations.
– constant propagation
– copy propagation
– dead code elimination
– common sub expression elimination
– jump to jump optimization
– loop invariant code motion
– constant condition evaluation and other condition evaluation optimizations
– constant evaluation and expression simplification
– all the optimizations in level 1
any redirection of read-only nonvolatile global or static data with a copy of the initial
expression.
•The Level 4 optimization option performs Level 2 optimizations three times, and
eliminates common sub-expressions by transforming expression trees.
1–16UM004001-COR1103
Page 29
IntroductionSample Session
Defining Preprocessor Symbols
The C-Compiler Preprocessor page allows you to define preprocessor definitions, and specify additional search paths for included files.
Perform the following steps to configure the Optimizations page .
1. Select Preprocessor from the Category pop-up list in the C-Compiler Settings dialog box.
The Preprocessor page appears.
2. In the Additional Include Directories field enter the C-Compiler’s installation path and
\INCLUDE.
For example: If the compiler’s installation path is C:\PROGRAMS\380 enter c:PRO-
GRAMS\380\INCLUDE.
3. Click Apply.
FIGURE 1-9. C-COMPILER PREPROCESSORPAGE
The Preprocessor page defines the following:
•The Preprocessor definitions field is used to define the names of the symbols that are
used by the preprocessor. Symbols may be defined with or without a value and
successive symbols should be separated by a comma.
EXAMPLE: DEBUG,VERSION=3 defines the symbol DEBUG, but does not
assign it a value. The statement also defines the symbol VERSION and assigns it
a value of 3.
UM004001-COR11031–17
Page 30
Sample SessionIntroduction
•The Additional Include Directories fie ld is use d t o e nte r a dd itional search paths the C-
compiler should use to locate included files. The search path can consist of directory
names separated by semicolons.
EXAMPLE: C:\PROGRAMS\ZDS\INCLUDE:LIB
Code Generation Configuration
The Code Generation page allows the user to define the name of memory sections.
Perform the following steps to configure the Memory page.
1. Select Code Generation from the Category pop-up list in the C-Compiler Settings dialog
box. The Memory page appears.
2. Enter the names that you wish to rename the memory sections to.
3. Click Apply.
FIGURE 1-10. CODE GENERATION MEMORYPAGE
1–18UM004001-COR1103
Page 31
IntroductionCompiling and Downloading
COMPILING AND DOWNLOADING
The following section shows how to compile a C file using ZDS and then download the created HEX file into the eval board’s EEPROM using the built in Debug Monitor program.
COMPILEA PROJECT
Perform the following steps to compile a project.
1. In ZDS open or create a project.
2. In the Project Viewer window, double click on the C file. The C file appears in the Edit
window.
3. Select Settings form the Project menu. The Setting Options dialog box appears.
4. Click the Linker tab and select Output from the Category pop-up menu.
5. Check Both in the Output Format window.
6. Click OK.
7. Select Build from the Build menu (the shortcut is F7). The project files are compiled and
linked. If an error occurs, double click on the error in the Output window .
8. If no errors occur, ZDS creates a HEX and COFF file and places them in the project
directory.
UM004001-COR11031–19
Page 32
Compiling and DownloadingIntroduction
DOWNLOADINGACOMPILEDFILE
Perform the following steps to load the a HEX file.
NOTE: A terminal program (PC host communication software) is required for initialization,
communication, and testing.
vided with Windows.
Open the Terminal
Perform the following steps to open the terminal:
1. Power-up the PC.
2. Launch a terminal program, Hyper Terminal is included with Windows.
3. Open the configuration screen of your terminal program, see Figure 1-11.
The following steps are shown using the Hyper terminal program pro-
FIGURE 1-11. SETTINGSFORHYPERTERMINALMONITOR
4. Select the COM port number where the evaluation board is connected.
5. Set the data rate at 9, 600 bps .
6. Set the bits to 8 bits with no parity.
7. Select no flow control.
8. Click OK.
9. Press the reset button on the board. This returns a command prompt and the board is ready
to communicate with host PC.
1–20UM004001-COR1103
Page 33
IntroductionTechnical Support
Download a HEX file
Perform the following steps to download a HEX file into the EEPROM memory on top of the
debug monitor program.
1. Type L at the debug monitor prompt. The user is prompted to begin downloading the file.
2. Select Send Text File from the Transfer menu.
3. Browse to the project directory and select the HEX file that was created when the C-file
was compiled
4. Click Open. The file is downloaded to the board. The download process can take up to two
minutes.
5. After the file is downloaded the debug monitor returns a result. If the monitor does not
return a result after 3 minutes, press Ctrl and Esc to exit the process and try again.
6. Type G at the debug monitor prompt. The user is prompted to enter a start address .
7. Enter a start address of 2100. The downloaded program should begin runnin g.
TECHNICAL SUPPORT
Technical support for ZDS or the C-Compilers can now be accessed on the web at
http://www.zilog.com.
To get the latest software upgrades for ZDS or 380 C-Compiler, go to the home page and
select Downloadable Software from the main menu.
UM004001-COR11031–21
Page 34
Page 35
380 C-COMPILER USER’S MANUAL
CHAPTER 2
C-COMPILER OVERVIEW
OVERVIEW
The 380 C compiler is an optimizing compiler that translates standard ANSI C programs into
ZiLOG assembly language source code. Key characteristics of the compiler are:
•Supports ANSI C language - ZiLOG’s C-Compiler conforms to the ANSI C standard
as defined by ANSI specifications a for free standing implementation.
•Assembly output - The compiler generates assembly language source files that can be
viewed and modified.
•Provides ANSI-standard run-time libraries - A run-time library for each device is
included with the compiler’s tools. All library functions conform to the ANSI C library
standard. These libraries include functions for string manipulation, buffer manipulation,
data conversion, math, variable length argument lists.
•COFF object files - Common object file format (COFF) is used. This format allows the
user to define the system’s memory map at link time. This maximizes performance by
linking C code and data objects into specific memory areas. Source-level debugging is
also supported by the COFF file format.
•Friendly assembly interface - The compilers calling conventions are easy to use and
flexible. These calling conventions allow the user to easily call assembly and C
functions.
•Preprocessor integration - The compiler front end has a built in preprocessor for faster
compilation.
•Optimization levels - The compiler allows the user to select optimization levels that
employ advanced techniques for compacting and streamlining C code.
•Language extensions - Language extensions are provided to support processor specific
features.
– Memory and I/O address spaces are supported through memory qualifiers
UM004001-COR11032–1
Page 36
Language ExtensionsC-Compiler Overview
– Support for interrupt functions
– Intrinsic functions are provided for in-line assembly.
•Intrinsic functions - Intrinsic functions are provided for inline assembly, setting
interrupt vectors and enabling and disabling interrupts.
LANGUAGE EXTENSIONS
The Z380 family of processors supports various address spaces that correspond to the different types of addressed locations and the method logical addresses are formed. The C-language, without extensions, is only capable of accessing data in one memory address space.
The Z380 C-compiler memory extensions allow the user to access data in the Z380 memory
address space, the external I/O address space, or the on-chip I/O address space.
ASSIGNING TYPES
Types are extended by adding memory qualifiers to the front of a statement. These memory
qualifiers are defined with the following keywords:
•__MEMORY assigns the type to the standard Z380 main memory address space.
•__EXTIO assigns the type to the external I/O port address space, through which
peripheral devices are accessed. There may be no allocations in this space, but pointers
to it may be defined and used.
•__INTIO assigns the type to the internal (on-chip) I/O port address space, through
which peripheral devices and system control registers are accessed. There may be no
allocations in this space, but pointers to it may be defined and used.
A derived type is not qualified by memory qualifiers (if any) of the type from where it was
derived. Derived types can be structures, unions and function return types.
EXAMPLE: __INTIO char * ptr;
In the above example ptr is a pointer to char in internal I/O address space. The ptr is
not memory qualified but is a pointer to a qualified memory type.)
DEFAULT MEMORY QUALIFIERS
Default memory qualifiers are applied if no memory qualifiers are specified. In all cases the
default memory qualifier is __MEMOR Y.
2–2UM004001-COR1103
Page 37
C-Compiler Overviewpointers
POINTERS
A pointer to a qualified memory type can not be converted to a different qualified memory
type.
SIZEOF POINTERS
Pointers are always 32-bits in size for the 380 C-compiler .
I/O ADDRESS SPACES
The compiler automatically generates the appropriate I/O instructions for accessing data in
the __INTIO and __EXTIO memory spaces. The machine instructions are described in
Table 2-1.
TABLE 2-1. I/O MACHINE INSTRUCTIONS
Action
LoadIN/INA/INAWIN0
StoreOUT/OUTA/OUTAWOUT0
__EXTIO__INTIO
UM004001-COR11032–3
Page 38
I/O ADDRESS SPACESC-Compiler Overview
ACCCESING I/O ADDRESS SPACE
The Z380 instruction set does not allow indirect acess of the internal I/O address space
through a register.
To acess the I/O adress space use the on-chip peripheral-addresses as operands to the
IN0/OUT0 machine instructions. Variable pointers can not be used to access the internal I/O
address space and address constants must be used.
The recommended usage the I/O adress space is hown in the below example.
typedef volatile unsigned char __INTIO *PBINTIO;
#defineIO_ADDR((PBINTIO)0x0002)
// …
unsigned char ch;
// …
IO_ADDR[0] = ch;// store to I/O address 2
// …
ch = IO_ADDR[0];// load from I/O address 2
// …
2–4UM004001-COR1103
Page 39
C-Compiler OverviewINTERRUPT FUNCTIONS
INTERRUPT FUNCTIONS
Interrupt functions are declared by preceding their definition with #pragma interrupt.
Such functions should not take parameters or return a value. For example:
#include <zilog.h>
#include <z382.h>
volatile int gprtCount;
#pragma interrupt
void timer(void)
{
char cDummy;
cDummy = tcr;
cDummy = tmdr0l;
cDummy = tmdr0h;
gprtCount++;
}
The compiler generates the following prologue and epilogue code for interrupt functions:
.align 2
_timer:
ex af,af’
exall
.
.
.
exall
ex af,af’
ei
reti
UM004001-COR11032–5
Page 40
INTERRUPT FUNCTIONSC-Compiler Overview
USING THE DOS COMMAND LINE
The z380 C compiler can be invoked from the DOS command line.
COMMANDLINEFORMAT
The syntax for the 380 C-Compiler command line is as follows:
z380 [switches] … source …
2–6UM004001-COR1103
Page 41
C-Compiler OverviewINTERRUPT FUNCTIONS
COMMANDLINESWITCHES
The following command-line switches are recognized.
TABLE 2-2. COMMANDLINESWITCHES
Switch Function
-D <macro>Define a preprocessor macro
-gGenerate symbolic debug information
-ISpecify include path. This option may be repeated to specify multiple
include paths
-Nbss<name> Names the uninitialized data section. Default is .bss.
-Ndata<name>Names the initialized data section. Default is .data.
-Ntext<name>Names the text section. Default is .text.
-0<name>Specifies the output assembly file name
-O0No optimization
-O1Level 1 optimization—Basic optimizations: Constant folding, dead
object removal and simple jump optimization
-O2Level 2 optimization—Constant propagation, copy propagation, dead
code elimination, common sub expression elimination, jump to jump
optimization, tail recursion elimination, loop invariant code motion,
constant condition evaluation and other condition evaluation
optimizations, constant evaluation and expression simplification and all
the optimizations in level 1
-O3Level 3 optimization—All the optimizations in level 2 are performed
twice. Also any redirection on a read only non-volatile global or static
data is replaced by a copy of its initial expression.
-O4Level 4 optimization—All the optimizations in level 2 are performed three
times. Also common subexpression elimination is attempted through
transformation of expression trees (
level)
-PSpecifies where to write the pre-processors’ ouput file
-VDisplay compiler version number
-WEnable warning messages
-WaEnable portability warnings about accuracy loss in conversions
-WallEquivalent to specifying all of the warning options
-WansiEnable warnings about non-ANSI usage
-WbEnable warnings about unreachable break statements
-WdEnable warnings about variable usage, such as unused variable, defined
but not used, etc.
This is the default optimization
UM004001-COR11032–7
Page 42
INTERRUPT FUNCTIONSC-Compiler Overview
TABLE 2-2. COMMANDLINESWITCHES
Switch Function
-WfEnable warnings about function return values
-WhEnable some heuristic warnings
-WpEnable portability warnings, and warnings about handling enumeration
types
-WstrictEnable strict warnings
-WvEnable warnings about unused parameters (not included in –Wd)
-WxEnable warnings about unused global objects
-ZiLOGAllow // style comments
-Zp2Pack data on word (2 byte) boundary. By default, 32-bit objects are
aligned on 32-bit (4 byte) boundaries. This option aligns 16-bit and 32-bit
objects on 16-bit (2 byte) boundaries.
NOTE: Other switches are for ZiLOG use only in this version.
COMMAND LINE EXAMPLES
Compiling
The command for Z380:
Z380 test.c generates test.s. By default the -04 options is used.
Assembling
The command for 380:
zma -pz380 -j -otest.o test.s generates test.o
Linking
The command for 380:
zld -mtest -otest (compiler installation path)\z380inits.o test.o gener-
ates test.ld and test.map.
2–8UM004001-COR1103
Page 43
C-Compiler OverviewOptimization Levels
OPTIMIZATION LEVELS
The Z380 C-compiler allows the user to manually specify the level of optimization they want
to have performed on their code. The optimization levels are controlled through the C-com
piler options dialog box. See Configuring Optimization Levels on page 1-15 for more information on the C-compiler Settings Option dialog box.
The Z380 C-compiler allows you to specify four levels of optimizations. The optimizations
are:
– constant propagation
– copy propagation
– dead-code elimination
– common sub-expression elimination
– jump-to-jump optimization
– loop invariant code motion
– constant condition evaluation and other condition evaluation optimizations
– constant evaluation and expression simplification
– all the optimizations in level 1
-
•Check Level 3 optimization to perform Level 2 optimizations twice, and replace any
redirection of read-only nonvolatile global or static data with a copy of its initial
expression.
•Check Level 4 optimization to perform Level 2 optimizations three times, and
eliminate common sub-expressions by transforming of expression trees.
DEBUGGING CODEAFTER OPTIMIZATION
Debugging of code should be complete before performing any level of optimization on the
code. If the generate debug information is on no optimizations are performed, even if an opti
mization level is chosen.
NOTE: To enable or disable debug information in ZDS select Settings from the Options menu. Click
the
Linker tab and select Output from the Category pop-up list.
UM004001-COR11032–9
-
Page 44
Optimization LevelsC-Compiler Overview
Level 1 Optimizations
The following is a description of the optimizations that are performed during a level 1 optimization.
Constant Folding
The compiler simplifies expressions by folding them into equivalent forms that require fewer
instructions.
EXAMPLE: Before optimization: a=(b+2) +(c+3); After optimization:
a=b+c+5
Dead Object Removal
Local and static variables that are declared but never used are removed
Simple Jump Optimization
Jump to next instruction is removed. Unreachable code is also removed.
LEVEL 2 OPTIMIZATIONS
Level 2 optimization performs all the optimizations in Level 1 plus the following new optimizations.
Constant Propagation
Unaliased local variables are replaced by their assigned constant.
Copy Propagation
The compiler replaces references to the variable with its value. The value could be another
variable, a constant, or a common sub-expression. This replacement increases the chances for
constant folding, common sub-expression elimination, or total elimination of the variable.
Dead Code Elimination
Useless code is removed or changed. For example: assignments to local variables that are not
used afterwards are removed.
Common Sub Expression Elimination
When the same value is produced by two or more expressions, the compiler computes the
value once, saves it, and reuses it.
2–10UM004001-COR1103
Page 45
C-Compiler OverviewUnderstanding errors
Jump to Jump Optimization
Targets in the control statement are replaced by the ultimate target.
Loop Invariant Code Motion
Expression within loops that compute the same value are identified and are replaced by a reference to a precomputed value.
Constant Condition Evaluation
The conditional expressions that are constant are computed at compile time.
Constant Evaluation and Expression Simplification
Replaces an expression by a simpler expression with the same semantics using constant folding, algebraic identities and tree transformations.
LEVEL 3 OPTIMIZATIONS
Level 3 optimization perform all the Level 2 optimizations twice, and replaces any redirection of read-only nonvolatile global or static data with a copy of its initial expression.
LEVEL 4 OPTIMIZATIONS
Level 4 optimization performs Level 2 optimizations three times, and eliminates common
sub-expressions by transforming of expression trees.
UNDERSTANDING ERRORS
The Z380 C-Compiler detects and reports errors in the source program. When an error is
encountered, an error message is displayed in the ZDS Output window.
For example:
“ file.c”, line n: error message
ENABLING WARNING MESSAGES
Warning messages can be disabled or enabled through the command line. See Table 2-2 for
more information on the various warnings that can be enabled.
UM004001-COR11032–11
Page 46
Included FilesC-Compiler Overview
INCLUDED FILES
A path to included files must be defined before the C-Compiler can recognize included files.
An included files path is set in the Preprocessor page in the C-Compiler setting options dia
log box. For more information on the Preprocessor page, see Defining Preprocessor Symbols
on page 1-17. For command line version -I command line option can be used to specify the
include path.
PREDEFINED NAMES
The Z380 C-compiler comes with four predefined macro names. These names are:
•_LINE_ Expands to the current line number
•_FILE_ Expands to the current source filename
•_DATE_ Expands to the compilation date in the form of mm dd yy
•_TIME_ Expands to the compilation time in the form of hh:mm:ss
NOTE: For more information on using the command line see page 2-6.
GENERATED ASSEMBLY FILE
-
After compiling a c-file an assembly file is generated and placed in the project directory . The
assembly files are downloaded and linked and a COFF file is produced that is downloaded to
the emulator. The user can modify the assembly in the ZDS Editor window.
To open and edit the assembly file:
1. Select Open File from the ZDS Edit menu. The Open file dialog box appears.
2. Select Assembler Files from the files of type pull down menu.
3. Browse to the project directory and double click on the file you want to open. The selected
file appears in the ZDS edit window.
OBJECT SIZES
The following table lists basic objects and their size.
Type Size
char8 bits
short16 bits
int32 bits
long32 bits
2–12UM004001-COR1103
Page 47
C-Compiler OverviewSection Names
Type Size
float32 bits
double32 bits
long double32 bits
SECTION NAMES
The compiler places code and data into separate sections in the object file. Every section has
a name that is used by the linker to determine which sections to combine and how sections
are ultimately grouped in the executable file.
•Code Section (.text)
•Initialized Data Section (.data)
•Uninitialized Data Section (.bss)
•Constant Data Section (.const)
NOTE: All sections are allocated in the __MEMORY address space. The default sections .text,
.data, and .bss can be renamed using the –Ntext, –Ndata, and –Nbss command line options.
UM004001-COR11032–13
Page 48
Incorporating Assembly with CC-Compiler Overview
INCORPORATING ASSEMBLY WITH C
The Z380- C-Compiler allows the user to incorporate assembly code into their C code.
In the body of a function, use the asm statement. The syntax for the ASM statement is
_asm(“<assembly line>”);.
•The contents of <assembly line> must be legal assembly syntax
•The only processing done on the <assembly line> is escape sequences
•Normal C escape sequences are translated
Example
#include <zilog.h>
int main()
{
_asm(“\tnop\n”);
return (0);
}
INCORPORATING C WITH ASSEMBLY
The C libraries that are provided with the compiler can also be used to add functionality to an
assembly program. The user can create their own function or they can reference the library
using the ref statement.
NOTE: The C-compiler precedes the use of globals with an underscore in the generated assembly.
Example
The following example shows the C function imul() being called from assembly lan-
guage. The assembly routine pushes two words onto the stack (parameters x and y for the
function imul), calls the function imul, then cleans the arguments off the stack.
Assembly file.
.ref _imul; Compiler prepends ‘_’ to names
.text
_main:
push.w20; parameter <y>
push.w10; parameter <x>
2–14UM004001-COR1103
Page 49
C-Compiler OverviewIncorporating C with assembly
call.ib _imul; (hl)=product
add sp,4; clean the stack
ret; return result in (hl)
Referenced C file.
typedef unsigned long uint32;
typedef unsigned short uint16;
typedef char int8;
uint32
imul(uint16 x, uint16 y)
{
uint32 res;
int8 i;
res = 0;
for (i=0; i < 16; i++)
{
if (y & 1)
{
res += x;
}
x = x << 1;
y = y >> 1;
}
return res;
}
UM004001-COR11032–15
Page 50
Page 51
380 C-COMPILER USER’S MANUAL
CHAPTER 3
LINKING FILES
INTRODUCTION
The purpose of the Zilog cross linker is to read relocatable object files and libraries and link
them together to generate an executable load file. The file may then be loaded or written to a
target system and debugged using ZDS. This chapter briefly describes the linker’s inputs and
outputs, and how the inputs to the linker are transformed into those outputs.
Relocatable
Object File (s)
Librarian
Library File
FIGURE 3-1. LINKERFUNCTIONALRELATIONSHIP
Relocatable
Object File (s)
Linker
Executable
Load File
Debugger
WHATTHE LINKER DOES
The linker performs the following fundamental actions:
UM004001-COR11033–1
Page 52
IntroductionLinking Files
•Reads in Relocatable object modules and library files in Common Object File Format
(COFF) or ZiLOG Object Module Format (ZOMF)
•Resolves external references
•Assigns absolute addresses to Relocatable sections
•Supports Source-Level Debugging (SLD)
•Generates a single executable module to download into the target system or burn into
OTP or EPROM programmable devices
•Generates a map file
•Generates COFF files (for Libraries)
Linkage Editing
The linker creates a single executable load module from multiple relocatable objects.
Resolving External References
After reading multiple object modules, the linker searches through each of them to resolve
external references to public symbols. The linker looks for the definition of public symbols
corresponding to each external symbol in the object module.
Relocating Addresses
The linker allows the user to specify where the code and data are stored in the target processor system’s memory at run-time. Changing relocation addresses within each section to an
absolute address is handled in this phase.
Debugging Support
When the debug option is specified, the linker creates an executable file that can be loaded
into the debugger at run-time. A warning message is generated if any of the object modules
do not contain a special section that has debug symbols for the corresponding source module.
Such a warning indicates that a source file was compiled or assembled without turning on a
special switch that tells the compiler or assembler to include debug symbols information
while creating a relocatable object module.
Creating Map Files
The linker can be directed to create a map file that details the location of the Relocatable sections and Public Symbols.
3–2UM004001-COR1103
Page 53
Linking FilesUsing the Linker with the C-compiler
Outputting OMF Files
Depending upon the options specified by the user, the linker can produce two types of OMF
files:
•Intel Hex Format Executable File
•COFF Format Executable File
USING THE LINKER WITH THE C-COMPILER
The linker is used to link compiled and assembled object files, C-Compiler libraries, user
created libraries and C runtime initialization files. These files are linked according to the
commands that are given in the linker command file. Once the files are linked an executable
file in COFF (.ld) format is produced. The linker can also produce Intel hex (.hex, .dat) files,
map files (.map) and symbol files (.sym) in ZiLOG symbol format.
The primary components of the linker are shown in Figure 3-2.
Link Command
Line or File
(text file)
Symbol File in Zilog Sym-
bol Format
(text file)
Map File
C-compiler libraries
Linker
Link and Relocate
Linker Messages
Relocatable Object Mod-
ules
and
ZOMF or COFF Library
Files
(binary files)
C run-time Initialization files.
Executable Intel Hex
(.hex & .dat) or COFF
(.ld) Format File
FIGURE 3-2. LINKERCOMPONENTS
UM004001-COR11033–3
Page 54
Invoking the LinkerLinking Files
RUN TIME INITIALIZATION FILE
The C run-time initialization file is an assembly program that initializes memory before linking. This assembly program clears the .bss section, sets the pointer, and initializes the processor mode resister. Once these initializations are complete the program calls main, which is
the C entry point.
INSTALLEDFILES
The following linker associated files are installed in the C-Compiler installation directory.
TABLE 3-1. LINKERREFERENCEDFILES
FileDescription
z380boot.sAssembly language source of example C startup module
z380.lnkExample linker command file for z380
libc.libStandard C library for small model.
lhf.libLibrary of runtime helper functions
NOTE: Source files for the run-time initialization files are provided in Appendix A, Initialization and
Link Files.
INVOKING THE LINKER
The linker can be invoked either through ZDS or the DOS command line.
USINGTHE LINKERIN ZDS
The linker is automatically invoked when performing a build in ZDS. Th e following steps are
performed when using the linker with ZDS.
1. ZDS calls the linker after compiling and assembling all the files.
2. All the object files and libraries that are include in the project are linked.
3. Error or warning messages that are generated by the linker are displayed in the ZDS output
window.
4. If no errors are encountered the linker produces an executable file in either a COFF or HEX
format. This executable file is placed in the project directory.
3–4UM004001-COR1103
Page 55
Linking FilesInvoking the Linker
NOTE: The user needs to include the C-run time initialization file that is appropriate for the compila-
tion model chosen in the project. See Table 3-1 for a list of initialization files that are included with
the C-Compiler. For more information on adding included files see Manually Configuring the Compiler on page 1-9.
Configuring the Linker with ZDS
Perform the following steps to set the linker command file options in ZDS :
1. Open the project
2. Select Settings from the Project menu. The Settings Options dialog box appears.
3. Click the C-Compiler tab.
4. Select General from the Category pop-up list in the C-Compiler Settings dialog box. The
C-compiler General page appears.
5. Click the Set Default button.
6. Click Apply.
NOTE: The linker’s setting s can also be modified through the Linker Settings dialog box. Consult
ZDS’s on-line help for more information on configuring the linker.
USINGTHELINKERWITHTHECOMMANDLINE
Use the syntax below to invoke the linker on the command line :
zld -o output name -a init-object-files {object files} c-comp-lib-file lib-filesmap-file
linker-command-file
•output-name is th e .ld filename. For example if test.ld is the desired output file,
then the output name should be test.
•init. -object- file is the C run time initialization file. The user can specify their own
initialization files to use. If the file is not in the current directory the path needs to be
included in the file name.
•{object files} is the list of object files that are to be linked.
•c-comp-lib-file is the C-compiler library files that need to be linked. See Table 3-1 for
a list of library files that are include with the C-compiler.
•lib-files is the library files created by the user using the ZDS archiver (ZAR).
•map-file is the map file’s name that is to be generated by the linker.
UM004001-COR11033–5
Page 56
Linker symbolsLinking Files
•linker-command-file is the command file to be linked by the linker. Sample command
files are provided in the lib directory. See
include with the C-compiler.
Linker Command Line example
The following example shows how to invoke the linker using the DOS command line.
zld -otest -A lib-path\z380boot.o test.o lib-path\libc.lib
lib-path\z380.link -mtest.map
This example generates a test.ld, test.hex, test.dat, test.sym and
test.map as output. The lib-path is the (c-compiler installation path)\lib, and test.o
is the object file corresponding to the C file created after compiling and assembling.
For more information on the linker command line see Linker Command Line on page 3-10.
LINKER SYMBOLS
The linker command file defines the symbols that are used by the C run-time initialization
file to initialize the stack pointer, register pointer and clear the BSS section.
the symbols that are used by the linker.
Table 3-1 for a list of command files that are
Table 3-2 shows
TABLE 3-2. LINKERSYMBOLS
SymbolDescription
BSS_BASEBase of .BSS section
BSS_LENGTHLength of .BSS section
TOSTop of stack
3–6UM004001-COR1103
Page 57
Linking FilesLinker Command File
LINKER COMMAND FILE
The linker command file is text file that contains the linker command and options. The linker
commands that can be used in the command file are summarized in
options see Table 3-4.
TABLE 3-3. SUMMARYOF LINKER COMMANDS
CommandDescription
AssignAssigns a control section to an address space
CopyMakes a copy of a control section
DefineCreates a public symbol at link-time; helps resolve an external symbol referenced at
assembly time
GroupCreates a group of control sections that can be defined using the range command
LocateSet the base address for the control section
OrderSpecifies the ordering of specified control sections
Table 3-3. For linker
RangeSets a lower bound and an upper bound for an address space or a control section
NOTE: The linker commands are listed alphabetically in the table, for convenience; however, it is not
required that commands be specified alphabetically in the command file. Command words and param
eters other than those shown in the table are not legal. If any other word or parameter is used, an error
message is written to the messages file, and the linker terminates without linking anything.
Linker Command ASSIGN
The ASSIGN command assigns a control section to an address space. This command is
designed to be used in conjunction with the assembler’s .SECT instruction.
Syntax: ASSIGN <section> <address-space>
The <section> must be a control section name, and the <address-space> must be an address
space name.
Example: ASSIGN DSEG DATA
Linker Command COPY
This command makes a copy of a control section. The control section is loaded at the specified location, rather than at its linker-determined location. This command is designed to
UM004001-COR11033–7
-
Page 58
Linker Command FileLinking Files
make a copy of an initialized RAM data section in a ROM address space, so that the RAM
may be initialized from the ROM at run time.
Syntax: COPY <section> <address-space> [ AT <expression> ]
The <section> must be a control section name, and the <address-space> must be an address
space name. The optional AT <expression> is used to copy the control section to a specific
address in the target address space.
Example: COPY bank1_data ROM or COPY bank1_data ROM at %1000
Linker Command DEFINE
This command is used for a link-time creation of a user defined public symbol. It helps in
resolving any external references (EXTERN) used in assembly time.
Syntax: DEFINE <symbol name> = <expression>
<symbol name> is the name of the public symbol. <expression> is the value of the public
symbol.
Example: DEFINE copy_size = copy top of usr_seg - copy base of usr_seg
3–8UM004001-COR1103
Page 59
Linking FilesLinker Command File
The “Expression Formats” section, which follows, explains different types of expressions
that can be used.
Linker Command GROUP
This command allows the user to group control sections together and define the size of the
grouped sections using the RANGE command.
Syntax: GROUP <group name> = <section1> <section2> ]
The group name is the name of the grouped sections. The group name can not be the same
name as an existing address space. Section1 and section2 are the sections assigned to the
group. Sections within a group are allocated in the specified order.
NOTE: The new group’s lower address location and size must be defined uisng the linker’s RANGE
command.
Example:
GROUP RAM =.data,.bss
RANGE RAM = 1000h:1FFFh
This example defines RAM as a block of memory in the range of 1000h to 1FFFh. The
.data and
.bss control sections are allocated to this block. The .data section is allo-
cated at address 1000h and the .bss section is allocated at the end of the .data section.
Linker command LOCATE
This command sets the base address for a control section.
The name must be a control section name. The address be within the address range of the
address space to which the control section belongs.
Linker Command ORDER
This command determines a sequence of linking.
Syntax: ORDER <name1> [,<name2> ...]
<namen> must be a control section name.
Example: ORDER CODE1, CODE2
UM004001-COR11033–9
Page 60
Linker Command LineLinking Files
Linker Command RANGE
This command sets the lower and upper limits of a control section or an address space. The
linker issues a warning message if an address falls beyond the range declared with this com
mand.
The linker provides multiple ways for the user to apply this command for a link session. Each
separate case of the possible syntax is described below.
CASE 1
Syntax : RANGE <name> <expression> , <length> [ , ... ]
<name> may be a control section, or an address space. The first <expression> indicates the
lower bound for the given address RANGE. The <length> is the length, in words, of the
object.
<name> may be a control section or an address space. The first <expression> indicates the
lower bound for the given address RANGE. The second <expression> is the upper bound for
it.
Example: RANGE ROM %17ff : %2000
-
NOTE: Refer to the Expression Formats for the format of writing an expression.
LINKER COMMAND LINE
The syntax for the linker command line is:
ZLD [<options>]<filename1> ...<filenamen>.
•The “[ ]” enclosing the string “options” denotes that the options are not mandatory. In
this document this convention is continued for further discussion on linker’s syntax and
operations.
•The items enclosed in “< >” indicate the non-literal items.
•The “. . .” (ellipses) indicate that multiple tokens can be specified. These tokens are of
the type of the non-literal specified in the syntax just prior to the ellipses.
•The syntax uses “%” prefix to a number to specify a hexadecimal numeric
representation.
•The linker links the files listed in <filename> list. Each <filename> is the name of a
COFF object file or library file, or the name of a text file containing linker commands
and options.
3–10UM004001-COR1103
Page 61
Linking FilesLinker Command Line
COMMAND LINE SPECIFICATIONS
The following rules govern the command line specification:
•ZLD examines the named files’ content to determine the file type (object, library, or
command).
•The file names of the input files specified on the command line must be separated by
spaces or tabs.
•The commands are not case sensitive; however, command line options and symbol
names are case sensitive.
•The order of specifying options does not matter.
•The options must appear before the filenames.
•Specifying that input files use both command line and list creates a union of the two sets
of inputs that is treated as input object and library files. The linker links the file twice,
if the file names appear twice.
•During linking, the linker combines all object files in the order specified and resolves
the external references. linker searches through the library files when it is unable to
resolve references.
•A command file is a text file containing linker commands and options. Comments can
be specified by use of the “;” character.
•If the linker is unable to open a named object file, library file, or a link command file,
an error message is written to the standard error device, and the linker terminates
without linking anything.
•If an unsupported OMF type of object file is included in the <filename> list, the linker
displays an error message and terminates without linking anything.
UM004001-COR11033–11
Page 62
Linker Command LineLinking Files
LINKER COMMAND LINE OPTIONS
Linker options are specified by prefixing an option word with a minus (-). The linker options
are summarized in
TABLE 3-4. SUMMARYOF LINKER OPTIONS
OptionsDescription
-?Displays product logo, version number, and brief description of command line format
-aGenerates an absolute object file in Intel Hex Format or Zilog Symbol Format.
-e <entry>Specifies the program entry point. <entry> is any Public symbol.
-gGenerates symbolic debug information.
-m <mapfile>Generates the map file.
-o <objectfile>Generates the output file.
-qDisables disp lay of linker’s copyright notice.
Table 3-4 .
and options.
-r
-WTreats warnings as errors.
-wDisables the generation of warning messages.
1. It is not required that options be specified alphabetically on the command line.
2. If any other option word is used, an error message is written to the messages file, and the linker termi nates withou t
linking anything.
3. All options must be preceded by a dash (-).
NOTE: For more information on the linker options refer to the ZDS On-line help.
3–12UM004001-COR1103
Disables address range checking on relocatable expression. This option should be
used when linking compiler generated code
.
Page 63
Linking FilesUsing the Librarian
Symbol File In Zilog Symbol Format
A symbol file in the Zilog symbol format is generated when the user specifies the absolute
link mode (-a linker option). It is in the standard Zilog symbol format as shown in
which follows. In each row, the first column lists the symbol name, second column lists the
attribute of the symbol (“I” stands for internal symbol, “N” stands for local symbol, and “X”
stands for public symbol), and the third column provides the value of the symbol expressed
as four hexadecimal bytes.
_dgt_outbfrI 0000800d
_digit_cntrI 00008011
_dgt_inbfrI 00008012
_led_refreshI 000000b5
hex_regN 00008009
_bcd_hex_conv
I fffff7f5
Figure 3-3,
_7conv_reg_4N 00008009
_8conv_reg_3N 0000800a
FIGURE 3-3. SAMPLE SYMBOL FILE
USING THE LIBRARIAN
The librarian allows the user to modify libraries and view the contents of individual library
files.
The syntax for the librarian command line is as follows:
Zar [options] library [ member1 … membern ]
The librarian performs the operation specified in the options on the named library using the
named member files. Libraries conventionally have an extension of .lib and library mem
bers have an extension of .o.
UM004001-COR11033–13
-
Page 64
COMMAND LINE OPTIONS
Command line options are specified by prefixing an option letter with a minus (-). The command line options are summarized in Table 3-5.
.
TABLE 3-5. SUMMARYOF LIBRARY OPTIONS
OptionsDescription
-?
-a
-d
-q
-r
-t
-x
Requests a usage display.
Appends the specified members to the library. This command does not replace
an existing member that has the same name as an added member; it simply
appends new members to the end of the library.
Deletes the specified members from the library.
Quiet mode: suppress display of the librarian copyright notice.
Replaces the specified members in the library. If a specified member is not
found in the library, the librarian adds it instead of replacing it.
Prints a table of contents of the library. If you don’t specify any member
names, the librarian lists the names of all members of the library. If you
specify any member names, only those members are listed.
Extracts the specified members from the library. The librarian does not
remove from the library those members that it extracts.
Page 65
380 C-COMPILER USER’S MANUAL
CHAPTER 4
RUN TIME ENVIRONMENT
FUNCTION CALLS
The C-compiler imposes a strict set of rules on function calls. Except for special runtimesupport functions, any function that calls or is called by a C-function must follow these rules.
Failure to adhere to these rules can disrupt the C-environment and cause a program to fail.
FUNCTION CALL STEPS
A function performs the following tasks when it calls another function:
1. The caller saves the registers that are in use.
2. The caller pushes the arguments on the stack in reverse order (the rightmost declared
argument is pushed first, and the leftmost is pushed last). This places the leftmost argument
on top of the stack when the function is called.
3. The caller calls the function.
4. When the called function is complete, the caller pops the arguments off the stack.
UM004001-COR11034–1
Page 66
Function CallsRun Time Environment
Run Time Stack
ParameterN
.
.
.
Parameter 1
Parameter 0
Return address
Frame Pointer
Stack Pointer
RESPONSIBILITIESOFA CALLED FUNCTION
A called function must perform the following tasks.
1. Push the frame pointer (IX) onto the stack.
Caller’s frame pointer (IX)
Locals
Temporaries
FIGURE 4-1. FRAMELAYOUT
High Address
Low Address
2. Allocate the local frame.
3. Execute the code for the function.
4. If the function returns a scalar value it is placed in the accumulator (HL register for scalars
greater than eight bits and the
5. Deallocate the local frame.
6. Restore the caller’s frame pointer.
7. Return.
4–2UM004001-COR1103
A register for eight-bit scalars).
Page 67
Run Time EnvironmentUsing the Run-Time Library
SPECIALCASESFORACALLEDFUNCTION
The following exceptions apply to special cases for called functions.
Returning a structure
If the function returns a structure, the caller allocates the space for the structure on top of the
stack. The size of the space allocated is the size of structure plus two additional bytes. To
return a structure, the called function then copies the structure to the space allocated by the
caller.
Not allocating a local frame
If there are no local variables, no arguments, no use of temporary locations, the code is not
being compiled to run under the debugger and the function does not return a structure, there
is no need to allocate a stack frame.
USING THE RUN-TIME LIBRARY
The C-Compiler provides a collection of run-time libraries that can be easily referenced and
incorporated into your code. The following sections describe the use and format of run-time
libraries. Each library function is declared in a supplied header file. These header files can be
included in C programs using the #include preprocessor directive. See
cessor Symbols on page 1-17 for more information on including header files.
Defining Prepro-
Each header file contains declarations for a set of related functions plus any necessary types
and additional macros. See
Table 4-1 for a description of each header file that is include with
the C-Compiler.
The header files are installed in the include directory of the compiler installation path. The
library files are installed in the lib directory of the compiler installation path.
UM004001-COR11034–3
Page 68
Using the Run-Time LibraryRun Time Environment
INSTALLEDFILES
The following header files are installed in the C-Compiler installation directory.
limits.hInte rger limits
math.hMath functions
stdarg.hVariable argument macros
stddef.hStandard defines
stdio.hStandard types and defines
stdlib.hGeneral utility functions
string.hString handling functions
zilog.h ZiLOG specific functions and defines
z382.hZ382 specific functions and defines
Errors
Floating point limits
4–4UM004001-COR1103
Page 69
Run Time EnvironmentLibrary Functions
LIBRARY FUNCTIONS
Run-time library routines are provided for the following:
•Buffer Manipulation
•Character Classification and Conversion
•Data Conversion
•Math
•Searching and Sorting
•String Manipulation
•Variable-Length Argument Lists
•Intrinsic functions
_asm FUNCTION
Header file statement: #include <zilog.h>
Syntax: _asm ("assembly language instruction")
The _asm pseudo-function emits the specified assembly language instruction to the compilergenerated assembly file. The _asm pseudo-function accepts a single parameter, which must
be a string literal.
Return Value
There is no return value.
abs FUNCTION
Header file statement: #include<stdlib.h>
Syntax: int abs( int n );
Parameter Description
nInteger Value
The abs function returns the absolute value of its integer parameter n.
Return Value
The abs function returns the absolute value of its parameter. There is no error return.
int atoi( const char *string );
long atol( const char *string );
Parameter Description
stringString to be converted
These functions convert a character string to a double-precision floating-point value (atof),
an integer value (atoi), or a long integer value (atol). The input string is a sequence of charac
ters that can be interpreted as a numerical value of the specified type.
The function stops reading the input string at the first character that it cannot recognize as
part of a number. This character may be the null character (‘\0’) terminating the string.
The atof function expects string to have the following form:
[whitespace] [sign] [digits] [.digits] [ {d | D | e | E }[sign]digits]
-
A whitespace consists of space and/or tab characters, which are ignored; sign is either plus
(+) or minus (-); and digits are one or more decimal digits. If no digits appear before the dec
imal point, at least one must appear after the decimal point. The decimal digits may be followed by an exponent, which consists of an introductory letter ( d, D, e, or E) and an
optionally signed decimal integer.
The atoi and atol functions do not recognize decimal points or exponents. The string argument for these functions has the form
[whitespace] [sign]digits
where whitespace, sign, and digits are exactly as described above for atof.
Return Value
Each function returns the double, int, or long value produced by interpreting the input characters as a number . The return value is 0 (for atoi), 0L (for atol), and 0.0 (for atof) if the input
cannot be converted to a value of that type.
•The return value is undefined in case of overflow.
4–6UM004001-COR1103
-
Page 71
Run Time EnvironmentLibrary Functions
div FUNCTION
Header file statement: #include <stdlib.h>
Syntax: div_t div( int num, int denom);
Parameter Description
numer
denomDenominator
The div function divides numer by denom, computing the quotient and the remainder. The
div_t structure contains the following elements:
Element Description
int quot
int remRemainder
The sign of the quotient is the same as that of the mathematical quotient. Its absolute value is
the largest integer that is less than the absolute value of the mathematical quotient. If the
denominator is 0, the behavior is undefined.
Numerator
Quotient
Return Value
The div function returns a structure of type div_t, comprising both the quotient and the
remainder. The structure is defined in the stdlib.h header file.
is FUNCTIONS
Header file statement: #include <ctype.h>
Syntax: int isalnum( int c );
int isalpha( int c );
int iscntrl( int c );
int isdigit( int c );
int isgraph( int c );
int islower( int c );
int isprint( int c );
int ispunct( int c );
UM004001-COR11034–7
Page 72
Library FunctionsRun Time Environment
int isspace( int c );
int isupper( int c );
int isxdigit( int c );
Parameter Description
c
Interger to be tested
Each function in the is family tests a given integer value, returning a nonzero value if the
integer satisfies the test condition and 0 if it does not. The ASCII character set is assumed.
The is functions and their test conditions are listed below:
4–8UM004001-COR1103
Page 73
Run Time EnvironmentLibrary Functions
FunctionTest Condition
isalnumAlphanumeric (‘A’-‘Z’, ‘a’-‘z’, or ‘0’-‘9’)
isalphaLetter (‘A’-‘Z’ or ‘a’-‘z’)
iscntrl Control character (0x00 - 0x1F or 0x7F)
isdigitDigit (‘0’-‘9’)
isgraphPrintable character except space (‘ ‘)
islowerLowercase letter (‘a’-‘z’)
isprint Printable character (0x20 - 0x7E)
ispunct Punctuation character
isspace White-space character (0x09 - 0x0D or 0x20)
isupperUppercase letter (‘A’-‘Z’)
isxdigitHexadecimal digit (‘A’-‘F’,’a’-‘f’, or ‘0’-‘9’)
Return Value
These routines return a nonzero value if the integer satisfies the test condition and 0 if it does
not.
labs FUNCTION
Header file statement: #include <stdlib.h>
Syntax: long labs( long n );
Parameter Description
n
The labs function produces the absolute value of its long-integer argument n.
Return Value
The labs function returns the absolute value of its argument. There is no error returned.
The memchr function looks for the first occurrence of c in the first count bytes of buf. It
stops when it finds c or when it has checked the first count bytes.
Return Value
If successful, memchr returns a pointer to the first location of c in buf. Otherwise, it returns
NULL.
The memcpy function copies count bytes of src to dest. If the source and destination overlap,
these functions do not ensure that the original source bytes in the overlapping region are cop
ied before being overwritten. Use memmove to handle overlapping regions.
The memmove function copies count characters from the source (src) to the destination
(dest). If some regions of the source area and the destination overlap, the memmove function
ensures that the original source bytes in the overlapping region are copied before being over
written.
The memset function sets the first count bytes of dest to the character c.
Return Value
The memset function returns the value of dest.
rand FUNCTION
Header file statement: #include <stdlib.h>
Syntax: int rand (void);
The rand function returns a pseudorandom integer in the range 0 to RAND_MAX. The srand
routine can be used to seed the pseudorandom-number generator before calling rand.
Return Value
The rand function returns a pseudorandom number, as described above. There is no error
returned.
The srand function sets the starting point for generating a series of pseudorandom integers.
To reinitialize the generator, use 1 as the seed argument. Any other value for seed sets the
generator to a random starting point.
The rand function is used to retrieve the pseudorandom numbers that are generated. Calling
rand before any call to srand generates the same sequence as calling srand with seed passed
as 1.
The strcat function appends string2 to string1, terminates the resulting string with a null character, and returns a pointer to the concatenated string (string1).
The strcat function operates on null-terminated strings. The string arguments to this function
are expected to contain a null character (‘\0’) marking the end of the string. No overflow
checking is performed when strings are copied or appended.
Return Value
The return values for this function are described above.
The strchr function returns a pointer to the first occurrence of c (converted to char) in string.
The converted character c may be the null character (‘\0’); the terminating null character of
string is included in the search. The function returns NULL if the character is not found.
The strchr function operates on null-terminated strings. The string arguments to these functions are expected to contain a null character (‘\0’) marking the end of the string.
Return Value
The return values for this function are described above.
The strcmp function compares string1 and string2 lexicographically and returns a value indicating their relationship, as follows:
Value Meaning
< 0string1 less than string2
= 0string1 identical to string2
> 0string1 greater than string2
The strcmp function operates on null-terminated strings. The string arguments to these func-
tions are expected to contain a null character (‘\0’) marking the end of the string.
String to compare
String to compare
Note that two strings containing characters located between ‘Z’ and ‘a’ in the ASCII table
(‘[’, ‘\’_’]’, ‘^’, ‘_’, and ‘‘’) compare differently depending on their case. For example, the
two strings, "ABCDE" and "ABCD^", compare one way if the comparison is lowercase
("abcde" > "abcd^") and compare the other way ("ABCDE" < "ABCD^") if it is uppercase.
Return Value
The return values for this functions are described above.
The strcpy function copies string2, including the terminating null character, to the location
specified by string1, and returns string1.
The strcpy function operates on null-terminated strings. The string arguments to th is function
are expected to contain a null character (‘\0’) marking the end of the string. No overflow
checking is performed when strings are copied or appended.
Return Value
The return values for this function are described above.
The strcspn functions return the index of the first character in string1 belonging to the set of
characters specified by string2. This value is equivalent to the length of the initial substring
of string1 consisting entirely of characters not in string2. Terminating null characters are not
considered in the search. If string1 begins with a character from string2, strcspn returns 0.
The strcspn function operates on null-terminated strings. The string arguments to these functions are expected to contain a null character (‘\0’) marking the end of the string.
Return Value
The return values for this function are described above.
string1
string2Source string
countNumber of characters appended
Destination string
The strncat function appends, at most, the first count characters of string2 to string1, terminate the resulting string with a null character (‘\0’), and return a pointer to the concatenated
string (string1). If count is greater than the length of string2, the length of string2 is used in
place of count.
Return Value
The return values for these functions are described above.
string1
string2
countNumber of characters compared
The strncmp function lexicographically compares, at most, the first count characters of
string1 and string2 and return a value indicating the relationship between the substrings, as
listed below:
ValueMeaning
< 0string1 less than string2
= 0string1 identical to string2
> 0string1 greater than string2
String to compare
String to compare
Return Value
The return values for this function are described above.
The strncpy function copies count characters of string2 to string1 and return string1. If count
is less than the length of string2, a null character (‘\0’) is not appended automatically to the
copied string. If count is greater than the length of string2, the string1 result is padded with
null characters (‘\0’) up to length count.
Note that the behavior of strncpy is undefined if the address ranges of the source and destination strings overlap.
Return Value
The return values for this function are described above.
The strpbrk function finds the first occurrence in string1 of any character from string2. The
terminating null character (‘\0’) is not included in the search.
Return Value
This function returns a pointer to the first occurrence of any character from string2 in string1.
A NULL return value indicates that the two string arguments have no characters in common.
The strrchr function finds the last occurrence of c (converted to char) in string. The string’s
terminating null character (‘\0’) is included in the search. (Use strchr to find the first occur
rence of c in string.)
Return Value
This function returns a pointer to the last occurrence of the character in the string. A NULL
pointer is returned if the given character is not found.
The strspn function returns the index of the first character in string1 that does not belong to
the set of characters specified by string2. This value is equivalent to the length of the initial
substring of string1 that consists entirely of characters from string2 . The null character (‘\0’)
terminating string2 is not considered in the matching process. If string1 begins with a charac
ter not in string2, strspn returns 0.
Return Value
This function returns an integer value specifying the length of the segment in string1 consisting entirely of characters in string2.
String containing token(s)
Set of delimiter characters
The strtok function reads string1 as a series of zero or more tokens and string2 as the set of
characters serving as delimiter of the tokens in string1. The tokens in string1 may be sepa
-
rated by one or more of the delimiters from string2.
The tokens can be broken out of string1 by a series of calls to strtok. In the first call to strtok
for string1, strtok searches for the first token in string1, skipping leading delimiters. A
pointer to the first token is returned. To read the next token from string1, call strtok with a
NULL value for the string1 argument. The NULL string1 argument causes strtok to search
for the next token in the previous token string. The set of delimiters may vary from call to
call, so string2 can take any value.
Note that calls to this function modify string1, because each time strtok is called it inserts a
null character (‘\0’) after the token in string1.
UM004001-COR11034–21
Page 86
Library FunctionsRun Time Environment
Return Value
The first time strtok is called, it returns a pointer to the first token in string1. In later calls
with the same token string, strtok returns a pointer to the next token in the string. A NULL
pointer is returned when there are no more tokens. All tokens are null-terminated.
long strtol( const char *nptr, char **endptr, int base );
unsigned long strtoul( const char *nptr, char **endptr, int base )
Parameter Description
nptrString to convert
endptrPointer to character that stops scan
baseNumber base to use
The strtod, strtol, and strtoul functions conv ert a character string to a double-precisio n value,
a long-integer value, or an unsigned long-integer value, respectively. The input string is a
sequence of characters that can be interpreted as a numerical value of the specified type.
These functions stop reading the string at the first character they cannot recognize as part of a
number. This may be the null character (‘\0’) at the end of the string. With strtol or strtoul,
this terminating character can also be the first numeric character greater than or equal to base.
If endptr is not NULL, a pointer to the character that stopped the scan is stored at the location
pointed to by endptr. If no conversion could be performed (no valid digits were found or an
invalid base was specified), the value of nptr is stored at the location pointed to by endptr.
The strtod function expects nptr to point to a string with the following form:
[whitespace] [sign] [digits] [.digits] [ {d | D | e | E}[sign]digits]
A whitespace consists of space and tab characters, which are ignored; sign is either plus (+)
or minus (-); and digits are one or more decimal digits. If no digits appear before the decimal
point, at least one must appear after the decimal point. The decimal digits can be followed by
an exponent, which consists of an introductory letter (b, D, e, or E) and an optionally signed
decimal integer.
The first character that does not fit this form stops the scan.
The strtol and strtoul functions expect nptr to point to a string with the following form:
4–22UM004001-COR1103
Page 87
Run Time EnvironmentLibrary Functions
[whitespace] [{ + | -}] [0 [{ x | X }]] [digits]
If base is between 2 and 36, then it is used as the base of the number . If base is 0, the initial
characters of the string pointed to by nptr are used to determine the base. If the first character
is 0 and the second character is not ‘x’ or ‘X’, then the string is interpreted as an octal integer;
otherwise, it is interpreted as a decimal number. If the first character is ‘0’ and the second
character is ‘x’ or ‘X’, then the string is interpreted as a hexadecimal integer. If the first char
acter is ‘1’ through ‘9’, then the string is interpreted as a decimal integer. The letters ‘a’
through ‘z’ (or ‘A’ through ‘Z’) are assigned the values 10 through 35; only letters whose
assigned values are less than base are permitted.
The strtoul function allows a plus (+) or minus (-) sign prefix; a leading minus sign indicates
that the return value is negated.
Return Value
The strtod function returns the value of the floating-point number, except when the representation would cause an overflow, in which case they return +/-HUGE_VAL. The functions
return 0 if no conversion could be performed or an underflow occurred.
The strtol function returns the value represented in the string, except when the representation
would cause an overflow, in which case it returns LONG_MAX or LONG_MIN. The func
tion returns 0 if no conversion could be performed.
-
-
The strtoul function returns the converted value, if any. If no conversion can be performed,
the function returns 0. The function returns ULONG_MAX on overflow.
In all these functions, errno is set to ERANGE if overflow or underflow occurs.
UM004001-COR11034–23
Page 88
Library FunctionsRun Time Environment
tolower, toupper FUNCTIONS
Header file statement: #include <ctype.h>
Syntax:int tolower( int c );
int toupper( int c );
Parameter Description
c
The tolower and toupper routines macros convert a single character, as described below:
FunctionMacroDescription
tolowertolower Converts c to lowercase if appropriate
touppertoupper Converts c to uppercase if appropriate
The tolower routine converts c to lowercase if c represents an uppercase letter. Otherwise, c
is unchanged.
The toupper routine converts c to uppercase if c represents an lowercase letter. Otherwise,
c is unchanged.
Character to be converted
Return Value
The tolower and toupper routines return the converted character c. There is no error returned.
4–24UM004001-COR1103
Page 89
Run Time EnvironmentLibrary Functions
va_arg, va_end, va_start FUNCTIONS
Header file statement: #include <stdarg.h>
Syntax: type va_arg( va_list arg_ptr, type );
arg_ptr
prev_paramPointer preceding first optional argument
typeType of argument to be retrieved
Pointer to list of arguments
The va_arg, va_end, and va_start macros provide a portable way to access the arguments to a
function when the function takes a variable number of arguments. The macros are listed
below:
MacroDescription
va_arg Macro to retrieve current argument
va_endMacro to reset arg_ptr
va_listThe typedef for the pointer to list of arguments
va_startMacro to set arg_ptr to beginning of list of optional arguments
The macros assume that the function takes a fixed number of required arguments, followed
by a variable number of optional arguments. The required ar guments are declared as ordinary
parameters to the function and can be accessed through the parameter names. The optional
arguments are accessed through the macros in STDARG.H, which set a pointer to the first
optional argument in the argument list, retrieve arguments from the list, and reset the pointer
when argument processing is completed.
The ANSI C standard macros, defined in STDARG.H, are used as follows:
•All required arguments to the function are declared as parameters in the usual way.
•The va_start macro sets arg_ptr to the first optional argument in the list of arguments
passed to the function. The argument arg_ptr must have va_list type. The argument
prev_param is the name of the required parameter immediately preceding the first
optional argument in the argument list. If prev_param is declared with the register
storage class, the macro’s behavior is undefined. The va_start macro must be used
before va_arg is used for the first time.
UM004001-COR11034–25
Page 90
Library FunctionsRun Time Environment
•The va_arg macro does the following:
– Retrieves a value of type from the location given by arg_ptr
– Increments arg_ptr to point to the next argument in the list, using the size of type
to determine where the next argument starts
– The va_arg macro can be used any number of times within the function to retrieve
arguments from the list.
– After all arguments have been retrieved, va_end resets the pointer to NULL.
Return Value
The va_arg macro returns the current argument va_start and va_end do not return values.
ld.ibhl,.BSS_LENGTH; Check for non-zero length
ldbc,hl; *
ldde,hl; *
swapde; *
orwhl,de; *
jrz,_c_bss_done; .BSS is zero-length ...
ldhl,bc; (hl)=Length
ldbc,hl; (bc)=length lo word
swaphl
ldix,hl; (ix)=length hi word
ld.ibhl,.BSS_BASE; [hl]=.bss
ld(hl),0
ldde,hl
incde; [de]=.bss+1
decwbc; 1st byte's taken care of
exhl,bc
orwhl,hl
exhl,bc
jrz,_c_bss_page; Just 1 byte on this page ...
The following is the initialization file that is included with the 380 C-comiler installation.
***********************************************
-a
assign .const rom
assign .startup rom
order .startup
range rom 0c400:0ffff
define .TOS=highaddr of rom-3
define .BSS_BASE=base of .bss
define .BSS_LENGTH=length of .bss
z380boot.o
z380eval.o
"..\lib\libc.lib"
"..\lib\lhf.lib"Link file
UM004001-COR1103A–3
Page 94
Page 95
380 C-COMPILER USER’S MANUAL
APPENDIX B
ASCII CHARACTER SET
TABLE B-1. ASCII CHARACTER SET
GraphicDecimalHexadecimalComments
00Null
11Start Of Heading
22Start Of Text
33End Of Text
44End Or Transmission
55Enquiry
66Acknowledge
77Bell
88Backspace
99Horizontal Tabulation
10ALine Feed
11BVertical Tabulation
12CForm Feed
13DCarriage Return
14EShift Out
15FShift In
UM004001-COR1103B–1
Page 96
ASCII Character Set
TABLE B-1. ASCII CHARACTER SET (CONTINUED)
GraphicDecimalHexadecimalComments
1610Data Link Escape
1711Device Control 1
1812Device Control 2
1913Device Control 3
2014Device Control 4
2115Negative Acknowledge
2216Synchronous Idle
2317End Of Block
2418Cancel
2519End Of Medium
261ASubstitute
271BEscape
281CFile Separator
291DGroup Separator
301ERecord Separator
311FUnit Separator
3220Space
!3321Exclamation Point
"3422Quotation Mark