Microchip Technology MPLAB XC16 C Compiler User guide

MPLAB® XC16 C Compiler
User’s Guide
2012 Microchip Technology Inc. DS52071B
Note the following details of the code protection feature on Microchip devices:
YSTEM
CERTIFIED BY DNV
== ISO/TS 16949 ==
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. All of these methods, to our knowledge, require using the Microchip products in a manner outside the operating specifications contained in Microchip’s Data Sheets. Most likely, the person doing so is engaged in theft of intellectual property.
Microchip is willing to work with the customer who is concerned about the integrity of their code.
Neither Microchip nor any other semiconductor manufacturer can guarantee the security of their code. Code protection does not mean that we are guaranteeing the product as “unbreakable.”
Code protection is constantly evolving. We at Microchip are committed to continuously improving the code protection features of our products. Attempts to break Microchip’s code protection feature may be a violation of the Digital Millennium Copyright Act. If such acts allow unauthorized access to your software or other copyrighted work, you may have a right to sue for relief under that Act.
Information contained in this publication regarding device applications and t he lik e is provided only for your convenience and may be su perseded by upda t es . It is y our responsibility to ensure that your application meets with your specifications. MICROCHIP MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED, WRITTEN OR ORAL, STATUTORY OR OTHERWISE, RELATED TO THE INFORMATION, INCLUDING BUT NOT LIMITED TO ITS CONDITION, QUALITY, PERFORMANCE, MERCHANTABILITY OR FITNESS FOR PURPOSE. Microchip disclaims all liability arising from this information and its use. Use of Microchip devices in life supp ort and/or safety ap plications is entir ely at the buyer’s risk, and the buyer agrees to defend, indemnify and hold harmless M icrochip from any and all dama ges, claims, suits, or expenses re sulting from such use. No licens es are conveyed, implicitly or otherwise, under any Microchip intellectual property rights.
Trademarks
The Microchip name and logo, the Microchip logo, dsPIC, K
EELOQ, KEELOQ logo, MPLAB, PIC, PICmicro, PICSTART,
32
PIC
logo, rfPIC and UNI/O are registered trademarks of Microchip Technology Incorporated in the U.S.A. and other countries.
FilterLab, Hampshire, HI-TECH C, Linear Active Thermistor, MXDEV, MXLAB, SEEVAL and The Embedded Control Solutions Company are registered trademarks of Microchip Technology Incorporated in the U.S.A.
Analog-for-the-Digital Age, Application Maestro, chipKIT, chipKIT logo, CodeGuard, dsPICDEM, dsPICDEM.net, dsPICworks, dsSPEAK, ECAN, ECONOMONITOR, FanSense, HI-TIDE, In-Circuit Serial Programming, ICSP, Mindi, MiWi, MPASM, MPLAB Certified logo, MPLIB, MPLINK, mTouch, Omniscient Code Generation, PICC, PICC-18, PICDEM, PICDEM.net, PICkit, PICtail, REAL ICE, rfLAB, Select Mode, Total Endurance, TSHARC, UniWinDriver, WiperLock and ZENA are trademarks of Microchip Technology Incorporated in the U.S.A. and other countries.
SQTP is a service mark of Microchip Technology Incorporated in the U.S.A.
All other trademarks mentioned herein are property of their respective companies.
© 2012, Microchip Technology Incorporated, Printed in the U.S.A., All Rights Reserved.
Printed on recycled paper.
QUALITY MANAGEMENT S
DS52071B-page 2 2012 Microchip Technology Inc.
ISBN: 978-1-62076-467-1
Microchip received ISO/TS-16949:2009 certification for its worldwide headquarters, design and wafer fabrication facilities in Chandler and Tempe, Arizona; Gresham, Oregon and design centers in California and India. The Company’s quality system processes and procedures are for its PIC devices, Serial EEPROMs, microperipherals, nonvolatile memory and analog products. In addition, Microchip’s quality system for the design and manufacture of development systems is ISO 9001:2000 certified.
®
MCUs and dsPIC® DSCs, KEELOQ
®
code hopping
MPLAB® XC16 C COMPILER
USER’S GUIDE

Table of Contents

