MPLAB® XC8 C Compiler User’s Guide 2012 Microchip Technology Inc.
Note the following details of the code protection feature on Microchip devices: • Microchip products meet the specification contained in their particular Microchip Data Sheet. • Microchip believes that its family of products is one of the most secure families of its kind on the market today, when used in the intended manner and under normal conditions. • There are dishonest and possibly illegal methods used to breach the code protection feature.
MPLAB® XC8 C COMPILER USER’S GUIDE Table of Contents Preface ........................................................................................................................... 7 Chapter 1. Compiler Overview 1.1 Introduction ................................................................................................... 11 1.2 Compiler Description and Documentation .................................................... 11 1.3 Device Description ......................................................
MPLAB® XC8 C Compiler User’s Guide 5.6 Operators and Statements ......................................................................... 179 5.7 Register Usage ........................................................................................... 181 5.8 Functions .................................................................................................... 182 5.9 Interrupts .................................................................................................... 189 5.
C.12 Statements (G.3.12) ................................................................................ 483 C.13 Preprocessing Directives (G.3.13) ........................................................... 484 C.14 Library Functions (G.3.14) ....................................................................... 485 Glossary ..................................................................................................................... 487 Index .....................................................
MPLAB® XC8 C Compiler User’s Guide NOTES: DS52053B-page 6 2012 Microchip Technology Inc.
MPLAB® XC8 C COMPILER USER’S GUIDE Preface NOTICE TO CUSTOMERS All documentation becomes dated, and this manual is no exception. Microchip tools and documentation are constantly evolving to meet customer needs, so some actual dialogs and/or tool descriptions may differ from those in this document. Please refer to our web site (www.microchip.com) to obtain the latest documentation available. Documents are identified with a “DS” number.
MPLAB® XC8 C Compiler User’s Guide CONVENTIONS USED IN THIS GUIDE This manual uses the following documentation conventions: DOCUMENTATION CONVENTIONS Description Arial font: Italic characters Initial caps Quotes Underlined, italic text with right angle bracket Bold characters N‘Rnnnn Text in angle brackets < > Courier New font: Plain Courier New Represents Examples Referenced books Emphasized text A window A dialog A menu selection A field name in a window or dialog A menu path MPLAB® IDE User’s Guide
Preface Readme for Chapter Name For the latest information on using Chapter Name, read the “Readme for Chapter Name.txt” file (an ASCII text file) in the Readmes subdirectory of the MPLAB® IDE installation directory. The Readme file contains update information and known issues that may not be included in this user’s guide. Readme Files For the latest information on using other tools, read the tool-specific Readme files in the Readmes subdirectory of the MPLAB IDE installation directory.
MPLAB® XC8 C Compiler User’s Guide CUSTOMER SUPPORT Users of Microchip products can receive assistance through several channels: • • • • Distributor or Representative Local Sales Office Field Application Engineer (FAE) Technical Support Customers should contact their distributor, representative or field application engineer (FAE) for support. Local sales offices are also available to help customers. A listing of sales offices and locations is included in the back of this document.
MPLAB® XC8 C COMPILER USER’S GUIDE Chapter 1. Compiler Overview 1.1 INTRODUCTION This chapter is an overview of the MPLAB XC8 C Compiler, including these topics. • Compiler Description and Documentation • Device Description 1.2 COMPILER DESCRIPTION AND DOCUMENTATION The MPLAB® XC8 C Compiler is a free-standing, optimizing ANSI C compiler. It supports all 8-bit PIC® microcontrollers: PIC10, PIC12, PIC16 and PIC18 series devices, as well as the PIC14000 device.
MPLAB® XC8 C Compiler User’s Guide 1.3 DEVICE DESCRIPTION This compiler supports 8-bit Microchip PIC devices with baseline, Mid-Range, Enhanced Mid-Range, and PIC18 cores. The following descriptions indicate the distinctions within those device cores: The baseline core uses a 12-bit-wide instruction set and is available in PIC10, PIC12 and PIC16 part numbers. The Mid-Range core uses a 14-bit-wide instruction set that includes more instructions than the baseline core.
MPLAB® XC8 C COMPILER USER’S GUIDE Chapter 2. Common C Interface 2.1 INTRODUCTION The Common C Interface (CCI) is available with all MPLAB XC C compilers and is designed to enhance code portability between these compilers. For example, CCI-conforming code would make it easier to port from a PIC18 MCU using the MPLAB XC8 C compiler to a PIC24 MCU using the MPLAB XC16 C compiler. The CCI assumes that your source code already conforms to the ANSI Standard.
MPLAB® XC8 C Compiler User’s Guide 2.2.1 The ANSI Standard The ANSI C Standard has to reconcile two opposing goals: freedom for compilers vendors to target new devices and improve code generation, with the known functional operation of source code for programmers. If both goals can be met, source code can be made portable. The standard is implemented as a set of rules which detail not only the syntax that a conforming C program must follow, but the semantic rules by which that program will be interpreted.
Common C Interface For freestanding implementations – or for what we typically call embedded applications – the standard allows non-standard extensions to the language, but obviously does not enforce how they are specified or how they work. When working so closely to the device hardware, a programmer needs a means of specifying device setup and interrupts, as well as utilizing the often complex world of small-device memory architectures. This cannot be offered by the standard in a consistent way.
MPLAB® XC8 C Compiler User’s Guide 2.3 USING THE CCI The CCI allows enhanced portability by refining implementation-defined behavior and standardizing the syntax for extensions to the language. The CCI is something you choose to follow and put into effect, thus it is relevant for new projects, although you may choose to modify existing projects so they conform. For your project to conform to the CCI, you must do the following things.
Common C Interface 2.4 ANSI STANDARD REFINEMENT The following topics describe how the CCI refines the implementation-defined behaviors outlined in the ANSI C Standard. 2.4.1 Source File Encoding Under the CCI, a source file must be written using characters from the 7-bit ASCII set. Lines may be terminated using a line feed ('\n') or carriage return ('\r') that is immediately followed by a line feed.
MPLAB® XC8 C Compiler User’s Guide 2.4.3.2 DIFFERENCES Header file specifications that use directory separators have been allowed in previous versions of all compilers. Compatibility problems arose when Windows-style separators “\” were used and the code compiled under other host operating systems. Under the CCI, no directory specifiers should be used. 2.4.3.3 MIGRATION TO THE CCI Any #include directives that use directory separators in the header file specifications should be changed.
Common C Interface 2.4.5 The Number of Significant Initial Characters in an Identifier At least the first 255 characters in an identifier (internal and external) are significant. This extends upon the requirement of the ANSI C Standard which states a lower number of significant characters are used to identify an object. 2.4.5.1 EXAMPLE The following example shows two poorly named variables, but names which are considered unique under the CCI.
MPLAB® XC8 C Compiler User’s Guide 2.4.7 Plain char Types The type of a plain char is unsigned char. It is generally recommended that all definitions for the char type explicitly state the signedness of the object. 2.4.7.1 EXAMPLE The following example char foobar; defines an unsigned char object called foobar. 2.4.7.2 DIFFERENCES The 8-bit compilers have always treated plain char as an unsigned type. The 16- and 32-bit compilers used signed char as the default plain char type.
Common C Interface 2.4.9 Integer conversion When converting an integer type to a signed integer of insufficient size, the original value is truncated from the most-significant bit to accommodate the target size. 2.4.9.1 EXAMPLE The following shows an assignment of a value that will be truncated. signed char destination; unsigned int source = 0x12FE; destination = source; Under the CCI, the value of destination after the alignment will be -2 (i.e., the bit pattern 0xFE). 2.4.9.
MPLAB® XC8 C Compiler User’s Guide 2.4.11.2 DIFFERENCES All compilers have performed right shifting as described in this section. 2.4.11.3 MIGRATION TO THE CCI No action required. 2.4.12 Conversion of Union Member Accessed Using Member With Different Type If a union defines several members of different types and you use one member identifier to try to access the contents of another (whether any conversion is applied to the result) is implementation-defined behavior in the standard.
Common C Interface 2.4.13.2 DIFFERENCES The 8-bit compilers have previously issued a warning if type int was used for bit-fields, but would implement the bit-field with an unsigned int type. The 16- and 32-bit compilers have implemented bit-fields defined using int as having a signed int type, unless the option -funsigned-bitfields was specified. 2.4.13.3 MIGRATION TO THE CCI Any code that defines a bit-field with the plain int type should be reviewed.
MPLAB® XC8 C Compiler User’s Guide 2.4.15.1 EXAMPLE The following shows a structure containing bit-fields being defined. struct { unsigned lo : 1; unsigned mid :6; unsigned hi : 1; } foo; The bit-field lo will be assigned the least significant bit of the storage unit assigned to the structure foo. The bit-field mid will be assigned the next 6 least significant bits, and hi, the most significant bit of that same storage unit byte. 2.4.15.
Common C Interface 2.5 ANSI STANDARD EXTENSIONS The following topics describe how the CCI provides device-specific extensions to the standard. 2.5.1 Generic Header File A single header file must be used to declare all compiler- and device-specific types and SFRs. You must include this file into every module to conform with the CCI. Some CCI definitions depend on this header being seen. 2.5.1.
MPLAB® XC8 C Compiler User’s Guide 2.5.2.3 MIGRATION TO THE CCI Avoid making objects and functions absolute if possible. In XC8, change absolute object definitions such as the following example: int scanMode @ 0x200; to: int scanMode __at(0x200); In XC16/32, change code such as: int scanMode __attribute__(address(0x200))); to: int scanMode __at(0x200); 2.5.2.
Common C Interface 2.5.3.3 MIGRATION TO THE CCI For 8-bit compilers, change any occurrence of the far qualifier, as in the following example: far char template[20]; to __far, i.e., __far char template[20]; In the 16- and 32-bit compilers, change any occurrence of the far attribute, as in the following void bar(void) __attribute__ ((far)); int tblIdx __attribute__ ((far)); to void __far bar(void); int __far tblIdx; 2.5.3.4 CAVEATS None. 2.5.
MPLAB® XC8 C Compiler User’s Guide 2.5.4.3 MIGRATION TO THE CCI For 8-bit compilers, change any occurrence of the near qualifier, as in the following example: near char template[20]; to __near, i.e., __near char template[20]; In 16- and 32-bit compilers, change any occurrence of the near attribute, as in the following void bar(void) __attribute__ ((near)); int tblIdx __attribute__ ((near)); to void __near bar(void); int __near tblIdx; 2.5.4.4 CAVEATS None. 2.5.
Common C Interface 2.5.6 X and Y Data Objects The __xdata and __ydata qualifiers may be used to indicate that variables may be located in special memory regions. Exactly what constitutes X and Y memory is dependent on the target device, but it is typically memory that can be accessed independently on separate buses. Such memory is often required for some DSP instructions. Use the native keywords discussed in the Differences section to look up information on the semantics of these qualifiers.
MPLAB® XC8 C Compiler User’s Guide 2.5.7.2 DIFFERENCES The 8-bit compilers have used the four qualifiers bank0, bank1, bank2 and bank3 to indicate the same, albeit more limited, memory placement. Equivalent specifiers have never been defined for any other compiler. 2.5.7.3 MIGRATION TO THE CCI For 8-bit compilers, change any occurrence of the bankx qualifiers, as in the following example: bank2 int logEntry; to __bank(), i.e., __bank(2) int logEntry; 2.5.7.4 CAVEATS None. 2.5.
Common C Interface 2.5.9 EEPROM Objects The __eeprom qualifier may be used to indicate that variables should be positioned in EEPROM. Use the native keywords discussed in the Differences section to look up information on the semantics of this qualifier. Some devices may not implement EEPROM. Use of this qualifier for such devices will generate a warning. Stack-based (auto and parameter) variables cannot use the __eeprom specifier. 2.5.9.1 EXAMPLE The following shows a variable qualified using __eeprom.
MPLAB® XC8 C Compiler User’s Guide save(symbol-list) Save on entry and restore on exit the listed symbols (XC16) irq(irqid) Specify the interrupt vector associated with this interrupt (XC16) altirq(altirqid) Specify the alternate interrupt vector associated with this interrupt (XC16) preprologue(asm) Specify assembly code to be executed before any compiler-generated interrupt code (XC16) shadow Allow the ISR to utilise the shadow registers for context switching (XC16) auto_psv The ISR will set the PSVPAG re
Common C Interface to void __interrupt(auto_psv,(irq(52)))) myIsr(void); For 32-bit compilers, the __interrupt() keyword takes two parameters, the vector number and the (optional) IPL value.
MPLAB® XC8 C Compiler User’s Guide 2.5.11.3 MIGRATION TO THE CCI No migration is required for XC8. For 16- and 32-bit compilers, change any occurrence of the packed attribute, as in the following example: struct DOT { char a; int x[2] __attribute__ ((packed)); }; to: struct DOT { char a; __pack int x[2]; }; Alternatively, you may pack the entire structure, if required. 2.5.11.4 CAVEATS None. 2.5.
Common C Interface 2.5.13 Assigning Objects to Sections The __section() specifier may be used to indicate that an object should be located in the named section (or psect, using the XC8 terminology). This is typically used when the object has special and unique linking requirements which cannot be addressed by existing compiler features. Use the native keywords discussed in the Differences section to look up information on the semantics of this specifier. 2.5.13.
MPLAB® XC8 C Compiler User’s Guide 2.5.13.4 CAVEATS With XC8, the __section() specifier cannot be used with any interrupt function. 2.5.14 Specifying Configuration Bits The #pragma config directive may be used to program the configuration bits for a device. The pragma has the form: #pragma config setting = state|value where setting is a configuration setting descriptor (e.g., WDT), state is a descriptive value (e.g., ON) and value is a numerical value.
Common C Interface TABLE 2-1: MANIFEST MACROS DEFINED BY THE CCI Name Meaning if defined Example __CCI__ Compiler is CCI compliant and CCI enforcement is enabled __CCI__ __XC##__ The specific XC compiler used (## can be 8, 16 or 32) __XC8__ __DEVICEFAMILY__ __DEVICENAME__ 2.5.15.1 The family of the selected target device The selected target device name __dsPIC30F__ __18F452__ EXAMPLE The following shows code which is conditionally compiled dependent on the device having EEPROM memory.
MPLAB® XC8 C Compiler User’s Guide 2.5.16 In-line Assembly The asm() statement may be used to insert assembly code in-line with C code. The argument is a C string literal which represents a single assembly instruction. Obviously, the instructions contained in the argument are device specific. Use the native keywords discussed in the Differences section to look up information on the semantics of this statement. 2.5.16.1 EXAMPLE The following shows a MOVLW instruction being inserted in-line.
Common C Interface 2.6 COMPILER FEATURES The following items detail compiler options and features that are not directly associated with source code that 2.6.1 Enabling the CCI It is assumed you are using the MPLAB X IDE to build projects that use the CCI. The widget in the MPLAB X IDE Project Properties to enable CCI conformance is Use CCI Syntax in the Compiler category. A widget with the same name is available in MPLAB IDE v8 under the Compiler tab.
MPLAB® XC8 C Compiler User’s Guide NOTES: DS52053A-page 40 2012 Microchip Technology Inc.
MPLAB® XC8 C COMPILER USER’S GUIDE Chapter 3. How To’s 3.1 INTRODUCTION This section contains help and references for situations that are frequently encountered when building projects for Microchip 8-bit devices. Click the links at the beginning of each section to assist finding the topic relevant to your question. Some topics are indexed in multiple sections. Start here: • • • • • • 3.
MPLAB® XC8 C Compiler User’s Guide 3.2.3 Can I Install More Than One Version of the Same Compiler? Yes, the compilers and installation process has been designed to allow you to have more than one version of the same compiler installed, and you can easily swap between version by changing options in MPLAB IDE, see Section 3.3.4 “How Can I Select Which Compiler I Want to Build With?”. Compilers should be installed into a directory whose name is related to the compiler version.
How To’s 3.3 INVOKING THE COMPILER This section discusses how the compiler is run, both on the command-line and from the MPLAB IDE. It includes information about how to get the compiler to do what you want in terms of options and the build process itself.
MPLAB® XC8 C Compiler User’s Guide 3.3.4 How Can I Select Which Compiler I Want to Build With? The compilation and installation process has been designed to allow you to have more than one compiler installed at the same time. You can create a project in MPLAB X IDE and then build this project with different compilers by simply changing a setting in the project properties. To select which compiler is actually used when building a project under MPLAB X IDE, go to the Project properties dialog.
How To’s 3.3.7 How Do I Know What Compiler Options Are Available and What They Do? A list of all compiler options can be obtained by using the --HELP option on the command line, see Section 4.8.33 “--HELP: Display Help”. If you give the --HELP option an argument, being an option name, it will give specific information on that option. Alternatively, all options are all listed in Section 4.8 “Option Descriptions” in this user’s guide. If you are compiling in MPLAB X IDE, see Section 4.
MPLAB® XC8 C Compiler User’s Guide 3.4 WRITING SOURCE CODE This section presents issues pertaining to the source code you write. It has been subdivided into sections listed below. • • • • • • • C Language Specifics Device-Specific Features Memory Allocation Variables Functions Interrupts Assembly Code 3.4.1 C Language Specifics This section discusses source code issues that are directly relates to the C language itself but which are commonly asked.
How To’s Only use a cast in situations where the types used by the compiler are not the types that you require. For example consider the result of a division assigned to a floating point variable: int i, j; float fl; fl = i/j; In this case integer division is performed, then the rounded integer result is converted to a float format. So if i contained 7 and j contained 2, the division will yield 3 and this will be implicitly converted to a float type (3.0) and then assigned to fl.
MPLAB® XC8 C Compiler User’s Guide 3.4.2 Device-Specific Features This section discusses the code that needs to be written to set up or control a feature that is specific to Microchip PIC devices. • • • • • • How Do I Set the Configuration Bits? How Do I Use the PIC’s ID Locations? How Do I Determine the Cause of Reset on Mid-range Parts? How Do I Access SFRs? How Do I Stop the Compiler Using Certain Memory Locations? What Do I Need to Do When Compiling to Use a Debugger? 3.4.2.
How To’s 3.4.2.5 HOW DO I FIND THE NAMES USED TO REPRESENT SFRS AND BITS? Special function registers and the bits within those are accessed via special variables that map over the register, Section 3.4.2.4 “How Do I Access SFRs?”; however, the names of these variables sometimes differ from those indicated in the data sheet for the device you are using. You can work your way through the
MPLAB® XC8 C Compiler User’s Guide 3.4.3.3 HOW DO I PLACE VARIABLES IN PROGRAM MEMORY? The const qualifier implies that the qualified variable is read only. As a consequence of this, any variables (except for auto variables or function parameters) qualified const are placed in program memory, thus freeing valuable data RAM, see Section 5.5.3 “Variables in Program Space”. Variables qualified const can also be made absolute, so that they can be positioned at an address you nominate, see Section 5.5.4.
How To’s 3.4.4.2 HOW CAN I ACCESS INDIVIDUAL BITS OF A VARIABLE? There are several ways of doing this. The simplest and most portable way is to define an integer variable and use macros to read, set or clear the bits within the variable using a mask value and logical operations, such as the following.
MPLAB® XC8 C Compiler User’s Guide 3.4.5 Functions This section examines questions that relate to functions. • • • • • • • What is the Optimum Size For Functions? How Can I Tell How Big a Function Is? How Do I Know What Resources Are Being Used by Each Function? How Do I Find Out Where Variables and Functions Have Been Positioned? How Do I Use Interrupts in C? How Do I Stop An Unused Function Being Removed? How Do I Make a Function Inline? 3.4.5.
How To’s 3.4.6 Interrupts Interrupt and interrupt service routine questions are discussed in this section. • How Do I Use Interrupts in C? • How Can I Make My Interrupt Routine Faster? • How Do I Share Data Between Interrupt and Main-line Code? 3.4.6.1 HOW DO I USE INTERRUPTS IN C? First, be aware of what interrupt hardware is available on your target device.
MPLAB® XC8 C Compiler User’s Guide 3.4.7.2 WHAT DO I NEED OTHER THAN INSTRUCTIONS IN AN ASSEMBLY SOURCE FILE? Assembly code typically needs assembler directives as well as the instructions themselves. The operation of all the directives are described in the subsections of Section 6.4.9 “Assembler Directives”. Common directives required are mentioned below. All assembly code must be placed in a psect so it can be manipulated as a whole by the linker and placed in memory. See Section 5.15.
How To’s • You must ensure that the address of the RAM variable you are accessing has been masked so that only the bank offset is being used as the instruction’s file register operand. This should not be done if you are using an instruction that takes a full address (such as the MOVFF instruction on PIC18 devices). Check your device data sheet to see what address operand instructions requires. Failure to mask an address may lead to a fixup error (see Section 3.7.
MPLAB® XC8 C Compiler User’s Guide 3.5 GETTING MY APPLICATION TO DO WHAT I WANT This section provides programming techniques, applications and examples. It also examines questions that relate to making an application perform a specific task.
How To’s The contents of the HEX file for the bootloader can be merged with the code of the application by adding the HEX file as a project file, either on the command line, or in MPLAB IDE. This results in a single HEX file that contains the bootloader and application code in the one image. HEX files are merged by the HEXMATE application, see Section 8.6 “HEXMATE”.
MPLAB® XC8 C Compiler User’s Guide 3.5.5 How Do I Share Data Between Interrupt and Main-line Code? Variables accessed from both interrupt and main-line code can easily become corrupted or mis-read by the program. The volatile qualifier (see Section 5.4.7.2 “Volatile Type Qualifier”) tells the compiler to avoid performing optimizations on such variables. This will fix some of the issues associated with this problem. The other issues relates to whether the compiler/device can access the data atomically.
How To’s A stub for the putch function can be found in the compiler’s sources directory. Copy it into your project then modify it to send the single byte parameter passed to it to the required destination. Before you can use printf, peripherals that you use will need to be initialized in the usual way. Here is an example of putch for a USART on a mid-range device.
MPLAB® XC8 C Compiler User’s Guide 3.6 UNDERSTANDING THE COMPILATION PROCESS This section tells you how to find out what the compiler did during the build process, how it encoded output code, where it placed objects, etc. It also discusses the features that are supported by the compiler.
How To’s 3.6.2 How Can I Make My Code Smaller? There are a number of ways that this can be done, but results vary from one project to the next. Use the assembly list file, see Section 6.6 “Assembly List Files”, to observe the assembly code produced by the compiler to verify that the following tips are relevant to your code. Use the smallest data types possible as less code is needed to access these. (This also reduces RAM usage.
MPLAB® XC8 C Compiler User’s Guide 3.6.3 How Can I Reduce RAM Usage? Use the smallest data types possible. (This also reduces code size as less code is needed to access these.) Note that a bit type and non-standard 24-bit integer type (short long) exists for this compiler. See Section 5.4 “Supported Data Types and Variables” for all data types and sizes. There are two sizes of floating-point type, as well, and these are discussed in the same section.
How To’s 3.6.6 How Can I Make My Interrupt Routine Faster? Consider suggestions made in Section 3.6.2 “How Can I Make My Code Smaller?” (code size) for any interrupt code. Smaller code is often faster code. In addition to the code you write in the ISR there is the code the compiler produces to switch context. This is executed immediately after an interrupt occurs and immediately before the interrupt returns, so must be included in the time taken to process an interrupt, see Section 5.9.
MPLAB® XC8 C Compiler User’s Guide 3.6.10 How Do I Utilize the Linear Memory on Enhanced Mid-range PIC Devices? The linear addressing mode is a means of accessing the banked data memory as one contiguous and linear block, see Section 5.5.1 “Address Spaces”. Use of the linear memory is fully automatic. Objects that are larger than a data bank can be defined in the usual way and will be accessed using the linear addressing mode, see Section 5.5.2.3 “Size Limits of Auto Variables” and Section 5.5.2.1.
How To’s The list of functions, memory location and size is available in a file called funclist. Each function will have a line similar to the following. _main: CODE, 2012 0 30 This indicates that generated assembly code associated with the function, main, was placed in the CODE linker class (see Section 6.4.9.3.3 “Class”), was located at address 2012 (decimal) in address space number 0 (see Section 6.4.9.3.13 “Space”), and was 30 (again decimal) words/bytes long.
MPLAB® XC8 C Compiler User’s Guide 3.6.17 How Do I Know How Much Memory Is Still Available? Although the memory summary printed by the compiler after compilation (see Section 4.8.56 “--SUMMARY: Select Memory Summary Output Type” options) or the memory gauge available in MPLAB IDE both indicate the amount of memory used and the amount still available, neither of these features indicate whether this memory is one contiguous block or broken into many small chunks.
How To’s 3.7 FIXING CODE THAT DOES NOT WORK This section examines issues relating to projects that do not build due to compiler errors, or which build but do not work as expected. • How Do I Find Out What an Warning/error Message Means? • How Do I Find the Code that Caused Compiler Errors Or Warnings in My Program? • How Can I Stop Spurious Warnings from Being Produced? • Why Can’t I Even Blink an LED? • How Do I Know If the Stack Has Overflowed? • How Do I Fix a "Can’t find space...
MPLAB® XC8 C Compiler User’s Guide Finally, there are errors that do not relate to any particular line of code at all. An error in a compiler option or a linker error are examples of these. If the program defines too many variables, there is no one particular line of code that is at fault; the program as a whole uses too much data. Note that the name and line number of the last processed file and source may be printed in some situations even though that code is not the direct source of the error.
How To’s • Make sure you do not have a "read-modify-write" problem. If the device you are using does not have a separate "latch" register (as is the case with mid-range PIC devices) this problem can occur, particularly if the port outputs are driving large loads, such as an LED. You may see that setting one bit turns off another or other unusual events. Create your own latch by using a temporary variable. Rather than read and write the port directly, make modifications to the latch variable.
MPLAB® XC8 C Compiler User’s Guide 3.7.8 How Do I Fix a Fixup Overflow Error? Fixup — the process of replacing a symbolic reference with an actual address — can overflow if the address assigned to the symbol is too large to fit in the address field of the assembly instruction. Most 8-bit PIC assembly instructions specify a file address that is an offset into the currently selected memory bank.
MPLAB® XC8 C COMPILER USER’S GUIDE Chapter 4. XC8 Command-line Driver 4.1 INTRODUCTION The name of the command-line driver is xc8. XC8 can be invoked to perform all aspects of compilation, including C code generation, assembly, and link steps. Even if an IDE is used to assist with compilation, the IDE will ultimately call xc8.
MPLAB® XC8 C Compiler User’s Guide 4.2 INVOKING THE COMPILER This section explain how to invoke xc8 on the command line, as well as the files that it can read. 4.2.1 Driver Command-line Format xc8 has the following basic command format. xc8 [options] files [libraries] Throughout this manual, it is assumed that the compiler applications are in the console’s search path or that the full path is specified when executing an application.
XC8 Command-line Driver 4.2.2 Environment Variables When hosted on a Windows environment, the compiler uses the registry to store information relating to the compiler installation directory and activation details, along with other configuration settings. That information is required whether the compiler is run on the command line or from within an IDE. Under Linux and Apple OS X environments, the registry is replaced by an XML file which stores the same information.
MPLAB® XC8 C Compiler User’s Guide There are no compiler restrictions imposed on the names of source files, but be aware of case, name-length and other restrictions imposed by your operating system. If you are using an IDE, avoid assembly source files whose basename is the same as the basename of any project in which the file is used. This may result in the source file being overwritten by a temporary file during the build process.
XC8 Command-line Driver 4.3 THE COMPILATION SEQUENCE When you compile a project, there are many internal applications that are called to do the work. This section looks at when these internal applications are executed and how this relates to the build process of multiple source files. This section should be of particular interest if you are using a make system to build projects. 4.3.1 The Compiler Applications The main internal compiler applications and files are illustrated in Figure 4-1.
MPLAB® XC8 C Compiler User’s Guide Table 4-2 lists the compiler applications. The names shown are the names of the executables, which can be found in the bin directory under the compiler’s installation directory.
XC8 Command-line Driver FIGURE 4-2: MULTI-FILE COMPILATION Intermediate files C file preprocess & parse pcode C file preprocess & parse pcode code generation assemble link library files First stage of compilation 4.3.2 Second stage of compilation Single-Step Compilation Figure 4-1 showed us the files that are generated by each application and the order in which these applications are executed.
MPLAB® XC8 C Compiler User’s Guide FIGURE 4-3: THE TRADITIONAL COMPILATION SEQUENCE Intermediate files C file preprocess & parse code generation assemble .obj files C file preprocess & parse code generation assemble .obj files link library files Second stage of compilation First stage of compilation When compiling files of mixed types, this can still be achieved with just one invocation of the compiler driver. As discussed in Section 4.
XC8 Command-line Driver 4.3.3 Multi-Step Compilation Make utilities and IDEs, such as MPLAB IDE, allow for an incremental build of projects that contain multiple source files. When building a project, they take note of which source files have changed since the last build and use this information to speed up compilation. For example, if compiling two source files, but only one has changed since the last build, the intermediate file corresponding to the unchanged source file need not be regenerated.
MPLAB® XC8 C Compiler User’s Guide 4.3.4 Compilation of Assembly Source Since the code generator performs many tasks that were traditionally performed by the linker, there could be complications when assembly source is present in a project. Assembly files are traditionally processed after C code, but it is necessary to have this performed first so that specific information contained in the assembly code can be conveyed to the code generator.
XC8 Command-line Driver 4.4 RUNTIME FILES In addition to the C and assembly source files specified on the command line, there are also compiler-generated source files and pre-compiled library files which might be compiled into the project by the driver. These files contain: • • • • • • C Standard library routines Implicitly called arithmetic routines User-defined library routines The runtime startup code The powerup routine The printf routine.
MPLAB® XC8 C Compiler User’s Guide 4.4.1.2 USER-DEFINED LIBRARIES User-defined libraries may be created and linked in with programs as required. Library files are more easy to manage and may result in faster compilation times, but must be compatible with the target device and options for a particular project. Several versions of a library may need to be created to allow it to be used for different projects. Libraries can be created manually using the compiler and the librarian, LIBR. See Section 8.
XC8 Command-line Driver Generation of the runtime startup code is an automatic process which does not require any user interaction; however, some aspects of the runtime code can be controlled, if required, using the --RUNTIME option. Section 4.8.50 “--RUNTIME: Specify Runtime Environment” describes the use of this option. See Section 5.10.1 “Runtime Startup Code” which describes the functional aspects of the code contained in this module and its effect on program operation.
MPLAB® XC8 C Compiler User’s Guide 4.5 COMPILER OUTPUT There are many files created by the compiler during the compilation. A large number of these are intermediate files and some are deleted after compilation is complete, but many remain and are used for programming the device, or for debugging purposes. 4.5.1 Output Files The names of many output files use the same base name as the source file from which they were derived. For example, the source file input.c will create a p-code file called input.p1.
XC8 Command-line Driver 4.5.2 Diagnostic Files Two valuable files produced by the compiler are the assembly list file, produced by the assembler, and the map file, produced by the linker. The compiler options --ASMLIST (Section 4.8.16 “--ADDRQUAL: Set Compiler Response to Memory Qualifiers”) generates a list file, and the -M option (Section 4.8.8 “-M: Generate Map File”) specifies generation of a map file.
MPLAB® XC8 C Compiler User’s Guide 4.6 COMPILER MESSAGES All compiler applications, including the command-line driver, xc8, use textual messages to report feedback during the compilation process. A centralized messaging system is used to produce the messages, which allows consistency during all stages of the compilation process. The messaging system is described in this section and a complete list of all warning and error messages can be found in Appendix B. “Error and Warning Messages”. 4.6.
XC8 Command-line Driver 4.6.2 Message Language xc8 supports more than one language for displayed messages. There is one MDF for each language supported. Under Windows, the default language can be specified when installing the compiler. The default language may be changed on the command line using the --LANG option, see Section 4.8.35 “--LANG: Specify the Language for Messages”.
MPLAB® XC8 C Compiler User’s Guide 4.6.4 Message Format By default, messages are printed in a human-readable format. This format can vary from one compiler application to another, since each application reports information about different file formats.
XC8 Command-line Driver For example, a project is compiled, but, as shown, produces a warning from the parser and an error from the linker (numbered 362 and 492, respectively). main.c: main() 17: ip = &b; ^ (362) redundant "&" applied to array (warning) (492) attempt to position absolute psect "text" is illegal Notice that the parser message format identifies the particular line and position of the offending source code.
MPLAB® XC8 C Compiler User’s Guide 4.6.5 Changing Message Behavior Both the attributes of individual messages and general settings for the messaging system can be modified during compilation. There are both driver options and C pragmas that can be used to achieve this. 4.6.5.1 DISABLING MESSAGES Each warning message has a default number indicating a level of importance. This number is specified in the MDF and ranges from -9 to 9. The higher the number, the more important the warning.
XC8 Command-line Driver 4.7 XC8 DRIVER OPTIONS This section looks at the general form of xc8 command-line options and what action the compiler will perform if no option is specified for a certain feature. 4.7.0.1 GENERAL OPTION FORMATS All single letter options are identified by a leading dash character, “-”, for example: -C. Some single letter options specify an additional data field which follows the option name immediately and without any whitespace, for example: -Ddebug.
MPLAB® XC8 C Compiler User’s Guide 4.8 OPTION DESCRIPTIONS Most aspects of the compilation can be controlled using the command-line driver, xc8. The driver will configure and execute all required applications, such as the code generator, assembler and linker. xc8 recognizes the compiler options which are tabled below and are explained in detail in the sections following.
XC8 Command-line Driver TABLE 4-6: DRIVER OPTIONS (CONTINUED) Option Meaning --MSGDISABLE=list Disable warning messages --MSGFORMAT=specification Set advisory message format --NODEL Do not remove temporary files --NOEXEC Do not execute compiler applications --OBJDIR=path Set object files directory --OPT=optimizations Control optimization --OUTDIR=path Set output directory --OUTPUT=path Set output formats --PASS1 Produce intermediate p-code file and stop --PRE Produce preprocessed sourc
MPLAB® XC8 C Compiler User’s Guide 4.8.2 -D: Define Macro The -D option is used to define a preprocessor macro on the command line, exactly as if it had been defined using a #define directive in the source code. This option may take one of two forms, -Dmacro which is equivalent to: #define macro 1 placed at the top of each module compiled using this option, or -Dmacro= text which is equivalent to: #define macro text where text is the textual substitution required.
XC8 Command-line Driver 4.8.4 -G: Generate Source-Level Symbol File The -G option allows specification of the filename used for the source-level symbol file (.sym extension) for use with supported debuggers and simulators such as MPLAB IDE. See also Section 4.5 “Compiler Output”. If no filename is given, the symbol file will have the project name (see Section 4.2 “Invoking the Compiler”), and an extension of .sym. For example, the option -Gtest.sym generates a symbol file called test.sym.
MPLAB® XC8 C Compiler User’s Guide 4.8.7 -L-: Adjust Linker Options Directly The -L driver option can be used to specify an option which will be passed directly to the linker. If -L is followed immediately by text starting with a dash character “-”, the text will be passed directly to the linker without being interpreted by xc8. If the -L option is not followed immediately by a dash character, it is assumed the option is the library scan option, Section 4.8.6 “-L: Scan Library”.
XC8 Command-line Driver 4.8.9 -N: Identifier Length This option allows the significant C identifier length (used by functions and variables) to be decreased from the default value of 255. Valid sizes for this option are from 32 to 255. The option has no effect for all other values. This option also controls the significant length of identifiers used by the preprocessor, such as macro names. The default length is also 255, and can be adjusted to a minimum of 31.
MPLAB® XC8 C Compiler User’s Guide 4.8.13 -S: Compile to Assembler Code The -S option stops compilation after generating an assembly output file. One assembly file will be generated for all the C source code, including p-code library code. The command xc8 --CHIP=16F877A -S test.c will produce an assembly file called test.as, which contains the assembly code generated from test.c.
XC8 Command-line Driver 4.8.16 --ADDRQUAL: Set Compiler Response to Memory Qualifiers The --ADDRQUAL option indicates the compiler’s response to non-standard memory qualifiers in C source code. By default these qualifiers are ignored; i.e., they are accepted without error, but have no effect. Using this option allows these qualifiers to be interpreted differently by the compiler. The near qualifier is affected by this option.
MPLAB® XC8 C Compiler User’s Guide 4.8.19 --CHECKSUM: Calculate a Checksum This option will perform a checksum over the address range specified and store the result at the destination address specified. The general form of this option is as follows. -CHECKSUM=start-end@destination[,offset=][,width=w][,code=c][,algorith m=a] Additional specifications are appended as a comma-separated list to this option. Such specifications are: width=n selects the width of the checksum result in bytes.
XC8 Command-line Driver 4.8.22 --CODEOFFSET: Offset Program Code to Address In some circumstances, such as bootloaders, it is necessary to shift the program image to an alternative address. This option is used to specify a base address for the program code image and to reserve memory from address 0 to that specified in the option. When using this option, all code psects (including Reset and interrupt vectors and constant data) will be adjusted to the address specified.
MPLAB® XC8 C Compiler User’s Guide 4.8.24 --DOUBLE: Select Kind of Double Types This option allows the kind of double-precision floating-point types to be selected. By default the compiler will choose the truncated IEEE754 24-bit implementation for double types. With this option, this can be changed to the full 32-bit IEEE754 implementation. See Section 4.9 “MPLAB IDE V8 Universal Toolsuite Equivalents” or Section 4.10 “MPLAB X Universal Toolsuite Equivalents” for use of this option in MPLAB IDE. 4.8.
XC8 Command-line Driver 4.8.27 --ERRATA: Specify Errata Workarounds This option allows specification of software workarounds to documented silicon errata issues. A default set of errata issues apply to each device, but this set can be adjusted by using this option and the arguments presented in Table 4-10.
MPLAB® XC8 C Compiler User’s Guide 4.8.28 --ERRFORMAT: Define Format for Compiler Messages If the --ERRFORMAT option is not used, the default behavior of the compiler is to display any errors in a “human readable” form. This standard format is perfectly acceptable to a person reading the error output, but is not generally usable with environments which support compiler error handling.
XC8 Command-line Driver • The options following fill_expr result in the following behavior: - @unused (or nothing) fill all unused memory with fill_expr; i.e., --FILL=0xBEEF@unused fills all unused memory with 0xBEEF. The driver will expand this to the appropriate ranges and pass these to HEXMATE. - @address fill a specific address with fill_expr; i.e., --FILL=0xBEEF@0x1000 puts 0xBEEF at address 1000h - @address:end_address fill a range of memory with fill_expr; i.e.
MPLAB® XC8 C Compiler User’s Guide 4.8.34 --HTML: Generate HTML Diagnostic Files This option will generate a series of HTML files that can be used to explore the compilation results of the latest build. The files are stored in a directory called html, located in the output directory. The top level file (which can be opened with your favorite web browser) is called index.html. Use this option at all stages of compilation to ensure files associated with all compilation stages are generated.
XC8 Command-line Driver Only those modes permitted by the compiler license status will be accepted. For example if you have purchased a Standard compiler license, that compiler may be run in Standard or Free mode, but not the PRO mode. See Section 4.9 “MPLAB IDE V8 Universal Toolsuite Equivalents” or Section 4.10 “MPLAB X Universal Toolsuite Equivalents” for use of this option in MPLAB IDE. 4.8.
MPLAB® XC8 C Compiler User’s Guide 4.8.42 --OPT: Invoke Compiler Optimizations The --OPT option allows control of all the compiler optimizers. If this option is not specified, or it is specified as --OPT=all, the space and asm optimizations are enabled (see below). Optimizations may be disabled by using --OPT=none, or individual optimizers may be controlled, for example: --OPT=asm will only enable some assembler optimizations. Table 4-13 lists the available optimization types.
XC8 Command-line Driver 4.8.44 --OUTPUT= type: Specify Output File Type This option allows the type of the output file(s) to be specified. If no --OUTPUT option is specified, the output file’s name will be the same as the project name (see Section 4.3 “The Compilation Sequence”). The available output file format are shown in Table 4-14. More than one output format may be specified by supplying a comma-separated list of tags. Not all formats are supported by Microchip development tools.
MPLAB® XC8 C Compiler User’s Guide 4.8.47 --PROTO: Generate Prototypes The --PROTO option is used to generate .pro files containing both ANSI C and K&R style function declarations for all functions within the specified source files. Each .pro file produced will have the same base name as the corresponding source file. Prototype files contain both ANSI C-style prototypes and old-style C function declarations within conditional compilation blocks. The extern declarations from each .
XC8 Command-line Driver 4.8.48 --RAM: Adjust RAM Ranges This option is used to adjust the default RAM, which is specified for the target device. The default memory will include all the on-chip RAM specified for the target PIC10/12/16 device, thus this option only needs be used if there are special memory requirements. Typically this option is used to reserve memory (reduce the amount of memory available).
MPLAB® XC8 C Compiler User’s Guide 4.8.49 --ROM: Adjust ROM Ranges This option is used to change the default ROM which is specified for the target device. The default memory will include all the on-chip ROM specified for the target PIC10/12/16 device, thus this option only needs to be used if there are special memory requirements. Typically this option is used to reserve memory (reduce the amount of memory available).
XC8 Command-line Driver Note that the code that clears or initializes variables, which is included by default, will clobber the contents of the STATUS register. For mid-range and baseline devices, if you need to check the cause of Reset using the TO or PD bits in this register, then you must enable the resetbits suboption as well. See 5.10.1.4 “STATUS Register Preservation” for how this feature is used. The usable suboptions include those shown in Table 4-15.
MPLAB® XC8 C Compiler User’s Guide 4.8.51 --SCANDEP: Scan for Dependencies When this option is used, .dep and .d dependency files are generated. The dependency file lists those files on which the source file is dependant. Dependencies result when one file is #included into another. The .d file format is used by GCC-based compilers and contains the same information as the .dep file. Compilation will stop after the preprocessing stage if this option is used. 4.8.
XC8 Command-line Driver 4.8.55 --STRICT: Strict ANSI Conformance The --STRICT option is used to enable strict ANSI C conformance of all special, non-standard keywords. The MPLAB XC8 C compiler supports various special keywords (for example the persistent type qualifier). If the --STRICT option is used, these keywords are changed to include two underscore characters at the beginning of the keyword (for example, __persistent) so as to strictly conform to the ANSI standard.
MPLAB® XC8 C Compiler User’s Guide 4.8.59 --WARN: Set Warning Level The --WARN option is used to set the compiler warning level threshold. Allowable warning levels range from -9 to 9. The warning level determines how pedantic the compiler is about dubious type conversions and constructs. Each compiler warning has a designated warning level; the higher the warning level, the more important the warning message.
XC8 Command-line Driver 4.9 MPLAB IDE V8 UNIVERSAL TOOLSUITE EQUIVALENTS When compiling from within Microchip’s MPLAB IDE, it is still the compiler’s command-line driver, xc8, that is being executed and compiling the program. The Universal Toolsuite plugin manages the MPLAB IDE Build Options dialog that is used to access the compiler options, and most of these graphical controls ultimately adjust the driver’s command-line options.
MPLAB® XC8 C Compiler User’s Guide 4.9.1 Directories Tab The options in this dialog control the output and search directories for some files. See Figure 4-5 in conjunction with the following command line option equivalents. FIGURE 4-5: THE DIRECTORIES TAB 1 2 1. The output directory: This selection uses the buttons and fields grouped in the bracket to specify an output directory for files output by the compiler.
XC8 Command-line Driver 4.9.2 Compiler Tab The options in this dialog control the aspects of compilation up to code generation. See Figure 4-6 in conjunction with the following command line option equivalents. 1. Define macros: The buttons and fields grouped in the bracket can be used to define preprocessor macros. See Section 4.8.2 “-D: Define Macro”. 2. Undefine macros: The buttons and fields grouped in the bracket can be used to undefine preprocessor macros. See Section 4.8.14 “-U: Undefine a Macro”.
MPLAB® XC8 C Compiler User’s Guide 6. Verbose: This checkbox controls whether the full command-lines for the compiler applications are displayed when building. See Section 4.8.15 “-V: Verbose Compile”. 7. Warning level: This selector allows the warning level print threshold to be set. See Section 4.8.59 “--WARN: Set Warning Level”. 8. Operation Mode: This selector allows the user to force another available operating mode (e.g., Free, Standard or PRO) other than the default. See Section 4.8.
XC8 Command-line Driver 1. Runtime options: These checkboxes control the many runtime features the compiler can employ. See Section 4.8.50 “--RUNTIME: Specify Runtime Environment”. 2. Fill: This field allows a fill value to be specified for unused memory locations. See Section 4.8.30 “--FILL: Fill Unused Program Memory”. 3. Codeoffset: This field allows an offset for the program to be specified. See Section 4.8.22 “--CODEOFFSET: Offset Program Code to Address”. 4.
MPLAB® XC8 C Compiler User’s Guide 4.9.4 Global Tab The options in this dialog control aspects of compilation that are applicable throughout code generation and link steps — the second stage of compilation. See Figure 4-8 in conjunction with the following command line option equivalents. FIGURE 4-8: 1 2 3 4 5 THE GLOBAL TAB 6 7 8 9 10 11 1. Memory model: Not applicable. 2. Double float: This selector allows the size of the double type to be selected. See Section 4.8.
XC8 Command-line Driver 7. External memory: This option affect the code generated when accessing the external data interface on applicable PIC18 devices. See Section 4.8.26 “--EMI: Select External Memory Interface Operating Mode”. 8. Instruction set: Not applicable. 9. Printf: Not applicable. 10. ROM ranges: This field allows the default ROM (program space) memory used to be adjusted. See Section 4.8.49 “--ROM: Adjust ROM Ranges”. 11.
MPLAB® XC8 C Compiler User’s Guide 4.10 MPLAB X UNIVERSAL TOOLSUITE EQUIVALENTS When compiling under the MPLAB X IDE, it is still the compiler’s command-line driver that is being executed and compiling the program. The MPLAB XC8 compiler plugins controls the MPLAB X IDE Properties dialog that is used to access the compiler options, however these graphical controls ultimately adjust the command-line options passed to the command-line driver when compiling.
XC8 Command-line Driver 4.10.2 Compiler Category The panels in this category control aspects of compilation of C source. 4.10.2.1 PREPROCESSING AND MESSAGES These options relate to the C preprocessor and messages produced by the compiler (see Section 4.6 “Compiler Messages” for more information). See Figure 4-10 in conjunction with the following command-line option equivalents. FIGURE 4-10: PREPROCESSING AND MESSAGES OPTIONS 1 2 3 4 5 6 7 8 1.
MPLAB® XC8 C Compiler User’s Guide 4.10.2.2 OPTIMIZATION These options, shown in Figure 4-11, relate to optimizations performed by the compiler, 1. Optimization controls: These controls adjust the optimizations employed by the compiler. See Section 4.8.42 “--OPT: Invoke Compiler Optimizations”. Select an optimizations set (--OPT suboptions: all or none), or any of the custom options below (--OPT suboptions: asm, asmfile, speed/space and debug). 2.
XC8 Command-line Driver 4.10.3 Linker Category The options in this dialog control the aspects of the second stage of compilation including code generation and linking. 4.10.3.1 RUNTIME All the widgets in Figure 4-13 correspond to suboptions of the --RUNTIME option, see Section 4.8.50 “--RUNTIME: Specify Runtime Environment”. Respectively, these map to the clear, init, keep, no_startup, osccal, oscval, resetbits, download, stackcall, config, clib and plib suboptions of the --RUNTIME option.
MPLAB® XC8 C Compiler User’s Guide 4.10.3.2 REPORTING These options, shown in Figure 4-14 relate to information produced during and after compilation. 1. Display memory usage after compilation: These checkboxes allow you to specify what information is displayed after compilation. The correspond to the psect, class, mem and hex suboptions to the --SUMMARY option, see Section 4.8.56 “--SUMMARY: Select Memory Summary Output Type”. 2.
XC8 Command-line Driver 4.10.3.3 ADDITIONAL These options, shown in Figure 4-15 relate to miscellaneous options. 1. Fill: This field allows a fill value to be specified for unused memory locations, see Section 4.8.30 “--FILL: Fill Unused Program Memory”. 2. Serial: This option allows you to specify a string which can be inserted into your output HEX file. See Section 4.8.52 “--SERIAL: Store a Value At This Program Memory Address”. 3.
MPLAB® XC8 C Compiler User’s Guide NOTES: DS52053B-page 130 2012 Microchip Technology Inc.
MPLAB® XC8 C COMPILER USER’S GUIDE Chapter 5. C Language Features 5.1 INTRODUCTION MPLAB XC8 C Compiler supports a number of special features and extensions to the C language which are designed to ease the task of producing ROM-based applications for 8-bit PIC devices. This chapter documents the special language features which are specific to these devices. • • • • • • • • • • • • • • 5.
MPLAB® XC8 C Compiler User’s Guide 5.2.3 Common Compiler Interface Standard This compiler conforms to the Microchip XC compiler Common Compiler Interface standard (CCI). This is a further refinement of the ANSI standard that attempts to standardize implementation-defined behavior and non-standard extensions across the entire MPLAB XC compiler family. If you choose to write code which conforms to this standard, a compiler option (see Section 4.8.
C Language Features 5.3 DEVICE-RELATED FEATURES MPLAB XC8 has several features which relate directly to the 8-bit PIC architectures and instruction sets. These are detailed in the following sections. 5.3.1 Device Support MPLAB XC8 C Compiler aims to support all 8-bit PIC devices. However, new devices in these families are frequently released. There are several ways you can check if the compiler you are using supports a particular device. From MPLAB IDE (v8), open the Build Options dialog.
MPLAB® XC8 C Compiler User’s Guide 5.3.3 Device Header Files There is one header file that is typically included into each C source file you write. The file is and is a generic header file that will include other device- and architecture-specific header files when you build your project. Inclusion of this file will allow access to SFRs via special variables, as well as macros which allow special memory access or inclusion of special instructions, like CLRWDT.
C Language Features 5.3.5 Configuration Bit Access The PIC devices have several locations which contain the configuration bits or fuses. These bits specify fundamental device operation, such as the oscillator mode, watchdog timer, programming mode and code protection. Failure to correctly set these bits may result in code failure, or a non-running device. For PIC18 devices, these bits may be set using a configuration pragma. (Pragmas will also be introduced for other 8-bit devices in future releases.
MPLAB® XC8 C Compiler User’s Guide 5.3.5.1 LEGACY SUPPORT FOR PIC18 DEVICES You may continue to use the PIC18 configuration macros for legacy projects. The compiler supports the __CONFIG and __PROG_CONFIG macros which allow configuration bit symbols or a configuration word value, respectively, to be specified. The __CONFIG macro used for PIC18 devices takes an additional argument being the number of the configuration word location.
C Language Features 5.3.6 Using SFRs From C Code The Special Function Registers (SFRs) are registers which control aspects of the MCU operation or that of peripheral modules on the device. Most of these registers are memory mapped, which means that they appear at, and can be accessed using, specific addresses in the device’s data memory space. Individual bits within some registers control independent features. Some registers are read-only; some are write-only.
MPLAB® XC8 C Compiler User’s Guide 5.3.6.1 SPECIAL BASELINE/MID-RANGE REGISTER ISSUES Some SFRs are not memory mapped, do not have a corresponding variable defined in the device specific header file, and cannot be directly accessed from C code. For example, the W register is not memory mapped on baseline devices. Some devices use OPTION and TRIS registers, that are only accessible via special instructions and that are also not memory mapped. See Section 5.3.
C Language Features 5.3.7 ID Locations The 8-bit PIC devices have locations outside the addressable memory area that can be used for storing program information, such as an ID number. For PIC18 devices, the config pragma is also used to place data into these locations by using a special register name. The pragma is used as follows. #pragma config IDLOCx = value where x is the number (position) of the ID location, and value is the nibble or byte which is to be positioned into that ID location.
MPLAB® XC8 C Compiler User’s Guide 5.3.8 Bit Instructions Wherever possible, the MPLAB XC8 C Compiler will attempt to use bit instructions, even on non-bit integer values. For example, when using a bitwise operator and a mask to alter a bit within an integral type, the compiler will check the mask value to determine if a bit instruction can achieve the same functionality.
C Language Features 5.3.9.1 OSCILLATOR CALIBRATION CONSTANTS Some Baseline and Mid-range devices come with an oscillator calibration constant which is pre-programmed into the device’s program memory. This constant can be read from program memory and written to the OSCCAL register to calibrate the internal RC oscillator. On some Baseline PIC devices, the calibration constant is stored as a MOVLW instruction at the top of program memory, e.g. the PIC10F509 device.
MPLAB® XC8 C Compiler User’s Guide 5.3.10 REAL ICE Support The compiler supports log and trace functions (instrumented trace) when using Microchip’s REAL ICE debugger. See the REAL ICE documentation for more information on the instrumented trace features. Only native trace is currently supported by the compiler. Not all devices support instrumented trace, and the IDE you are using also needs to have instrumented trace support for your target device, as well.
C Language Features 5.4 SUPPORTED DATA TYPES AND VARIABLES 5.4.1 Identifiers A C variable identifier (the following is also true for function identifiers) is a sequence of letters and digits, where the underscore character “_” counts as a letter. Identifiers cannot start with a digit. Although they may start with an underscore, such identifiers are reserved for the compiler’s use and should not be defined by your programs.
MPLAB® XC8 C Compiler User’s Guide Signed values are stored as a two’s complement integer value. The range of values capable of being held by these types is summarized in Table 5-2 The symbols in this table are preprocessor macros which are available after including in your source code. As the size of data types are not fully specified by the ANSI Standard, these macros allow for more portable code which can check the limits of the range of values held by the type on this implementation.
C Language Features 5.4.2.1 BIT DATA TYPES AND VARIABLES The MPLAB XC8 C Compiler supports bit integral types which can hold the values 0 or 1. Single bit variables may be declared using the keyword bit, for example: bit init_flag; These variables cannot be auto or parameters to a function, but can be qualified static, allowing them to be defined locally within a function. For example: int func(void) { static bit flame_on; // ...
MPLAB® XC8 C Compiler User’s Guide 5.4.3 Floating-Point Data Types The MPLAB XC8 compiler supports 24- and 32-bit floating-point types. Floating point is implemented using either a IEEE 754 32-bit format, or a modified (truncated) 24-bit form of this. Table 5-3 shows the data types and their corresponding size and arithmetic type.
C Language Features Here are some examples of the IEEE 754 32-bit formats shown in Table 5-5. Note that the Most Significant Bit (MSb) of the mantissa column (i.e., the bit to the left of the radix point) is the implied bit, which is assumed to be 1 unless the exponent is zero (in which case the float is zero). TABLE 5-5: Format 32-bit 24-bit FLOATING-POINT FORMAT EXAMPLE IEEE 754 Number 7DA6B69Bh 42123Ah Biased exponent 1.mantissa Decimal 11111011b 1.0100110101101101 0011011b 2.
MPLAB® XC8 C Compiler User’s Guide Two sets of macros are available for float and double types, where XXX represents FLT and DBL, respectively. So, for example, FLT_MAX represents the maximum floating-point value of the float type. It can have two values depending on whether float is a 24 or 32 bit wide format. DBL_MAX represents the same values for the double type.
C Language Features 5.4.4 Structures and Unions MPLAB XC8 C Compiler supports struct and union types. Structures and unions only differ in the memory offset applied to each member. These types will be at least 1 byte wide. The members of structures and unions may not be objects of type bit, but bit-fields are fully supported. Structures and unions may be passed freely as function arguments and function return values. Pointers to structures and unions are fully supported. 5.4.4.
MPLAB® XC8 C Compiler User’s Guide 5.4.4.2 BIT-FIELDS IN STRUCTURES MPLAB XC8 C Compiler fully supports bit-fields in structures. Bit-fields are always allocated within 8-bit words, even though it is usual to use the type unsigned int in the definition. The first bit defined will be the LSb of the word in which it will be stored. When a bit-field is declared, it is allocated within the current 8-bit unit if it will fit; otherwise, a new byte is allocated within the structure.
C Language Features The MPLAB XC8 compiler supports anonymous unions. These are unions with no identifier and whose members can be accessed without referencing the enclosing union. These unions can be used when placing inside structures. For example: struct { union { int x; double y; }; } aaa; void main(void) { aaa.x = 99; // ...} Here, the union is not named and its members accessed as if they are part of the structure.
MPLAB® XC8 C Compiler User’s Guide 5.4.5 Pointer Types There are two basic pointer types supported by the MPLAB XC8 C Compiler: data pointers and function pointers. Data pointers hold the addresses of variables which can be indirectly read, and possible indirectly written, by the program. Function pointers hold the address of an executable function which can be called indirectly via the pointer. To conserve memory requirements and reduce execution time, pointers are made different sizes and formats.
C Language Features 5.4.5.2 DATA POINTERS The MPLAB XC8 compiler monitors and records all assignments of addresses to each data pointer the program contains. This includes assignment of the addresses of objects to pointers; assignment of one pointer to another; initialization of pointers when they are defined; and takes into account when pointers are ordinary variables and function parameters, and when pointers are used to access basic objects, or structures or arrays.
MPLAB® XC8 C Compiler User’s Guide Information about the pointers and their targets are shown in the pointer reference graph, which is described in Section 6.6.5 “Pointer Reference Graph”. This graph is printed in the assembly list file, which is controlled by the option described in Section 4.8.17 “--ASMLIST: Generate Assembler List Files”. Consider the following mid-range device program in the early stages of development.
C Language Features 5.4.5.2.1 Pointers to Both Memory Spaces When a pointer is assigned the address of one or more objects that have been allocated memory in the data space, and also assigned the address of one or more const objects, the pointer will fall into one of the mixed target space pointers listed in Section 5.4.5.2 “Data Pointers”, and the address will be encoded so that the target memory space can be determined at runtime. The encoding of these pointer types are as follows.
MPLAB® XC8 C Compiler User’s Guide 5.4.5.3 FUNCTION POINTERS The MPLAB XC8 compiler fully supports pointers to functions, which allows functions to be called indirectly. These are often used to call one of several function addresses stored in a user-defined C array, which acts like a lookup table. For baseline and mid-range devices, function pointers are always one byte in size and hold an offset into a jump table that is output by the compiler. This jump table contains jumps to the destination functions.
C Language Features Note that the const array does not need initial values to be specified in this instance, see Section 5.4.7.1 “Const Type Qualifier” and can reside over the top of other objects at these addresses. If the pointer has to access objects in data memory, you need to define a different object to act as a dummy target. For example, if the checksum was to be calculated over 10 bytes starting at address 0x90 in data memory, the following code could be used.
MPLAB® XC8 C Compiler User’s Guide 5.4.6 Constant Types and Formats A constant is used to represent an immediate value in the source code, as opposed to a variable that could hold the same value. For example 123 is a constant. Like any value, a constant must have a C type. In addition to a constant’s type, the actual value can be specified in one of several formats. 5.4.6.1 INTEGRAL CONSTANTS The format of integral constants specifies their radix.
C Language Features Here is an example of code that may fail because the default type assigned to a constant is not appropriate: unsigned long int result; unsigned char shifter; void main(void) { shifter = 20; result = 1 << shifter; // code that uses result } The constant 1 (one) will be assigned an int type, hence the result of the shift operation will be an int.
MPLAB® XC8 C Compiler User’s Guide 5.4.6.3 CHARACTER AND STRING CONSTANTS Character constants are enclosed by single quote characters, ’, for example ’a’. A character constant has int type, although this may be later optimized to a char type by the compiler. To comply with the ANSI C standard, the compiler does not support the extended character set in characters or character arrays.
C Language Features 5.4.7 Standard Type Qualifiers Type qualifiers provide additional information regarding how an object may be used. The MPLAB XC8 compiler supports both ANSI C qualifiers and additional special qualifiers which are useful for embedded applications and which take advantage of the 8-bit PIC MCU architecture. 5.4.7.1 CONST TYPE QUALIFIER MPLAB XC8 supports the use of the ANSI type qualifiers const and volatile.
MPLAB® XC8 C Compiler User’s Guide A C statement that consists only of a volatile variable’s name will produce code that reads the variable’s memory location and discards the result. For example the entire statement: PORTB; will produce assembly code the reads PORTB, but does nothing with this value. This is useful for some peripheral registers that require reading to reset the state of interrupt flags. Normally such a statement is not encoded as it has no effect.
C Language Features This qualifier is controlled by the compiler option --ADDRQUAL, which determines its effect, see Section 4.8.16 “--ADDRQUAL: Set Compiler Response to Memory Qualifiers”. Based on this option’s settings, this qualifier may be binding or ignored (which is the default operation). Qualifiers which are ignored will not produce an error or warning, but will have no effect.
MPLAB® XC8 C Compiler User’s Guide Although a few devices implement more than 4 banks of data RAM, bank qualifiers to allow placement into these upper banks are not currently available. These qualifiers are controlled by the compiler option --ADDRQUAL, which determines their effect, see Section 4.8.16 “--ADDRQUAL: Set Compiler Response to Memory Qualifiers”. Based on this option’s settings, these qualifiers may be binding or ignored (which is the default operation).
C Language Features 5.5 MEMORY ALLOCATION AND ACCESS There are two broad groups of RAM-based variables: auto/parameter variables, which are allocated to some form of stack, and global/static variables, which are positioned freely throughout the data memory space at static locations. The memory allocation of these two groups is discussed separately in the following sections. 5.5.
MPLAB® XC8 C Compiler User’s Guide Note: 5.5.2.1 The terms “local” and “global” are commonly used to describe variables, but are not ones defined by the language Standard. The term “local variable” is often taken to mean a variable which has scope inside a function, and “global variable” is one which has scope throughout the entire program. However, the C language has three common scopes: block, file (i.e., internal linkage) and program (i.e.
C Language Features Note that the data psect used to hold initialized variables is the psect that holds the RAM variables themselves. There is a corresponding psect (called idata) that is placed into program memory (so it is non-volatile) and which is used to hold the initial values that are copied to the RAM variables by the runtime startup code. All non-auto variables, except for static variables, discussed in Section 5.5.2.1.
MPLAB® XC8 C Compiler User’s Guide With any device, reserving memory in general purpose RAM (see Section 4.8.48 “--RAM: Adjust RAM Ranges”), or defining absolute variables in the middle of data banks (see Section 5.5.4 “Absolute Variables”), further restricts the contiguous memory in the data banks and may reduce the maximum size of objects you can define. 5.5.2.1.
C Language Features 5.5.2.2 AUTO VARIABLE ALLOCATION AND ACCESS This section discusses allocation of auto variables (those with automatic storage duration). This also include function parameter variables, which behave like auto variables in terms of their storage duration and scope. Temporary variables defined by the compiler also fall into this group. They are identical to autos except they are defined by the compiler, not the programmer, and as a result, have no C name.
MPLAB® XC8 C Compiler User’s Guide Fundamental to the generation of the compiled stack is the call graph, which defines a tree-like hierarchy of function calls, i.e it shows what functions may be called by each function. There will be one graph produced for each root function. A root function is typically not called, but which is executed via other means and contains a program entry point. The function main() is an example of a root function that will be in every project.
C Language Features Figure 5-3 graphically shows an example of how the compiled stack is formed.
MPLAB® XC8 C Compiler User’s Guide The end result is a block of memory which forms the compiled stack. This block can then be placed into the device’s memory by the linker. For devices with more than one bank of data memory, the compiled stack may be built up into components, each located in a different memory bank. The compiler will try to allocate the compiled stack in one bank, but if this fills, it will consider other banks.
C Language Features 5.5.3 Variables in Program Space The only variables that are placed into program memory are those that are not auto and which have been qualified const. Any auto variables qualified const are placed in the compiled stack along with other auto variables, and all components of the compiled stack will only ever be located in the data space memory.
MPLAB® XC8 C Compiler User’s Guide 5.5.3.1 SIZE LIMITATIONS OF CONST VARIABLES Arrays of any type (including arrays of aggregate types) can be qualified const and placed in the program memory. So too can structure and union aggregate types, see 5.4.4 “Structures and Unions”. These objects can often become large in size and may affect memory allocation. For baseline PIC devices, the maximum size of a single const object is 255 bytes.
C Language Features 5.5.4 Absolute Variables Most variables can be located at an absolute address by following its declaration with the construct @ address, where address is the location in memory where the variable is to be positioned. Such a variables is known as an absolute variables. 5.5.4.
MPLAB® XC8 C Compiler User’s Guide 5.5.4.2 ABSOLUTE OBJECTS IN PROGRAM MEMORY Non-auto objects qualified const can also be made absolute in the same way, however, the address will indicate an address in program memory. For example: const int settings[] @ 0x200 = { 1, 5, 10, 50, 100 }; will place the array settings at address 0x200 in the program memory. Both initialized and uninitialized const objects can be made absolute.
C Language Features 5.5.5.2 EEPROM ACCESS FUNCTIONS The library functions eeprom_read() and eeprom_write(), can be called to read from, and write to, the EEPROM during program execution. On PIC18 devices, these functions are derived from the peripheral library. The prototypes for these functions are as below. #include
MPLAB® XC8 C Compiler User’s Guide 5.5.6 Variables in Registers Allocating variables to registers, rather than to a memory location, can make code more efficient. With MPLAB XC8, there is no direct control of placement of variables in registers. The register keyword (which can only be used with auto variables) is silently ignored and has no effect on memory allocation of variables.
C Language Features 5.6 OPERATORS AND STATEMENTS The MPLAB XC8 C Compiler supports all the ANSI operators. The exact results of some of these are implementation defined. Implementation-defined behavior is fully documented in Appendix C. “Implementation-Defined Behavior”. The following sections illustrate code operations that are often misunderstood as well as additional operations that the compiler is capable of performing. 5.6.
MPLAB® XC8 C Compiler User’s Guide The consequence of integral promotion as illustrated above is that operations are not performed with char -type operands, but with int -type operands. However, there are circumstances when the result of an operation is identical regardless of whether the operands are of type char or int. In these cases, the compiler will not perform the integral promotion so as to increase the code efficiency. Consider this example.
C Language Features 5.7 REGISTER USAGE The assembly generated from C source code by the compiler will use certain registers in the PIC MCU register set. Most importantly, the compiler assumes that nothing other than code it generates can alter the contents of these registers. So if compiler-generated assembly code loads a register with a value and no subsequent code requires this register, the compiler will assume that the contents of the register are still valid later in the output sequence.
MPLAB® XC8 C Compiler User’s Guide 5.8 FUNCTIONS Functions may be written in the usual way in accordance with the C language. Implementation and special features associated with functions are discussed in the following sections. 5.8.1 Function Specifiers Functions may, in the usual way, use the standard specifier static. A function defined using the static specifier only affects the scope of the function; i.e., limits the places in the source code where the function may be called.
C Language Features This specifier performs the same task as the #pragma inline directive, see Section 5.14.4.4 “The #pragma Intrinsic Directive”. 5.8.2 External Functions If a call to a function that is defined outside the program C source code is required (it may be part of code compiled separately, e.g., the bootloader, or in assembly code), you will need to provide a declaration of the function so that the compiler knows how to encode the call.
MPLAB® XC8 C Compiler User’s Guide in one page to a label in another must use a longer sequence of instructions to accomplish this. See your device data sheet for more information on the program memory and instruction set. PIC18 devices do not implement any program memory paging. The CALL and GOTO instruction are two-word instructions and their destinations are not limited. The relative branch instructions have a limited range, but this is not based on any paging boundaries.
C Language Features If this construct is used with interrupt functions it will only affect the position of the code associated with the interrupt function body. The interrupt context switch code that precedes the function code will not be relocated as it must be linked to the interrupt vector. See also Section4.8.22 “--CODEOFFSET: Offset Program Code to Address” for information on how to move Reset and interrupt vector locations, which may be useful for designing applications such as bootloaders.
MPLAB® XC8 C Compiler User’s Guide Unlike auto variables, parameter variables are allocated memory strictly in the order in which they appear in the function’s prototype. This means that the parameters will always be placed in the same memory bank. The auto variables for a function can be allocated across multiple banks and in any order.
C Language Features 5.8.7 Function Return Values Function return values are passed to the calling function using either the W register, or the function’s parameter memory in its auto-parameter block. Having return values also located in the same memory as that used by the parameters can reduce the code size for functions that return a modified copy of their parameter. Eight-bit values are returned from a function in the W register.
MPLAB® XC8 C Compiler User’s Guide 5.8.8.1 BANK SELECTION WITHIN FUNCTIONS A function can, and may, return with any RAM bank selected. See Section 5.5.1 “Address Spaces” for more information on RAM banks. The compiler tracks the bank selections made in the generated code associated with each function, even across function calls to other functions.
C Language Features 5.9 INTERRUPTS The MPLAB XC8 compiler incorporates features allowing interrupts to be fully handled from C code. Interrupt functions are often called Interrupt Service Routines, or ISRs. Note: Baseline devices do not utilize interrupts and so the following sections are only applicable for mid-range, Enhanced mid-range and PIC18 devices. There is only one interrupt vector on mid-range and Enhanced mid-range devices.
MPLAB® XC8 C Compiler User’s Guide An example of an interrupt function is shown here. int tick_count; void interrupt tc_int(void) { if (TMR0IE && TMR0IF) { TMR0IF=0; ++tick_count; return; } // process other interrupt sources here, if required } Code generated by the compiler will be placed at the interrupt vector address which will execute this function after any context switch that is required.
C Language Features 5.9.3 Context Switching 5.9.3.1 CONTEXT SAVING ON INTERRUPTS Some registers are automatically saved by the hardware when an interrupt occurs. Any registers or compiler temporary objects used by the interrupt function, other than those saved by the hardware, must be saved in code generated by the compiler. This is the context save, or context switch code. See Section 5.
MPLAB® XC8 C Compiler User’s Guide 5.9.4 Enabling Interrupts Two macros are available, once you have included , which control the masking of all available interrupts. These macros are ei(), which enable or unmask all interrupts, and di(), which disable or mask all interrupts. On all devices, they affect the GIE bit in the INTCON register. These macros should be used once the appropriate interrupt enable bits for the interrupts that are required in a program have been enabled.
C Language Features Examination of the assembly list file will show assembly code for both the original and duplicate function outputs. The output corresponding to the C function input() will use the assembly label _input. The corresponding label used by the duplicate function will be i1_input. If the original function makes reference to a temporary variable, the generated output will use the symbol ??_input, compared to ??i1_input for the duplicate output.
MPLAB® XC8 C Compiler User’s Guide 5.10 MAIN, RUNTIME STARTUP AND RESET The identifier main is special. You must always have one and only one function called main() in your programs. This is the first function to execute in your program. Code associated with main(); however, is not the first code to execute after Reset. Additional code provided by the compiler, and known as the runtime startup code, is executed first and is responsible for transferring control to the main() function.
C Language Features 5.10.1.1 INITIALIZATION OF OBJECTS One task of the runtime startup code is to ensure that any initialized variables contain their initial value before the program begins execution. Initialized variables are those which are not auto objects and which are assigned an initial value in their definition, for example input in the following example. int input = 88; void main(void) { ...
MPLAB® XC8 C Compiler User’s Guide The psects used for storing these components are described in Section 5.15.2 “Compiler-Generated Psects” and typically have a name based on the initialism “bss” (Block Started by Symbol). The runtime startup code will clear all the memory location occupied by uninitialized variables so they will contain zero before main() is executed. Variables whose contents should be preserved over a Reset should be qualified with persistent. See Section 5.4.8.
C Language Features 5.10.1.4 STATUS REGISTER PRESERVATION The resetbits suboption of the --RUNTIME option (see 4.8.50 “--RUNTIME: Specify Runtime Environment”) preserves some of the bits in the STATUS register before being clobbered by the remainder of the runtime startup code. The state of these bits can be examined after recovering from a Reset condition to determine the cause of the Reset. The entire STATUS register is saved to an assembly variable ___resetbits.
MPLAB® XC8 C Compiler User’s Guide 5.11 LIBRARY ROUTINES 5.11.0.1 USING LIBRARY ROUTINES Library functions (and any associated variables) will be automatically linked into a program once they have been referenced in your source code. The use of a function from one library file will not include any other functions from that library. Only used library functions will be linked into the program output and consume memory. Your program will require declarations for any functions or symbols used from libraries.
C Language Features As more features of printf() are detected, the size of the code generated for the printf() function will increase. If the format string in a call to printf() is not a string literal as above, but is rather a pointer to a string, then the compiler will not be able to reliably predict the printf() usage, and so it forces a more complete version of printf() to be generated.
MPLAB® XC8 C Compiler User’s Guide 5.12 MIXING C AND ASSEMBLY CODE Assembly language code can be mixed with C code using two different techniques: writing assembly code and placing it into a separate assembler module, or including it as inline assembly in a C module. Note: 5.12.1 The more assembly code a project contains, the more difficult and time consuming will be its maintenance. As the project is developed, the compiler may perform different optimizations a these are based on the entire program.
C Language Features See Section 6.4.9.3 “PSECT” for detailed information on the flags used with the PSECT assembler directive. This psect is called text0. It is flagged local, which means that it is distinct from other psects with the same name. This flag is not important in this example and can be omitted, if required. It lives in the CODE class. This flag is important as it means it will be automatically placed in the area of memory set aside for code.
MPLAB® XC8 C Compiler User’s Guide Here is an example of the complete routine for a mid-range device which could be placed into an assembly file and added to your project. The GLOBAL and SIGNAT directives do not generator code, and hence do not need to be inside the mytext psect, although you can place them there if you prefer. The BANKSEL directive and BANKMASK macro have been used to ensure that the correct bank was selected and that all addresses are masked to the appropriate size. #include
C Language Features You may use the asm() form of inline assembly at any point in the C source code as it will correctly interact with all C flow-of-control structures. The following example shows both methods used: unsigned int var; void main(void) { var = 1; #asm // like this... BCF 0,3 BANKSEL(_var) RLF (_var)&07fh RLF (_var+1)&07fh #endasm // do it again the other way...
MPLAB® XC8 C Compiler User’s Guide 5.12.3.1 EQUIVALENT ASSEMBLY SYMBOLS Most C symbols map to an corresponding assembly equivalent. This mapping is such that an “ordinary” symbol defined in the assembly domain cannot interfere with an “ordinary” symbol in the C domain. So for example, if the symbol main is defined in the assembly domain, it is quite distinct to the main symbol used in C code and they refer to different locations.
C Language Features If there is more than one static function with the same name, and they contain definitions for static variables of the same name, then the assembly symbol used for these variables will be of the form: fileName@functionName@variableName. Having two static variables or functions with the same name is legal, but not recommended as the wrong variable may be accessed or the wrong function called.
MPLAB® XC8 C Compiler User’s Guide If you wish to access register definitions from assembly that is inline with C code, a different header file is available for this purpose. Include the header file into the assembly code. This file can only be used with baseline and mid-range devices. There is non comparable file for PIC18 devices. The symbols used for register names will be the same as those defined by
C Language Features 5.12.3.4 UNDEFINED SYMBOLS If a variable needs to be accessible from both assembly and C source code, it can be defined in assembly code, if required, but it is easier to do so in C source code. A problem could occur if there is a variable defined in C source, but is only ever referenced in the assembly code. In this case, the code generator would remove the variable believing it is unused.
MPLAB® XC8 C Compiler User’s Guide 5.13 OPTIMIZATIONS The optimizations in MPLAB XC8 compiler can broadly be broadly grouped into C-level optimizations performed on the source code before conversion into assembly; and assembly-level optimizations performed on the assembly code generated by the compiler. The C-level optimizations are performed early during the code generation phase and so have flow-on benefits: performing one optimizations may mean that another can then be applied.
C Language Features Variables assigned a value before being read are not cleared or initialized by the runtime startup code. Only non-auto variables are considered and if they are assigned a value before other code can read their value, they are treated as being persistent, see Section 5.4.8.1 “Persistent Type Qualifier”. All persistent objects are not cleared by the runtime startup code, so this optimization will speed execution of the program startup.
MPLAB® XC8 C Compiler User’s Guide 5.14 PREPROCESSING All C source files are preprocessed before compilation. The preprocessed file is not deleted after compilation. It will have a .pre extension and the same base name as the source file from which it is derived. The --PRE option can be used to preprocess and then stop the compilation. See Section 4.8.46 “--PRE: Produce Preprocessed Source Code”. Assembler files can also be preprocessed if the -P driver option is issued. See Section 4.8.
C Language Features TABLE 5-11: PREPROCESSOR DIRECTIVES Directive Meaning Example # Preprocessor null directive, do nothing # #assert Generate error if condition false #asm Signifies the beginning of inline assem- #asm MOVLW FFh bly #endasm #define Define preprocessor macro #define SIZE 5 #define FLAG #define add(a,b) ((a)+(b)) #elif Short for #else #if see #ifdef #else Conditionally include source lines see #if #endasm Terminate inline assembly see #asm #endif Terminate conditional
MPLAB® XC8 C Compiler User’s Guide 5.14.3 Predefined Macros The compiler drivers define certain symbols to the preprocessor, allowing conditional compilation based on chip type, etc. The symbols listed in Table 5-12 show the more common symbols defined by the drivers. TABLE 5-12: PREDEFINED MACROS Symbol Usage __CHIPNAME When chip selected __DATABANK If eeprom or flash memory imple- Identifies which bank the EEDmented ATA/PMDATA register is found __DATE__ Always To indicate the current date, e.
C Language Features TABLE 5-12: PREDEFINED MACROS (CONTINUED) Symbol When set Usage _EEPROMSIZE Always To indicate how many bytes of EEPROM are available. _ERRATA_TYPES If PIC18 device Indicates the errata workarounds being applied, see --ERRATA option Section 4.8.27.
MPLAB® XC8 C Compiler User’s Guide TABLE 5-12: PREDEFINED MACROS (CONTINUED) Symbol When set Usage HI_TECH_C Always To indicate that the C language variety is HI-TECH C compatible. MPLAB_ICD If compiling for MPLAB® ICD or MPLAB ICD 2/3 debugger Assigned 1 to indicate that the code is generated for use with the Microchip MPLAB ICD 1. Assigned 2 for MPLAB ICD 2; 3 for MPLAB ICD 3. Each symbol, if defined, is equated to 1 unless otherwise stated. 5.14.
C Language Features 5.14.4.1 THE #PRAGMA ADDRQUAL DIRECTIVE This directive allows you to control the compiler’s response to non-standard memory qualifiers. This pragma is an in-code equivalent to the --ADDRQUAL option and both use the same arguments, see Section 4.8.16 “--ADDRQUAL: Set Compiler Response to Memory Qualifiers”. The pragma has effect over the entire C program and should be issued once, if required. If the pragma is issued more than once, the last pragma determines the compiler’s response.
MPLAB® XC8 C Compiler User’s Guide 5.14.4.7 THE #PRAGMA PRINTF_CHECK DIRECTIVE Certain library functions accept a format string followed by a variable number of arguments in the manner of printf(). Although the format string is interpreted at runtime, it can be compile-time checked for consistency with the remaining arguments. This directive enables this checking for the named function, for example the system header file
C Language Features This pragma affects the entire module in which it is located, regardless of the position of the pragma in the file. Any given psect should only be redirected once in a particular module. That is, you cannot redirect the standard psect for some of the module, then swap back to using the standard psect for the remainder of the source code. The pragma should typically be placed at the top of the source file.
MPLAB® XC8 C Compiler User’s Guide So it is allocated to a textn psect. The source code for the masher() function is removed from this source file and placed in is own file. The psect pragma is then applied so that this new file contains the following. #pragma psect text%%u=myMasherPsect int masher(int val) { return val; } After recompiling, the function is now located in its own psect. The updated map file now shows the following. Note that its address has not changed.
C Language Features 5.14.4.9 THE #PRAGMA REGSUSED DIRECTIVE The #pragma regsused directive allows the programmer to indicate register usage for functions that will not be “seen” by the code generator, for example if they were written in assembly code. It has no effect when used with functions defined in C code, but in these cases the register usage of these functions can be accurately determined by the compiler and the pragma is not required.
MPLAB® XC8 C Compiler User’s Guide Specifying the time option to the #pragma switch directive forces the compiler to generate a table look-up style switch method. The time taken to execute each case is the same, so this is useful where timing is an issue, e.g state machines. This pragma affects all subsequent code. The auto option may be used to revert to the default behavior. There is information printed in the assembly list file for each switch statement showing the chosen strategy, see Section 6.6.
C Language Features 5.14.4.11.2 The Warning Error/warning Pragma It is also possible to change the type of some messages. This is only possible by the use of the warning pragma and only affects messages generated by the parser or code generator. The position of the pragma is only significant for the parser; i.e., a parser message number may have its type changed for one section of the code to target specific instances of the message.
MPLAB® XC8 C Compiler User’s Guide 5.15 LINKING PROGRAMS The compiler will automatically invoke the linker unless the compiler has been requested to stop after producing an intermediate file. The linker will run with options that are obtained from the command-line driver. These options specify the memory of the device and how the psects should be placed in the memory. No linker scripts are used.
C Language Features 5.15.1.2 THE COMPILER EQUIVALENT Let’s now look at the similarities and differences between this situation and the compilation process. Both these processes are compared in Figure 5-4.
MPLAB® XC8 C Compiler User’s Guide 5.15.1.2.2 Boxes, Labels and Sections In our analogy, the components for each order are placed in a box. In the same way, the assembly output generated is also placed into boxes, called program sections (or psects, for short). There are several reasons why code is placed in a section. • • • • • The generated assembly code is more manageable. The ordering of the code sequence within the section is preserved. The ordering of sections with the same name are preserved.
C Language Features 5.15.1.2.3 Down the Conveyor Belt and Object files Once the robot has assembled an order and placed the components in a box, the contents of the box are no longer relevant, and the remaining activities in the warehouse only deal with boxes. It is a similar situation in the compiler: Once assembly code has been placed into a section, the instructions are no longer relevant during the link process. The linker only handles sections and is oblivious to each section’s contents.1 5.15.1.2.
MPLAB® XC8 C Compiler User’s Guide TABLE 5-15: SECTION NAMES FOR OUR SIMPLE EXAMPLE Section name Contents Linker class Memory location text Executable code CODE Flash bss0 Variables that need to be cleared BANK0 RAM data0 Variables that need to be initialized BANK0 RAM idata Initialized variable’s values CODE Flash The code generator starts to read the program description in C and produces the assembly code required to implement this on the target device.
C Language Features This process continues until all the program has been generated. The output is passed to the linker (via the assembler) which then looks for the sections it contains. The linker sorts each section as it is encountered. All text sections are collated, as well as the bss0, data0 and idata sections. The order in which they will be assembled will match the order in which they are passed to the linker, which in turn will be the order in which they were produced by the code generator.
MPLAB® XC8 C Compiler User’s Guide The compiler can, and often does, use more than one class to represent the same memory range. This is illustrated in Section 5.15.1.5 “More Advanced Sections at Work” where the example uses CODE and CONST classes for flash memory. Although classes may cover the same range, typically the size of the containers vary. This allows code with different restrictions and requirements to be accommodated.
C Language Features The assembly code associated with ordinary functions is still placed in a “text” section, but as there are now two pages of flash, we have to ensure that both pages can be used. If each function was placed into the same section, they will be merged by the linker and that section would grow until it is too large to fit into either page. To ensure that all the “text” sections do not merge, each function is placed in its own unique numbered section: text0, text1, text2, etc.
MPLAB® XC8 C Compiler User’s Guide Previously all uninitialized variables were placed in the bss0 section. Now the code generator first checks that there will actually be enough room in bank 0 memory before doing so. If not, it chooses the bss1 section that will ultimately be linked into bank 1 memory. The code generator keeps track of any object allocated to RAM so it can maintain the amount of free memory in each RAM bank.
C Language Features The hold of a ship or aircraft might be a very large space, but freight is always packed into shipping containers and it is the size of the shipping container that dictates the maximum size of a object that can be transported. In the same way, the total amount of memory on a target device is irrelevant if sections must first be allocated to a class. Classes may seem restrictive, but without them, code will typically be less efficient or may simply fail to work altogether.
MPLAB® XC8 C Compiler User’s Guide If assembly code is not in a section, the compiler will actually place it into a default section. But since there are no specific instructions as to what to do with this section, it could be linked anywhere. Such sections are like boxes labelled “ship to anywhere you want”. As a rule of thumb, put all assembly code inside a section, but some directives (e.g., GLOBAL or EQU) do not generate code and can be placed anywhere.
C Language Features 5.15.2.1 PROGRAM SPACE PSECTS checksum This is a psect that is used to mark the position of a checksum that has been requested using the --CHECKSUM option, see Section 4.8.17 “--ASMLIST: Generate Assembler List Files”. The checksum value is added after the linker has executed so you will not see the contents of this psect in the assembly list file, nor specific information in the map file.
MPLAB® XC8 C Compiler User’s Guide intentry Contains the entry code for the interrupt service routine which is linked to the interrupt vector. This code saves the necessary registers and jumps to the main interrupt code in the case of mid-range devices; for enhanced mid-range devices this psect will contain the interrupt function body. (PIC18 devices use the intcode psects.) This psect must be linked at the interrupt vector. Do not change the default linker options relating to this psect.
C Language Features stringtext The stringtext psect is used for const objects when compiling for baseline devices. This psect is linked into ROM, since the contents do not need to be modified. This psect must be linked within the first half of each program memory page. textn These psects (where n is a decimal number) contain all other executable code that does not require a special link location.
MPLAB® XC8 C Compiler User’s Guide 5.15.3 Default Linker Classes The linker uses classes to represent memory ranges. For an introductory guide to psects and linker classes, see Section 5.15.1 “Program Sections”. The classes are defined by linker options, see Section 7.2.1 “-Aclass =low-high,...” passed to the linker by the compiler driver. Psects are typically allocated space in the class they are associated with. The association is made using the class flag of the PSECT directive, see Section 6.4.9.3.
C Language Features 5.15.3.2 DATA MEMORY CLASSES RAM consist of ranges that cover all the general purpose RAM memory of the target device, but excluding any common (unbanked) memory. Thus, it is useful for psects that must be placed in general-purpose banked RAM, but can be placed in any bank, BIGRAM consists of a single memory range that is designed to cover the linear data memory of enhanced mid-range devices. It is suitable for any psect whose contents are accessed using linear addressing.
MPLAB® XC8 C Compiler User’s Guide All library source code is written in C, and the p-code library files that contain these library routines are actually passed to the code generator, not the linker, but both these applications work in the way described above in resolving library symbols. You cannot replace a C library function with an equivalent written in assembly code using the above method. If this is required, you will need to use the librarian to edit or create a new library file. 5.15.
C Language Features 5.15.6 Linker-Defined Symbols The linker defines some special symbols that can be used to determine where some psects where linked in memory. These symbols can be used in code, if required. The link address of a psect can be obtained from the value of a global symbol with name __Lname (two leading underscores) where name is the name of the psect. For example, __LbssBANK0 is the low bound of the bssBANK0 psect. The highest address of a psect (i.e.
MPLAB® XC8 C Compiler User’s Guide NOTES: DS52053B-page 240 2012 Microchip Technology Inc.
MPLAB® XC8 C COMPILER USER’S GUIDE Chapter 6. Macro Assembler 6.1 INTRODUCTION Two macro assemblers are included with the MPLAB XC8 C Compiler to assemble source files for all 8-bit PIC devices. The operation and assembler directives are almost identical for both assemblers. The appropriate assembler application is invoked when you use the compiler driver to build projects.
MPLAB® XC8 C Compiler User’s Guide 6.3 OPTIONS The command line options recognized by ASPIC[18] are given in Table 6-1, and a full description of each option followings. TABLE 6-1: ASPIC[18] COMMAND-LINE OPTIONS Option Meaning Default -A Produce assembler output Produce object code -Cchipinfo Define the chipinfo file dat\picc[18].
Macro Assembler 6.3.3 -E: Specify Error Format/File The default format for an error message is in the form: filename: line: message where the error of type message occurred on line line of the file filename. The -E option with no argument will make the assembler use an alternate format for error and warning messages. Specifying a filename as argument will force the assembler to direct error and warning messages to a file with the name specified. 6.3.
MPLAB® XC8 C Compiler User’s Guide 6.3.9 -O: Specify Output File By default the assembler determines the name of the object file to be created by stripping any suffix or extension from the first source filename and appending .obj. The -O option allows the user to override the default filename and specify a new name for the object file. 6.3.10 -T: Specify Listing Page Width This option allows specification of the assembly list file page width, in characters.
Macro Assembler 6.3.16 --EDF: Set Message File Path This option is mainly used by the command-line driver, xc8, to specify the path of the message description file. The default file is located in the dat directory in the compiler’s installation directory. See Section 4.6 “Compiler Messages” for full information about the compiler’s messaging system. 6.3.
MPLAB® XC8 C Compiler User’s Guide 6.4 MPLAB XC8 ASSEMBLY LANGUAGE The source language accepted by the macro assembler, ASPIC[18], is described below. All opcode mnemonics and operand syntax are specific to the target device. Although the PIC17 family instruction set is supported at the assembler level, the code generator cannot produce code for these devices so no C projects can target these devices. Additional mnemonics and assembler directives are documented in this section.
Macro Assembler For example, the following instructions show the W register being moved to first, an absolute location and then to an address represented by an identifier. The op codes for these instructions, assuming that the address assigned to _foo is 0x516 and to _bar is 0x55, are shown.
MPLAB® XC8 C Compiler User’s Guide 6.4.1.4 LONG JUMPS AND CALLS The assembler recognizes several mnemonics which expand into regular PIC MCU assembly instructions. The mnemonics are FCALL and LJMP.
Macro Assembler 6.4.2 Statement Formats Legal statement formats are shown in Table Section Table 6-2: “ASPIC[18] Statement Formats”. The label field is optional and, if present, should contain one identifier. A label may appear on a line of its own, or precede a mnemonic as shown in the second format. The third format is only legal with certain assembler directives, such as MACRO, SET and EQU. The name field is mandatory and should also contain one identifier.
MPLAB® XC8 C Compiler User’s Guide 6.4.4.1 SPECIAL COMMENT STRINGS Several comment strings are appended to compiler-generated assembly instructions by the code generator. These comments are typically used by the assembler optimizer. The comment string ;volatile is used to indicate that the memory location being accessed in the instruction is associated with a variable that was declared as volatile in the C source code.
Macro Assembler 6.4.6 Identifiers Assembly identifiers are user-defined symbols representing memory locations or numbers. A symbol may contain any number of characters drawn from the alphabetics, numerics and the special characters dollar, $, question mark, ? and underscore, _. The first character of an identifier may not be numeric. The case of alphabetics is significant, e.g., Fred is not the same symbol as fred.
MPLAB® XC8 C Compiler User’s Guide Any address offset added to $ has the native addressability of the target device. So for baseline and mid-range devices, the offset is the number of instructions away from the current location, as these devices have word-addressable program memory. For PIC18 instructions, which use byte addressable program memory, the offset to this symbol represents the number of bytes from the current location.
Macro Assembler Labels may be used (and are preferred) in assembly code, rather than using an absolute address with other instructions. Thus they can be used as the target location for jump-type instructions or to load an address into a register. Like variables, labels have scope. By default, they may be used anywhere in the module in which they are defined. They may be used by code located before their definition. To make a label accessible in other modules, use the GLOBAL directive. See Section 6.4.9.
MPLAB® XC8 C Compiler User’s Guide 6.4.8 Program Sections Program sections, or psects, are simply a section of code or data. They are a way of grouping together parts of a program (via the psect’s name) even though the source code may not be physically adjacent in the source file, or even where spread over several modules. For an introductory guide to psects, see Section 5.15.1 “Program Sections”. A psect is identified by a name and has several attributes.
Macro Assembler TABLE 6-5: ASPIC[18] ASSEMBLER DIRECTIVES (CONTINUED) Directive Purpose PAGESEL Generate set/clear instruction to set PCLATH bits for this page PROCESSOR Define the particular chip for which this file is to be assembled. REPT Repeat a block of code n times IRP Repeat a block of code with a list IRPC Repeat a block of code with a character list SIGNAT Define function signature 6.4.9.1 GLOBAL The GLOBAL directive declares a list of comma-separated symbols.
MPLAB® XC8 C Compiler User’s Guide 6.4.9.3 PSECT The PSECT directive declares or resumes a program section. For an introductory guide to psects, see Section 5.15.1 “Program Sections”. The directive takes as argument a name and, optionally, a comma-separated list of flags. The allowed flags are listed in Table 6-6 and specify attributes of the psect. The psect name is in a separate name space to ordinary assembly symbols, so a psect may use the same identifier as an ordinary assembly identifier.
Macro Assembler 6.4.9.3.3 Class The class flag specifies a corresponding linker class name for this psect. A class is a range of addresses in which psects may be placed. Class names are used to allow local psects to be located at link time, since they cannot always be referred to by their own name in a -P linker option (as would be the case if there are more than one local psect with the same name).
MPLAB® XC8 C Compiler User’s Guide 6.4.9.3.9 Ovrld A psect defined as ovrld will have the contribution from each module overlaid, rather than concatenated at link time. This flag in combination with the abs flag (see Section 6.4.9.3.1 “Abs”) defines a truly absolute psect; i.e., a psect within which any symbols defined are absolute. 6.4.9.3.10 Pure The pure flag instructs the linker that this psect will not be modified at runtime and may therefore, for example, be placed in ROM.
Macro Assembler 6.4.9.4 ORG The ORG directive changes the value of the location counter within the current psect. This means that the addresses set with ORG are relative to the base address of the psect, which is not determined until link time. Note: The much-abused ORG directive does not move the location counter to the absolute address you specify. Only if the psect in which this directive is placed is absolute and overlaid will the location counter be moved to the address specified.
MPLAB® XC8 C Compiler User’s Guide 6.4.9.7 DB The DB directive is used to initialize storage as bytes. The argument is a comma-separated list of expressions, each of which will be assembled into one byte and assembled into consecutive memory locations. Examples: alabel: DB ’X’,1,2,3,4, If the size of an address unit in the program memory is 2 bytes, as it will be for baseline and mid-range devices (see Section 6.4.9.3.4 “Delta”), the DB pseudo-op will initialise a word with the upper byte set to zero.
Macro Assembler 6.4.9.11 DABS This directive allows one or more bytes of memory to be reserved at the specified address. The general form of the directive is: DABS memorySpace, address, bytes where memorySpace is a number representing the memory space in which the reservation will take place, address is the address at which the reservation will take place, and bytes is the number of bytes that is to be reserved.
MPLAB® XC8 C Compiler User’s Guide 6.4.9.13 MACRO AND ENDM These directives provide for the definition of assembly macros, optionally with arguments. See Section 6.4.9.5 “EQU” for simple association of a value with an identifier, or Section 5.14.1 “C Language Comments” for the preprocessor’s #define macro directive, which can also work with arguments. The MACRO directive should be preceded by the macro name and optionally followed by a comma-separated list of formal arguments.
Macro Assembler 6.4.9.14 LOCAL The LOCAL directive allows unique labels to be defined for each expansion of a given macro. Any symbols listed after the LOCAL directive will have a unique assembler generated symbol substituted for them when the macro is expanded. For example: down MACRO count LOCAL more more: DECFSZ count GOTO more ENDM when expanded will include a unique assembler generated label in place of more.
MPLAB® XC8 C Compiler User’s Guide 6.4.9.17 IRP AND IRPC The IRP and IRPC directives operate in a similar way to REPT; however, instead of repeating the block a fixed number of times, it is repeated once for each member of an argument list. In the case of IRP, the list is a conventional macro argument list; in the case or IRPC, it is each character in one argument. For each repetition the argument is substituted for one formal parameter.
Macro Assembler 6.4.9.21 SIGNAT This directive is used to associate a 16-bit signature value with a label. At link time the linker checks that all signatures defined for a particular label are the same and produces an error if they are not. The SIGNAT directive is used by MPLAB XC8 to enforce link time checking of C function prototypes and calling conventions. Use the SIGNAT directive if you want to write assembly language routines which are called from C.
MPLAB® XC8 C Compiler User’s Guide 6.4.10.1 ASMOPT_OFF AND ASMOPT_ON These controls allow the assembler optimizer to be selectively disabled for sections of assembly code. No code will be modified after an ASMOPT_OFF control, until a subsequent ASMOPT_ON control is encountered. 6.4.10.2 COND Any conditional code will be included in the listing output. See also the NOCOND control in Section 6.4.10.6 “NOCOND”. 6.4.10.
Macro Assembler 6.4.10.6 NOCOND Using this control will prevent conditional code from being included in the assembly list file output. See also the COND control in Section 6.4.10.2 “COND”. 6.4.10.7 NOEXPAND The NOEXPAND control disables macro expansion in the assembly list file. The macro call will be listed instead. See also the EXPAND control in Section 6.4.10.3 “EXPAND”. Assembly macro are discussed in Section 6.4.9.13 “MACRO and ENDM”. 6.4.10.
MPLAB® XC8 C Compiler User’s Guide 6.5 ASSEMBLY-LEVEL OPTIMIZATIONS The assembler performs optimizations on assembly code in addition to those optimizations performed by the code generator directly on the C code, see Section 5.13 “Optimizations”. The xc8 driver by default instructs the assembler to optimizer assembly code that is generated from C code, but to not perform optimizations on hand-written assembly source modules. The latter code can be optimized if required, see Section 4.8.
Macro Assembler 6.6 ASSEMBLY LIST FILES The assembler will produce an assembly list file if instructed. The xc8 driver option --ASMLIST is typically used to request generation of such a file, see Section 4.8.17 “--ASMLIST: Generate Assembler List Files”. The assembly list file shows the assembly output produced by the compiler for both C and assembly source code.
MPLAB® XC8 C Compiler User’s Guide 6.6.2 Psect Information The assembly list file can be used to determine the name of the psect in which a data object or section of code has been placed by the compiler. For labels (symbols), check the symbol table at the end of the file. It indicates the name of the psect in which it resides, as well as the address associated with the symbol. For other code, find the code in the list file. You can usually search for the C statement associated with the code.
Macro Assembler FIGURE 6-2: FUNCTION INFORMATION 4064 ;; 1 *************** function _render ***************** 4065 ;; Defined at: 4066 ;; line 29 in file "draw.
MPLAB® XC8 C Compiler User’s Guide 6.6.4 Switch Statement Information Along with the generated code for each switch statement is information about how that statement was encoded. There are several strategies the compiler can use for switch statements. The compiler determines the appropriate strategy, see Section 5.6.3 “Switch Statements”, or you can indicate a preference for a particular type of strategy using a pragma, see Section 5.14.4.10 “The #pragma switch Directive”.
Macro Assembler 6.6.6 Call Graph The other important information block in the assembly list file is the call graph (look for Call Graph Tables: in the list file). This is produced for target devices that use a compiled stack to facilitate local variables, such as function parameters and auto variables. See Section 5.5.2.2.1 “Compiled Stack Operation” for more detailed information on compiled stack operation.
MPLAB® XC8 C Compiler User’s Guide All the functions that main() calls, or may call, are shown below. These have been grouped in the orange box in the figure. A function’s inclusion into the call graph does not imply the function was actually called, but there is a possibility that the function was called. For example, code such as: int test(int a) { if(a) foo(); else bar(); } will list foo() and bar() under test(), as either may be called.
Macro Assembler The code generator also produces a warning if the maximum stack depth appears to have been exceeded. For the above reasons, this warning, too, is intended to be a only a guide to potential stack problems. 6.6.6.2 CALL GRAPH CRITICAL PATHS Immediately prior to the call graph tables in the list file are the critical paths for memory usage identified in the call graphs. A critical path is printed for each memory space and for each call graph.
MPLAB® XC8 C Compiler User’s Guide NOTES: DS52053B-page 276 2012 Microchip Technology Inc.
MPLAB® XC8 C COMPILER USER’S GUIDE Chapter 7. Linker 7.1 INTRODUCTION This chapter describes the theory behind, and the usage of, the linker. The application name of the linker is HLINK. In most instances it will not be necessary to invoke the linker directly, as the compiler driver, xc8, will automatically execute the linker with all necessary arguments. Using the linker directly is not simple, and should be attempted only by those with a sound knowledge of the compiler and linking in general.
MPLAB® XC8 C Compiler User’s Guide TABLE 7-1: LINKER COMMAND-LINE OPTIONS (CONTINUED) Option Effect -I Ignore undefined symbols -J num Set maximum number of errors before aborting -K Prevent overlaying function parameter and auto areas -L Preserve relocation items in .obj file -LM Preserve segment relocation items in .
Linker 7.2.1 -Aclass =low-high,... Normally psects are linked according to the information given to a -P option (see Section 7.2.19 “-Pspec”) but sometimes it is desirable to have a class of psects linked into more than one non-contiguous address range. This option allows a number of address ranges to be specified as a class. For example: -ACODE=1020h-7FFEh,8000h-BFFEh specifies that psects in the class CODE are to be linked into the given address ranges, unless they are specifically linked otherwise.
MPLAB® XC8 C Compiler User’s Guide 7.2.7 -F Normally the linker will produce an object file that contains both program code and data bytes, and symbol information. Sometimes it is desired to produce a symbol-only object file that can be used again in a subsequent linker run to supply symbol values. The -F option will suppress data and code bytes from the output file, leaving only the symbol records. This option can be used when part of one project (i.e.
Linker 7.2.11 -I Usually failure to resolve a reference to an undefined symbol is a fatal error. Use of this option will cause undefined symbols to be treated as warnings instead. 7.2.12 -Jerrcount The linker will stop processing object files after a certain number of errors (other than warnings). The default number is 10, but the -J option allows this to be altered. 7.2.
MPLAB® XC8 C Compiler User’s Guide If present, the minimum value, min, is preceded by a + sign. It sets a minimum value for the link or load address. The address will be calculated as described below, but if it is less than the minimum then it will be set equal to the minimum. The link and load addresses are either numbers, or the names of other psects, classes, or special tokens.
Linker The final link and load address of psects are shown in the map file. See Section 7.4.2.2 “Psect Information Listed by Module”. 7.2.20 -Qprocessor This option allows a device type to be specified. This is purely for information placed in the map file. The argument to this option is a string describing the device. There are no behavioral changes attributable to the device type. 7.2.
MPLAB® XC8 C Compiler User’s Guide 7.2.28 --DISL=message numbers Disable Messages This option is mainly used by the command-line driver, xc8, to disable particular message numbers. It takes a comma-separate list of message numbers that will be disabled during compilation. This option is applied if compiling using xc8, the command-line driver and the --MSGDISABLE driver option, see Section 4.8.38 “--MSGDISABLE: Disable Warning Messages”. See Section 4.
Linker 7.3 RELOCATION AND PSECTS This section looks at the input files that the linker has to work with. The linker can read both relocatable object files and object-file libraries (.lib extension). The library files are a collection of object files packaged into a single unit, so essentially we only need consider the format of object files. Each object file consists of a number of records. Each record has a type that indicates what sort of information it holds.
MPLAB® XC8 C Compiler User’s Guide 7.4 MAP FILES The map file contains information relating to the relocation of psects and the addresses assigned to symbols within those psects. 7.4.1 Generation If compilation is being performed via an IDE such as HI-TIDE or MPLAB IDE, a map file is generated by default without you having to adjust the compiler options. If you are using the driver from the command line then you’ll need to use the -M option to request that the map file be produced, see Section 7.2.
Linker A typical map file may begin something like the following. This example has been cut down for clarity. --edf=/home/jeff/Microchip/XC8/1.00/dat/en_msgs.txt -cs -h+main.sym -z \ -Q16F946 -ol.obj -Mmain.
MPLAB® XC8 C Compiler User’s Guide The load address, which is often the same as the link address, is the address at which the psect will start within the output file (HEX or binary file etc.). If a psect is used to hold bits, the load address is irrelevant and is instead used to hold the link address (in bit units) converted into a byte address. The Length of the psect is shown in the units used by that psect. The Selector is less commonly used and is of no concern when compiling for PIC devices.
Linker 7.4.2.4 SEGMENT LISTING The class listing in the map file is followed by a listing of segments. A segment is conceptual grouping of contiguous psects in the same memory space, and are used by the linker as an aid in psect placement. There is no segment assembler directive and segments cannot be controlled in any way.
MPLAB® XC8 C Compiler User’s Guide If the psect of a symbol is shown as (abs), this implies that the symbol is not directly associated with a psect. Such is the case for absolute C variables, or any symbols that are defined using an EQU directive in assembly. Note that a symbol table is also shown in each assembler list file. (See Section 4.8.16 “--ADDRQUAL: Set Compiler Response to Memory Qualifiers” for information on generating these files.
MPLAB® XC8 C COMPILER USER’S GUIDE Chapter 8. Utilities 8.1 INTRODUCTION This chapters discusses some of the utility applications that are bundled with the compiler. Some of these applications may not be normally invoked when building, but can be manually executed to perform certain tasks. The following applications are described in this chapter of the MPLAB XC8 C Compiler User’s Guide: • • • • • 8.
MPLAB® XC8 C Compiler User’s Guide 8.2.2 Using the Librarian Library files can be built directly using the command-line driver, see Section 4.8.44 “--OUTPUT= type: Specify Output File Type”. In this case the driver will invoke LIBR with the appropriate options saving you from having to use the librarian directly. You may wish to perform this step manually, or you may need to look at the contents of library files, for example. This section shows how the librarian can be executed from the command-line.
Utilities The o key takes a list of module names and re-orders the matching modules in the library file so that they have the same order as the one listed on the command line. Modules that are not listed are left in their existing order, and will appear after the re-ordered modules. 8.2.2.1 EXAMPLES Here are some examples of usage of the librarian. The following command: LIBR s pic-stdlib-d24.lpp ctime.p1 lists the global symbols in the modules ctime.p1, as shown here: ctime.
MPLAB® XC8 C Compiler User’s Guide 8.2.5 Error Messages LIBR issues various error messages, most of which represent a fatal error, while some represent a harmless occurrence which will nonetheless be reported unless the -W option was used. In this case all warning messages will be suppressed. DS52053B-page 294 2012 Microchip Technology Inc.
Utilities 8.3 OBJTOHEX The linker is capable of producing object files as output. Any other format required must be produced by running the utility program OBJTOHEX. This allows conversion of object files as produced by the linker into a variety of different formats, including various HEX formats. The program is invoked thus: OBJTOHEX [options] inputfile outputfile All of the arguments are optional. The options for OBJTOHEX are listed in Table 8-3.
MPLAB® XC8 C Compiler User’s Guide 8.3.1 Checksum Specifications If you are generating a HEX file output, use HEXMATE’s checksum tools, described in Section 8.6 “HEXMATE”. For other file formats, the OBJTOHEX checksum specification allows automated checksum calculation and takes the form of several lines, each line describing one checksum. The syntax of a checksum line is: addr1-addr2 where1-where2 +offset All of addr1, addr2, where1, where2 and offset are HEX numbers, without the usual H suffix.
Utilities 8.4 CREF The cross reference list utility, CREF, is used to format raw cross-reference information produced by the compiler or the assembler into a sorted listing. A raw cross-reference file is produced with the --CR command-line driver option. The assembler will generate a raw cross-reference file with a -C assembler option or a XREF control line.
MPLAB® XC8 C Compiler User’s Guide 8.4.4 -Ooutfile Allows specification of the output file name. By default the listing will be written to the standard output and may be redirected in the usual manner. Alternatively outfile may be specified as the output file name. 8.4.5 -Pwidth This option allows the specification of the width to which the listing is to be formatted, e.g., -P132 will format the listing for a 132 column printer. The default is 80 columns. 8.4.
Utilities 8.4.11 --VER: Print Version Number This option prints information relating to the version and build of CREF. CREF will terminate after processing this option, even if other options and files are present on the command line. 2012 Microchip Technology Inc.
MPLAB® XC8 C Compiler User’s Guide 8.5 CROMWELL The CROMWELL utility converts code and symbol files into different formats. These files are typically used by debuggers and allow source-level debugging of code. The output formats available are shown in Table 8-5.
Utilities 8.5.1 -Pname[,architecture] The -P options takes a string which is the name of the device used. CROMWELL may use this in the generation of the output format selected. Note that to produce output in COFF format an additional argument to this option which also specifies the device architecture is required. Hence for this format the usage of this option must take the form: -Pname,architecture. Table 8-7 enumerates the architectures supported for producing COFF files.
MPLAB® XC8 C Compiler User’s Guide 8.5.8 -L Use this option to show what file format types are supported. A list similar to that given in Table 8-5 will be shown. 8.5.9 -E Use this option to tell CROMWELL to ignore any filename extensions that were given. The default extension will be used instead. 8.5.10 -B In formats that support different endian types, use this option to specify big-endian byte ordering. 8.5.
Utilities 8.6 HEXMATE The HEXMATE utility is a program designed to manipulate Intel HEX files. HEXMATE is a post-link stage utility which is automatically invoked by the compiler driver, and that provides the facility to: • • • • • • • • • Calculate and store variable-length checksum values Fill unused memory locations with known data sequences Merge multiple Intel HEX files into one output file Convert INHX32 files to other INHX formats (e.g.
MPLAB® XC8 C Compiler User’s Guide 8.6.1 HEXMATE Command Line Options HEXMATE is automatically called by the command line driver, xc8. This is primarily to merge in HEX files with the output generated by the source files; however, there are some xc8 options which directly map to HEXMATE options, and so other functionality can be requested without having to run HEXMATE explicitly on the command line. For other functionality, the following details the options available when running this application.
Utilities 8.6.1.1 SPECIFICATIONS,FILENAME.HEX Intel HEX files that can be processed by HEXMATE should be in either INHX32 or INHX8M format. Additional specifications can be applied to each HEX file to put restrictions or conditions on how this file should be processed. If any specifications are used they must precede the filename. The list of specifications will then be separated from the filename by a comma. A range restriction can be applied with the specification rStart-End.
MPLAB® XC8 C Compiler User’s Guide 8.6.1.5 -CK The -CK option is for calculating a checksum. The usage of this option is: -CK=start-end@destination [+offset][wWidth][tCode][gAlogithm] where: • start and end specify the address range over which the checksum will be calculated. • destination is the address where the checksum result will be stored. This value cannot be within the range of calculation. • offset is an optional initial value to add to the checksum result.
Utilities 8.6.1.6 -FILL The -FILL option is used for filling unused memory locations with a known value. The usage of this option is: -FILL=[const_width:]fill_expr[@address[:end_address]] where: • const_width has the form wn and signifies the width (n bytes) of each constant in fill_expr. If const_width is not specified, the default value is the native width of the architecture. That is, -FILL=w1:1 with fill every byte with the value 0x01.
MPLAB® XC8 C Compiler User’s Guide Here are some examples. The option -FIND=3412@0-7FFF/2w will detect the code sequence 1234h when aligned on a 2 (two) byte address boundary, between 0h and 7FFFh. w indicates that a warning will be issued each time this sequence is found. In this next example, -FIND=3412M0F00@0-7FFF/2wt”ADDXY”, the option is the same as in last example but the code sequence being matched is masked with 000Fh, so HEXMATE will search for any of the opcodes 123xh, where x is any digit.
Utilities 8.6.1.10 -FORMAT The -FORMAT option can be used to specify a particular variant of INHX format or adjust maximum record length. The usage of this option is: -FORMAT=Type [,Length] where: • Type specifies a particular INHX format to generate. • Length is optional and sets the maximum number of bytes per data record. A valid length is between 1 and 16, with 16 being the default.
MPLAB® XC8 C Compiler User’s Guide 8.6.1.13 -MASK Use this option to logically AND a memory range with a particular bitmask. This is used to ensure that the unimplemented bits in program words (if any) are left blank. The usage of this option is as follows: -MASK=hexcode@start-end Where hexcode is a hexadecimal value that will be ANDed with data within the start to end address range. Multibyte mask values can be entered in little endian byte order. 8.6.1.
Utilities 8.6.1.17 -STRING The -STRING option will embed an ASCII string at a fixed address. The usage of this option is: -STRING@Address [tCode]=”Text” where: • Address is the location to store this string. • Code is optional and allows a byte sequence to trail each byte in the string. This can allow the bytes of the string to be encoded within an instruction. • Text is the string to convert to ASCII and embed.
MPLAB® XC8 C Compiler User’s Guide NOTES: DS52053B-page 312 2012 Microchip Technology Inc.
MPLAB® XC8 C COMPILER USER’S GUIDE Appendix A. Library Functions The functions and preprocessor macros within the standard compiler library are alphabetically listed in this chapter. The synopsis indicates the header file in which a declaration or definition for function or macro is found. It also shows the function prototype for functions, or the equivalent prototype for macros. __CONFIG (BASELINE & MID-RANGE DEVICES) Synopsis #include
MPLAB® XC8 C Compiler User’s Guide __CONFIG (PIC18) Synopsis #include __CONFIG(num, data) Description This macro is provided for legacy support only. Use the #pragma config for new projects. This macro is used to program the configuration fuses that set the device’s operating modes. The macro accepts the number corresponding to the configuration register it is to program, then the 16-Bit value it is to update it with.
Library Functions __EEPROM_DATA Synopsis #include __EEPROM_DATA(a,b,c,d,e,f,g,h) Description This macro is used to store initial values into the device’s EEPROM registers at the time of programming. The macro must be given blocks of 8 bytes to write each time it is called, and can be called repeatedly to store multiple blocks. __EEPROM_DATA() will begin writing to EEPROM address zero, and will auto-increment the address written to by 8, each time it is used. Example #include
MPLAB® XC8 C Compiler User’s Guide See also __IDLOC7(), __CONFIG() __IDLOC7 Synopsis #include __IDLOC7(a,b,c,d) Description This macro is provided for legacy support only. Use the #pragma config for new projects. This macro places data into the device’s special locations outside of addressable memory reserved for ID. This would be useful for storage of serial numbers etc. The macro will attempt to write 7 bits of data to each of the 4 locations reserved for ID purposes. Example #include
Library Functions Example #include void main (void) { control |= 0x80; _delay(10); // delay for 10 cycles control &= 0x7F; } See Also _delay3(), __delay_us(), __delay_ms() _DELAY3() Synopsis #include void _delay3(unsigned char cycles); Description This is an inline function that is expanded by the code generator. When called, this routine expands to an inline assembly delay sequence.The sequence will consist of code that delays for 3 times the number of cycles that is specified as argument.
MPLAB® XC8 C Compiler User’s Guide Example #include #include void main (void) { int a = -5; printf(“The absolute value of %d is %d\n”, a, abs(a)); } See Also labs(), fabs() Return Value The absolute value of j. ACOS Synopsis #include double acos (double f) Description The acos() function implements the inverse of cos(); i.e., it is passed a value in the range -1 to +1, and returns an angle in radians whose cosine is equal to that value. Example #include
Library Functions ASCTIME Synopsis #include char * asctime (struct tm * t) Description The asctime() function takes the time broken down into the struct tm structure, pointed to by its argument, and returns a 26 character string describing the current date and time in the format: Sun Sep 16 01:03:52 1973\n\0 Note the newline at the end of the string. The width of each field in the string is fixed.
MPLAB® XC8 C Compiler User’s Guide Example #include #include void main (void) { float i, a; for(i = -1.0; i < 1.0 ; i += 0.1) { a = asin(i)*180.0/3.141592; printf(“asin(%f) = %f degrees\n”, i, a); } } See Also sin(), cos(), tan(), acos(), atan(), atan2() Return Value An angle in radians, in the range - ASSERT Synopsis #include
Library Functions ATAN Synopsis #include double atan (double x) Description This function returns the arc tangent of its argument; i.e., it returns an angle ‘e’ in the range - . Example #include #include void main (void) { printf(“atan(%f) is %f\n”, 1.5, atan(1.5)); } See Also sin(), cos(), tan(), asin(), acos(), atan2() Return Value The arc tangent of its argument. ATAN2 Synopsis #include
MPLAB® XC8 C Compiler User’s Guide ATOF Synopsis #include double atof (const char * s) Description The atof() function scans the character string passed to it, skipping leading blanks. It then converts an ASCII representation of a number to a double. The number may be in decimal, normal floating point or scientific notation. Example #include #include
Library Functions Example #include #include void main (void) { char buf[80]; int i; gets(buf); i = atoi(buf); printf(“Read %s: converted to %d\n”, buf, i); } See Also xtoi(), atof(), atol() Return Value A signed integer. If no number is found in the string, 0 will be returned. ATOL Synopsis #include long atol (const char * s) Description The atol() function scans the character string passed to it, skipping leading blanks.
MPLAB® XC8 C Compiler User’s Guide BSEARCH Synopsis #include void * bsearch (const void * key, void * base, size_t n_memb, size_t size, int (*compar)(const void *, const void *)) Description The bsearch() function searches a sorted array for an element matching a particular key. It uses a binary search algorithm, calling the function pointed to by compar to compare elements in the array. Example #include #include #include
Library Functions CEIL Synopsis #include double ceil (double f) Description This routine returns the smallest whole number not less than f. Example #include #include void main (void) { double j; scanf(“%lf” &j); printf(“The ceiling of %lf is %lf\n”, j, ceil(j)); } CGETS Synopsis #include char * cgets (char * s) Description The cgets() function will read one line of input from the console into the buffer passed as an argument.
MPLAB® XC8 C Compiler User’s Guide See Also getch(), getche(), putch(), cputs() Return Value The return value is the character passed as the sole argument. CLRWDT Synopsis #include CLRWDT(); Description This macro is used to clear the device’s internal watchdog timer. Example #include void main (void) { WDTCON=1; /* enable the WDT */ CLRWDT(); } COS Synopsis #include double cos (double f) Description This function yields the cosine of its argument, which is an angle in radians.
Library Functions Return Value A double in the range -1 to +1. COSH, SINH, TANH Synopsis #include double cosh (double f) double sinh (double f) double tanh (double f) Description These functions are the implement hyperbolic equivalents of the trigonometric functions; cos(), sin() and tan(). Example #include #include void main (void) { printf(“%f\n”, cosh(1.5)); printf(“%f\n”, sinh(1.5)); printf(“%f\n”, tanh(1.
MPLAB® XC8 C Compiler User’s Guide Example #include #include char buffer[80]; void main (void) { for(;;) { cgets(buffer); if(strcmp(buffer, “exit” == 0) break; cputs(“Type ’exit’ to finish\n”; } } See Also cputs(), puts(), putch() CTIME Synopsis #include char * ctime (time_t * t) Description The ctime() function converts the time in seconds pointed to by its argument to a string of the same form as described for asctime().
Library Functions DEVICE_ID_READ() Synopsis #include unsigned int device_id_read(void); Description This function returns the device ID code that is factory-programmed into the chip. This code can be used to identify the device and its revision number. Example #include
MPLAB® XC8 C Compiler User’s Guide Example #include long count; void interrupt tick (void) { count++; } long getticks (void) { long val; /* Disable interrupts around access to count, to ensure consistency.*/ di(); val = count; ei(); return val; } DIV Synopsis #include div_t div (int numer, int denom) Description The div() function computes the quotient and remainder of the numerator divided by the denominator. Example #include #include
Library Functions EVAL_POLY Synopsis #include double eval_poly (double x, const double * d, int n) Description The eval_poly() function evaluates a polynomial, whose coefficients are contained in the array d, at x, for example: y = x*x*d2 + x*d1 + d0. The order of the polynomial is passed in n. Example #include #include void main (void) { double x, y; double d[3] = {1.1, 3.5, 2.7}; x = 2.
MPLAB® XC8 C Compiler User’s Guide FABS Synopsis #include double fabs (double f) Description This routine returns the absolute value of its double argument. Example #include #include void main (void) { printf("%f %f\n", fabs(1.5), fabs(-1.5)); } See Also abs(), labs() FLASH ROUTINES Description These functions are now supplied in the peripheral library. See the peripheral library documentation for full information on this library function. FLOOR Synopsis #include
Library Functions FMOD Synopsis #include double fmod (double x, double y) Description The function fmod returns the remainder of x/y as a floating-point quantity. Example #include void main (void) { double rem, x; x = 12.34; rem = fmod(x, 2.1); } Return Value The floating-point remainder of x/y. FREXP Synopsis #include double frexp (double f, int * p) Description The frexp() function breaks a floating-point number into a normalized fraction and an integral power of 2.
MPLAB® XC8 C Compiler User’s Guide FTOA Synopsis #include char * ftoa (float f, int * status) Description The function ftoa converts the contents of f into a string which is stored into a buffer which is then return. Example #include #include void main (void) { char * buf; float input = 12.
Library Functions GETCHE Synopsis #include char getche (void) Description The getche() function is provided as an empty stub which can be completed as each project requires. Typically this function will read one byte of data from a peripheral that is associated with stdin, and return this value. Unlike getch(), it echoes this character received. Example #include char result; void main (void) { result = getche(); } See Also getch(), getchar() GETCHAR Synopsis #include
MPLAB® XC8 C Compiler User’s Guide GETS Synopsis #include char * gets (char * s) Description The gets() function reads a line from standard input into the buffer at s, deleting the newline (compare: fgets()). The buffer is null terminated. In an embedded system, gets() is equivalent to cgets(), and results in getche() being called repeatedly to get characters. Editing (with backspace) is available. Example #include
Library Functions Example #include void main (void) { double x; unsigned char y; /* Get the slope reference ratio. */ x = get_cal_data(KREF); /* Get the WDT time-out. */ y = TWDT; } Return Value The value of the calibration parameter Note This function can only be used on the PIC14000. GMTIME Synopsis #include
MPLAB® XC8 C Compiler User’s Guide Note The example will require the user to provide the time() routine as one cannot be supplied with the compiler. See time() for more detail. ISALNUM, ISALPHA, ISDIGIT, ISLOWER, ET. AL. Synopsis #include
Library Functions See Also toupper(), tolower(), toascii() ISDIG Synopsis #include int isdig (int c) Description The isdig() function tests the input character c to see if is a decimal digit (0 – 9) and returns true is this is the case; false otherwise. Example #include void main (void) { char buf[] = "1998a"; if(isdig(buf[0])) printf(" type detected\n"); } See Also isdigit() (listed under isalnum()) Return Value Zero if the character is a decimal digit; a non-zero value otherwise.
MPLAB® XC8 C Compiler User’s Guide Return Value This routine returns a copy of the buffer into which the result is written. LABS Synopsis #include int labs (long int j) Description The labs() function returns the absolute value of long value j. Example #include #include void main (void) { long int a = -5; printf("The absolute value of %ld is %ld\n", a, labs(a)); } See Also abs() Return Value The absolute value of j. LDEXP Synopsis #include
Library Functions Return Value The return value is the integer i added to the exponent of the floating-point value f. LDIV Synopsis #include ldiv_t ldiv (long number, long denom) Description The ldiv() routine divides the numerator by the denominator, computing the quotient and the remainder. The sign of the quotient is the same as that of the mathematical quotient. Its absolute value is the largest integer which is less than the absolute value of the mathematical quotient.
MPLAB® XC8 C Compiler User’s Guide Example #include #include char * wday[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; void main (void) { time_t clock; struct tm * tp; time(&clock); tp = localtime(&clock); printf("Today is %s\n", wday[tp->tm_wday]); } See Also ctime(), asctime(), time() Return Value Returns a structure of type tm. Note The example will require the user to provide the time() routine as one cannot be supplied with the compiler.
Library Functions Return Value Zero if the argument is negative. LONGJMP Synopsis #include void longjmp (jmp_buf buf, int val) Description The longjmp() function, in conjunction with setjmp(), provides a mechanism for non-local goto’s. To use this facility, setjmp() should be called with a jmp_buf argument in some outer level function. The call from setjmp() will return 0.
MPLAB® XC8 C Compiler User’s Guide Note The function which called setjmp() must still be active when longjmp() is called. Breach of this rule will cause disaster, due to the use of a stack containing invalid data. LTOA Synopsis #include char * ltoa (char * buf, long val, int base) Description The function ltoa converts the contents of val into a string which is stored into buf. The conversion is performed according to the radix specified in base.
Library Functions Example #include #include unsigned int ary[] = {1, 5, 0x6789, 0x23}; void main (void) { char * cp; cp = memchr(ary, 0x89, sizeof ary); if(!cp) printf("Not found\n"); else printf("Found at offset %u\n", cp - (char *)ary); } See Also strchr() Return Value A pointer to the first byte matching the argument if one exists; NULL otherwise. MEMCMP Synopsis #include
MPLAB® XC8 C Compiler User’s Guide See Also strncpy(), strncmp(), strchr(), memset(), memchr() Return Value Returns negative one, zero or one, depending on whether s1 points to string which is less than, equal to or greater than the string pointed to by s2 in the collating sequence. MEMCPY Synopsis #include
Library Functions Return Value The function memmove() returns its first argument. MEMSET Synopsis #include void * memset (void * s, int c, size_t n) Description The memset() function fills n bytes of memory starting at the location pointed to by s with the byte c. Example #include #include
MPLAB® XC8 C Compiler User’s Guide Example #include #include void main (void) { struct tm birthday; birthday.tm_year = 83; // the 5th of May 1983 birthday.tm_mon = 5; birthday.tm_mday = 5; birthday.tm_hour = birthday.tm_min = birthday.
Library Functions NOP Synopsis #include NOP(); Description Execute NOP instruction here. This is often useful to fine tune delays or create a handle for breakpoints. The NOP instruction is sometimes required during some sensitive sequences in hardware. Example #include void crude_delay(unsigned char x) { while(x--){ NOP(); /* Do nothing for 3 cycles */ NOP(); NOP(); } } 2012 Microchip Technology Inc.
MPLAB® XC8 C Compiler User’s Guide POW Synopsis #include double pow (double f, double p) Description The pow() function raises its first argument, f, to the power p. Example #include #include void main (void) { double f; for(f = 1.0 ; f <= 10.0 ; f += 1.0) printf("pow(2, %1.0f) = %f\n", f, pow(2, f)); } See Also log(), log10(), exp() Return Value f to the power of p. PRINTF, VPRINTF Synopsis #include int printf (const char * fmt, ...) #include
Library Functions The printf() routine is passed a format string, followed by a list of zero or more arguments. In the format string are conversion specifications, each of which is used to print out one of the argument list values. Each conversion specification is of the form %m.nc where the percent symbol % introduces a conversion, followed by an optional width specification m.
MPLAB® XC8 C Compiler User’s Guide Example printf("Total = %4d%", 23); yields ’Total = 23%’ printf("Size is %lx", size); where size is a long, prints size as hexadecimal. printf("Name = %.8s", "a1234567890"); yields ’Name = a1234567’ printf("xx%*d", 3, 4); yields ’xx 4’ /* vprintf example */ #include int error (char * s, ...
Library Functions Example #include char * x = "This is a string"; void main (void) { char * cp; cp = x; while(*x) putch(*x++); putch(’\n’); } See Also printf(), putchar() PUTCHAR Synopsis #include int putchar (int c) Description The putchar() function calls putch() to print one character to stdout, and is defined in stdio.h. Example #include
MPLAB® XC8 C Compiler User’s Guide PUTS Synopsis #include int puts (const char * s) Description The puts() function writes the string s to the stdout stream, appending a newline. The null character terminating the string is not copied. Example #include void main (void) { puts("Hello, world!"); } See Also fputs(), gets(), freopen(), fclose() Return Value EOF is returned on error; zero otherwise. QSORT Synopsis #include
Library Functions Example #include #include
MPLAB® XC8 C Compiler User’s Guide Example #include #include #include void main (void) { time_t toc; int i; time(&toc); srand((int)toc); for(i = 0 ; i != 10 ; i++) printf("%d\t", rand()); putchar(’\n’); } See Also srand() Note The example will require the user to provide the time() routine as one cannot be supplied with the compiler. See time() for more detail. ROUND Synopsis #include
Library Functions SETJMP Synopsis #include int setjmp (jmp_buf buf) Description The setjmp() function is used with longjmp() for non-local goto’s. See longjmp() for further information. Example #include #include #include jmp_buf jb; void inner (void) { longjmp(jb, 5); } void main (void) { int i; if(i = setjmp(jb)) { printf("setjmp returned %d\n", i); exit(0); } printf("setjmp returned 0 - good\n"); printf("calling inner...
MPLAB® XC8 C Compiler User’s Guide Example #include #include #define C 3.141592/180.0 void main (void) { double i; for(i = 0 ; i <= 180.0 ; i += 10) printf("sin(%3.0f) = %f\n", i, sin(i*C)); printf("cos(%3.0f) = %f\n", i, cos(i*C)); } See Also cos(), tan(), asin(), acos(), atan(), atan2() Return Value Sine vale of f. SLEEP Synopsis #include SLEEP(); Description This macro is used to put the device into a low-power standby mode. Example #include
Library Functions Description The sprintf() function operates in a similar fashion to printf(), except that instead of placing the converted output on the stdout stream, the characters are placed in the buffer at buf. The resultant string will be null terminated, and the number of characters in the buffer will be returned. The vsprintf() function is similar to sprintf() but takes a variable argument list parameter rather than a list of arguments.
MPLAB® XC8 C Compiler User’s Guide SRAND Synopsis #include void srand (unsigned int seed) Description The srand() function initializes the random number generator accessed by rand() with the given seed. This provides a mechanism for varying the starting point of the pseudo-random sequence yielded by rand(). Example #include #include #include
Library Functions STRCAT Synopsis #include char * strcat (char * s1, const char * s2) Description This function appends (concatenates) string s2 to the end of string s1. The result will be null terminated. The argument s1 must point to a character array big enough to hold the resultant string. Example #include #include void main (void) { char buffer[256]; char * s1, * s2; strcpy(buffer, "Start of line"); s1 = buffer; s2 = "...
MPLAB® XC8 C Compiler User’s Guide Example #include #include void main (void) { static char temp[] = "Here it is..."; char c = ’s’; if(strchr(temp, c)) printf("Character %c was found in string\n", c); else printf("No character was found in string"); } See Also strrchr(), strlen(), strcmp() Return Value A pointer to the first match found, or NULL if the character does not exist in the string.
Library Functions See Also strlen(), strncmp(), strcpy(), strcat() Return Value A signed integer less than, equal to or greater than zero. Note Other C implementations may use a different collating sequence; the return value is negative, zero, or positive; i.e., do not test explicitly for negative one (-1) or one (1). STRCPY Synopsis #include char * strcpy (char * s1, const char * s2) Description This function copies a null terminated string s2 to a character array pointed to by s1.
MPLAB® XC8 C Compiler User’s Guide Example #include #include void main (void) { static char set[] = "xyz"; printf("%d\n", strcspn("abcdevwxyz", set)); printf("%d\n", strcspn("xxxbcadefs", set)); printf("%d\n", strcspn("1234567890", set)); } See Also strspn() Return Value Returns the length of the segment. STRLEN Synopsis #include
Library Functions STRNCAT Synopsis #include char * strncat (char * s1, const char * s2, size_t n) Description This function appends (concatenates) string s2 to the end of string s1. At most n characters will be copied, and the result will be null terminated. s1 must point to a character array big enough to hold the resultant string. Example #include #include void main (void) { char buffer[256]; char * s1, * s2; strcpy(buffer, "Start of line"); s1 = buffer; s2 = "...
MPLAB® XC8 C Compiler User’s Guide Example #include #include void main (void) { int i; i = strncmp("abcxyz", "abcxyz", 6); if(i == 0) printf("The strings are equal\n"); else if(i > 0) printf("String 2 less than string 1\n"); else printf("String 2 is greater than string 1\n"); } See Also strlen(), strcmp(), strcpy(), strcat() Return Value A signed integer less than, equal to or greater than zero.
Library Functions See Also strcpy(), strcat(), strlen(), strcmp() Return Value The destination buffer s1 is returned. STRPBRK Synopsis #include char * strpbrk (const char * s1, const char * s2) Description The strpbrk() function returns a pointer to the first occurrence in string s1 of any character from string s2, or a null if no character from s2 exists in s1. Example #include #include void main (void) { char * str = "This is a string.
MPLAB® XC8 C Compiler User’s Guide Example #include #include void main (void) { char * str = "This is a string."; while(str != NULL) { printf("%s\n", str); str = strrchr(str+1, ’s’); } } See Also strchr(), strlen(), strcmp(), strcpy(), strcat() Return Value A pointer to the character, or NULL if none is found. STRSPN Synopsis #include
Library Functions Description The strstr() function locates the first occurrence of the sequence of characters in the string pointed to by s2 in the string pointed to by s1. The stristr() routine is the case-insensitive version of this function. Example #include #include void main (void) { printf("%d\n", strstr("This is a string", "str")); } Return Value to the located string or a null if the string was not found. STRTOD Synopsis #include
MPLAB® XC8 C Compiler User’s Guide STRTOL Synopsis #include double strtol (const char * s, const char ** res, int base) Description Parse the string s converting it to a long integer type. This function converts the first occurrence of a substring of the input that is made up of characters of the expected form after skipping leading white-space characters. The radix of the input is determined from base. If this is zero, then the radix defaults to base 10.
Library Functions Example #include #include void main (void) { char * ptr; char buf[] = "This is a string of words."; char * sep_tok = ",?! " ptr = strtok(buf, sep_tok); while(ptr != NULL) { printf("%s\n", ptr); ptr = strtok(NULL, sep_tok); } } Return Value Returns a pointer to the first character of a token, or a null if no token was found. Note The separator string s2 may be different from call to call. TAN Synopsis #include
MPLAB® XC8 C Compiler User’s Guide TIME Synopsis #include time_t time (time_t * t) Description This function is not provided as it is dependent on the target system supplying the current time. This function will be user implemented. When implemented, this function should return the current time in seconds since 00:00:00 on Jan 1, 1970. If the argument t is not equal to NULL, the same value is stored into the object pointed to by t. Example #include #include
Library Functions Example #include #include #include void main (void) { char * array1 = "aBcDE"; int i; for(i=0;i < strlen(array1); ++i) { printf("%c", tolower(array1[i])); } printf("n"); } See Also islower(), isupper(), isascii(), et. al. TRUNC Synopsis #include double trunc (double x) Description The trunc function rounds the argument to the nearest integer value, in floating-point format, that is not larger in magnitude than the argument.
MPLAB® XC8 C Compiler User’s Guide Example #include void main (void) { udiv_t result; unsigned num = 1234, den = 7; result = udiv(num, den); } See Also uldiv(), div(), ldiv() Return Value Returns the quotient and remainder as a udiv_t structure. ULDIV Synopsis #include
Library Functions Description The function utoa() converts the unsigned contents of val into a string which is stored into buf. The conversion is performed according to the radix specified in base. buf is assumed to reference a buffer which has sufficient space allocated to it. Example #include #include
MPLAB® XC8 C Compiler User’s Guide Example #include #include void pf (int a, ...) { va_list ap; va_start(ap, a); while(a--) puts(va_arg(ap, char *)); va_end(ap); } void main (void) { pf(3, "Line 1", "Line 2", "Line 3"); } XTOI Synopsis #include unsigned xtoi (const char * s) Description The xtoi() function scans the character string passed to it, skipping leading blanks reading an optional sign, and converts an ASCII representation of a hexadecimal number to an integer.
MPLAB® XC8 C COMPILER USER’S GUIDE Appendix B. Error and Warning Messages This chapter lists the MPLAB XC8 C Compiler error, warning and advisory messages with an explanation of each message. This is the complete and historical message set covering all former HI-TECH C compilers and all compiler versions. Not all messages shown here may be relevant for the compiler version you are using.
MPLAB® XC8 C Compiler User’s Guide (101) #* may not follow #else (Preprocessor) A #else or #elif has been used in the same conditional block as a #else. These can only follow a #if, for example: #ifdef FOO result = foo; #else result = bar; #elif defined(NEXT) result = next(0); #endif /* the #else above terminated the #if */ (102) #* must be in an #if (Preprocessor) The #elif, #else or #endif directive must be preceded by a matching #if line.
Error and Warning Messages (107) illegal # directive "*" (Preprocessor, Parser) The compiler does not understand the # directive. It is probably a misspelling of a pre-device # directive, for example: #indef DEBUG /* oops -- that should be #undef DEBUG */ (108) #if[n][def] without an argument (Preprocessor) The preprocessor directives #if, #ifdef and #ifndef must have an argument.
MPLAB® XC8 C Compiler User’s Guide (116) end of file within preprocessor macro argument from line * (Preprocessor) A macro argument has not been terminated. This probably means the closing parenthesis has been omitted from a macro invocation.
Error and Warning Messages (125) illegal character (* decimal) in #if (Preprocessor) There is a non-printable character in a #if expression that has no business being there.
MPLAB® XC8 C Compiler User’s Guide (132) no type specified in #[el]if sizeof() (Preprocessor) Sizeof() was used in a preprocessor #if expression, but no type was specified. The argument to sizeof() in a preprocessor expression must be a valid simple type, or pointer to a simple type, for example: #if sizeof() i = 0; #endif /* oops -- size of what? */ (133) unknown type code (0x*) in #[el]if sizeof() (Preprocessor) The preprocessor has made an internal error in evaluating a sizeof() expression.
Error and Warning Messages (141) can’t open * file "*": * (Any) An output file could not be created. Confirm the spelling and path of the file specified on the command line. (144) too many nested #if blocks (Preprocessor) #if , #ifdef etc. blocks may only be nested to a maximum of 32. (146) #include filename too long (Preprocessor) A filename constructed while looking for an include file has exceeded the length of an internal buffer. Since this buffer is 4096 bytes long, this is unlikely to happen.
MPLAB® XC8 C Compiler User’s Guide (161) control line "*" within preprocessor macro expansion (Preprocessor) A preprocessor control line (one starting with a #) has been encountered while expanding a macro. This should not happen. (162) #warning: * (Preprocessor, Driver) This warning is either the result of user-defined #warning preprocessor directive or the driver encountered a problem reading the map file.
Error and Warning Messages (171) wrong number of preprocessor macro arguments for "*" (* instead of *) (Preprocessor) A macro has been invoked with the wrong number of arguments, for example: #define ADD(a, b) (a+b) ADD(1, 2, 3) /* oops -- only two arguments required */ (172) formal parameter expected after # (Preprocessor) The stringization operator # (not to be confused with the leading # used for preprocessor control lines) must be followed by a formal macro parameter, for example: #define str(x) #y
MPLAB® XC8 C Compiler User’s Guide (180) unterminated comment in included file (Preprocessor) Comments begun inside an included file must end inside the included file.
Error and Warning Messages (188) constant expression required (Parser) In this context an expression is required that can be evaluated to a constant at compile time, for example: int a; switch(input) { case a: /* oops! can’t use variable as part of a case label */ input++; } (189) illegal type for array dimension (Parser) An array dimension must be either an integral type or an enumerated value. int array[12.
MPLAB® XC8 C Compiler User’s Guide (198) undefined struct/union "*" (Parser) The specified structure or union tag is undefined, for example: struct WHAT what; /* a definition for WHAT was never seen */ (199) logical type required (Parser) The expression used as an operand to if, while statements or to boolean operators like ! and && must be a scalar integral type, for example: struct FORMAT format; if(format) /* this operand must be a scaler type */ format.
Error and Warning Messages (204) void function can’t return a value (Parser) A void function cannot return a value. Any return statement should not be followed by an expression, for example: void run(void) { step(); return 1; /* either run should not be void, or remove the 1 */ } (205) integral type required (Parser) This operator requires operands that are of integral type only.
MPLAB® XC8 C Compiler User’s Guide (215) missing argument to pragma "switch" (Parser) The pragma switch requires an argument of auto, direct or simple, for example: #pragma switch /* oops -- this requires a switch mode */ maybe you meant something like: #pragma switch simple (216) missing argument to pragma "psect" (Parser) The pragma psect requires an argument of the form oldname = newname where oldname is an existing psect name known to the compiler, and newname is the desired new name, for example
Error and Warning Messages (224) illegal "#" directive (Parser) An illegal # preprocessor has been detected. Likely a directive has been misspelled in your code somewhere.
MPLAB® XC8 C Compiler User’s Guide (237) function "*" redefined (Parser) More than one definition for a function has been encountered in this module.
Error and Warning Messages (243) inappropriate break/continue (Parser) A break or continue statement has been found that is not enclosed in an appropriate control structure.
MPLAB® XC8 C Compiler User’s Guide (247) duplicate label "*" (Parser) The same name is used for a label more than once in this function. Note that the scope of labels is the entire function, not just the block that encloses a label, for example: start: if(a > 256) goto end; start: if(a == 0) goto start; /* error flagged here */ /* which start label do I jump to? */ (248) inappropriate "else" (Parser) An else keyword has been encountered that cannot be associated with an if statement.
Error and Warning Messages (253) argument list conflicts with prototype (Parser) The argument list in a function definition is not the same as a previous prototype for that function. Check that the number and types of the arguments are all the same. extern int calc(int); int calc(int a, int b) { return a + b; } /* this is supposedly calc’s prototype */ /* hmmm -- which is right? */ /* error flagged here */ (254) undefined *: "*" (Parser) This is an internal compiler error.
MPLAB® XC8 C Compiler User’s Guide (262) struct/union "*" redefined (Parser) A structure or union has been defined more than once, for example: struct { int a; } ms; struct { int a; } ms; /* was this meant to be the same name as above? */ (263) members can’t be functions (Parser) A member of a structure or a union may not be a function.
Error and Warning Messages (267) bad storage class (Code Generator) The code generator has encountered a variable definition whose storage class is invalid, for example: auto int foo; /* auto not permitted with global variables */ int power(static int a) /* parameters may not be static */ { return foo * a; } (268) inconsistent storage class (Parser) A declaration has conflicting storage classes.
MPLAB® XC8 C Compiler User’s Guide (276) type specifier required for prototyped argument (Parser) A type specifier is required for a prototyped argument. It is not acceptable to just have an identifier. (277) can’t mix prototyped and non-prototyped arguments (Parser) A function declaration can only have all prototyped arguments (i.e., with types inside the parentheses) or all K&R style args (i.e.
Error and Warning Messages (285) no identifier in declaration (Parser) The identifier is missing in this declaration. This error can also occur where the compiler has been confused by such things as missing closing braces, for example: void interrupt(void) { } /* what is the name of this function? */ (286) declarator too complex (Parser) This declarator is too complex for the compiler to handle. Examine the declaration and find a way to simplify it.
MPLAB® XC8 C Compiler User’s Guide (294) can’t allocate * bytes of memory (Code Generator, Hexmate) This is an internal compiler error. Contact Microchip Technical Support with details. (295) expression too complex (Parser) This expression has caused overflow of the compiler’s internal stack and should be re-arranged or split into two expressions. (296) out of memory (Objtohex) This could be an internal compiler error. Contact Microchip Technical Support with details.
Error and Warning Messages (310) "]" expected (Parser) A closing square bracket was expected in an array declaration or an expression using an array index, for example: process(carray[idx); /* oops -should be: process(carray[idx]); */ (311) closing quote expected (Parser) A closing quote was expected for the indicated string. (312) "*" expected (Parser) The indicated token was expected by the parser.
MPLAB® XC8 C Compiler User’s Guide (319) while expected (Parser) The keyword while is expected at the end of a do statement, for example: do { func(i++); } if(i > 5) end(); /* do the block while what condition is true? */ /* error flagged here */ (320) ":" expected (Parser) A colon is missing after a case label, or after the keyword default.
Error and Warning Messages (327) long long int argument required in printf-style format string (Parser) A long long argument is required for this format specifier. Check the number and order of format specifiers and corresponding arguments, for example: printf("%llx", 2); // maybe you meant: printf("%llx", 2LL); Note that MPLAB XC8 does not provide direct support for a long long integer type.
MPLAB® XC8 C Compiler User’s Guide (336) string concatenation across lines (Parser) Strings on two lines will be concatenated. Check that this is the desired result, for example: char * cp = "hi" "there"; /* this is okay, but is it what you had intended? */ (337) line does not have a newline on the end (Parser) The last line in the file is missing the newline (operating system dependent character) from the end. Some editors will create such files, which can cause problems for include files.
Error and Warning Messages (345) unreachable code (Parser) This section of code will never be executed, because there is no execution path by which it could be reached, for example: while(1) process(); flag = FINISHED; /* how does this loop finish? */ /* how do we get here? */ (346) declaration of "*" hides outer declaration (Parser) An object has been declared that has the same name as an outer declaration (i.e., one outside and preceding the current function or block).
MPLAB® XC8 C Compiler User’s Guide (350) unused * "*" (from line *) (Parser) The indicated object was never used in the function or module being compiled. Either this object is redundant, or the code that was meant to use it was excluded from compilation or misspelled the name of the object. Note that the symbols rcsid and sccsid are never reported as being unused.
Error and Warning Messages (357) illegal conversion of integer to pointer (Parser) An integer has been assigned to or otherwise converted to a pointer type. This will usually mean you have used the wrong variable, but if this is genuinely what you want to do, use a typecast to inform the compiler that you want the conversion and the warning will be suppressed.
MPLAB® XC8 C Compiler User’s Guide (360) array index out of bounds (Parser) An array is being indexed with a constant value that is less than zero, or greater than or equal to the number of elements in the array.
Error and Warning Messages (365) pointer to non-static object returned (Parser) This function returns a pointer to a non-static (e.g., auto) variable.
MPLAB® XC8 C Compiler User’s Guide (371) missing basic type; int assumed (Parser) This declaration does not include a basic type, so int has been assumed. This declaration is not illegal, but it is preferable to include a basic type to make it clear what is intended, for example: char c; i; /* don’t let the compiler make assumptions, use : int i */ func(); /* ditto, use: extern int func(int); */ (372) "," expected (Parser) A comma was expected here.
Error and Warning Messages (383) text record has length (*) too small (Linker) This is an internal compiler error. Contact Microchip Technical Support with details. (384) assertion failed: file *, line *, expression * (Linker, Parser) This is an internal compiler error. Contact Microchip Technical Support with details. (387) illegal or too many -G options (Linker) There has been more than one linker -g option, or the -g option did not have any arguments following.
MPLAB® XC8 C Compiler User’s Guide (400) bad object code format (Linker) This is an internal compiler error. The object code format of an object file is invalid. Ensure it is a valid object file. Contact Microchip Technical Support with details. (402) bad argument to -F (Objtohex) The -F option for objtohex has been supplied an invalid argument. If you are invoking this command-line tool directly, refer to Section 8.3 “OBJTOHEX” for more details.
Error and Warning Messages (417) seek error in "*" (Linker) This is an internal compiler error. Contact Microchip Technical Support with details. (418) image too big (Objtohex) This is an internal compiler error. Contact Microchip Technical Support with details. (419) object file is not absolute (Objtohex) The object file passed to OBJTOHEX has relocation items in it. This may indicate it is the wrong object file, or that the linker or OBJTOHEX have been given invalid options.
MPLAB® XC8 C Compiler User’s Guide (432) usage: objtohex [-ssymfile] [object-file [exe-file]] (Objtohex) Improper usage of the command-line tool objtohex. If you are invoking objtohex directly, refer to Section 8.3 “OBJTOHEX” for more details. Otherwise this may be an internal compiler error and you should contact Microchip Technical Support with details. (434) too many symbols (*) (Linker) There are too many symbols in the symbol table, which has a limit of * symbols.
Error and Warning Messages (442) missing address in -A spec (Linker) The format of a -A specification, giving address ranges to the linker, is invalid, for example: -ACODE= What is the range for this class? Maybe you meant: -ACODE=0h-1fffh (443) bad low address "*" in -A spec (Linker) The low address given in a -A specification is invalid: it should be a valid number, in decimal, octal or hexadecimal radix. The radix is specified by a trailing O (for octal) or H for HEX.
MPLAB® XC8 C Compiler User’s Guide (447) bad load address "*" in -A spec (Linker) The load address given in a -A specification is invalid: it should be a valid number, in decimal, octal or hexadecimal radix. The radix is specified by a trailing O (for octal) or H for HEX. A leading 0x may also be used for hexadecimal. Case in not important for any number or radix.
Error and Warning Messages (454) link and load address can’t both be set to "." in -P option (Linker) The link and load address of a psect have both been specified with a dot character. Only one of these addresses may be specified in this manner, for example: -Pmypsect=1000h/. -Pmypsect=./1000h Both of these options are valid and equivalent. However, the following usage is ambiguous: -Pmypsect=./.
MPLAB® XC8 C Compiler User’s Guide (469) undefined symbol "*" in FNROOT record (Linker) The linker has found an undefined symbol in the FNROOT record for a non-reentrant function. Contact Microchip Technical Support if this is not handwritten assembler code. (470) undefined symbol "*" in FNSIZE record (Linker) The linker has found an undefined symbol in the FNSIZE record for a non-reentrant function. Contact Microchip Technical Support if this is not handwritten assembler code.
Error and Warning Messages (474) no psect specified for function variable/argument allocation (Linker) The FNCONF assembler directive which specifies to the linker information regarding the auto/parameter block was never seen. This is supplied in the standard runtime files if necessary. This error may imply that the correct run-time startup module was not linked. Ensure you have used the FNCONF directive if the runtime startup module is hand-written.
MPLAB® XC8 C Compiler User’s Guide MOVWF (_foo&0ffh) which masks out the top bits of the address containing the bank information. If the assembler instruction that caused this error was generated by the compiler, in the assembler list file look back up the file from the instruction at fault to determine which C statement has generated this instruction. You will then need to examine the C code for possible errors. incorrectly qualified pointers are an common trigger.
Error and Warning Messages (485) unknown "with" psect referenced by psect "*" (Linker) The specified psect has been placed with a psect using the psect with flag. The psect it has been placed with does not exist, for example: psect starttext,class=CODE,with=rext ; was that meant to be with text? (486) psect "*" selector value redefined (Linker) The selector value for this psect has been defined more than once.
MPLAB® XC8 C Compiler User’s Guide The second cause of this message is when the total amount of memory needed by the psect being positioned is sufficient, but that this memory is fragmented in such a way that the largest contiguous block is too small to accommodate the psect. The linker is unable to split psects in this situation. That is, the linker cannot place part of a psect at one location and part somewhere else.
Error and Warning Messages (494) bad -P format "*/*" (Linker) The -P option given to the linker is malformed. This option specifies placement of a psect, for example: -Ptext=10g0h Maybe you meant: -Ptext=10f0h (495) use of both "with=" and "INCLASS/INCLASS" allocation is illegal (Linker) It is not legal to specify both the link and location of a psect as within a class, when that psect was also defined using a with psect flag.
MPLAB® XC8 C Compiler User’s Guide (505) no end record found inobject file (Linker) An object file did not contain an end record. This probably means the file is corrupted or not an object file. Contact Microchip Technical Support if the object file was generated by the compiler. (506) object file record too long: *+* (Linker) This is an internal compiler error. Contact Microchip Technical Support with details. (507) unexpected end of file in object file (Linker) This is an internal compiler error.
Error and Warning Messages (522) library "*" is badly ordered (Linker) This library is badly ordered. It will still link correctly, but it will link faster if better ordered. (523) argument to -W option (*) illegal and ignored (Linker) The argument to the linker option -w is out of range. This option controls two features. For warning levels, the range is -9 to 9. For the map file width, the range is greater than or equal to 10.
MPLAB® XC8 C Compiler User’s Guide (600) No chip arch given for COFF write (Cromwell) CROMWELL requires that the chip architecture be specified to produce a COFF file. Ensure that you are using the -P option as per Table 8-7. (601) Unknown chip arch "*" for COFF write (Cromwell) The chip architecture specified for producing a COFF file isn’t recognized by CROMWELL. Ensure that you are using the -P option as per Section 8.5.
Error and Warning Messages (616) option -Cbaseaddr is illegal with options -R or -L (Linker) The linker option -Cbaseaddr cannot be used in conjunction with either the -R or -L linker options. (618) error reading COD file data (Cromwell) An error occurred reading the input COD file. Confirm the spelling and path of the file specified on the command line. (619) I/O error reading symbol table (Cromwell) The COD file has an invalid format in the specified record.
MPLAB® XC8 C Compiler User’s Guide (634) error dumping "*" (Cromwell) Either the input file to CROMWELL is of an unsupported type or that file cannot be dumped to the screen. (635) invalid HEX file "*" on line * (Cromwell) The specified HEX file contains an invalid line. Contact Microchip Technical Support if the HEX file was generated by the compiler.
Error and Warning Messages (681) bad common spec in -P option (Code Generator) This is an internal compiler error. Contact Microchip Technical Support with details. (682) this architecture is not supported by the PICC™ Lite compiler (Code Generator) A target device other than baseline, mid-range or highend was specified. This compiler only supports devices from these architecture families.
MPLAB® XC8 C Compiler User’s Guide (693) interrupt level may only be 0 (default) or 1 (Code Generator) The only possible interrupt levels are 0 or 1. Check to ensure that all interrupt_level pragmas use these levels. #pragma interrupt_level 2 /* oops -- only 0 or 1 */ void interrupt isr(void) { /* isr code goes here */ } (694) no interrupt strategy available (Code Generator) The device does not support saving and subsequent restoring of registers during an interrupt service routine.
Error and Warning Messages (702) regused(): bad arg to G (Code Generator) This is an internal compiler error. Contact Microchip Technical Support with details. (703) bad GN (Code Generator) This is an internal compiler error. Contact Microchip Technical Support with details. (704) bad RET_MASK (Code Generator) This is an internal compiler error. Contact Microchip Technical Support with details. (705) bad which (*) after I (Code Generator) This is an internal compiler error.
MPLAB® XC8 C Compiler User’s Guide (716) bad argument to -M option "*" (Code Generator) The code generator has been passed a -M option that it does not understand. This should not happen if it is being invoked by a standard compiler driver. (718) incompatible intermediate code version; should be *.* (Code Generator) The intermediate code file produced by P1 is not the correct version for use with this code generator.
Error and Warning Messages (733) bad string "*" in pragma "psect" (Code Generator) The code generator has been passed a pragma psect directive that has a badly formed string, for example: #pragma psect text /* redirect text psect into what? */ Maybe you meant something like: #pragma psect text=special_text (734) too many "psect" pragmas (Code Generator) Too many #pragma psect directives have been used.
MPLAB® XC8 C Compiler User’s Guide (743) divide by zero (Code Generator) An expression involving a division by zero has been detected in your code. (744) static object "*" has zero size (Code Generator) A static object has been declared, but has a size of zero. (745) nodecount = * (Code Generator) This is an internal compiler error. Contact Microchip Technical Support with details.
Error and Warning Messages MESSAGES 750-999 (750) constant operand to || or && (Code Generator) One operand to the logical operators || or && is a constant. Check the expression for missing or badly placed parentheses.
MPLAB® XC8 C Compiler User’s Guide (754) bitfield comparison out of range (Code Generator) This is the result of comparing a bit-field with a value when the value is out of range of the bit-field. That is, comparing a 2-bit bit-field to the value 5 will never be true as a 2-bit bit-field has a range from 0 to 3. For example: struct { unsigned mask : 2; /* mask can hold values 0 to 3 */ } value; int compare(void) { return (value.
Error and Warning Messages A similar situation arises with for loops, for example: { int a, b; /* this loop must iterate at least once */ for(a=0; a!=10; a++) b = func(a); In this case the code generator can again pick up that a is assigned the value 0, then immediately checked to see if it is equal to 10.
MPLAB® XC8 C Compiler User’s Guide (761) sizeof yields 0 (Code Generator) The code generator has taken the size of an object and found it to be zero. This almost certainly indicates an error in your declaration of a pointer; i.e., you may have declared a pointer to a zero length array. In general, pointers to arrays are of little use. If you require a pointer to an array of objects of unknown length, you only need a pointer to a single object that can then be indexed or incremented.
Error and Warning Messages (768) constant relational expression (Code Generator) There is a relational expression that will always be true or false. This, for example, may be the result of comparing an unsigned number with a negative value; or comparing a variable with a value greater than the largest number it can represent, for example: unsigned int a; if(a == -10) /* if a is unsigned, how can it be -10? */ b = 9; (769) no space for macro definition (Assembler) The assembler has run out of memory.
MPLAB® XC8 C Compiler User’s Guide (787) can’t handle "v_rtype" of * in copyexpr (Assembler) This is an internal compiler error. Contact Microchip Technical Support with details. (788) invalid character "*" in number (Assembler) A number contained a character that was not part of the range 0-9 or 0-F. (790) end of file inside conditional (Assembler) END-of-FILE was encountered while scanning for an “endif” to match a previous “if”.
Error and Warning Messages (804) write error on object file (Assembler) The assembler failed to write to an object file. This may be an internal compiler error. Contact Microchip Technical Support with details. (806) attempted to get an undefined object (*) (Assembler) This is an internal compiler error. Contact Microchip Technical Support with details. (807) attempted to set an undefined object (*) (Assembler) This is an internal compiler error. Contact Microchip Technical Support with details.
MPLAB® XC8 C Compiler User’s Guide (822) duplicate ROMSIZE for "*" in chipinfo file at line * (Assembler) The chipinfo file has a device section with multiple ROMSIZE values. Only one ROMSIZE value is allowed. If you have not manually edited the chip info file, contact Microchip Technical Support with details. (823) duplicate START for "*" in chipinfo file at line * (Assembler) The chipinfo file has a device section with multiple START values. Only one START value is allowed.
Error and Warning Messages (835) form length must be >= 15 (Assembler) The form length specified using the -F length option must be at least 15 lines. Setting this length to zero is allowed and turns off paging altogether. The default value is zero (pageless). (836) no file arguments (Assembler) The assembler has been invoked without any file arguments. It cannot assemble anything.
MPLAB® XC8 C Compiler User’s Guide (848) symbol has been declared EXTERN (Assembler) An assembly label uses the same name as a symbol that has already been declared as EXTERN. (849) illegal instruction for this device (Assembler) The instruction is not supported by this device. (850) PAGESEL not usable with this device (Assembler) The PAGESEL pseudo-instruction is not usable with the device selected.
Error and Warning Messages (862) symbol is not external (Assembler) A symbol has been declared as EXTRN but is also defined in the current module. (863) symbol can’t be both extern and public (Assembler) If the symbol is declared as extern, it is to be imported. If it is declared as public, it is to be exported from the current module. It is not possible for a symbol to be both.
MPLAB® XC8 C Compiler User’s Guide (872) psect flag "space" redefined (Assembler) The space flag to the PSECT assembler directive is different from a previous PSECT directive, for example: psect spdata,class=RAM,space=0 ; elsewhere: psect spdata,class=RAM,space=1 (873) a psect may only be in one class (Assembler) You cannot assign a psect to more than one class. The psect was defined differently at this point than when it was defined elsewhere.
Error and Warning Messages (884) please ensure you have write permissions to the configuration file (Driver) The compiler was not successfully setup using the --setup driver option because the driver was unable to access the XML configuration file. Ensure that you have write permission to this file. The driver will search the following configuration files in order: • the file specified by the environment variable XC_XML • the file /etc/xc.xml if the directory ’/etc ’ is writable and there is no .xc.
MPLAB® XC8 C Compiler User’s Guide (899) can’t open option file "*" for application "*": * (Driver) An option file specified by a --getoption or --setoption driver option could not be opened. If you are using the --setoption option ensure that the name of the file is spelt correctly and that it exists. If you are using the --getoption option ensure that this file can be created at the given location or that it is not in use by any other application.
Error and Warning Messages (922) chip "*" not present in chipinfo file "*" (Driver) The chip selected does not appear in the compiler’s chip configuration file. Contact Microchip to see whether support for this device is available or it is necessary to upgrade the version of your compiler. (923) unknown suboption "*" (Driver) This option can take suboptions, but this suboption is not understood. This may just be a simple spelling error. If not, –HELP to look up what suboptions are permitted here.
MPLAB® XC8 C Compiler User’s Guide (944) data conflict at address *h between * and * (Hexmate) Sources to Hexmate request differing data to be stored to the same address. To force one data source to override the other, use the ’+’ specifier. If the two named sources of conflict are the same source, then the source may contain an error. (945) checksum range (*h to *h) contained an indeterminate value (Hexmate) The range for this checksum calculation contained a value that could not be resolved.
Error and Warning Messages (965) -STRPACK option not yet implemented, option will be ignored (Hexmate) This option currently is not available and will be ignored. (966) no END record for HEX file "*" (Hexmate) Intel HEX file did not contain a record of type END. The HEX file may be incomplete. (967) unused function definition "*" (from line *) (Parser) The indicated static function was never called in the module being compiled.
MPLAB® XC8 C Compiler User’s Guide (979) this identifier is already a struct tag (Parser) This identifier following a union or enum keyword is already the tag for a structure, and thus should only follow the keyword struct, for example: struct IN { int a, b; }; enum IN {ONE=1, TWO}; /* oops -- IN is already defined */ (980) this identifier is already a union tag (Parser) This identifier following a struct or enum keyword is already the tag for a union, and thus should only follow the keyword union, fo
Error and Warning Messages (989) module has code below file base of *h (Linker) This module has code below the address given, but the -C option has been used to specify that a binary output file is to be created that is mapped to this address. This would mean code from this module would have to be placed before the beginning of the file! Check for missing psect directives in assembler files.
MPLAB® XC8 C Compiler User’s Guide MESSAGES 1000-1249 (1015) missing "*" specification in chipinfo file "*" at line * (Driver) This attribute was expected to appear at least once but was not defined for this chip. (1016) missing argument* to "*" specification in chipinfo file "*" at line * (Driver) This value of this attribute is blank in the chip configuration file.
Error and Warning Messages (1029) compiler not installed correctly - error code (*) (Driver) This compiler has failed to find any activation information and cannot proceed to execute. The compiler may have been installed incorrectly or incompletely. The error code quoted can help diagnose the reason for this failure. You may be asked for this failure code if contacting Microchip for assistance with this problem. (1030) Hexmate - Intel HEX editing utility (Build 1.
MPLAB® XC8 C Compiler User’s Guide (1044) end of file encountered (Cromwell, Linker) The end of the file was found while more data was expected. Has this input file been truncated? (1045) short read on block of * bytes (Cromwell) A while reading a block of byte data from a UBROF record, the block ended before the expected length. (1046) short string read (Cromwell) A while reading a string from a UBROF record, the string ended before the specified length.
Error and Warning Messages (1059) rewrite loop (Code Generator) This is an internal compiler error. Contact Microchip Technical Support with details. (1081) static initialization of persistent variable "*" (Parser, Code Generator) A persistent variable has been assigned an initial value.
MPLAB® XC8 C Compiler User’s Guide (1118) bad string "*" in getexpr(J) (Code Generator) This is an internal compiler error. Contact Microchip Technical Support with details. (1119) bad string "*" in getexpr(LRN) (Code Generator) This is an internal compiler error. Contact Microchip Technical Support with details. (1121) expression error (Code Generator) This is an internal compiler error. Contact Microchip Technical Support with details.
Error and Warning Messages (1187) invalid activation request ( Driver) The compiler has not been correctly activated. (1188) network error * (Activation) The compiler activation software was unable to connect to the Microchip activation server via the network. (1190) FAE license only - not for use in commercial applications (Driver) Indicates that this compiler has been activated with an FAE license. This license does not permit the product to be used for the development of commercial applications.
MPLAB® XC8 C Compiler User’s Guide (1203) unpaired nibble in * value will be truncated (Hexmate) Data to this option was not entered as whole bytes. Perhaps the data was incomplete or a leading zero was omitted. For example, the value Fh contains only four bits of significant data and is not a whole byte. The value 0Fh contains eight bits of significant data and is a whole byte. (1204) * value must be between 1 and * bytes long (Hexmate) An illegal length of data was given to this option.
Error and Warning Messages (1230) dereferencing uninitialized pointer "*" (Code Generator) A pointer that has not yet been assigned a value has been dereferenced. This can result in erroneous behavior at runtime. (1235) unknown keyword * (Driver) The token contained in the USB descriptor file was not recognized. (1236) invalid argument to *: * (Driver) An option that can take additional parameters was given an invalid parameter value.
MPLAB® XC8 C Compiler User’s Guide (1247) no access RAM defined for variable placement (Code Generator) No memory has been specified to cover the access bank memory. (1248) symbol (*) encountered with undefined type size (Code Generator) The code generator was asked to position a variable, but the size of the variable is not known. This is an internal compiler error. Contact Microchip Technical Support with details.
Error and Warning Messages (1260) macro "*" redefined (Assembler) More than one definition for a macro with the same name has been encountered, for example: MACRO fin ret ENDM MACRO fin reti ENDM ; oops -- was this meant to be a different macro? (1261) string constant required (Assembler) A string argument is required with the DS or DSU directive, for example: DS ONE ; oops -- did you mean DS "ONE"? (1262) object "*" lies outside available * space (Code Generator) An absolute variable was position
MPLAB® XC8 C Compiler User’s Guide (1278) omitting "*" which does not have a location (Cromwell) A variable has no storage location listed and will be omitted from the debug output. Contact Microchip Technical Support with details. (1284) malformed mapfile while generating summary: CLASS expected but not found (Driver) The map file being read to produce a memory summary is malformed.
Error and Warning Messages (1295) there are * days left until this license will expire (Driver) The compiler is running as a demo and will be unable to run in PRO mode after the evaluation license has expired in the indicated time. After expiration, the compiler can be operated in Free mode indefinitely, but will produce a larger output binary. (1296) source file "*" conflicts with "*" (Driver) The compiler has encountered more than one source file with the same basename.
MPLAB® XC8 C Compiler User’s Guide (1308) missing/conflicting interrupts sub-option, defaulting to "*" (Driver) The suboptions to the --INTERRUPT option are missing or malformed, for example: --INTERRUPTS=single,multi Oops, did you mean single-vector or multi-vector interrupts? (1309) ignoring invalid runtime * sub-option (*) using default (Driver) The indicated suboption to the --RUNTIME option is malformed, for example: --RUNTIME=default,speed:0y1234 Oops, that should be 0x1234.
Error and Warning Messages (1319) invalid type "*" for attribute "*" (Parser) This indicated a bad option passed to the parser. Contact Microchip Technical Support with details. (1320) attribute "*" already exists (Parser) This indicated the same attribute option being passed to the parser more than once. Contact Microchip Technical Support with details. (1321) bad attribute -T option "%s" (Parser) The attribute option passed to the parser is malformed.
MPLAB® XC8 C Compiler User’s Guide (1330) only functions or function pointers may have an instruction set architecture qualifier (Code Generator) An instruction set qualifier has been used with something that does not represent executable code. mips16e int input; /* oops -- you can’t qualify a variable with an instruction set type */ (1331) interrupt functions may not be qualified "*" (Code Generator) A illegal function qualifier has been used with an interrupt function.
Error and Warning Messages (1339) operand must be a * bit * value (Assembler) The constant operand to an instruction is too large to fit in the instruction field width and must have the indicated type. addiu a3, a3, 0x123456 /* oops -the constant operand to this MIPS16E instruction is too large */ (1340) operand must be >= * and <= * (Assembler) The operand must be within the specified range.
MPLAB® XC8 C Compiler User’s Guide (1352) truncation of operand value (0x*) to * bits (Assembler) The operand to an assembler instruction was too large and was truncated. movlw 0x321 ; oops -- is this the right value? (1354) ignoring configuration setting for unimplemented word * (Driver) A configuration word setting was specified for a word that does not exist on the target device.
Error and Warning Messages (1363) unknown configuration setting (* = *) used (Driver) The configuration value and setting is not known for the target device. #pragma config WDR=ON /* oops -- did you mean WDT? */ (1364) can’t open configuration registers data file * (Driver) The file containing value configuration settings could not be found. (1365) missing argument to pragma "varlocate" (Parser) The argument to #pragma varlocate was malformed.
MPLAB® XC8 C Compiler User’s Guide (1376) initial value (*) too large for bitfield width (*) (Code Generator) A structure with bit-fields has been defined an initialized with values. The value indicated it too large to fit in the corresponding bit-field width.
Error and Warning Messages (1387) inline delay argument must be constant (Code Generator) The __delay inline function can only take a constant expression as its argument. int delay_val = 99; __delay(delay_val); // oops, argument must be a constant expression (1388) configuration setting/register of "*" with 0x* will be truncated by 0x* (Parser, Code Generator) A configuration bit has been programmed with a value that is either too large for the setting, or not one of the prescribed values.
MPLAB® XC8 C Compiler User’s Guide (1395) notable code sequence candidate suitable for compiler validation suite detected (*) (Code Generator) The compiler has in-built checks that can determine if combinations of internal code templates have been encountered. Where unique combinations are uncovered when compiling code, this message is issued.
Error and Warning Messages (1406) auto eeprom variables are not supported (Code Generator) Variables qualified as eeprom cannot be auto. You can define static local objects qualified as eeprom, if required. void main(void) { eeprom int mode; // oops -- make this static or global (1407) bit eeprom variables are not supported (Code Generator) Variables qualified as eeprom cannot have type bit.
MPLAB® XC8 C Compiler User’s Guide (1414) option * is defunct and has no effect (Driver) The option used is now longer supported. It will be ignored. xc8 --chip=18f452 --cp=24 main.c Oops -- the --cp option is no longer required. (1415) argument to "merge" psect flag must be 0 or 1 (Assembler) This psect flag must be assigned a 0 or 1.
Error and Warning Messages (1424) short long integer types are not supported (Parser) The use of the short long type does not conform to the CCI Standard. Use the corresponding long type instead. short long typeMod; // oops -- not a valid type for CCI (1425) __pack qualifier only applies to structures and structure members (Parser) The qualifier you have specified only makes sense when used with structures or structure members. It will be ignored.
MPLAB® XC8 C Compiler User’s Guide (1433) function "*" could not be inlined (Assembler) The specified function could not be made inline. The function will called in the usual way. int inline getData(int port) { //... // sorry -- no luck inlining this (1434) missing name after pragma "intrinsic" (Parser) The instrinsic pragma needs a function name. This pragma is not needed in most situation. If you mean to inline a function, see the inline keyword or pragma.
MPLAB® XC8 C COMPILER USER’S GUIDE Appendix C. Implementation-Defined Behavior This section discusses implementation-defined behavior for this implementation of the MPLAB XC8 C Compiler. The exact behavior of some C code can vary from compiler to compiler, and the ANSI standard for C requires that vendors document the specifics of implementation-defined features of the language. The number in brackets after each item refers to the section number in the Standard to which the item relates. C.
MPLAB® XC8 C Compiler User’s Guide C.3 IDENTIFIERS (G.3.3) C.3.1 The number of significant initial characters (beyond 31) in an identifier without external linkage (6.1.2) By default, the first 31 characters are significant. This can be adjusted up to 255 by the user. C.3.2 The number of significant initial characters (beyond 6) in an identifier with external linkage (6.1.2) By default, the first 31 characters are significant. This can be adjusted up to 255 by the user. C.3.
Implementation-Defined Behavior C.5 INTEGERS (G.3.5) C.5.1 The representations and sets of values of the various types of integers (6.1.2.5) See Section 5.4.2 “Integer Data Types”. C.5.2 The result of converting an integer to a shorter signed integer, or the result of converting an unsigned integer to a signed integer of equal length, if the value cannot be represented (6.2.1.
MPLAB® XC8 C Compiler User’s Guide C.6 FLOATING-POINT (G.3.6) C.6.1 The representations and sets of values of the various types of floating-point numbers (6.1.2.5) See Section 5.4.3 “Floating-Point Data Types”. C.6.2 The direction of truncation when an integral number is converted to a floating-point number that cannot exactly represent the original value (6.2.1.3) The integer value is rounded to the nearest floating-point value that can be represented. C.6.
Implementation-Defined Behavior C.9 STRUCTURES, UNIONS, ENUMERATIONS, AND BIT-FIELDS (G.3.9) C.9.1 A member of a union object is accessed using a member of a different type (6.3.2.3) The value stored in the union member is accessed and interpreted according to the type of the member by which it is accessed. C.9.2 The padding and alignment of members of structures (6.5.2.1) No padding or alignment is imposed on structure members. C.9.
MPLAB® XC8 C Compiler User’s Guide C.13 PREPROCESSING DIRECTIVES (G.3.13) C.13.1 Whether the value of a single-character character constant in a constant expression that controls conditional inclusion matches the value of the same character constant in the execution character set (6.8.1) The character constant evaluates to the same value in both environments. C.13.2 Whether such a character constant may have a negative value (6.8.1) It may not be negative. C.13.
Implementation-Defined Behavior C.14 LIBRARY FUNCTIONS (G.3.14) C.14.1 The null constant to which the macro NULL expands (7.1.6) The macro NULL expands to 0. C.14.2 The diagnostic printed by and the termination behavior of the assert function (7.2) The function prints to stderr "Assertion failed: %s line %d: \"%s\"\n" where the placeholders are replaced with the filename, line number and message string, respectively. The program does not terminate. C.14.
MPLAB® XC8 C Compiler User’s Guide C.14.8 The output for %p conversion in the fprintf function (7.9.6.1) The address is printed as an unsigned long. C.14.9 The local time zone and Daylight Saving Time (7.12.1) Default time zone is GMT. Can be specified by setting the variable time_zone. Daylight saving is not implemented. DS52053B-page 486 2012 Microchip Technology Inc.
MPLAB® XC8 C COMPILER USER’S GUIDE Glossary A Absolute Section A GCC compiler section with a fixed (absolute) address that cannot be changed by the linker. Absolute Variable/Function A variable or function placed at an absolute address using the OCG compiler’s @ address syntax. Access Memory PIC18 Only – Special registers on PIC18 devices that allow access regardless of the setting of the Bank Select Register (BSR).
MPLAB® XC8 C Compiler User’s Guide ANSI American National Standards Institute is an organization responsible for formulating and approving standards in the United States. Application A set of software and hardware that may be controlled by a PIC microcontroller. Archive/Archiver An archive/library is a collection of relocatable object modules. It is created by assembling multiple source files to object files, and then using the archiver/librarian to combine the object files into one archive/library file.
Glossary C C\C++ C is a general-purpose programming language which features economy of expression, modern control flow and data structures, and a rich set of operators. C++ is the object-oriented version of C. Calibration Memory A special function register or registers used to hold values for calibration of a PIC microcontroller on-board RC oscillator or other device peripherals.
MPLAB® XC8 C Compiler User’s Guide Cross Reference File A file that references a table of symbols and a list of files that references the symbol. If the symbol is defined, the first file listed is the location of the definition. The remaining files contain references to the symbol. D Data Directives Data directives are those that control the assembler’s allocation of program or data memory and provide a way to refer to data items symbolically; that is, by meaningful names.
Glossary E EEPROM Electrically Erasable Programmable Read Only Memory. A special type of PROM that can be erased electrically. Data is written or erased one byte at a time. EEPROM retains its contents even when power is turned off. ELF Executable and Linking Format. An object file of this format contains machine code. Debugging and other information is specified in with DWARF. ELF/DWARF provide better debugging of optimized code than COFF. Emulation/Emulator See ICE/ICD.
MPLAB® XC8 C Compiler User’s Guide Extended Mode (PIC18 MCUs) In Extended mode, the compiler will utilize the extended instructions (i.e., ADDFSR, ADDULNK, CALLW, MOVSF, MOVSS, PUSHL, SUBFSR and SUBULNK) and the indexed with literal offset addressing. External Label A label that has external linkage. External Linkage A function or variable has external linkage if it can be referenced from outside the module in which it is defined. External Symbol A symbol for an identifier which has external linkage.
Glossary Free-Standing An implementation that accepts any strictly conforming program that does not use complex types and in which the use of the features specified in the library clause (ANSI ‘89 standard clause 7) is confined to the contents of the standard headers , , , , , and . G GPR General Purpose Register. The portion of device data memory (RAM) available for general use. H Halt A stop of program execution.
MPLAB® XC8 C Compiler User’s Guide Import Bring data into the MPLAB IDE from an outside source, such as from a hex file. Initialized Data Data which is defined with an initial value. In C, int myVar=5; defines a variable which will reside in an initialized data section. Instruction Set The collection of machine language instructions that a particular processor understands.
Glossary Linker A language tool that combines object files and libraries to create executable code, resolving references from one module to another. Linker Script Files Linker script files are the command files of a linker. They define linker options and describe available memory on the target platform. Listing Directives Listing directives are those directives that control the assembler listing file format. They allow the specification of titles, pagination and other listing control.
MPLAB® XC8 C Compiler User’s Guide Macro Macro instruction. An instruction that represents a sequence of instructions in abbreviated form. Macro Directives Directives that control the execution and data allocation within macro body definitions. Makefile Export to a file the instructions to Make the project. Use this file to Make your project outside of MPLAB IDE, i.e., with a make.
Glossary MPLAB ICD Microchip’s in-circuit debuggers that works with MPLAB IDE. See ICE/ICD. MPLAB IDE Microchip’s Integrated Development Environment. MPLAB IDE comes with an editor, project manager and simulator. MPLAB PM3 A device programmer from Microchip. Programs PIC18 microcontrollers and dsPIC digital signal controllers. Can be used with MPLAB IDE or stand-alone. Replaces PRO MATE II. MPLAB REAL ICE™ In-Circuit Emulator Microchip’s next-generation in-circuit emulators that works with MPLAB IDE.
MPLAB® XC8 C Compiler User’s Guide NOP No Operation. An instruction that has no effect when executed except to advance the program counter. O Object Code/Object File Object code is the machine code generated by an assembler or compiler. An object file is a file containing machine code and possibly debug information. It may be immediately executable or it may be relocatable, requiring linking with other object files, e.g., libraries, to produce a complete executable program.
Glossary PIC MCUs PIC microcontrollers (MCUs) refers to all Microchip microcontroller families. PICkit 2 and 3 Microchip’s developmental device programmers with debug capability through Debug Express. See the Readme files for each tool to see which devices are supported. Plug-ins The MPLAB IDE has both built-in components and plug-in modules to configure the system for a variety of software and hardware tools. Several plug-in tools may be found under the Tools menu.
MPLAB® XC8 C Compiler User’s Guide Prologue A portion of compiler-generated code that is responsible for allocating stack space, preserving registers and performing any other machine-specific requirement specified in the runtime model. This code executes before any user code for a given function. Prototype System A term referring to a user’s target application, or target board. Psect The OCG equivalent of a GCC section, short for program section.
Glossary Relaxation The process of converting an instruction to an identical, but smaller instruction. This is useful for saving on code size. MPLAB ASM30 currently knows how to RELAX a CALL instruction into an RCALL instruction. This is done when the symbol that is being called is within +/- 32k instruction words from the current instruction. Relocatable An object whose address has not been assigned to a fixed location in memory.
MPLAB® XC8 C Compiler User’s Guide Simulator A software program that models the operation of devices. Single Step This command steps though code, one instruction at a time. After each instruction, MPLAB IDE updates register windows, watch variables, and status displays so you can analyze and debug instruction execution.
Glossary Static RAM or SRAM Static Random Access Memory. Program memory you can read/write on the target board that does not need refreshing frequently. Status Bar The Status Bar is located on the bottom of the MPLAB IDE window and indicates such current information as cursor position, development mode and device, and active tool bar. Step Into This command is the same as Single Step. Step Into (as opposed to Step Over) follows a CALL instruction into a subroutine.
MPLAB® XC8 C Compiler User’s Guide Target Application Software residing on the target board. Target Board The circuitry and programmable device that makes up the target application. Target Processor The microcontroller device on the target application board. Template Lines of text that you build for inserting into your files at a later time. The MPLAB Editor stores templates in template files. Tool Bar A row or column of icons that you can click on to execute MPLAB IDE functions.
Glossary V Vector The memory locations that an application will jump to when either a Reset or interrupt occurs. Volatile A variable qualifier which prevents the compiler applying optimizations that affect how the variable is accessed in memory. W Warning MPLAB IDE – An alert that is provided to warn you of a situation that would cause physical damage to a device, software file, or equipment. 16-bit assembler/compiler – Warnings report conditions that may indicate a problem, but do not halt processing.
MPLAB® XC8 C Compiler User’s Guide NOTES: DS52053B-page 506 2012 Microchip Technology Inc.
MPLAB® XC8 C COMPILER USER’S GUIDE Index Symbols _ assembly label character .............................204, 251 __align qualifier ........................................................ 30 __bank qualifier........................................................ 29 __Bool type ............................................................ 145 __Bxxxx type symbols ........................................... 239 __CONFIG macro ...................................135, 313, 314 __DATABANK macor..................
MPLAB® XC8 C Compiler User’s Guide #asm directive ........................................................ 202 #define directive ....................................................... 94 #endasm directive .................................................. 202 #include directive ........................................74, 95, 114 #pragma addrqual .......................................................... 215 inline................................................................ 215 interrupt_level .........
Index format...............................................243, 244, 266 hexadecimal constants ................................... 243 including conditional code............................... 266 macros .............................................243, 266, 267 new page ........................................................ 267 titles and subtitles ........................................... 267 assembly source files............................................... 74 assembly variables C equivalent ......
MPLAB® XC8 C Compiler User’s Guide CONFIG class ........................................................ 237 config pragma ........................................................ 135 config psect ............................................................ 233 configuration bits .................................................... 135 CONST class.......................................................... 236 const objects initialization .....................................................
Index none.................................................................. 91 O ....................................................................... 97 OBJDIR........................................................... 107 OPT .................................................108, 119, 243 OUTDIR ...........................................107, 108, 118 OUTPUT ............................................84, 109, 121 P ................................................ 97, 119, 205, 210 PASS1 ...............
MPLAB® XC8 C Compiler User’s Guide return bank ...................................................... 188 return values ................................................... 187 signatures ............................................... 238, 265 size limits ........................................................ 185 specifiers......................................................... 182 stack usage ..................................................... 187 functions absolute ..................................
Index islower function ...................................................... 338 itoa function............................................................ 339 J jmp_tab psect......................................................... 234 K keywords, see qualifiers L L constant suffix ..................................................... 158 l.obj file ................................................................... 281 labels, assembly .............................................
MPLAB® XC8 C Compiler User’s Guide warning, see warning messages messaging system.............................................. 86–90 appending messages to file .............................. 94 default langauge ............................................... 87 default warning level ......................................... 90 environment variables ....................................... 88 message count.................................................. 86 redirecting messages to file .....................
Index containing strings .............................................. 94 defining ............................................................. 94 predefined ..................................................36, 212 undefining ......................................................... 98 unique length of ................................................ 97 printf function ................................ 58, 80, 81, 198, 350 format checking .............................................. 216 preprocessing ..
MPLAB® XC8 C Compiler User’s Guide read-modify-write problems...................................... 69 read-only variables ................................................. 161 REAL ICE debugger............................................... 142 REALICE, see debuggers rebuilding projects .................................................... 79 reentrant functions ......................................... 169, 192 registers allocation to .....................................................
Index sorting ............................................................. 281 symbol-only object file............................................ 280 symbols assembler-generated ...................................... 251 linker defined .................................................. 239 undefined ........................................................ 283 T tan function ............................................................ 371 tanh function .....................................................
Worldwide Sales and Service AMERICAS ASIA/PACIFIC ASIA/PACIFIC EUROPE Corporate Office 2355 West Chandler Blvd. Chandler, AZ 85224-6199 Tel: 480-792-7200 Fax: 480-792-7277 Technical Support: http://www.microchip.com/ support Web Address: www.microchip.