Preface .........................................................................................................................11
Chapter 1. Compiler Overview
1.1 Introduction ...................................................................................................17
1.2 Device De s cr ip t io n .............. ......................................................................... 17
1.3 Compiler Des c ription and Do cu mentation ......... ... ............. .. .. .............. .. ....... 17
1.3.1 ANSI C Standard .......................................................................................17
1.3.2 Optimization ..............................................................................................17
1.3.3 ANSI Standard Library Support .................................................................18
1.3.4 Flexible Memory Models ............................................................................18
1.3.5 Attributes and Qualifiers ............................................................................18
1.3.6 Compiler Driver ......................................................................................... 18
1.3.7 Documentation ..........................................................................................18
1.4 Compiler and Other Development Tools ......................................................19
Chapter 2. Common C Interface
2.1 Introduction ...................................................................................................21
2.2 Background – The Desire for Portable Code ...............................................21
2.2.1 The ANSI Standard ...................................................................................22
2.2.2 The Common C Interface ..........................................................................23
2.3 Using the CC I .. .. .. ......................................................................................... 24
2.4 ANSI Standard Refinement ..........................................................................25
2.4.1 Source File Encoding ................................................................................ 25
2.4.2 The Prototype for main ..............................................................................25
2.4.3 Header File Specification ..........................................................................25
2.4.4 Include Search Paths ................................................................................ 26
2.4.5 The number of Significant Initial Characters in an Identifier ......................27
2.4.6 Sizes of Types ...........................................................................................27
2.4.7 Plain char Types ........................................................................................28
2.4.8 Signed Integer Representation .................................................................. 28
2.4.9 Integer conversion .....................................................................................29
2.4.10 Bit-wise Operations on Signed Values ....................................................29
2.4.11 Right-shifting Signed Values ................................................................... 29
2.4.12 Conversion of Union Member Accessed Using Member
With Different Type .. ....... ...... ...... ....... ...... ....... ...... ....... ..........................30
2.4.13 Default Bit-field int Type ......................................... ....... ...... ....... ...... ....... 30
2.4.14 Bit-fields Straddling a Storage Unit Boundary .........................................31
2.4.15 The Allocation Order of Bits-field ............................................................. 31
2.4.16 The NULL macro ..................................................................................... 32
2.4.17 Floating-point sizes .......... .......................................................................32
2012 Microchip Technology Inc. DS52071B-page 3
MPLAB® XC16 C Compiler User’s Guide
2.5 ANSI Standard Extensions ...........................................................................33
2.5.1 Generic Header File ...................................................................................33
2.5.2 Absolute addressing ..................................................................................33
2.5.3 Far Objects and Functions .........................................................................34
2.5.4 Near Objects ..............................................................................................35
2.5.5 Persistent Objects ......................................................................................36
2.5.6 X and Y Data Objects ................................................................................37
2.5.7 Banked Data Objects .................................................................................37
2.5.8 Alignment of Objects ..................................................................................38
2.5.9 EEPROM Objects ......................................................................................39
2.5.10 Interrupt Functions ........................................... ....... ...... ...........................3 9
2.5.11 Packing Objects .......................................................................................42
2.5.12 Indicating Antiquated Objects ....................................... ....... ...... ....... ...... . 4 3
2.5.13 Assigning Objects to Sections .................................................................43
2.5.14 Specifying Configuration Bits ...................................................................45
2.5.15 Manifest Macros ............... ....... ...... ...........................................................46
2.5.16 In-line Assembly ............... ........................................................................47
2.6 Compiler Fe a tu r e s . .. ..................................................................................... 48
2.6.1 Enabling the CCI ........................................................................................48
Chapter 3. Compiler Command-Line Driver
3.1 Introduction ................................................................................................... 49
3.2 Invoking th e C o m p ile r .. ................................................................................. 50
3.2.1 Drive Command-Line Format .....................................................................50
3.2.2 Environment Variables ...............................................................................50
3.2.3 Input File Types .........................................................................................51
3.3 The Compilation Sequence ..........................................................................52
3.3.1 The Compiler Applications .........................................................................52
3.3.2 Single-Step Compilation ............................................................................54
3.3.3 Multi-Step Compilation ...............................................................................55
3.3.4 Assembly Compilation ...............................................................................56
3.4 Runtime File s ........................................................ ....................................... 5 7
3.4.1 Library Files ...............................................................................................57
3.4.2 Startup and Initialization .............................................................................57
3.5 Compiler Ou t p u t ............... .. .......................................................................... 58
3.5.1 Output Files ................................................................................................58
3.5.2 Diagnostic Files ..........................................................................................58
3.6 Compiler Messages ...................................................................................... 59
DS52071B-page 4 2012 Microchip Technology Inc.
3.7 Driver Option Descriptions ........................................................................... 60
3.7.1 Options Specific to 16-Bit Devices ............................................................60
3.7.2 Options for Controlling the Kind of Output ................................................. 62
3.7.3 Options for Controlling the C Dialect .........................................................63
3.7.4 Options for Controlling Warnings and Errors .............................................64
3.7.5 Options for Debugging ..............................................................................70
3.7.6 Options for Controlling Optimization .......................................................... 71
3.7.7 Options for Controlling the Preprocessor ..................................................76
3.7.8 Options for Assembling .............................................................................79
3.7.9 Options for Linking .................................................................................... 79
3.7.10 Options for Directory Search ................................................................... 82
3.7.11 Options for Code Generation Conventions ............................................. 82
3.8 MPLAB IDE Toolsuite Equivalents ............................................................... 83
Chapter 4. Device-Related Features
4.1 Introduction ...................................................................................................85
4.2 Device Support .............................................................................................85
4.3 Device Header Files .....................................................................................85
4.3.1 Register Definition Files ............................................................................85
4.4 Stack . .......................................... ................................................................. 86
4.5 Configur ation Bit Access ............................................... .. .. ............. .. ... ......... 86
4.6 Using SFRs ......... .. ....................................................................................... 87
4.7 Bit-Reversed and Modulo Addressing ..........................................................89
Table of Contents
Chapter 5. Differences Between MPLAB XC16 and ANSI C
5.1 Divergence from the ANSI C Standard ................................ ........................91
5.2 Extensions to the ANSI C Standard .............................................................91
5.2.1 Keyword Differences .................................................................................91
5.2.2 Expression Differences .............................................................................91
5.3 Implementation-Defined Behavior ................................................................91
Chapter 6. Supported Data Types and Variables
6.1 Introduction ...................................................................................................93
6.2 Identifiers ......................................................................................................93
6.3 Integer Data Types .......................................................................................94
6.3.1 Double-Word Integers ...............................................................................94
6.3.2 char Types .................................................................................................95
6.4 Floating- P o in t D a ta T ype s ............................................................................ 95
6.5 Structures and Unions ..................................................................................96
6.5.1 Structure and Union Qualifiers ..................................................................96
6.5.2 Bit-Fields in Structures ..............................................................................96
6.6 Pointer Typ e s ........ .......................................... ............................................. 98
6.6.1 Combining Type Qualifiers and Pointers ...................................................98
6.6.2 Data Pointers .............................................................................................99
6.6.3 Function Pointers ......................................................................................99
6.6.4 Special Pointer Targets .............................................................................99
6.7 Complex Data Types .................................................................................. 100
6.8 Literal Constant Types and Formats .................................................... .. ....101
2012 Microchip Technology Inc. DS52071 B-page 5
MPLAB® XC16 C Compiler User’s Guide
6.9 Standard Type Qualifiers ............................................................................103
6.9.1 Const Type Qualifier ................................................................................103
6.9.2 Volatile Type Qualifier ..............................................................................103
6.10 Compile r -S p e c ific type Qualifie rs ............... ... ............... ............................ 104
6.10.1 __psv__ Type Qualifier .................................... ....... ...... .........................10 4
6.10.2 __prog__ Type Qualifier ..................... ....... ...... ......................................104
6.10.3 __eds__ Type Qualifier ..........................................................................105
6.10.4 __pack_upper_byte Type Quali fi er ......................... ...... ....... ...... ....... .....105
6.10.5 __pmp__ Type Qualifier .........................................................................105
6.10.6 __external__ Type Qualifier ...................................................................106
6.11 Variab le Attributes .............. ...................................................................... 107
Chapter 7. Memory Allocation and Access
7.1 Introduction .................................................................................................117
7.2 Address Sp a ce s ............... .......................................................................... 117
7.3 Variables in Data Space Memory ............................................................... 118
7.3.1 Non-Auto Variable Allocation and Access ...............................................118
7.3.2 Auto Variable Allocation and Access .......................................................121
7.3.3 Changing Auto Variable Allocation ..........................................................124
7.4 Variables in Pr o g ra m Sp a ce . ...................................................................... 125
7.4.1 Allocation and Access of Program Memory Objects ................................125
7.4.2 Access of objects in Program Memory ....................................................127
7.4.3 Size Limitations of Program Memory Variables .......................................128
7.4.4 Changing Program Memory Variable Allocation ......................................129
7.5 Parallel Master Port Access ....................................................................... 130
7.5.1 Initialize PMP ...........................................................................................130
7.5.2 Declare a New Memory Space ................................................................131
7.5.3 Define Variables within PMP Space ........................................................131
7.6 External Me m o r y A c ce s s .. ....................................... ... .. .............................. 132
7.6.1 Declare a New Memory Space ................................................................132
7.6.2 Define Variables Within an External Space .............................................132
7.6.3 Define How to Access Memory Spaces ...................................................133
7.6.4 An External Example ...............................................................................135
7.7 Extended Data Space Access ....................................................................136
7.8 Packing Da ta S to re d in Fl as h .... .. ............. .. .. .............................................. 137
7.8.1 Packed Example ......................................................................................137
7.8.2 Usage Considerations ..............................................................................137
7.8.3 Addressing Information ............................................................................138
7.9 Allocatio n of V a ria b les to Registers ............................................................ 139
7.10 Variables in EEPROM .......................................... .. ........................... ....... 139
7.10.1 Accessing EEDATA via User Managed PSV .........................................139
7.10.2 Accessing EEDATA Using TBLRDx Instructions ...................................140
7.10.3 Accessing EEDATA Using Managed Access ........................................141
7.10.4 Additional Sources of Information ..........................................................141
7.11 Dynamic Memory Allo ca t io n ...... ..................................................... .. .. ...... 141
7.12 Memory M o d el s ....... ....................................................... .......................... 1 4 2
7.12.1 Near or Far Data ....................................................................................143
DS52071B-page 6 2012 Microchip Technology Inc.
Chapter 8. Operators and Statements
8.1 Introduction .................................................................................................145
8.2 Built-In Fu n ct io n s .......... .......................................... .................................... 145
8.3 Integral Pr o mo tion ...................................................................................... 145
Chapter 9. Register Usage
9.1 Introduction .................................................................................................147
9.2 Register V a ri a bl e s . ..................................................... ... .. ........................... 147
9.3 Changing R e g is te r Co n t en ts ......................................... .. .. ............. .. .......... 148
Chapter 10. Functions
10.1 Introd uc t io n ............................................................................................... 149
10.2 Writing F u nc t i on s ...................................................................................... 149
10.2.1 Function Specifiers ................................................................................ 149
10.2.2 Function Attributes .... ....... ...... ...... ....... ...... ....... ...... ....... ........................149
10.3 Functi o n Siz e Li m it s .......................................................................... .. .. ...1 5 6
10.4 Allocation of Function Code .....................................................................156
10.5 Changing the Default Function Allocation ................................................157
10.6 Inline F u nc t io n s ............................................................... .. .. ..................... 158
10.7 Memory M o d el s . ....................................................... ................................ 159
10.7.1 Near or Far Code .................................................................................. 160
10.8 Function Call Conventions ....................................................................... 161
10.8.1 Function Parameters ........ ...... ...... ....... ...... ....... ...... ....... ...... ....... ...... ..... 16 1
10.8.2 Return Value .................... ...... ............................................. ..................163
10.8.3 Preserving Registers Across Function Calls .........................................163
Table of Contents
Chapter 11. Interrupts
11.1 Introd uc t io n ............................................................................................... 165
11.2 Interru p t O p e ra t io n ......... ... ....................................................................... 166
11.3 Writing an Interrupt Service Routine ........................................................166
11.3.1 Guidelines for Writing ISRs ................................................................... 166
11.3.2 Syntax for Writing ISRs .......................................... ....... ........................167
11.3.3 Coding ISRs ........................................ ...... ....... ...... ....... ...... ....... ...........167
11.3.4 Using Macros to Declare Simple ISRs ..................................................168
11.4 Specifying the Interrupt Vector ................................................................. 169
11.4.1 Non-SMPS dsPIC30F DSCs Interrupt Vectors ......................................170
11.4.2 SMPS dsPIC30F DSCs Interrupt Vectors .............................................172
11.4.3 PIC24F MCUs Interrupt Vectors ............................................................174
11.4.4 dsPIC33F DSCs/PIC24H MCUs Interrupt Vectors ................................ 177
11.5 Interru p t S e rv ic e R o utine Context S aving . .......................... ... .. ............. .. . 180
11.6 Nesting In te rrupts ......... ............................................................................ 180
11.7 Enabling/Disabling Interrupts ...................................................................181
11.8 ISR Considerations ............... .. .. ........................................ .. ... .................. 182
11.8.1 Sharing Memory with Mainline Code ..................................................... 182
11.8.2 PSV Usage with Interrupt Service Routines ..........................................186
11.8.3 Latency ......... ....... ...... ....... ...... ...... ....... ...... ....... ..................................... 18 6
2012 Microchip Technology Inc. DS52071 B-page 7
MPLAB® XC16 C Compiler User’s Guide
Chapter 12. Main, Runtime Startup and Reset
12.1 Introd uc t io n ..... .......................................................................................... 18 7
12.2 The main F u n c tion ............ .. ...................................................................... 187
12.3 Runtime Startup and Initialization ............................................................. 187
Chapter 13. Mixing C and Assembly Code
13.1 Introd uc t io n ..... .......................................................................................... 18 9
13.2 Mixing Assembly Language and C Variables and Functions ...................189
13.3 Using Inline Assembly Language ............................................................. 192
13.4 Predefined Assembly Macros ...................................................................196
Chapter 14. Library Routines Chapter 15. Optimizations
15.1 Introd uc t io n ..... .......................................................................................... 19 9
Chapter 16. Preprocessing
16.1 Introd uc t io n ..... .......................................................................................... 20 1
16.2 C Language Comments ........................................................................... 201
16.3 Preprocessing Directives .......................................................................... 201
16.4 Predefined Macro Names .........................................................................202
16.4.1 Compiler Version Macro ........................................................................202
16.4.2 Output Types Macros .............................................................................203
16.4.3 Target Device Macros ............................................................................203
16.4.4 Device Features Macros ........................................................................203
16.4.5 Other Macros .........................................................................................204
16.5 Pragma s vs . A tt rib u tes ..... .. .. .................................................................... 2 0 5
Chapter 17. Linking Programs
17.1 Introd uc t io n ..... .......................................................................................... 20 7
17.2 Defau lt Me m o r y Sp a c e s ....... ... .. ............................................................... 207
17.3 Repla ci n g L ib rary Symbols ... .............. .. .. ............. .. ... ............. .. .. ............... 209
17.4 Linker-Defined Symbols ...........................................................................209
17.5 Defau lt L in k e r Script .. ... ............................................................................ 21 0
DS52071B-page 8 2012 Microchip Technology Inc.
Appendix A. Implementation-Defined Behavior
A.1 Introduction ................................................................................................211
A.2 Translati o n .......... .. ..................................................................................... 212
A.3 Environme n t ........................................................................................ .. .. ... 212
A.4 Identifiers ...................................................................................................213
A.5 Character s ............ ................ ..................................................................... 213
A.6 Integers ......................................................................................................214
A.7 Floating Po in t .. ....................................................... .................................... 215
A.8 Arrays and P o in te r s ............ ............................ ...........................................2 1 5
A.9 Register s ............. .. ........................................................ ............................. 216
A.10 Structures, Unions, Enumerations and Bit Fields ....................................216
A.11 Qualifiers .................................................................. ................................ 216
A.12 Declara to r s .......... .............. .. .. ..................................................... .. .. .......... 216
A.13 Stateme nt s ............... ................................................................................ 217
A.14 Preproce s s in g Di re c tives ......................................................................... 217
A.15 Library F u n ct io n s .............. ....................................... ... .. ........................... 218
A.16 Signals .....................................................................................................219
A.17 Streams and Files ....................................................................................220
A.18 tmpfile ...................................................................................................... 221
A.19 errno ......................................................................................................... 221
A.20 Memory .. .. .................................................................................. .............. 221
A.21 abort ................ .................................................................... ..................... 221
A.22 exit ................ .. .. ..................................................... .. ... ............................. 221
A.23 getenv ........ ... ........................................................................................... 221
A.24 system ........... .. ......................................................................................... 221
A.25 strerror .......... ............. .. .. ................................................................... .. .. ... 222
Table of Contents
Appendix B. Diagnostics
B.1 Introduction ................................................................................................223
B.2 Errors ........... .............................................................................................. 223
B.3 Warnings ....................................................... .......................................... ... 242
Appendix C. GNU Free Documentation License
C.1 Preamble ............ ........................... .. .. ........................................................ 263
C.2 Applicability and Definitions .......................................................................263
C.3 Verbatim C op y i ng ........ .. ....................................................... ..................... 265
C.4 Copying in Quantity ...................................................................................265
C.5 Modifica tio n s .............. .. ............................. ................................................. 266
C.6 Combining D o c um e nts ....... ....................................................................... 267
C.7 Collectio n s of D o cu ments ....... ................................................................... 267
C.8 Aggregation with Independent Works ........................................................267
C.9 Translati o n ... ... ....................................................... .................................... 268
C.10 Terminat io n .............. ................................................................................ 268
C.11 Future Re visions of this Lic e nse ...... .. ............. ... .. ............. .. ... ............. .. .. . 268
C.12 Relicens in g ......... ..................................................................................... 269
Appendix D. ASCII Character Set ............................................................................271
2012 Microchip Technology Inc. DS52071 B-page 9
MPLAB® XC16 C Compiler User’s Guide
Appendix E. Deprecated Features
E.1 Introduction ................................................................................................ 273
E.2 Predefined Constants ................................................................................ 273
E.3 Variable s in Sp ecified Regist e rs ............ .. .................................................. 274
E.3.1 Defining Global Register Variables ..........................................................274
E.3.2 Specifying Registers for Local Variables .................................................275
E.4 Changing Non-Auto Variable Allocation ..................................................... 275
Appendix F. Built-in Functions
F.1 Introduction ................................................................................................277
F.2 Built-In Fu n ct io n Description s ..... .. ..................................................... .. .. .... 279
Appendix G. XC16 Configuration Settings
G.1 Introduction ................................................................................................305
Glossary .....................................................................................................................307
Index ...........................................................................................................................327
Worldwide Sales and Service ...................................................................................338
DS52071B-page 10 2012 Microchip Technology Inc.
MPLAB® XC16 C COMPILER
USER’S GUIDE

Preface

NOTICE TO CUSTOMERS
All documentation becomes dated, and this manual is no exception. Microchip tools and documenta­tion are constantly evolving to meet customer needs, so some actual dialogs and/or tool descriptions may differ from those in this document.
For the most up-to-date information on development tools, see the MPLAB Help. Select the Help menu and then “Topics” or “Help Contents” to open a list of available Help files.
For the most current PDFs, please refer to our web site (http://www.microchip.com). Documents are identified by “DSXXXXXA”, where “XXXXX” is the document number and “A” is the revision level of the document. This number is located on the bottom of each page, in front of the page number.

INTRODUCTION

MPLAB XC16 C Compiler documentation and support information is discussed in the sections below:
• Document Layout
• Conventions Used
• Recommended Reading
• myMicrochip Personalized Notification Service
• The Microchip Web Site
• Microchip Forums
• Customer Support
®
IDE or MPLAB X I DE
2012 Microchip Technology Inc. DS52071B-page 11
MPLAB® XC16 C Compiler User’s Guide

DOCUMENT LAYOUT

This document describes how to use GNU language tools to write code for 16-bit applications. The document layout is as follows:
Chapter 1. “Compiler Overvie w ” – describes the compiler, development tools and feature set.
Chapter 3. “Compiler Command-Line Driver” – describes how to use the compiler from the command line.
Chapter 5. “Differences Between MPLAB XC16 and ANSI C” – describes the differences between the C language supported by the compiler syntax and the standard ANSI-89 C.
Chapter 4. “Device-Re lat ed Fea tures” – describes the compiler header and register definition files, as well as how to use with SFRs.
Chapter 6. “Supported Data Types and Variables” – describes the compiler integer, floating point and pointer data types.
Chapter 7. “Memory Allocation and Access” – describes the compiler run-time model, including information on sections, initialization, memory models, the software stack and much more.
Chapter 8. “Operators and Statements” – discusses operators and statements.
Chapter 9. “Registe r Usage” – explains how to access and use SFRs.
Chapter 10. “Functions” – details available functions.
Chapter 11. “Interrupts” – describes how to use interrupts.
Chapter 12. “Main, Runtime Startup and Reset” – describes important elements of C code.
Chapter 14. “Libr ary Routi nes” – explains how to use libraries.
Chapter 13. “Mixing C and Assembly Code” – provides guidelines to using the compiler with 16-bit assembly language modules.
Chapter 15. “Opt imizat ion s” – describes optimization options.
Chapter 16. “Prep r oces sin g” – details preprocessing operation.
Chapter 17. “Linki ng Pr ogr ams” – explains how linking works.
Appendix A. “Implementation-Defined Behavior” – details compiler-specific parameters described as implementation-defined in the ANSI standard.
Appendix B. “Diagnostics” – lists error and warning messages generated by the compiler.
Appendix C. “MPLAB XC16 vs. MPLAB XC8” – contains the ASCII character set.
Appendix C. “GNU Free Documentation License” – usage license for the Free Software Foundation.
Appendix E. “Deprecated Features” – details features that are considered obsolete.
Appendix F. “Built-in Functions” – lists the built-in functions of the C compiler.
Appendix G. “XC16 Configuration Settings” – information about configuration settings macros.
DS52071B-page 12 2012 Microchip Technology Inc.

CONVENTIONS USED

DD
The following conventions may appear in this documentation:
DOCUMENTATION CONVENTIONS
Arial font:
Italic chara c ters Referenced books MPLAB
Initial caps A window the Output window
Quotes A field name in a window or
Underlined, italic text with right angle bracket
Bold characters A dialog button Click OK
Text in angle brackets < > A key on the keyboard Press <Enter>, <F1>
Courier font:
Plain Courier Sample source code #define START
Italic Courier A variable argument file.c, where file can be
Square brackets [ ] Optional arguments mpasmwin [options]
Curly brackets and pipe character: { | }
Ellipses... Replaces r epeated text var_name [,
Sidebar T e xt
Preface
Description Represents Examples
®
IDE User’s Guide
Emphasized text ...is the only compiler...
A dialog the Settings dialog A menu selection select Enable Programmer
“Save project before build”
dialog A menu path File>Save
A tab Click the Power tab
File names autoexec.bat File paths c:\mcc18\h Keywords _asm, _endasm, static Command-line options -Opa+, -Opa- Bit values 0, 1 Constants 0xFF, ’A’
any valid file name
file [options]
Choice of mut ually exclus ive arguments; an OR selection
Represents code supplied by user
Device Dependent. This feature is not supported on all devices. Devices sup­ported will be listed in the title or text.
errorlevel {0|1}
var_name...] void main (void)
{ ... }
xmemory attribute
2012 Microchip Technology Inc. DS52071B-page 13
MPLAB® XC16 C Compiler User’s Guide

RECOMMENDED READING

This documentation describes how to use the MPLAB XC16 C Compiler. Other useful documents are listed below. The following Microchip documents are available and recommended as supplemental reference resources.
Release Notes (Readme Files)
For the latest information on Microchip tools, read the associated Release Notes (HTML files) included with the software.
MPLAB User’s Guide (DS51317)
A guide to using the 16-bit assembler, object linker, object archiver/librarian and various utilities.
16-Bit Language Tools Libraries (DS51456)
A descriptive listing of libraries available for Microchip 16-bit devices. This includes standard (including math) libraries and C compiler built-in functions. DSP and 16-bit peripheral libraries are described in Release Notes provided with each peripheral library type.
Device-Specific Documentation
The Microchip website contains many documents that describe 16-bit device functions and features. Among these are:
• Individual and family data sheets
• Family reference manuals
• Programmer’s reference manuals
C Standards Information
®
Assembler, Linker and Utilities for PIC24 MCUs and dsPIC® DSCs
American National Standard for Information Systems – Programming Language – C.
American National Standards Institute (ANSI), 11 West 42nd. Street, New York, New York, 10036.
This standard specifies the form and establishes the interpretation of programs expressed in the programming language C. Its purpose is to promote portability, reliability, maintainability and efficient execution of C language program s on a variety of computing systems.
C Reference Manuals
Harbison, Samuel P . and Steele, Guy L., C A Reference Manual, Fourth Edition,
Prentice-Hall, Englewood Cliffs, N.J. 07632.
Kernighan, Brian W. and Ritchie, Dennis M., The C Programming Language, Secon d
Edition. Prentice Hall, Englewood Cliffs, N.J. 07632.
Kochan, Steven G., Programming In ANSI C, Revised Edition. Hayden Books,
Indianapolis, Indiana 46268. Plauger, P.J., The Standard C Library, Prentice-Hall, Englewood Cliffs, N.J. 07632. Van Sickle, Ted., Programming Microcontrollers in C, First Edition. LLH Technology
Publishing, Eagle Rock, Virginia 24085.
DS52071B-page 14 2012 Microchip Technology Inc.

myMICROCHIP PERSONALIZED NOTIFICATION SERVICE

Microchip's personal notification service helps keep customers current on their
Microchip products of interest. Subscribers will receive e-mail notification whenever
there are changes, updates, revisions or errata related to a specified product family or
development tool.
Please visit http://www.microchip.com/pcn to begin the registration process and select
your preferences to receive personalized notifications. A FAQ and registration details
are available on the page, which can be opened by selecting the link above.
When you are selecting your preferences, choosing “Development Systems” will pop-
ulate the list with available development tools. The main categories of tools are listed
below:
Compilers – The latest info rmatio n on Microc hip C comp ilers, as semblers , linker s and other language tools. These include all MPLAB C compilers; all MPLAB assemblers (including MPASM™ assembler); all MPLAB linkers (including MPLINK™ object linker); and all MPLAB librarians (including MPLIB™ object librarian).
Emulators – The latest information on Microchip in-circuit emulators.These include the MPLAB REAL ICE™ and MPLAB ICE 2000 in-circuit emulators
In-Circuit Debuggers – The latest information on Microchip in-circuit debuggers. These include the MPLAB ICD 2 and 3 in-circuit debuggers and PICkit™ 2 and 3 debug express.
MPLAB the Windows source, cross-platform Integrated Development Environment. These lists focus on the IDE, Project Manager, Editor and Simulator, as well as general editing and debugging features.
Programmers – The latest information on Microchip programmers. These include the device (production) programmers MPLAB REAL ICE in-circuit emulator, MPLAB ICD 3 in-circuit debugger, MPLAB PM3 and development (nonproduction) programmers MPLAB ICD 2 in-circuit debugger, PICSTART and 3.
Starter/Demo Boards – These include MPLAB Starter Kit boards, PICDEM demo boards, and various other evaluation boards.
®
IDE/MPLAB X IDE – The latest information on Microchip MPLAB IDE,
®
Integrated Development Environment, or MPLAB X IDE, the open
Preface
®
Plus and PICkit 2

THE MICROCHIP WEB SITE

Microchip provides online support via our web site at http://www.microchip.com. This web site is used as a means to make files and information easily available to customers. Accessible by using your favorite Internet browser, the web site contains the following information:
Product Support – Data sheets and errata, application notes and sample programs, design resources, user’s guides and hardware support documents, latest software releases and archived software
General Technical Support – Frequently Asked Questions (FAQs), technical support requests, online discussion groups, Microchip consultant program member listing
Business of Microchip – Product selector and ordering guides, latest Microchip press releases, listing of seminars and events, listings of Microchip sales offices, distributors and factory representatives
2012 Microchip Technology Inc. DS52071B-page 15
MPLAB® XC16 C Compiler User’s Guide

MICROCHIP FORUMS

Microchip provides additional online support via our web forums at http://www.microchip.com/forums. Currently available forums are:
• Development Tools
•8-bit PIC MCUs
• 16-bit PIC MCUs
• 32-bit PIC MCUs

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. See our web site for a complete, up-to-date listing of sales offices.
Technical support is available through the web site at http://support.microchip.com. Documentation errors or comments may be emailed to docerrors@microchip.com.

DOCUMENT REVISION HISTORY

Revision A (April 2012)
Initial release of this document.
Revision B (July 2012)
Chapter 2. “Common C Interface” was added.
• Figure 3-1 "Software Development Tools Data Flow" was updated.
• Table 3-16 "Linking Options" now includes the -fill option.
• Added the -pack_upper_byte qualifier information in
Section 6.10.4 “__pack_upper_byte Type Qualifier” and Section 7.8 “Packing Data Stored in Flash”.
• Added DBRPAG/PSVP AG preservation bullet under Section 10.8 “Funct ion C all
Conventions”
• Fixed code syntax in Section 11.4 “Specifying the Interrupt Vector”.
• Fixed Eval Edition descri pti on unde r Chapter 15. “Optimizations”.
• Added "volatile" to SFR registers in Appendix F . “Built-in Functions”.
• Added built-in functions __builtin_write_CRYOTP and __builtin_write_NVM_secure in Appendix F. “Built-in Functions”.
DS52071B-page 16 2012 Microchip Technology Inc.

Chapter 1. Compiler Overview

1.1 INTRODUCTION

The MPLAB XC16 C compiler is defined and described in the following topics:
• Device Description
• Compiler Description and Documentation
• Compiler and Other Development Tools

1.2 DEVICE DESCRIPTION

The MPLAB XC16 C compiler fully supports all Microchip 16-bit devices:
®
• The dsPIC required in digital signal processor (DSP) applications with standard microcon­troller (MCU) features need ed for embedded app li cat ion s.
• The PIC24 family of MCUs are identical to the dsPIC DSCs with the exception that they do not have the digital signal controller module or that subset of instructions. They are a subset, and are high-performance MCUs intended for applications that do not require the power of the DSC capabilities.
family of digital signal controllers combines the high performance
MPLAB® XC16 C COMPILER
USER’S GUIDE

1.3 COMPILER DESCRIPTION AND DOCUMENTATION

The MPLAB XC16 C compiler is a full-featured, optimizing compiler that translates standard ANSI C programs into 16-bit device assembly language source. The compiler also supports many command-line options and language extensions that allow full access to the 16-bit device hardware capabilities, and affords fine control of the com­piler code generator.
The compiler is a port of the GNU Compiler Collection (GCC) compiler from the Free Software Foundation
This key features of the compiler are discussed in the following sections.

1.3.1 ANSI C Standard

The compiler is a fully validated compiler that conforms to the ANSI C standard as defined by the ANSI specification (ANSI x3.159-1989) and described in Kernighan and Ritchie’s The C Programming Language (second edition). The ANSI standard includes extensions to the original C definition that are now standard features of the language. These extensions enhance portability and offer increased capability. In addition, language extensions for dsPIC DSC embedded-control applications are included.

1.3.2 Optimization

The compiler uses a set of sophisticated optimization passes that employ many advanced techniques for generating efficient, compact code from C source. The optimization passes include high-level optimizations that are applicable to any C code, as well as 16-bit device-speci fic op timi zat ion s that take adva ntag e of the particular features of the device architecture.
For more on optimizations, see Chapter 15. “Optimizations”.
2012 Microchip Technology Inc. DS52071B-page 17
MPLAB® XC16 C Compiler User’s Guide

1.3.3 ANSI Standard Library Support

The compiler is distributed with a complete ANSI C standard library. All library functions have been validated, and conform to the ANSI C library standard. The library includes functions for string manipulation, dynamic memory allocation, data conversion, time­keeping and math functions (trigonometric, exponential and hyperbolic). The standard I/O functions for file handling are also included, and, as distributed, they support full access to the host file system using the command-line simulator. The fully functional source code for the low-level file I/O functions is provided in the compiler distribution, and may be used as a starting point for applications that require this capability.

1.3.4 Flexible Memory Models

The compiler supports both large and small code and data models. The small code model takes advantage of more efficient forms of call and branch instructions, while the small data model supports the use of compact instructions for accessing data in SFR space.
The compiler supports two models for accessing constant data. The “constants in data” model uses d ata memory, which is initiali ze d b y t h e ru n -t ime li brary. The “constants in code” model uses program memory, which is accessed through the Program Space Visibility (PSV) window.

1.3.5 Attributes and Qualifiers

The compiler keyword __attribute__ allows you to specify special attributes of variables, structure fields or functions. This keyword is followed by an attribute specification inside double parentheses, as in:
int last_mode __attribute__ ((persistent));
In other compilers, qualifiers are used to create qualified types:
persistent int last_mode;
The MPLAB XC16 C Compiler does have some non-standard qualifiers described in Section 6.10 “Compiler-Specific type Qualifiers”.
Generally speaking, qualifiers indicate how an object should be accessed, whereas attributes indicate where objects are to be located. Attributes also have many other purposes.

1.3.6 Compiler Driver

The compiler includes a powerful command-line driver program. Using the driver program, application programs can be compiled, assembled and linked in a single step.

1.3.7 Documentation

The compiler is supported under both the MPLAB IDE v8.xx and above, and the MPLAB X IDE. For simplicity, both IDEs are referred to throughout the book as simply MPLAB IDE.
Features that are unique to specific devices, and therefore specific compilers, are noted with a “DD” icon next to the section and text that identifies the specific devices to which the information applies (see the Preface).
DS52071B-page 18 2012 Microchip Technology Inc.

1.4 COMPILER AND OTHER DEVELOPMENT TOOLS

The compiler works with many other Microchip tools including:
• MPLAB XC16 Assembler and Linker - see the MPLAB Assembler, Linker and Util- ities for PIC24 MCUs and dsPIC DSCs User’s Guide (DS51317).
• MPLAB IDE v8.xx and MPLAB X IDE
• The MPLAB SIM Simulator and MPLAB X Simulator
• All Microchip debug tools and programmers
• Demonstration boards and Starter kits that support 16-bit devices
Compiler Overview
2012 Microchip Technology Inc. DS52071B-page 19
MPLAB® XC16 C Compiler User’s Guide
NOTES:
DS52071B-page 20 2012 Microchip Technology Inc.

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. If you intend to use the CCI, it is your responsibility to write code that conforms. Legacy proj­ects will need to be migrated to achieve conformance. A compiler option must also be set to ensure that the operation of the compiler is consistent with the interface when the project is built.
The following topics are examined in this chapter of the MPLAB XC16 C Compiler User’s Guide:
• ANSI Standard Extensions
• Using the CCI
• ANSI Standard Refinement
• ANSI Standard Extensions
MPLAB® XC16 C COMPILER
USER’S GUIDE

2.2 BACKGROUND – THE DESIRE FOR PORTABLE CODE

All programmers want to write portable source code. Portability means that the same source code can be compiled and run in a different
execution environment than that for which it was written. Rarely can code be one hun­dred percent portable, but the more tolerant it is to change, the less time and effort it takes to have it running in a new environment.
Embedded engineers typically think of code portability as being across target devices, but this is only part of the situation. The same code could be compiled for the same target but with a different compiler. Differences between those compilers might lead to the code failing at compile time or runtime, so this must be considered as well.
Y ou may only write code for one target device and only use one brand of compiler, but if there is no regulation of the compiler’s operation, simply updating your compiler version may change your code’s behavior.
Code must be portable across targets, tools, and time to be truly flexible. Clearly, this portability cannot be achieved by the programmer alone, since the com-
piler vendors can base their products on different technologies, implement different fea­tures and code syntax, or improve the way their product works. Many a great compiler optimization has broken many an unsuspecting project.
Standards for the C language have been developed to ensure that change is managed and code is more portable. The American National Standards Institute (ANSI) pub­lishes standards for many disciplines, including programming languages. The ANSI C Standard is a universally adopted standard for the C programming language.
2012 Microchip Technology Inc. DS52071B-page 21
MPLAB® XC16 C Compiler User’s Guide

2.2.1 The ANSI Standard

The ANSI C Standard has to reconcile two opposing goals: freedom for compilers ven­dors 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. Thus, for a compiler to conform to the standard, it must ensure that a conforming C program functions as described by the standard.
The standard describes implementation, the set of tools and the runtime environment on which the code will run. If any of these change, e.g., you build for, and run on, a dif­ferent target device, or if you update the version of the compiler you use to build, then you are using a different implementation.
The standard uses the term behavior to mean the external appearance or action of the program. It has nothing to do with how a program is encoded.
Since the standard is trying to achieve goals that could be construed as conflicting, some specifications appear somewhat vague. For example, the standard states that an int type must be able to hold at least a 16-bit value, but it does not go as far as saying what the size of an int actually is; and the action of right-shifting a signed integer can produce different results on different implementations; yet, these different results are still ANSI C compliant.
If the standard is too strict, device architectures may not allow the compiler to conform. But, if it is too weak, programmers would see wildly differing results within different compilers and architectures, and the standard would loose its effectiveness.
The standard organizes source code whose behavior is not fully defined into groups that include the following behaviors:
Implementation-defined behavior
This is unspecified behavior where each implementation documents how the choice is made.
Unspecified behavior The standard provides two or more possibilities and imposes no further requirements
on which possibility is chos en in any part ic ula r ins ta nc e. Undefined behavior This is behavior for which the standard imposes no requirements.
1
Code that strictly conforms to the standard does not produce output that is dependent on any unspecified, undefined, or implementation-defined behavior. The size of an int, which we used as an example earlier, falls into the category of behavior that is defined by implementation. That is to say, the size of an int is defined by which com­piler is being used, how that compiler is being used, and the device that is being tar­geted.
All the MPLAB XC compilers conform to the ANS X3.159-1989 Standard for program­ming languages (with the exception of the XC8 compiler’s inability to allow recursion, as mentioned in the footnote). This is commonly called the C89 Standard. Some fea­tures from the later standard, C99, are also supported.
1. Case in point: The mid-range PIC® microcontrollers do not have a data stack. Because a compiler
targeting this device cannot implement recursion, it (strictly speaking) cannot conform to the ANSI C Standard. This example illustrate a situation in which the standard is too strict for mid-range devices and tools.
DS52071B-page 22 2012 Microchip Technology Inc.
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 inter­rupts, as well as utilizing the often complex world of small-device memory architectures. This cannot be offered by the standard in a consistent way.
While the ANSI C Standard provides a mutual understanding for programmers and compiler vendors, programmers need to consider the implementation-defined behavior of their tools and the probability that they may need to use extensions to the C language that are non-standard. Both of these circumstances can have an impact on code por­tability.

2.2.2 The Common C Interface

The Common C Interface (CCI) supplements the ANSI C Standard and makes it easier for programmers to achieve consistent outcomes on all Microchip devices when using any of the MPLAB XC C compilers.
It delivers the following improvements, all designed with portability in mind.
Refinement of the ANSI C Standard The CCI documents specific behavior for some code in which actions are implemen-
tation-defined behavior under the ANSI C Standard. For example, the result of right-shifting a signed integer is fully defined by the CCI. Note that many implementation-defined items that closely couple with device characteristics, such as the size of an int, are not defined by the CCI.
Consistent syntax for non-standard extensions The CCI non-standard extensions are mostly implemented using keywords with a uni-
form syntax. They replace keywords, macros and attributes that are the native com­piler implementation. The interpretation of the keyword may differ across each com­piler, and any arguments to the keywords may be device specific.
Coding guidelines The CCI may indicate advice on how code should be written so that it can be ported
to other devices or compilers. While you may choose not to follow the advice, it will not conform to the CCI.
2012 Microchip Technology Inc. DS52071B-page 23
MPLAB® XC16 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.
Enable the CCI Select the MPLAB IDE widget Use CCI Syntax
command-line option that is equivalent. Include <xc.h> in every module
Some CCI features are only enabled if this header is seen by the compiler. Ensure ANSI compliance
Code that does not conform to the ANSI C Standard does not confirm to the CCI. Observe refinements to ANSI by the CCI
Some ANSI implementation-defined behavior is defined explicitly by the CCI. Use the CCI extensions to the language
Use the CCI extensions rather than the native language extensions
in your project, or use the
The next sections detail specific items associated with the CCI. These items are seg­regated into those that refine the standard, those that deal with the ANSI C Standard extensions, and other miscellaneous compiler options and usage. Guidelines are indi­cated with these item s.
If any implementation-defined behavior or any non-standard extension is not discussed in this document, then it is not part of the CCI. For example, GCC case ranges, label addresses and 24-bit short long types are not part of the CCI. Programs which use these features do not conform to the CCI. The compiler may issue a warning or error to indicate when you use a non-CCI feature and the CCI is enabled.
DS52071B-page 24 2012 Microchip Technology Inc.

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 immedi­ately followed by a line feed. Escaped characters may be used in character constants or string literals to represent extended characters not in the basic character set.
2.4.1.1 EXAMPLE
The following shows a string constant being defined that uses escaped characters.
const char myName[] = "Bj\370rk\n";
2.4.1.2 DIFFERENCES
All compilers have used this character set.
2.4.1.3 MIGRATION TO THE CCI
No action required.
Common C Interface

2.4.2 The Prototype for main

The prototype for the main() function is
int main(void);
2.4.2.1 EXAMPLE
The following shows an example of how main() might be defined
int main(void) {
while(1)
process();
}
2.4.2.2 DIFFERENCES
The 8-bit compilers used a void return type for this function.
2.4.2.3 MIGRATION TO THE CCI
Each program has one definition for the main() function. Confirm the return type for main() in all projects previously compiled for 8-bit targets.

2.4.3 Header File Specification

Header file specifications that use directory separators do not conform to the CCI.
2.4.3.1 EXAMPLE
The following example shows two confor mi ng incl ude dir ect ive s.
#include <usb_main.h> #include "global.h"
2012 Microchip Technology Inc. DS52071B-page 25
MPLAB® XC16 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 separa­tors “\” 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 directiv es that use di rectory sep arators in the header fil e specifica tions
should be changed. Remove all but the header file name in the directive. Add the direc­tory path to the compiler’s include search path or MPLAB IDE equivalent. This will force the compiler to search the directories specified with this option.
For example, the following code:
#include <inc/lcd.h>
should be changed to:
#include <lcd.h>
and the path to the inc directory added to the compiler’s header search path in your MPLAB IDE project properties, or on the command-line as follows:
-Ilcd

2.4.4 Include Search Paths

When you include a header file under the CCI, the file should be discoverable in the paths searched by the compiler detailed below.
For any header files specified in angle bracket delimiters < >, the search paths should be those specified by -I options (or the equivalent MPLAB IDE option), then the stan­dard compiler include directories. The -I options are searched in the order in which they are specified.
For any file specified in quote characters " ", the search paths should first be the cur­rent working directory . In the case of an MPLAB X project, the current working directory is the directory in which the C source file is located. If unsuccessful, the search paths should be the same directories searched when the header files is specified in angle bracket delimiters.
Any other options to specify search paths for header files do not conform to the CCI.
2.4.4.1 EXAMPLE If including a header file as in the following directive
#include "myGlobals.h"
The header file should be locatable in the current working directory, or the paths spec­ified by any -I options, or the standard compiler directories. If it is located elsewhere, this does not conform to the CCI.
2.4.4.2 DIFFERENCES The compiler operation under the CCI is not changed. This is purely a coding guide line.
2.4.4.3 MIGRATION TO THE CCI Remove any option that specifies header file search paths other than the -I option (or
the equivalent MPLAB IDE option), and use the -I option in place of this. Ensure the header file can be found in the directories specified in this section.
DS52071B-page 26 2012 Microchip Technology Inc.
Common C Interface

2.4.5 The number of Significant Initial Characters in an Identi fier

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 num­ber 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.
int stateOfPortBWhenTheOperatorHasSelectedAutomaticModeAndMotorIsRunningFast; int stateOfPortBWhenTheOperatorHasSelectedAutomaticModeAndMotorIsRunningSlow;
2.4.5.2 DIFFERENCES
Former 8-bit compilers used 31 significant characters by default, but an option allowed this to be extended.
The 16- and 32-bit compilers did not impose a limit on the number of significant char­acters.
2.4.5.3 MIGRATION TO THE CCI
No action required. You may take advantage of the less restrictive naming scheme.

2.4.6 Sizes of Types

The sizes of the basic C types, for example char, int and long, are not fully defined by the CCI. These types, by design, reflect the size of registers and other architectural features in the target device. They allow the device to efficiently access objects of this type. The ANSI C Standard does, however, indicate minimum requirements for these types, as specified in <limits.h>.
If you need fixed-size types in your project, use the types defined in <stdint.h>, e.g., uint8_t or int16_t. These types are consistently defined across all XC compilers, even outside of the CCI.
Essentially, the C language offers a choice of two groups of types: those that offer sizes and formats that are tailored to the device you are using; or those that have a fixed size, regardless of the target.
2.4.6.1 EXAMPLE
The following example shows the definition of a variable, native, whose size will allow efficient access on the target device; and a variable, fixed, whose size is cle a rl y i n di ­cated and remains fixed, even though it may not allow efficient access on every device.
int native; int16_t fixed;
2.4.6.2 DIFFERENCES
This is consistent with previous types implemented by the compiler.
2.4.6.3 MIGRATION TO THE CCI
If you require a C type that has a fixed size, regardless of the target device, use one of the types defined by <stdint.h>.
2012 Microchip Technology Inc. DS52071B-page 27
MPLAB® XC16 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 def­initions 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. The
-funsigned-char option on those compilers changed the default type to be unsigned char.
2.4.7.3 MIGRATION TO THE CCI Any definition of an object defined as a plain char and using the 16- or 32-bit compilers
needs review. Any plain char that was intended to be a signed quantity should be replaced with an explicit definition, for example.
signed char foobar;
You may use the -funsigned-char option on XC16/32 to change the type of plain char, but since this option is not supported on XC8, the code is not strictly conforming.

2.4.8 Signed Integer Representation

The value of a signed integer is determined by taking the two’s complement of the inte­ger.
2.4.8.1 EXAMPLE The following shows a variable, test, that is assigned the value -28 decimal.
signed char test = 0xE4;
2.4.8.2 DIFFERENCES All compilers have represented signed integers in the way described in this section.
2.4.8.3 MIGRATION TO THE CCI No action required.
DS52071B-page 28 2012 Microchip Technology Inc.
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.2 DIFFERENCES
All compilers have performed integer conversion in an identical fashion to that described in this section.
2.4.9.3 MIGRATION TO THE CCI
No action required.

2.4.10 Bit-wise Operations on Signed Values

Bitwise operations on signed values act on the two’s complement representation, including the sign bit. See also Section 2.4.11 “Right-shifting Signed Values”.
2.4.10.1 EXAMPLE
The following shows an example of a negative quantity involved in a bitwise AND oper­ation.
signed char output, input = -13; output = input & 0x7E;
Under the CCI, the value of output after the assignment will be 0x72.
2.4.10.2 DIFFERENCES
All compilers have performed bitwise operations in an identical fashion to that described in this section.
2.4.10.3 MIGRATION TO THE CCI
No action required.

2.4.11 Right-shifting Signed Values

Right-shifting a signed value will involve sign extension. This will preserve the sign of the original value.
2.4.11.1 EXAMPLE
The following shows an example of a negative quantity involved in a bitwise AND operation.
signed char input, output = -13; output = input >> 3;
Under the CCI, the value of output after the assignment will be -2 (i.e., the bit pattern 0xFE).
2012 Microchip Technology Inc. DS52071B-page 29
MPLAB® XC16 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 identi­fier to try to access the contents of another (whether any conversion is applied to the result) is implementation-defined behavior in the standard. In the CCI, no conversion is applied and the bytes of the union object are interpreted as an object of the type of the member being accessed, without regard for alignment or other possible invalid condi­tions.
2.4.12.1 EXAMPLE
The following shows an example of a union defining several members.
union {
signed char code; unsigned int data; float offset;
} foobar;
Code that attempts to extract offset by reading data is not guaranteed to read the correct value.
float result; result = foobbar.data;
2.4.12.2 DIFFERENCES
All compilers have not converted union members accessed via other members.
2.4.12.3 MIGRATION TO THE CCI
No action required.

2.4.13 Default Bit-field int Type

The type of a bit-field specified as a plain int will be identical to that of one defined using unsigned int. This is quite different to other objects where the types int, signed and signed int are synonymous. It is recommended that the signedness of the bit-field be explicitly stated in all bit-field definitions.
2.4.13.1 EXAMPLE
The following shows an example of a structure tag containing bit-fields which are unsigned integers and with the size specified.
struct OUTPUTS {
int direction :1; int parity :3; int value :4;
};
DS52071B-page 30 2012 Microchip Technology Inc.
Loading...
+ 308 hidden pages