Microchip Technology MPLAB XC32 C/C Compiler User guide

MPLAB
®
XC32 C/C++ Compiler
User’s Guide
2012 Microchip Technology Inc. DS51686E
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. 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.
ISBN: 978-1-62076-455-8
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
DS51686E-page 2 2012 Microchip Technology Inc.
MPLAB® XC32 C/C++ COMPILER
USER’S GUIDE
Table of Contents
Preface ...........................................................................................................................7
Chapter 1. Compiler Overview
1.1 Introduction ...................................................................................................13
1.2 Device De s cr ip t io n .............. ......................................................................... 13
1.3 Compiler Des c ription and Do cu mentation .............. .. ........................... .. ....... 1 3
1.4 Compiler and Other Development Tools ......................................................15
Chapter 2. Common C Interface
2.1 Introduction ...................................................................................................17
2.2 Background – The Desire for Portable Code ...............................................17
2.3 Using the CC I ............................................................................................... 20
2.4 ANSI Standard Refinement ..........................................................................21
2.5 ANSI Standard Extensions ...........................................................................29
2.6 Compiler Fe a tu r e s ................. .. .. ................................................................... 43
Chapter 3. Compiler Command Line D river
3.1 Introduction ...................................................................................................45
3.2 Invoking th e C o m p ile r ....... ............................................................................ 45
3.3 The C Compilation Sequence ......................................................................49
3.4 The C++ Compilation Sequence ..................................................................51
3.5 Runtime File s ............. ................................................................................. . 55
3.6 Start-up and In it ia li zation ..... .......................................... ............................... 5 8
3.7 Compiler Ou t p u t ......... .. ................................................................................ 58
3.8 Compiler Messages ......................................................................................60
3.9 Driver Option Descriptions ........................................................................... 60
Chapter 4. Device-Related Features
4.1 Introduction ...................................................................................................85
4.2 Device Support .............................................................................................85
4.3 Device Header Files .....................................................................................85
4.4 Stack . .......................................... ................................................................. 86
4.5 Using SFRs From C Code ...................................................................... .. .. ..88
Chapter 5. ANSI C Standard Issues
5.1 Divergence from the ANSI C Standard ................................ ........................91
5.2 Extensions to the ANSI C Standard .............................................................91
5.3 Implementation-defined behavior .................................................................92
Chapter 6. Supported Data Types and Variables
6.1 Introduction ...................................................................................................93
6.2 Identifiers ......................................................................................................93
2012 Microchip Technology Inc. DS51686E-page 3
MPLAB® XC32 C/C++ Compiler User’s Guide
6.3 Data Repre se ntation .................................................................................... 93
6.4 Integer Data Types ....................................................................................... 94
6.5 Floating- P o in t D a ta T ype s ............................ ... .. ........................................... 96
6.6 Structures and Unions ....................................................................... ........... 98
6.7 Pointer Typ e s . .. ............................. ............................................................. 100
6.8 Complex Data Types .................................................................................. 102
6.9 Constant Types and Formats .....................................................................102
6.10 Standard Type Qualifiers ................................................................. .. ....... 104
6.11 Compile r -S p e c ific Qualifiers ............... .. .......................................... .......... 10 5
6.12 Variab le A tt rib u t e s .............. .. ................ .................................................... 1 0 5
Chapter 7. Memory Allocation and Access
7.1 Introduction .................................................................................................109
7.2 Address Sp a ce s . ... ..................................................................................... 109
7.3 Variables in Da t a Memory .................... .. .................................................... 1 1 0
7.4 Auto Variable Allocation and Access .......................................................... 112
7.5 Variables in Pr o g ra m Me m o r y ... ....................................................... .......... 11 3
7.6 Variables in Re g is t e rs .... ............................................................................ 11 4
7.7 Dynamic Memory Allocation ....................................................................... 114
7.8 Memory Models ..........................................................................................114
Chapter 8. Operators and Statements
8.1 Introduction .................................................................................................117
8.2 Integral Pr o mo tion ............................................... ....................................... 11 7
8.3 Type Refere n c e s .............. ..................................................... .. .. ................. 118
8.4 Labels as Values ........................................................................................119
8.5 Conditional Operator Operands ................................................................. 120
8.6 Case Range s .. .. .............. .. .. .................................................................. .. ... . 120
Chapter 9. Register Usage
9.1 Introduction .................................................................................................121
9.2 Register U s a g e . .. ........................................................................................ 121
9.3 Register C o n v en t i on s ....................................................... ... .. ............. .. .. .... 121
Chapter 10. Functions
10.1 Writing F u nc t i on s ...................................................................................... 123
10.2 Function Attributes and Specifiers .... ........................................................123
10.3 Allocation of Function Code .....................................................................127
10.4 Changing the Default Function Allocation ................................................127
10.5 Functi o n Siz e Li m it s ..... ............................................................................ 12 8
10.6 Functi o n Para meters ................................................................................ 128
10.7 Function Return Values ............................................................................ 130
10.8 Calling F u nc t io n s ..................................................................... .. ... ............ 13 0
10.9 Inline F u nc t io n s ..... ............................................................................... ... . 130
Chapter 11. Interrupts
11.1 Introd uc t io n ..... .......................................................................................... 13 3
11.2 Interru p t O p e ra t io n .... ... .. .......................................................................... 133
DS51686E-page 4 2012 Microchip Technology Inc.
11.3 Writing an Interrupt Service Routine ........................................................134
11.4 Associating a Handler Function with an Exception Vector .......................139
11.5 Exception Handlers ..................................................................................141
11.6 Interru p t S e rv ic e R o ut in e C ontext Switching ................... ......................... 141
11.7 Latency ..................................................................................................... 142
11.8 Nestin g In te rr u p ts ......... .. ... ....................................................................... 1 4 2
11.9 Enabling/Disabling Interrupts ...................................................................142
11.10 ISR Considerations ................................................................................ 142
Chapter 12. Main, Runtime Start-up and Reset
12.1 Introd uc t io n ............................................................................................... 143
12.2 The Main Fun c tion ...... .. ............................................................................ 143
12.3 Runtime Start-up Code .............................................................................143
12.4 The On Res e t R o u tine ....... .. .. ................................................................... 157
Chapter 13. Library Routines
13.1 Using L ib rary Routines ........ .. ............. .. ... .......................... .. ... ............. .. .. . 159
Chapter 14. Mixing C/C++ and Assembly Language
14.1 Introd uc t io n ............................................................................................... 161
14.2 Using Inline Assembly Language .............................................................161
14.3 Predefined Assembly Macros ...................................................................164
Chapter 15. Optimizations
15.1 Introd uc t io n ............................................................................................... 167
Chapter 16. Preprocessing
16.1 Introd uc t io n ............................................................................................... 169
16.2 C/C++ Language Comments ............................. .. .......................... .. .........169
16.3 Prepro c e s so r Di re c tives ...... ........................................ .. .. ......................... 169
16.4 Pragma D ire c tives ............... .. ................................................................... 171
16.5 Predefined Macros ...................................................................................172
Chapter 17. Linking Programs
17.1 Introd uc t io n ............................................................................................... 175
17.2 Repla ci n g L ib rary Symbols ............................................................. ... .. ..... 1 7 5
17.3 Linker-Defined Symbols ...........................................................................175
17.4 Defau lt L in k e r Script ................................................................................. 176
Appendix 18. Implementation-Defined Behavior
18.1 Introd uc t io n ............................................................................................... 191
18.2 Highlig h t s ........... ....................................................................................... 191
18.3 Overv ie w ................ .. .. .............................................................................. 191
18.4 Translation ...................... ......... ....... ......... ........ ....... ......... ......... ......... ...... . 192
18.5 Enviro n me n t .................................................. ........................................... 192
18.6 Identifiers ..................................................................................................193
18.7 Chara c te rs .................... .. ... .................................................................... ... 193
18.8 Integers ....................................................................................................194
18.9 Floatin g - P o in t ........... .. .............................................................................. 194
18.10 Arrays and Pointers .......................................................... ......................196
2012 Microchip Technology Inc. DS51686 E-page 5
MPLAB® XC32 C/C++ Compiler User’s Guide
18.11 Hints ....................................................................................................... 196
18.12 Structures, Unions, Enumerations, and Bit fields ............................ ....... 197
18.13 Qualifiers ................................................................................................ 197
18.14 Declarators ............................................................................................. 198
18.15 Statements ............................................................................................. 198
18.16 Pre-Processing Directives ...................................................................... 198
18.17 Library Functions .................................................................................... 199
18.18 Architecture ............................................................................................ 202
Appendix 19. ASCII Character Set Appendix 20. Deprecated Features
20.1 Introd uc t io n ..... .......................................................................................... 20 5
20.2 Variables in Specified Registers ............................................................... 205
Glossary .....................................................................................................................207
Index ...........................................................................................................................225
Worldwide Sales and Service ...................................................................................238
DS51686E-page 6 2012 Microchip Technology Inc.
MPLAB® XC32 C/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.
MPLAB® XC32 C/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. DS51686E-page 7
MPLAB® XC32 C/C++ Compiler User’s Guide
DOCUMENT LAYOUT
This document describes how to use GNU language tools to write code for 32-bit applications. The document layout is as follows:
Chapter 1. Compiler Overview – describes the compiler, development tools and feature set.
Chapter 2. Common C Interface – explains what you need to know about making code portable.
Chapter 3. Compiler Command Line Driver – describes how to use the compiler from the command line.
Chapter 4. Device-R elated Feat ures – describes the compiler header and register definition files, as well as how to use with the SFRs.
Chapter 5. ANSI C Standard Issues – describes the differences between the C/C++ language supported by the compiler syntax and the standard ANSI-89 C.
Chapter 6. Supported Data Types and Variables – describes the compiler integer and pointer data types.
Chapter 7. Memory Alloca tion and Access – desc rib es 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. Register 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 Start-up and Reset – describes important elements of C/C++ code.
Chapter 13. Librar y Routines – explains how to use libraries.
Chapter 14. Mixing C/C++ and Assembly Language – provides guidelines for using the compiler with 32-bit assembly language modules.
Chapter 15. Optimizations – describes optimization options.
Chapter 16. Prep roce ssin g – details the preprocessing operation.
Chapter 17. Linkin g Prog rams – explains how linking works.
Appendix 18. Implementation-Defined Behavior – details compiler-specific parameters described as implementation-defined in the ANSI standard.
Appendix 19. ASCII Character Set” – contains the ASCII character set.
Appendix 20. Deprecated Features – details features that are considered obsolete.
DS51686E-page 8 2012 Microchip Technology Inc.
CONVENTIONS USED
DD
The following conventions may appear in this documentation:

DOCUMENTATION CONVENTIONS

Arial font:
Italic characters Referenced books MPLAB
Initial caps A window the Output window
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
Quotes A field name in a window or dia-
log
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
Italic Courier A variable argument file.o, where file can be
Square brackets [ ] Optional arguments
A menu path File>Save
A tab Click the Power tab
Filenames File paths Keywords Command-line option s Bit values Constants
“Save project before build”
#define START autoexec.bat c:\mcc18\h _asm, _endasm, static
-Opa+, -Opa­0, 1 0xFF, ’A’
any valid fi lename
mpasmwin [options] file [options]
Curly brackets and pipe character: { | }
Ellipses... Replaces repeated text
Choice of mut ually exclusive arguments; an OR selection
errorlevel {0|1}
var_name [, var_name...]
Represents code sup pli ed by user
void main (void) { ... }
Sidebar T e xt
Device Dependent. This feature is not sup po rted on all devices. Devices supported will be listed in the title or text.
2012 Microchip Technology Inc. DS51686 E-page 9
xmemory attribute
MPLAB® XC32 C/C++ Compiler User’s Guide
RECOMMENDED READING
This documentation describes how to use the MPLAB XC32 C/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
A guide to using the 32-bit assembler, object linker, object archiver/librarian and various utilities.
32-Bit Language Tools Libraries (DS51685)
Lists all library functions provided with the MPLAB XC32 C/C++ Compiler with detailed descriptions of their use.
Dinkum Compleat Libraries
The Dinkum Compleat Libraries are organized into a number of headers, files that you include in your program to declare or define library facilities. A link to the Dinkum librar­ies is available in the MPLAB X IDE application, on the My MPLAB X IDE tab, Refer­ences & Featured Links section.
PIC32MX Configuration Settings
Lists the Configuration Bit settings for the Microchip PIC32MX devices supported by the MPLAB XC32 C/C++ Compiler’s #pragma config.
Device-Specific Documentation
The Microchip website contains many documents that describe 32-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 PIC32 MCUs User’s Guide (DS51833)
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++ Standards Information
Stroustrup, Bjarne, C++ Programming Language: Special Edition, 3rd Edition.
Addison-Wesley Professional; Indianapolis, Indiana, 46240.
ISO/IEC 14882 C++ Standard. The ISO C++ Standard is standardized by ISO (The
International Standards Organization) in collaboration with ANSI (The American National Standards Institute), BSI (The British Standards Institute) and DIN (The German national standards organization).
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 programs on a variety of computing systems.
DS51686E-page 10 2012 Microchip Technology Inc.
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.
GCC Documents
http://gcc.gnu.org/onlinedocs/ http://sourceware.org/binutils/
myMICROCHIP PERSONALIZED NOTIFICATION SERVICE
Microchip's personal notification service helps keep customers current on their Micro­chip products of interest. Subscribers will receive e-mail notification whenever there are changes, updates, revisions or errata related to a specified product family or develop­ment 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 information on Microchip C/C++ compilers, assemblers,
linkers and other language tools. These include all MPLAB C/C++ compilers; all MPLAB assemblers (including MPASM™ assembler); all MPLAB linkers (includ­ing 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 IDE/MPLAB X IDE – The latest information on Microchip MPLAB IDE,
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.
®
Integrated Development Environment, or MPLAB X IDE, the open
Preface
®
Plus and PICkit 2
2012 Microchip Technology Inc. DS51686E-page 11
MPLAB® XC32 C/C++ Compiler User’s Guide
THE MICROCHI P 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 listin g
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
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
• 16-bit PIC MCUs
• 32-bit PIC MCUs
®
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 D (January 2012)
• Changed product name from MPLAB C32 C Compiler to MPLAB XC32 C/C++ Compiler. Completely reorganized document to align with other Microchip compiler documentation.
Revision E (July 2012)
• Added information pertaining to C++ throughout the document.
• Added new section describing the Common Compiler Interface (CCI) Standard
DS51686E-page 12 2012 Microchip Technology Inc.
MPLAB® XC32 C/C++ COMPILER

Chapter 1. Compiler Overview

1.1 INTRODUCTION

The MPLAB XC32 C/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 XC32 C/C++ Compiler fully supports all Microchip 32-bit devices.

1.3 COMPILER DESCRIPTION AND DOCUMENTATION

The MPLAB XC32 C/C++ Compiler is a full-featured, optimizing compiler that trans­lates standard ANSI C programs into 32-bit device assembly language source. The compiler also supports many command-line options and language extensions that allow full access to the 32-bit device hardware capabilities, and affords fine control of the compiler code generator.
The compiler is a port of the GCC compiler from the Free Software Foundation. The compiler is available for several popular operating systems, including 32 and 64-bit
Windows The compiler can run in one of three operating modes: Free, Standard or PRO. The
Standard and PRO operating modes are licensed modes and require an activation key and Internet connectivity to enable them. Free mode is available for unlicensed cus­tomers. The basic compiler operation, supported devices and available memory are identical across all modes. The modes only differ in the level of optimization employed by the compiler.
®
, Linux and Apple OS X.
USER’S GUIDE

1.3.1 Conventions

Throughout this manual, the term “the compiler” is often used. It can refer to either all, or some subset of, the collection of applications that form the MPLAB XC32 C/C++ Compiler. Often it is not important to know, for example, whether an action is performed by the parser or code generator application, and it is sufficient to say it was performed by “the compiler”.
It is also reasonable for “the compiler” to refer to the command-line driver (or just driver) as this is the application that is always executed to invoke the compilation process. The driver for the MPLAB XC32 C/C++ Compiler package is called xc32-gcc. The driver for the C/ASM projects is also xc32-gcc. The driver for C/C++/ASM projects is
xc32-g++. The drivers and their options are discussed in Section 3.9 “Driver Option Descriptions”. Following this view, “compiler options” should be considered com-
mand-line driver options, unless otherwise specified in this manual. Similarly “compilation” refers to all, or some part of, the steps involved in generating
source code into an executable binary image.
2012 Microchip Technology Inc. DS51686E-page 13
MPLAB® XC32 C/C++ Compiler User’s Guide

1.3.2 ANSI C Standards

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, lan­guage extensions for PIC32 MCU embedded-control applications are included.

1.3.3 Optimization

The compiler uses a set of sophisticated optimization passes that employ many advanced techniques for generating efficient, compact code from C/C++ source. The optimization passes include high-level optimizations that are applicable to any C/C++ code, as well as PIC32 MCU-specific optimizations that take advantage of the particu­lar features of the device architecture.
For more on optimizations, see Chapter 15. “Optimizations”.

1.3.4 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.5 ISO/IEC C++ Standard

The compiler is distributed with the 2003 Standard C++ Library.
Note: Do not specify an MPLAB XC32 system include directory (e.g.
/pic32mx/include/) in your project properties. The xc32-gcc and xc32-g++ compilation drivers automatically select the XC libc or the Din-
kumware libc and their respective include-file directory for you. Manually adding a system include file path may disrupt this mechanism and cause the incorrect libc include files to be compiled into your project, causing a conflict between the include files and the library. Note that adding a system include path to your project properties has never been a recommended practice.

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 C compiler is supported under both the MPLAB IDE v8.xx or higher, and the MPLAB X IDE. For C++, MPLAB X IDE v1.40 or higher is required. 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 “DD” text the column (see the Preface) and text identifying the devices to which the information applies.
DS51686E-page 14 2012 Microchip Technology Inc.

1.4 COMPILER AND OTHER DEVELOPMENT TOOLS

The compiler works with many other Microchip tools including:
• MPLAB XC32 assembler and linker - see the “MPLAB Utilities for PIC32 MCUs User’s Guide”.
• MPLAB IDE v8.xx and MPLAB X IDE (C++ required MPLAB X IDE v1.30 or higher)
• The MPLAB Simulator
• All Microchip debug tools and programmers
• Demo boards and starter kits that support 32-bit devices
Compiler Overview
®
Assembler, Linker and
2012 Microchip Technology Inc. DS51686E-page 15
MPLAB® XC32 C/C++ Compiler User’s Guide
NOTES:
DS51686E-page 16 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 PIC32 MCU using the MPLAB XC32 C/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:
• Background — The Desire for Portable Code
• Using the CCI
• ANSI Standard Refinement
• ANSI Standard Extensions
• Compiler Features
MPLAB® XC32 C/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 ver­sion 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. DS51686E-page 17
MPLAB® XC32 C/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 unspecifi ed beha vi or wh er e e ac h i mplem entation documents ho w th e c hoi ce 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. Becau s e
a compiler targetin g this dev ice c annot i mplemen t recurs ion, i t (str ictly speaking ) cann ot conform to the ANSI C Standard. This example illustrate a situation in which the stan­dard is too strict for mid-range devices and tools.
DS51686E-page 18 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 portability.

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 replac e keywords, mac ros and attr ibute s that are the nativ e com­piler implementation. The interp retati on of the keywor d may di ffer across each c om­piler, and any arguments to the keywords may be device specific.
Coding guidelines The CCI may indicate advice on ho w cod e sho uld be writte n so tha t it ca n be por te d
to other devices o r compil ers. Wh ile you may ch oose not to follow the advice , it will not conform to the CCI.
2012 Microchip Technology Inc. DS51686E-page 19
MPLAB® XC32 C/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.
DS51686E-page 20 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 immediately 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. DS51686E-page 21
MPLAB® XC32 C/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.
DS51686E-page 22 2012 Microchip Technology Inc.
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 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. DS51686E-page 23
MPLAB® XC32 C/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.

DS51686E-page 24 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 oper­ation.
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. DS51686E-page 25
MPLAB® XC32 C/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;
};
DS51686E-page 26 2012 Microchip Technology Inc.
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. If the inten-

tion was for these to be signed quantities, then the type of these should be changed to
signed int, for example, in:
struct WAYPT {
int log :3; int direction :4;
};
the bit-field type should be changed to signed int, as in:
struct WAYPT {
signed int log :3; signed int direction :4;
};

2.4.14 Bit-fields Straddling a Storage Unit Boundary

Whether a bit-field can straddle a storage unit boundary is implementation-defined behavior in the standard. In the CCI, bit-fields will not straddle a storage unit boundary; a new storage unit will be allocated to the structure, and padding bits will fill the gap.
Note that the size of a storage unit differs with each compiler as this is based on the size of the base data type (e.g., int) from which the bit-field type is derived. On 8-bit compilers this unit is 8-bits in size; for 16-bit compilers, it is 16 bits; and for 32-bit com­pilers, it is 32 bits in size.

2.4.14.1 EXAMPLE The following shows a structure containing bit-fields being defined.

struct { unsigned first : 6; unsigned second :6; } order;
Under the CCI and using XC8, the storage allocation unit is byte sized. The bit-field second, will be allocated a new storage unit since there are only 2 bits remaining in the first storage unit in which first is allocated. The size of this structure, order, will be 2 bytes.

2.4.14.2 DIFFERENCES This allocation is identical with that used by all previous compilers.

2.4.14.3 MIGRATION TO THE CCI No action required.

2.4.15 The Allocation Order of Bits-field

The memory ordering of bit-fields into their storage unit is not specified by the ANSI C Standard. In the CCI, the first bit defined will be the least significant bit of the storage unit in which it will be allocated.
2012 Microchip Technology Inc. DS51686E-page 27
MPLAB® XC32 C/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.2 DIFFERENCES

This is identical with the previous operation of all compilers.

2.4.15.3 MIGRATION TO THE CCI

No action required.

2.4.16 The NULL macro

The NULL macro is defined in <stddef.h>; however, its definition is implementa­tion-defined behavior. Under the CCI, the definition of NULL is the expression (0).

2.4.16.1 EXAMPLE

The following shows a pointer being assigned a null pointer constant via the NULL macro.
int * ip = NULL;
The value of NULL, (0), is implicitly cast to the destination type.

2.4.16.2 DIFFERENCES

The 32-bit compilers previously assigned NULL the expression ((void *)0).

2.4.16.3 MIGRATION TO THE CCI

No action required.

2.4.17 Floating-point sizes

Under the CCI, floating-point types must not be smaller than 32 bits in size.

2.4.17.1 EXAMPLE

The following shows the definition for outY, which will be at least 32-bit in size.
float outY;

2.4.17.2 DIFFERENCES

The 8-bit compilers have allowed the use of 24-bit float and double types.

2.4.17.3 MIGRATION TO THE CCI

When using 8-bit compilers, the float and double type will automatically be made 32 bits in size once the CCI mode is enabled. Review any source code that may have assumed a float or double type and may have been 24 bits in size.
No migration is required for other compilers.
DS51686E-page 28 2012 Microchip Technology Inc.

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 <xc.h> 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.1 EXAMPLE The following shows this header file being included, thus allowing conformance with the

CCI, as well as allowing access to SFRs.
#include <xc.h>

2.5.1.2 DIFFERENCES Some 8-bit compilers used <htc.h> as the equivalent header. Previous versions of

the 16- and 32-bit compilers used a variety of headers to do the same job.

2.5.1.3 MIGRATION TO THE CCI Change:

#include <htc.h>
used previously in 8-bit compiler code, or family-specific header files as in the following examples:
#include <p32xxxx.h> #include <p30fxxxx.h> #include <p33Fxxxx.h> #include <p24Fxxxx.h> #include "p30f6014.h"
to:
#include <xc.h>
Common C Interface

2.5.2 Absolute addressing

Variables and functions can be placed at an absolute address by using the __at() construct.qualifier Note that XC16/32 may require the variable or function to be placed in a special section for absolute addressing to work. Stack-based (auto and parame­ter) varia bles cannot use the __at() specifier.

2.5.2.1 EXAMPLE The following shows two variables and a function being made absolute.

int scanMode __at(0x200); const char keys[] __at(123) = { ’r’, ’s’, ’u’, ’d’};
int modify(int x) __at(0x1000) {
return x * 2 + 3;
}

2.5.2.2 DIFFERENCES The 8-bit compilers have used an @ symbol to specify an absolute address.

The 16- and 32-bit compilers have used the address attribute to specify an object’s address.
2012 Microchip Technology Inc. DS51686E-page 29
MPLAB® XC32 C/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.4 CAVEATS

If the __at() and __section() specifiers are both applied to an object when using XC8, the __section() specifier is currently ignored.

2.5.3 Far Objects and Functions

The __far qualifier may be used to indicate that variables or functions may be located in ‘far memory’. Exactly what constitutes far memory is dependent on the target device, but it is typically memory that requires more complex code to access. Expressions involving far-qualified objects may generate slower and larger code.
Use the native keywords discussed in the Differences section to look up information on the semantics of this qualifier.
Some devices may not have such memory implemented, in which case, use of this qualifier will be ignored. Stack-based (auto and parameter) variables cannot use the __far specifier.

2.5.3.1 EXAMPLE

The following shows a variable and function qualified using __far.
__far int serialNo; __far int ext_getCond(int selector);

2.5.3.2 DIFFERENCES

The 8-bit compilers have used the qualifier far to indicate this meaning. Functions could not be qualified as far.
The 16-bit compilers have used the far attribute with both variables and functions. The 32-bit compilers have used the far attribute with functions, only.
DS51686E-page 30 2012 Microchip Technology Inc.
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.4 Near Objects

The __near qualifier may be used to indicate that variables or functions may be located in ‘near memory’. Exactly what constitutes near memory is dependent on the target device, but it is typically memory that can be accessed with less complex code. Expressions involving near-qualified objects may be faster and result in smaller code.
Use the native keywords discussed in the Differences section to look up information on the semantics of this qualifier.
Some devices may not have such memory implemented, in which case, use of this qualifier will be ignored. Stack-based (auto and parameter) variables cannot use the __near specifier.

2.5.4.1 EXAMPLE The following shows a variable and function qualified using __near.

__near int serialNo; __near int ext_getCond(int selector);

2.5.4.2 DIFFERENCES The 8-bit compilers have used the qualifier near to indicate this meaning. Functions

could not be qualified as near. The 16-bit compilers have used the near attribute with both variables and functions. The 32-bit compilers have used the near attribute for functions, only.
2012 Microchip Technology Inc. DS51686E-page 31
MPLAB® XC32 C/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 fol-
lowing
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.5 Persistent Objects

The __persistent qualifier may be used to indicate that variables should not be cleared by the runtime startup code.
Use the native keywords discussed in the Differences section to look up information on the semantics of this qualifier.

2.5.5.1 EXAMPLE

The following shows a variable qualified using __persistent.
__persistent int serialNo;

2.5.5.2 DIFFERENCES

The 8-bit compilers have used the qualifier, persistent, to indicate this meaning. The 16- and 32-bit compilers have used the persistent attribute with variables to
indicate they were not to be cleared.

2.5.5.3 MIGRATION TO THE CCI

With 8-bit compilers, change any occurrence of the persistent qualifier, as in the fol­lowing example:
persistent
char template[20];
to __persistent, i.e., __persistent char template[20]; For the 16- and 32-bit compilers, change any occurrence of the persistent attribute,
as in the following
int tblIdx __attribute__ ((persistent));
to
int __persistent tblIdx;

2.5.5.4 CAVEATS

None.
DS51686E-page 32 2012 Microchip Technology Inc.
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 depen­dent 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.
Some devices may not have such memory implemented; in which case, use of these qualifiers will be ignored.

2.5.6.1 EXAMPLE The following shows a variable qualified using __xdata, as well as another variable

qualified with __ydata.
__xdata char data[16]; __ydata char coeffs[4];

2.5.6.2 DIFFERENCES The 16-bit compilers have used the xmemory and ymemory space attribute with

variables. Equivalent specifiers have never been defined for any other compiler.

2.5.6.3 MIGRATION TO THE CCI For 16-bit compilers, change any occurrence of the space attributes xmemory or

ymemory, as in the following example:
char __attribute__((space(xmemory)))template[20];
to __xdata, or __ydata, i.e., __xdata char template[20];

2.5.6.4 CAVEATS None.

2.5.7 Banked Data Objects

The __bank(num) qualifier may be used to indicate that variables may be located in a particular data memory bank. The number, num, represents the bank number. Exactly what constitutes banked memory is dependent on the target device, but it is typically a subdivision of data memory to allow for assembly instructions with a limited address width field.
Use the native keywords discussed in the Differences section to look up information on the semantics of these qualifiers.
Some devices may not have banked data memory implemented, in which case, use of this qualifier will be ignored. The number of data banks implemented will vary from one device to another.

2.5.7.1 EXAMPLE The following shows a variable qualified using __bank().

__bank(0) char start; __bank(5) char stop;
2012 Microchip Technology Inc. DS51686E-page 33
MPLAB® XC32 C/C++ Compiler User’s Guide

2.5.7.2 DIFFERENCES

The 8-bit co mpile rs hav e used the fo ur qua lifie rs 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.8 Alignment of Objects

The __align(alignment) specifier may be used to indicate that variables must be aligned on a memory address that is a multiple of the alignment specified. The align­ment term must be a power of two. Positive values request that the object’s start address be aligned; negative values imply the object’s end address be aligned.
Use the native keywords discussed in the Differences section to look up information on the semantics of this specifier.

2.5.8.1 EXAMPLE

The following shows variables qualified using __align() to ensure they end on an address that is a multiple of 8, and start on an address that is a multiple of 2, respectively.
__align(-8) int spacer; __align(2) char coeffs[6];

2.5.8.2 DIFFERENCES

An alignment feature has never been implemented on 8-bit compilers. The 16- and 32-bit compilers used the aligned attribute with variables.

2.5.8.3 MIGRATION TO THE CCI

For 16- and 32-bit compilers, change any occurrence of the aligned attribute, as in the following example:
char __attribute__((aligned(4)))mode;
to __align, i.e., __align(4) char mode;

2.5.8.4 CAVEATS

This feature is not yet implemented on XC8.
DS51686E-page 34 2012 Microchip Technology Inc.
Common C Interface

2.5.9 EEPROM Objects

The __eeprom qualif ier may be us ed to indi cate that variable s should be positio ned 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.

__eeprom int serialNos[4];

2.5.9.2 DIFFERENCES The 8-bit compilers have used the qualifier, eeprom, to indicate this meaning for some

devices. The 16-bit compilers have used the space attribute to allocate variables to the memory
space used for EEPROM.

2.5.9.3 MIGRATION TO THE CCI For 8-bit compilers, change any occurrence of the eeprom qualifier, as in the following

example:
eeprom
to __eeprom, i.e., __eeprom char title[20]; For 16-bit compilers, change any occurrence of the eedata space attribute, as in the
following
int mainSw __attribute__ ((space(eedata)));
to
int __eeprom mainSw;

2.5.9.4 CAVEATS XC8 does not implement the __eeprom qualifiers for any PIC18 devices; this qualifier

will work as expected for other 8-bit devices.
char title[20];

2.5.10 Interrupt Functions

The __interrupt(type) specifier may be used to indicate that a function is to act as an interrupt service routine. The type is a comma-separated list of keywords that indicate information about the interrupt function.
The current interrupt types are:
<empty> Implement the default interrupt function
low_priority The interrupt function co rresponds t o the low priority interrupt source ( XC8 – PIC18
only) high_priority
The interrupt function corresponds to the high priority interrupt source (XC8)
2012 Microchip Technology Inc. DS51686E-page 35
MPLAB® XC32 C/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 register and restore it on exit (XC16)
no_auto_psv The ISR will not set the PSVPAG register (XC16)
Use the native keywords discussed in the Differences section to look up information on the semantics of this specifier.
Some devices may not implement interrupts. Use of this qualifier for such devices will generate a warning. If the argument to the __interrupt specifier does not make sense for the target device, a warning or error will be issued by the compiler.

2.5.10.1 EXAMPLE

The following shows a function qualified using __interrupt.
__interrupt(low_priority) void getData(void) {
if (TMR0IE && TMR0IF) {
TMR0IF=0; ++tick_count;
}
}

2.5.10.2 DIFFERENCES

The 8-bit compilers have used the interrupt and low_priority qualifiers to indi­cate this meaning for some devices. Interrupt routines were by default high priority.
The 16- and 32-bit compilers have used the interrupt attribute to define interrupt functions.

2.5.10.3 MIGRATION TO THE CCI

For 8-bit compilers, change any occurrence of the interrupt qualifier, as in the following examples:
void interrupt myIsr(void) void interrupt low_priority myLoIsr(void)
to the following, respectively
void __interrupt(high_priority) myIsr(void) void __interrupt(low_priority) myLoIsr(void)
For 16-bit compilers, change any occurrence of the interrupt attribute, as in the fol­lowing example:
void __attribute__((interrupt,auto_psv,(irq(52)))) myIsr(void);
DS51686E-page 36 2012 Microchip Technology Inc.
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. Change code which uses the interrupt attri­bute, similar to these examples:
void __attribute__((vector(0), interrupt(IPL7AUTO), nomips16)) myisr0_7A(void) {}
void __attribute__((vector(1), interrupt(IPL6SRS), nomips16)) myisr1_6SRS(void) {}
/* Determine IPL and context-saving mode at runtime */ void __attribute__((vector(2), interrupt(), nomips16)) myisr2_RUNTIME(void) {}
to
void __interrupt(0,IPL7AUTO) myisr0_7A(void) {}
void __interrupt(1,IPL6SRS) myisr1_6SRS(void) {}
/* Determine IPL and context-saving mode at runtime */ void __interrupt(2) myisr2_RUNTIME(void) {}

2.5.10.4 CAVEATS None.

2.5.11 Packing Objects

The __pack specifier may be used to indicate that structures should not use memory gaps to align structure members, or that individual structure members should not be aligned.
Use the native keywords discussed in the Differences section to look up information on the semantics of this specifier.
Some compilers may not pad structures with alignment gaps for some devices and use of this specifier for such devices will be ignored.

2.5.11.1 EXAMPLE The following shows a structure qualified using __pack as well as a structure where

one member has been explicitly packed.
__pack struct DATAPOINT {
unsigned char type;
int value; } x-point; struct LINETYPE {
unsigned char type;
__pack int start;
long total; } line;

2.5.11.2 DIFFERENCES The __pack specifier is a new CCI specifier available with XC8. This specifier has no

apparent effect since the device memory is byte addressable for all data objects. The 16- and 32-bit compilers have used the packed attribute to indicate that a struc-
ture member was not aligned with a memory gap.
2012 Microchip Technology Inc. DS51686E-page 37
MPLAB® XC32 C/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.12 Indicating Antiquated Objects

The __deprecate specifier may be used to indicate that an object has limited longev­ity and should not be used in new designs. It is commonly used by the compiler vendor to indicate that compiler extensions or features may become obsolete, or that better features have been developed and which should be used in preference.
Use the native keywords discussed in the Differences section to look up information on the semantics of this specifier.

2.5.12.1 EXAMPLE The following shows a function which uses the __deprecate keyword.

void __deprecate getValue(int mode) { //... }

2.5.12.2 DIFFERENCES No deprecate feature was implemented on 8-bit compilers.

The 16- and 32-bit compilers have used the deprecated attribute (note different spell­ing) to indicate that objects should be avoided if possible.

2.5.12.3 MIGRATION TO THE CCI For 16- and 32-bit compilers, change any occurrence of the deprecated attribute, as

in the following example:
int __attribute__(deprecated) intMask;
to:
int __deprecate intMask;

2.5.12.4 CAVEATS None.

DS51686E-page 38 2012 Microchip Technology Inc.
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.1 EXAMPLE The following shows a variable which uses the __section keyword.

int __section("comSec") commonFlag;

2.5.13.2 DIFFERENCES The 8-bit compilers have used the #pragma psect directive to redirect objects to a

new section, or psect. The operation of the __section() specifier is different to this pragma in several ways, described below.
Unlike with the pragma, the new psect created with __section() does not inherit the flags of the psect in which the object would normally have been allocated. This means that the new psect can be linked in any memory area, including any data bank. The compiler will also make no assumptions about the location of the object in the new sec­tion. Objects redirected to new psects using the pragma must always be linked in the same memory area, albeit at any address in that area.
The __section() specifier allows objects that are initialized to be placed in a different psect. Initialization of the object will still be performed even in the new psect. This will require the automatic allocation of an additional psect (whose name will be the same as the new psect prefixed with the letter i), which will contain the initial values. The pragma cannot be used with objects that are initialized.
Objects allocated a different psect with __section() will be cleared by the runtime startup code, unlike objects which use the pragma.
Y ou must reserve memory, and locate via a linker option, for any new psect created with a __section() specifier in the current XC8 compiler implementation.
The 16- and 32-bit compilers have used the section attribute to indicate a different destination section name. The __section() specifier works in a similar way to the attribute.

2.5.13.3 MIGRATION TO THE CCI For XC8, change any occurrence of the #pragma psect directive, such as

#pragma psect text%%u=myText int getMode(int target) { //... }
to the __section() specifier, as in
int __section ("myText") getMode(int target) { //... }
For 16- and 32-bit compilers, change any occurrence of the section attribute, as in the following example:
int __attribute__((section("myVars"))) intMask;
to:
int __section("myVars") intMask;
2012 Microchip Technology Inc. DS51686E-page 39
MPLAB® XC32 C/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 #pragma config register = value
where setting is a configuration setting descriptor (e.g., WDT), state is a de scriptive value (e.g., ON) and value is a numerical value. The register token may represent a whole configuration word register, e.g., CONFIG1L.
Use the native keywords discussed in the Differences section to look up information on the semantics of this directive.

2.5.14.1 EXAMPLE The following shows configuration bits being specified using this pragma.

#pragma config WDT=ON, WDTPS = 0x1A

2.5.14.2 DIFFERENCES The 8-bit compilers have used the __CONFIG() macro for some targets that did not

already have support for the #pragma config. The 16-bit compilers have used a number of macros to specify the configuration set-
tings. The 32-bit compilers supported the use of #pragma config.

2.5.14.3 MIGRATION TO THE CCI For the 8-bit compilers, change any occurrence of the __CONFIG() macro, such as

__CONFIG(WDTEN & XT & DPROT)
to the #pragma config directive, as in
#pragma config WDTE=ON, FOSC=XT, CPD=ON
No migration is required if the #pragma config was already used. For the 16-bit compilers, change any occurrence of the _FOSC() or _FBORPOR()
macros attribute, as in the following example:
_FOSC(CSW_FSCM_ON & EC_PLL16);
to:
#pragma config FCKSMEM = CSW_ON_FSCM_ON, FPR = ECIO_PLL16
No migration is required for 32-b it code.

2.5.14.4 CAVEATS None.

DS51686E-page 40 2012 Microchip Technology Inc.
Common C Interface

2.5.15 Manifest Macros

The CCI defines the general form for macros that manifest the compiler and target device characteristics. These macros can be used to conditionally compile alternate source code based on the compiler or the target device.
The macros and macro families are details in Table 2-1.

TABLE 2-1: MANIFEST MACROS DEFINED BY THE CCI

Name Meaning if defined Example
__XC__ Compiled with an MPLAB XC compiler __XC__ __CCI__ Compiler is CCI compliant and CCI enforce-
ment is enabled
__XC##__ The specific XC co mp iler u sed (## c an be 8,
16 or 32) __DEVICEFAMILY__ The family of the selected target device __dsPIC30F__ __DEVICENAME__ The selected target device name __18F452__

2.5.15.1 EXAMPLE The following shows code which is conditionally compiled dependent on the device

having EEPROM memory.
#ifdef __XC16__ void __interrupt(__auto_psv__) myIsr(void) #else void __interrupt(low_priority) myIsr(void) #endif
__CCI__
__XC8__

2.5.15.2 DIFFERENCES Some of these CCI macros are new (for example __CCI__), and others have different

names to previous symbols with identical meaning (for example __18F452 is now __18F452__).

2.5.15.3 MIGRATION TO THE CCI Any code which uses compiler-defined macros will need review. Old macros will con-

tinue to work as expected, but they are not compliant with the CCI.

2.5.15.4 CAVEATS None.

2012 Microchip Technology Inc. DS51686E-page 41
MPLAB® XC32 C/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.

asm("MOVLW _foobar");

2.5.16.2 DIFFERENCES The 8-bit compilers have used either the asm() or #asm ... #endasm constructs to

insert in-line assembly code. This is the same syntax used by the 16- and 32-bit compilers.

2.5.16.3 MIGRATION TO THE CCI For 8-bit compilers change any instance of #asm ... #endasm so that each instruction

in this #asm block is placed in its own asm() statement, for example:
#asm
MOVLW 20 MOVWF _i CLRF Ii+1
#endasm
to
asm("MOVLW20"); asm("MOVWF _i"); asm("CLRFIi+1");
No migration is required for the 16- or 32-bit compilers.

2.5.16.4 CAVEATS None.

DS51686E-page 42 2012 Microchip Technology Inc.

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.
If you are not using this IDE, then the command-line options are --CCI for XC8 or
-mcci for XC16/32.

2.6.1.1 DIFFERENCES This option has never been implemented previously.

2.6.1.2 MIGRATION TO THE CCI Enable the option.

2.6.1.3 CAVEATS None.

Common C Interface
2012 Microchip Technology Inc. DS51686E-page 43
MPLAB® XC32 C/C++ Compiler User’s Guide
NOTES:
DS51686E-page 44 2012 Microchip Technology Inc.

Chapter 3. Compiler Command Line Driver

3.1 INTRODUCTION

The command line driver (xc32-gcc or xc32-g++) is the application that can be invoked to perform all aspects of compilation, including C/C++ code generation, assembly and link steps. Even if you use an IDE to assist with compilation, the IDE will ultimately call xc32-gcc for C projects or xc32-g++ for C++ projects.
Although the internal compiler applications can be called explicitly from the command line, using the xc32-gcc or xc32-g++ driver is the recommended way to use the compiler as it hides the complexity of all the internal applications used and provides a consistent interface for all compilation steps.
This chapter describes the steps the driver takes during compilation, files that the driver can accept and produce, as well as the command line options that control the com­piler’s operation. It also shows the relationship between these command line options and the controls in the MPLAB IDE Build Options
Topics concerning the command line use of the driver are discussed below.
• Invoking the Compiler
• The C Compilation Sequence
• The C++ Compilation Sequence
• Runtime Files
• Start-up and Initialization
• Compiler Output
• Compiler Messages
• Driver Option Descriptions
MPLAB® XC32 C/C++ COMPILER
USER’S GUIDE
dialog.

3.2 INVOKING THE COMPILER

The compiler is invoked and runs on the command line as specified in the next section. Additionally, environmental variables and input files used by the compiler are discussed in the following sections.

3.2.1 Driver Command Line Format

The compilation driver program (xc32-gcc) compiles, assembles and links C and assembly language modules and library archives. The xc32-g++ driver must be used when the module source is written in C++. Most of the compiler command line options are common to all implementations of the GCC toolset (MPLAB XC16 uses the GCC toolset; XC8 does not). A few are specific to the compiler.
The basic form of the compiler command line is:
xc32-gcc [options] files xc32-g++ [options] files
For example, to compile, assemble and link the C source file hello.c, creating the absolute executable hello.elf,execute this command:
xc32-gcc -o hello.elf hello.c
2012 Microchip Technology Inc. DS51686E-page 45
MPLAB® XC32 C/C++ Compiler User’s Guide
Or, to compile, assemble and link the C++ source file hello.cpp, creating the absolute executable hello.elf, execute:
xc32-g++ -o hello.elf hello.cpp
The available options are described in Section 3.9 “Driver Option Descriptions”. It is conventional to supply options (identified by a leading dash “-” before the filenames), although this is not mandatory.
The files may be any mixture of C/C++ and assembler source files, relocatable object files (.o) or archive files. The order of the files is important. It may affect the order in which code or data appears in memory or the search order for symbols. Typi­cally archive files are specified after source files. The file types are described in
Section 3.2.2 “Input File Types”.
Note: Command line options and file name extensions are case sensitive.
Libraries is a list of user-defined object code library files that will be searched by the linker, in addition to the standard C libraries. The order of these files will determine the order in which they are searched. They are typically placed after the source filenames, but this is not mandatory.
It is assumed in this manual that the compiler applications are either in the console’s search path, the appropriate environment variables have been specified, or the full path is specified when executing any application.
Environment Variables
The variables in this section are optional, but, if defined, they will be used by the compiler. The compiler driver, or other subprogram, may choose to determine an appropriate value for some of the following environment variables if they are not set. The driver, or other subprogram, takes advantage of internal knowledge about the installation of the compiler. As long as the installation structure remains intact, with all subdirectories and executables remaining in the same relative position, the driver or subprogram will be able to determine a usable value. The “XC32” variables should be used for new projects; however, the “PIC32” variables may be used for legacy projects.

TABLE 3-1: COMPILER-RELATED ENVIRONMENTAL VARIABLES

Option Definition
XC32_C_INCLUDE_PATH PIC32_C_INCLUDE_PATH
XC32_COMPILER_PATH PIC32_COMPILER_PATH
This variable’s val ue is a semicol on-separated list of directo ries , much like PATH. When the compiler searches for header files, it tries the directories listed in the variable, after the directories specified with -I but before the standard header file directories. If the environment variable is undefined, the preprocessor chooses an appro priate v alue bas ed on the st andard i nstal lation. By default, the following directories are searched for include files:
<install-path>\pic32mx\include
The value of PIC32_COMPILER_PATH is a semicolon-separated list of directories, much like PATH. The compiler tries the directo­ries thus specified when searching f or subprograms, if it can’t find the subprograms using PIC32_EXEC_PREFIX.
DS51686E-page 46 2012 Microchip Technology Inc.
Compiler Command Line Driver
TABLE 3-1: COMPILER-RELATED ENVIRONMENTAL VARIABLES
Option Definition
XC32_EXEC_PREFIX PIC32_EXEC_PREFIX
XC32_LIBRARY_PATH PIC32_LIBRARY_PATH
TMPDIR If TMPDIR is set, it specifies the directory to use for temporary
If PIC32_EXEC_PREFIX is set, it specifies a prefix to use in the names of subprograms executed by the compiler. No directory delimiter is added when this prefix is combined with the nam e of a subprogram, bu t you ca n speci fy a pr efix that ends with a slas h if you wish. If the comp il er cannot find the subprogram us ing the specified prefix, it tries looking in your PATH enviro nment variable. If the PIC32_EXEC_PREFIX environment variable is unset or set to an empty value, the compiler driver chooses an appropri­ate value based on the standard installation. If the installation has not been modified, this will result in the driver being able to locate the required subprograms. Other prefixes specified with the -B command line option take precedence over the user- or driver-defined value of PIC32_EXEC_PREFIX. Under normal circumstances it is best to leave this value unde­fined and let the driver locate subprograms itself.
This variable’s val ue is a semicol on-separated list of directo ries , much like passed to the linker. The driver’s default evaluation of this vari­able is: <install-path>\lib; <install-path>\pic32mx\lib.
files. The compiler uses tempora ry files to hold th e output of one stage of compilati on t hat is to be us ed as in put to the n ext st a ge: for example, the output of the preprocessor, which is the input to the compiler proper.
PATH. This variable specifies a list of direc tories to be
2012 Microchip Technology Inc. DS51686E-page 47
MPLAB® XC32 C/C++ Compiler User’s Guide

3.2.2 Input File Types

The compilation driver recognizes the following file extensions, which are case sensitive.

TABLE 3-2: FILE NAMES

Extensions Definition
file.c A C source file that must be preprocessed.
file.cpp A C++ source file that must be preprocessed.
file.h A header file (not to be compiled or linked). file.i A C source file that has already been pre-processed. file.o An object file.
file.ii A C++ source file that has already been pre-processed.
file.s An assembly language so urc e file. file.S An assembly language so urc e file that must be prep roc es sed .
other A file to be passed to the linker.
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 base name is the same as the base name 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. The terms “source file” and “module” are often used when talking about computer programs. They are often used interchangeably, but they refer to the source code at different points in the compilation sequence. A source file is a file that contains all or part of a program. They may contain C/C++ code, as well as preprocessor directives and commands. Source files are initially passed to the preprocessor by the driver.
A module is the output of the preprocessor, for a given source file, after inclusion of any header files (or other source files) which are specified by #include preprocessor directives. All preprocessor directives and commands (with the possible exception of some commands for debugging) have been removed from these files. These modules are then passed to the remainder of the compiler applications. Thus, a module may be the amalgamation of several source and header files. A module is also often referred to as a translation unit. These terms can also be applied to assembly files, as they too can include other header and source files.
DS51686E-page 48 2012 Microchip Technology Inc.
Compiler Command Line Driver

3.3 THE C COMPILATION SEQUENCE

3.3.1 Single-step C Compilation

A single command-line instruction can be used to compile one file or multiple files.

3.3.1.1 COMPILING A SINGLE C FILE This section demonstrates how to compile and link a single file. For the purpose of this

discussion, it is assumed the compiler's <install-dir>/bin directory has been added to your PATH variable. The following are other directories of note:
<install-dir>/pic32mx/include the directory for standard C header files.
<install-dir>/pic32mx/include/proc the directory for PIC32MX device-specific header files.
<install-dir>/pic32mx/lib the directory structure for standard libraries and start-up files.
<install-dir>/pic32mx/include/peripheral the directory for PIC32MX peripheral library include files.
<install-dir>/pic32mx/lib/proc the directory for device-specific linker script fragments, register definition files and configuration data may be found.
The following is a simple C program that adds two numbers. Create the following program with any text editor and save it as ex1.c.
#include <xc.h> #include <plib.h>
// Device-Specific Configuration-Bit settings // SYSCLK = 80 MHz (8MHz Crystal/ FPLLIDIV * FPLLMUL / FPLLODIV) // PBCLK = 40 MHz // Primary Osc w/PLL (XT+,HS+,EC+PLL) // WDT OFF // Other options are don't care // #pragma config FPLLMUL = MUL_20, FPLLIDIV = DIV_2, FPLLODIV = DIV_1, FWDTEN = OFF #pragma config POSCMOD = HS, FNOSC = PRIPLL, FPBDIV = DIV_8
unsigned int x, y, z;
unsigned int add(unsigned int a, unsigned int b) { return(a+b); }
int main(void) { /* Configure the target for maximum performance at 80 MHz. */ SYSTEMConfigPerformance(80000000UL); x = 2; y = 5; z = add(x,y); return 0; }
2012 Microchip Technology Inc. DS51686E-page 49
MPLAB® XC32 C/C++ Compiler User’s Guide
The first line of the program includes the header file xc.h, which provides definitions for all Special Function Registers (SFRs) on that part.
Compile the program by typing the following at the prompt:
xc32-gcc –mprocessor=32MX795F512L -o ex1.out ex1.c
The command line option -o ex1.out names the output executable file (if the -o option is not specified, then the output file is named a.out). The executable file may be loaded into MPLAB IDE.
If a hex file is required, for example, to load into a device programmer, then use the following command:
xc32-bin2hex ex1.out
This creates an Intel hex file named ex1.hex.

3.3.1.2 COMPILING MULTIPLE C FILES This section demonstrates how to compile and link multiple files in a single step. Move

the Add() function into a file called add.c to demonstrate the use of multiple files in an application. That is:
File 1
/* ex1.c */ #include <xc.h> #include <plib.h>
// Device-Specific Configuration-Bit settings // SYSCLK = 80 MHz (8MHz Crystal/ FPLLIDIV * FPLLMUL / FPLLODIV) // PBCLK = 40 MHz // Primary Osc w/PLL (XT+,HS+,EC+PLL) // WDT OFF // Other options are don't care // #pragma config FPLLMUL = MUL_20, FPLLIDIV = DIV_2, FPLLODIV = DIV_1, FWDTEN = OFF #pragma config POSCMOD = HS, FNOSC = PRIPLL, FPBDIV = DIV_8
int main(void); unsigned int add(unsigned int a, unsigned int b); unsigned int x, y, z; int main(void) { /* Configure the target for maximum performance at 80 MHz. */ SYSTEMConfigPerformance(80000000UL); x = 2; y = 5; z = Add(x,y); return 0; }
File 2
/* add.c */ #include <xc.h> unsigned int add(unsigned int a, unsigned int b) { return(a+b); }
DS51686E-page 50 2012 Microchip Technology Inc.
Compiler Command Line Driver
Compile both files by typing the following at the prompt:
xc32-gcc -mprocessor=32MX795F512L -o ex1.out ex1.c add.c
This command compiles the modules ex1.c and add.c. The compiled modules are linked with the compiler libraries and the executable file ex1.out is created.

3.3.2 Multi-step C 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.
If the compiler is being invoked using a make utility, the make file will need to be con­figured to use the intermediate files (.o files) and the options used to generate the intermediate files (-c, see Section 3.9.2 “Options for Controlling the Kind of Out- put”). Make utilities typically call the compiler multiple times: once for each source file to generate an intermediate file, and once to perform the second stage compilation.
For example, the files ex1.c and add.c are to be compiled using a make utility. The command lines that the make utility should use to compile these files might be something like:
xc32-gcc -mprocessor=32MX795F512L -c ex1.c xc32-gcc -mprocessor=32MX795F512L -c add.c xc32-gcc -mprocessor=32MX795F512L -o ex1.out ex1.o add.o

3.4 THE C++ COMPILATION SEQUENCE

3.4.1 Single-step C++ Compilation

A single command-line instruction can be used to compile one file or multiple files.

3.4.1.1 COMPILING A SINGLE C++ FILE

This section demonstrates how to compile and link a single file.
discussion, it is assumed the compiler's added to your PATH variable. The following are other directories of note:
<install-dir>/pic32mx/include/cpp the directory for standard C++ header files.
<install-dir>/pic32mx/include/proc the directory for PIC32MXdevice-sp ec ifi c head er files .
•<install-dir>/pic32mx/lib the directory structure for standard libraries and start-up files.
<install-dir>/pic32mx/include/peripheral the directory for PIC32 peripheral library include files.
<install-dir>/pic32mx/lib/proc the directory for device-specific linker script fragments, register definition files, and configuration data may be found.
For the purpose of this
<install-dir>/bin directory has been
2012 Microchip Technology Inc. DS51686E-page 51
MPLAB® XC32 C/C++ Compiler User’s Guide
The following is a simple C++ program. Create the following program with any plain-text editor and save it as ex2.cpp.
/* ex2.cpp */ #include <xc.h> // __XC_UART #include <plib.h> // SYSTEMConfigPerformance()
#include <iostream> #include <vector> #include <deque> #include <list> #include <set> #include <map> #include <string> #include <algorithm> #include <iterator> #include <functional> #include <numeric> using namespace std;
// Device-Specific Configuration-bit settings #pragma config FPLLMUL=MUL_20, FPLLIDIV=DIV_2, FPLLODIV=DIV_1, FWDTEN=OFF #pragma config POSCMOD=HS, FNOSC=PRIPLL, FPBDIV=DIV_8
template <class T> inline void print_elements (const T& coll, const char* optcstr="") { typename T::const_iterator pos;
std::cout << optcstr; for (pos=coll.begin(); pos!=coll.end(); ++pos) { std::cout << *pos << ' '; } std::cout << std::endl; }
template <class T> inline void insert_elements (T& coll, int first, int last) { for (int i=first; i<=last; ++i) { coll.insert(coll.end(),i); } }
int main(void) {
// Configure the target for max performance at 80 MHz. SYSTEMConfigPerformance (80000000UL);
// Direct stdout to UART 1 for use with the simulator __XC_UART = 1;
deque<int> coll; insert_elements(coll,1,9); insert_elements(coll,1,9);
print_elements(coll, "on entry: ");
DS51686E-page 52 2012 Microchip Technology Inc.
Compiler Command Line Driver
//sort elements sort (coll.begin(), coll.end());
print_elements(coll, "sorted: ");
//sorted reverse sort (coll.begin(), coll.end(), greater<int>());
print_elements(coll, "sorted >: ");
while(1); }
The first line of the program includes the header file xc.h, which provides definitions for all Special Function Registers (SFRs) on the target device. The second file of the program includes the header file plib.h, which provides the necessary prototypes for the peripheral library.
Compile the program by typing the following at a command prompt.
xc32-g++ -mprocessor=32MX795F512L -Wl,--defsym=_min_heap_size=0xF000
-o ex2.elf ex2.cpp
The option -o ex2.elf names the output executable file. This elf file may be loaded into MPLAB X IDE.
If a hex file is required, for example, to load into a device programmer, then use the following command
xc32-bin2hex ex2.elf
This creates an Intel hex file named ex2.hex.
2012 Microchip Technology Inc. DS51686E-page 53
MPLAB® XC32 C/C++ Compiler User’s Guide

3.4.2 Compiling Multiple C and C++ files

This section demonstrates how to compile and link multiple C and C++ files in a single step.
File 1
/* main.cpp */ #include <xc.h> // __XC_UART #include <plib.h> // SYSTEMConfigPerformance()
#include <iostream> using namespace std;
// Device-Specific Configuration-bit settings #pragma config FPLLMUL=MUL_20, FPLLIDIV=DIV_2, FPLLODIV=DIV_1, FWDTEN=OFF #pragma config POSCMOD=HS, FNOSC=PRIPLL, FPBDIV=DIV_8
// add() must have C linkage extern "C" { extern unsigned int add(unsigned int a, unsigned int b); }
int main(void) { int myvalue = 6;
// Configure the target for max performance at 80 MHz. SYSTEMConfigPerformance (80000000UL);
// Direct stdout to UART 1 for use with the simulator __XC_UART = 1;
std::cout << "original value: " << myvalue << endl; myvalue = add (myvalue, 3); std::cout << "new value: " << myvalue << endl;
while(1); }
File 2
/* ex3.c */ unsigned int add(unsigned int a, unsigned int b) { return(a+b); }
Compile both files by typing the following at the prompt:
xc32-g++ -mprocessor=32MX795F512L -o ex3.elf main.cpp ex3.c
The command compiles the modules main.cpp and ex3.c. The compiled modules are linked with the compiler libraries for C++ and the executable file ex3.elf is cre­ated.
Note: Use the xc32-g++ driver (as opposed to the xc32-gcc driver) in order to link
the project with the C++ support libraries necessary for the C++ source file in the project.
DS51686E-page 54 2012 Microchip Technology Inc.

3.5 RUNTIME FILES

In addition to the C/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/C++ Standard library routines
• Implicitly called arithmetic routines
• User-defined library routines
• The runtime start-up code

3.5.1 Library Files

The names of the C/C++ standard library files appropriate for the selected target device, and other driver options, are determined by the driver.
The target libraries, called multilibs, are built multiple times with a permuted set of options. When the compiler driver is called to compile and link an application, the driver chooses the version of the target library that has been built with the same options.
By default, the 32-bit language tools use the directory
<install-directory>/lib/gcc/ to store the specific libraries and the directory <install-directory>/<pic32mx>/lib to store the target-specific libraries. Both
of these directory structures contain subdirectories for each of the multilib combinations specified above. These subdirectories, respectively, are as follows:
1. .
2. ./size
3. ./speed
4. ./mips32
5. ./no-float
6. ./mips32/no-float
7. ./size/mips32
8. ./size/no-float
9. ./size/mips32/no-float
10../speed/mips32
11../speed/no-float
12../speed/mips32/no-float
The target libraries that are distributed with the compiler are built for the following options:
• Size versus speed (-Os vs. -O3)
• 16-bit versus 32-bit (-mips16 vs. -mno-mips16)
Compiler Command Line Driver
2012 Microchip Technology Inc. DS51686E-page 55
MPLAB® XC32 C/C++ Compiler User’s Guide
By default the 32-bit language tools compile for -O0, -mno-mips16, and
-msoft-float. Therefore, the options that we are concerned with are -Os or -O3,
-mips16, and -mno-float. Libraries built with the following command line options
are made available:
1. Default command line options
2. -Os
3. -O3
4. -mips16
5. -mno-float
6. -mips16 -mno-float
7. -Os -mips16
8. -Os -mno-float
9. -Os -mips16 -mno-float
10.-O3 -mips16
11.-O3 -mno-float
12.-O3 -mips16 -mno-float
The following examples provide details on which of the multilibs subdirectories are chosen.
1. xc32-gcc foo.c xc32-g++ foo.cpp
For this example, no command line options have been specified (i.e., the default command line options are being used). In this case, the .subdirectories are used.
2. xc32-gcc -Os foo.c xc32-g++ -Os foo.cpp
For this example, the command line option for optimizing for size has been specified (i.e., -Os is being used). In this case, the ./size subdirectories are used.
3. xc32-gcc -O2 foo.c xc32-g++ -O2 foo.cpp
For this example, the command line option for optimizing has been specified; however, this command line option optimizes for neither size nor space (i.e., -O2 is being used). In this case, the .subdirectories are used.
4. xc32-gcc -Os -mips16 foo.c xc32-g++ -Os -mips16 foo.cpp
For this example, the command line options for optimizing for size and for MIPS16 code have been specified (i.e., -Os and -mips16 are being used). In this case, the ./size/mips16 subdi recto ries are used.

3.5.1.1 STANDARD LIBRARIES

The C/C++ standard libraries contain a standardized collection of functions, such as string, math and input/output routines. The range of these functions are described in Chapter 13. “Libr ary Routi ne s”.
These libraries also contain C/C++ routines that are implicitly called by the output code of the code generator. These are routines that perform tasks such as floating-point operations and that may not directly correspond to a C/C++ function call in the source code.
DS51686E-page 56 2012 Microchip Technology Inc.
Compiler Command Line Driver

3.5.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.
User-created libraries that should be searched when building a project can be listed on the command line along with the source files.
As with Standard C/C++ library functions, any functions contained in user-defined libraries should have a declaration added to a header file. It is common practice to cre­ate one or more header files that are packaged with the library file. These header files can then be included into source code when required.

3.5.2 Peripheral Library Functions

Many of the peripherals of the PIC32MX devices are supported by the peripheral library functions provided with the compiler tools. See the “32-Bit Language Tools Libraries” (DS51685) for details on the functions provided.
2012 Microchip Technology Inc. DS51686E-page 57
MPLAB® XC32 C/C++ Compiler User’s Guide

3.6 START-UP AND INITIALIZATION

For C: There is only one start-up module, which initializes the C runtime environment.
The source code for this is found in <install-directory>/pic32-libs/libpi32c/startup/crt0.S and it is precompiled into the library <install-directory>/pic32mx/lib/crt0.o. Multilib versions of these modules exist in order to support architectural differences between device families.
For C++ Code from five object files link sequentially to create a single initialization routine, which
initializes the C++ runtime environment. The source code for this is found in
<install-directory>/pic32-libs/libpic32/startup. The PIC32 precompiled startup objects are located in
<install-directory>/pic32mx/lib/ and the filenames are cpprt0.o, crti.o, and crtn.o.
The GCC precompiled startup objects are located in <install-directory>/lib/gcc/pic32mx/<gcc-version>/ and the file­names are crtbegin.o and crtend.o. Multilib variations of these modules exist in order to support architectural differences between device families and also optimization settings.
For more information about what the code in these start-up modules actual does, see Section 12.3 “Runtime Start-up Code”.
:

3.7 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.

3.7.1 Output Files

The compilation driver can produce output files with the following extensions, which are case-sensitive.

TABLE 3-3: FILE NAMES

Extensions Definition
file.hex Executable file file.elf ELF debug file
file.o Object file (intermediate file) file.s Assembly code file (intermediate file) file.i Preprocessed C file (int ermediate file)
file.ii Preprocessed C++ file (intermediate file)
file.map Map file
The names of many output files use the same base name as the source file from which they were derived. Fo r examp le the sour ce file input.c will create an object file called input.o.
The main output file is an ELF file called a.out, unless you override that name using the -o option.
DS51686E-page 58 2012 Microchip Technology Inc.
Compiler Command Line Driver
If you are using an IDE, such as MPLAB IDE, to specify options to the compiler, there is typically a project file that is created for each application. The name of this project is used as the base name for project-wide output files, unless otherwise specified by the user. However check the manual for the IDE you are using for more details.
Note: Throughout this manual, the term project name will refer to the name of the
project created in the IDE.
The compiler is able to directly produce a number of the output file formats which are used by Microchip develop men t tools .
The default behavior of xc32-gcc and xc32-g++ is to produce an ELF output. T o make changes to the file’s output or the file names, see Section 3.9 “Driver Option
Descriptions”.

3.7.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 assembly list file contains the mapping between the original source code and the generated assembly code. It is useful for information such as how C source was encoded, or how assembly source may have been optimized. It is essential when con­firming if compiler-produced code that accesses objects is atomic, and shows the region in which all objects and code are placed.
The option to create a listing file in the assembler is -a (or -Wa,-a if passed to the driver). There are many variants to this option, which may be found in the “MPLAB Assembler, Linker and Utilities for PIC32 MCUs User’s Guide”(DS51833). To pass the option from the compiler, see Section 3.9.9 “Options for Assembling”.
There is one list file produced for each build. There is one assembler listing file for each
translation unit. This is a pre-link assembler listin g so it will not show final addresses.
Thus, if you require a list file for each source file, these files must be compiled sepa­rately, see Section 3.3.2 “Multi-step C Compilation”. This is the case if you build using MPLAB IDE. Each list file will be assigned the module name and extension .lst.
The map file shows in formatio n relati ng to wh ere obje cts were positio ned in me mory. It is useful for confirming that user-defined linker options were correctly processed, and for determining the exact placement of objects and functions.
The option to create a map file in the linker is -Map file (or -Wl,-Map=file if
passed to the driver), which may be found in the MPLAB Assembler, Linker and Utili­ties for PIC32 User’s Guide”. To pass the option from the compiler, see
Section 3.9.10 “Options for Linking”. There is one map file produced when you build a project, assuming the linker was
executed and ran to completion.
2012 Microchip Technology Inc. DS51686E-page 59
MPLAB® XC32 C/C++ Compiler User’s Guide

3.8 COMPILER MESSAGES

There are three types of messages. These are described below along with the compiler’s behavior when encountering a message of each type.
Warning Messages indicate source code or some other situation that can be
compiled, but is unusual and ma y le ad to a runtime failure of the c ode. Th e code or situation that triggered the warning should be investigated; however, compilation of the current module will contin ue, as will compilation of any remaining modules.
Error Messages indicate source code that is illegal or that compilation of this code
cannot take place. Compi lation will be attempted for the re maining source code in the current mod ule, but no ad dition al modu les wi ll be comp iled an d the compilation process will then conclude.
Fatal Error Messages i ndic ate a situa tion th at ca nnot a llow c ompi lation to proc eed
and which requires the compilation process to stop immediately.
For information on options that control compiler output of errors, warnings or comments, see Section 3.9.4 “Options for Controlling the C++ Dialect”.

3.9 DRIVER OPTION DESCRIPTIONS

All single letter options are identified by a leading dash character, “-”, e.g. -c. Some single letter options specify an additional data field which follows the option name immediately and without any whitespace, e.g. -Idir. Options are case sensitive, so
-c is a different option to -C.
The compiler has many options for controlling compilation, all of which are case sensitive.
• Options Specific to PIC32MX Devices
• Options for Controlling the Kind of Output
• Options for Controlling the C Dialect
• Options for Controlling the C++ Dialect
• Options for Debugging
• Options for Controlling Optimization
• Options for Controlling the Preprocessor
• Options for Assembling
• Options for Linking
• Options for Directory Search
• Options for Code Generation Conventions
DS51686E-page 60 2012 Microchip Technology Inc.
Compiler Command Line Driver
3.9.1 Options Specific to PIC32MX Devices
These options are specific to the device, not the compiler.

TABLE 3-4: PIC32MX DEVICE-SPECIFIC OPTIONS

Option Definition
-mprocessor
-mips16
-mno-mips16
-mno-float Do not use software floating-point libraries.
num Put global and static items less than or equal to num
-G
-membedded-data
-mno-embedded-data
-muninit-const-in-rodata
-mno-uninit-const-in-rodata
-mcheck-zero-division
-mno-check-zero-division
-mmemcpy
-mno-memcpy
-mlong-calls
-mno-long-calls
-mno-peripheral-libs -mno-peripheral-libs
-msmart-io=[0|1|2] This option attempt s to stat icall y analyz e format s trings
Selects the device for which to compile. (e.g., -mprocessor=32MX360F512L)
Generate (do not generate) MIPS16 code.
bytes into the small data or bss section instead of the normal data or bss section. This allows the data to be accessed using a single instruction. All modules shou ld be c ompiled with th e same value.
Allocate variables to the read-only data section first if possible, then ne xt in th e sma ll dat a se cti on if po ssibl e, otherwise in data. This gi ves slightly slower code than the default, but reduces the amount of RAM required when executing, and thus may be preferred for some embedded systems.
Put uninitialized const variables in the read-only data section. This option is only meaningful in conjunction with -membedded-data.
Trap (do not trap) on integer division by zero. The default is -mcheck-zero-division.
Force (do not force) the use of memcpy() for non-trivi al block moves. The default is -mno-memcpy, which allows GCC to inline most constant-sized copies.
Disable (do not disable) use of the jal instruction. Calling functions using jal is more efficient but requires the caller and callee to be in the same 256 megabyte segment. This option has no effect on abicalls code. The default is -mno-long-calls.
-G num
is now the default.
-mperipheral-libs is optional. By default, the peripheral libraries are lin ke d spec ifi ed via the device-spec ific linker script. peripheral libraries when linki ng .
passed to printf, scanf and the ‘f’ and ‘v’ variations of these functions. Uses of nonfloating-point format arguments will be converted to use an integer-only variation of the library function. For many app lic ati on s, this feature can reduce program-memory usage.
-msmart-io=0 disables this option, while
-msmart-io=2 causes the compiler to be optimistic
and convert function calls with variable or unknown format arguments. -msmart-io=1 is the default and will convert only when the compiler can prove that floating-point support is not required.
Do not use the standard
2012 Microchip Technology Inc. DS51686E-page 61
MPLAB® XC32 C/C++ Compiler User’s Guide
TABLE 3-4: PIC32MX DEVICE-SPECIFIC OPTIONS (CONTINUED)
Option Definition
-mappio-debug Enable the APPIN/APPOUT debugging library functions for the MPLAB REAL ICE™ in-circuit emulato r . This feature allows y ou to use the DBPRINTF and related functions and macros as described in the “32-bit Lan gua ge Tool Libraries” document (DS51685). Enable this option only when using a target PIC32 device that supports the APPIN/APPOUT feature.
-mcci Enables the Microchip Common C Interface compilation mode.
3.9.2 Options for Controlling the Kind of Output
The following options control the kind of output produced by the compiler.

TABLE 3-5: KIND-OF-OUTPUT CONTROL OPTIONS

Option Definition
-c Compile or assemble the source files, but do not link. The default file
extension is .o.
-E Stop after the preprocessing stage (i.e., before running the compiler
proper). The default output file is stdout.
-fexceptions Enable exception handling. You may need to enable this option when
compiling C code that needs to interoperate properly with exception handlers written in C++.
-o file Place the output in file.
-S Stop after compilation proper (i.e., before invoking the assembler). The
default output file extension is .s.
-v Print the commands executed during each stage of compilation.
-x You can specify the input language explicitly with the -x option:
language
-x
Specify explicitly the la nguage for the fol lowing inpu t files (rather than letting the compiler choose a default based on the file name suffix). This option applies to all following input files until the next -x option. The following values are supported by the compiler:
c c++ c-header cpp-output assembler assembler-with-cpp
®
ICD 3 debugger and M PLAB
-x none
Turn off any specification of a language, so that subsequent files are handled according to their file name suffixes. This is the default behavior but is needed if another -x option has been used. For example:
xc32-gcc -x assembler foo.asm bar.asm -x none main.c mabonga.s
Without the -x assembler.
--help Print a description of the command line options.
DS51686E-page 62 2012 Microchip Technology Inc.
none, the compiler assumes all the input files are for the
Compiler Command Line Driver
3.9.3 Options for Controlling the C Dialect
The following options define the kind of C dialect used by the compiler.

TABLE 3-6: C DIALECT CONTROL OPTIONS

Option Definition
-ansi Support all (and only) ANSI-standard C programs.
-aux-info filename Output to the given filename prototyped declarations for all
functions declared and/or defined in a translation unit, including those i n he ad er fi les . Th is opt ion is si lently ignored in any language other than C. Besides declarations, the file indicates, in comments, the origin of each declaration (source file and line), whether the declaration was implicit, prototyped or unprototyped (I, N for new or O for old, respectively, in the first character after the line number and the colon), and whether it came from a declaration or a definition (C or F, respectively, in the following character). In the case of function definitio ns, a K&R-style list of argume nts followed by their declarations is also provided, inside comments, after the declaration.
-fcheck-new /
-fno-check-new (default)
-fenforce-eh-specs (default) /
-fno-enforce-eh-specs
-ffreestanding Assert that compilation takes place in a freestanding
-fno-asm Do not recognize asm, inline or
-fno-builtin
-fno-builtin-function
-fno-exceptions Disable C++ exception handling. This option disables the
-fno-rtti Enable/Disable runtime type-identification features. The
Check that the pointer returned by operator new is non-null.
Generate/Do not generate code to check for violation of exception specifications at runtime. The
-fno-enforce-eh-specs option violates the C++ standard, but may be useful for reducing code size in production builds, much like defining `NDEBUG'. This does not give user code permission to throw exceptions in violation of the ex cepti on spe cific ations ; the c ompiler w ill s till optimize based on the specifications, so throwing an unexpected exception will result in undefined behavior.
environment. This implies -fno-builtin. A freestanding environment is one in which the standard library may not exist, and program start-up may not necessarily be at main. The most obvious example is an OS kernel. This is equivalent to -fno-hosted.
typeof as a keywor d, so
that code can use these words as identifiers. You can use the keywords __asm__, __inline__ and __typeof__ instead.
-ansi implies -fno-asm. Don’t recognize built-in functions that do not begin with
__builtin_ as prefix.
generation of extra code needed to propagate exceptions.
-fno-rtti option disables generation of information about every class with virtual functions for use by the C++ runtime type identification features ('dynamic_cast' and 'typeid'). If you don't use those parts of the language, you can save some space by using this flag. Note that exception handling uses the same information, but it will generate it as needed. The 'dynamic_cast' operator can still be used for casts that do not require run time typ e informa tion, i.e . cast s to or to unambiguous base classes.
void *
2012 Microchip Technology Inc. DS51686E-page 63
MPLAB® XC32 C/C++ Compiler User’s Guide
TABLE 3-6: C DIALECT CONTROL OPTIONS (CONTINUED)
Option Definition
-fsigned-char
-fsigned-bitfields
-funsigned-bitfields
-fno-signed-bitfields
-fno-unsigned-bitfields
-funsigned-char Let the type char be unsigned, like unsigned char.
-fwritable-strings Store strings in the writable data segment and do not make
3.9.4 Options for Controlling the C++ Dialect
The following options define the kind of C++ dialect used by the compiler.

TABLE 3-7: C++ DIALECT CONTROL OPTIONS

Option Definition
-ansi Support all (and only) ANSI-standard C++ programs.
-aux-info filename Output to the given filename prototyped declarations for all
-ffreestanding Assert that compilation takes place in a freestanding
-fno-asm Do not recognize asm, inline or
-fno-builtin
-fno-builtin-function
-fsigned-char Let the type char be signed, like signed char.
-fsigned-bitfields
-funsigned-bitfields
-fno-signed-bitfields
-fno-unsigned-bitfields
-funsigned-char Let the type char be unsigned, like unsigned char.
-fwritable-strings Store strings in the writable data segment and do not make
Let the type char be signed, like signed char .
(This is the default.)
These options control whether a bit field is signed or unsigned, when the declaration does not use either signed or unsigned. By default, such a bit field is signed, unless
-traditional is used, in which case bit fields are always unsigned.
them unique.
functions declared and/or defined in a translation unit, including those in h ead er f iles. This option is s ile ntl y i gno red in any language other than C++. Besides declarations, the file indicates, in comments, the origin of each declaration (source file and line), whether the declaration was implicit, prototyped or unprototyped (I, N for new or O for old, respectively, in the first character after the line number and the colon), and whether it came from a declaration or a definition (C or F, respectively, in the following character). In the case of function definiti ons, a K&R-style list of argum ents followed by their declaratio ns is also prov id ed, ins id e comments, after the declaration.
environment. This implies -fno-builtin. A freestanding environment is one in which the standard library may not exist, and program start-up may not necessarily be at main. The most obvious example is an OS kernel. This is equivalent to -fno-hosted.
typeof as a key word, so
that code can use these words as identifiers. You can use the keywords __asm__, __inline__ and __typeof__ instead.
-ansi implies -fno-asm. Don’t recognize built-in functions that do not begin with
__builtin_ as prefix.
(This is the default.)
These options control whether a bit field is signed or unsigned, when the declaration does not use either signed or unsigned. By default, such a bit field is signed, unless
-traditional is used, in which case bit fields are always unsigned.
them unique.
DS51686E-page 64 2012 Microchip Technology Inc.
Compiler Command Line Driver
3.9.5 Options for Controlling Warnings and Errors
Warnings are diagnostic messages that report constructions that are not inherently erroneous, but that are risky or suggest there may have been an error.
You can request many specific warnings with options beginning -W; for example,
-Wimplicit, to request warnings on implicit declarations. Each of these specific warning options also has a negative form beginning -Wno- to turn off warnings; for example, -Wno-implicit. This manual lists only one of the two forms, whichever is not the default.
The following options control the amount and kinds of warnings produced by the compiler.

TABLE 3-8: WARNING AND ERROR OPTIONS IMPLIED BY ALL WARNINGS

Option Definition
-fsyntax-only Check the code for syntax, but don’t do anything beyond that.
-pedantic Issue all the warnings demanded by strict ANSI C. Reject all
programs that use forbidden extensions.
-pedantic-errors Like -pedantic, except that errors are produced rather than warnings.
-w Inhibit all warning messages.
-Wall This enables all the warnings about constructions that some
users consider questionable, and that are easy to avoid (or modify to prevent the warning), even in conjunction with macros. Note that some warni ng flags a re not i mplied by -Wall. Some of them warn about constructions that users generally do not consider question abl e, but whi ch occa si ona ll y you might wish to check for; others wa rn abou t construc tions that ar e nece ssary or hard to avoid in some cases, and there is no simple way to modify the code to suppress the warning. Some of them are enabled by -Wextra but many of them must be enabled individually.
-Waddress Warn about suspicious uses of memory addresses. These include using the address of a function in a conditional expression , such as void func(void); if (func), and comparisons against the memory ad dress of a st ring lit eral, such as if (x == "abc"). Such uses typically indicate a program mer error: the address of a fun ction alw ays eval uates to true, so th eir use in a condit ion al us ual ly in dic ate s that the programmer forgot the parentheses in a function call; and comparisons against string literals result in unspecified behavior and are not portable in C, so they usually indicate that the programmer intended to use strcmp.
-Wchar-subscripts Warn if an array subscript has type char.
-Wcomment Warn whenever a comment-start sequence /* appears in a /*
comment, or whenever a Backslash-Newline appears in a // comment.
-Wdiv-by-zero Warn about compile-time integer division by zero. To inhibit the warning messages, use -Wno-div-by-zero. Floating-point division by zero is not warned about, as it can be a legitimate way of obtaining infinities and NaNs.
(This is the default.)
-Wformat Check calls to printf and scanf, etc., to make sure that the arguments supplied have types appropriate to the format string specified.
2012 Microchip Technology Inc. DS51686E-page 65
MPLAB® XC32 C/C++ Compiler User’s Guide
TABLE 3-8: WARNING AND ERROR OPTIONS IMPLIED BY ALL WARNINGS
Option Definition
-Wimplicit Equivalent to specifying both -Wimplicit-int and
-Wimplicit-function-declaration.
-Wimplicit-function­ declaration
-Wimplicit-int Warn when a declaration does not specify a type.
-Wmain Warn if the type of main is suspicious. main should be a
-Wmissing-braces Warn if an aggregate or union initializer is not fully bracketed. In
-Wno-multichar Warn if a multi-cha racter character constant is used. Usually,
-Wparentheses Warn if parentheses are omitted in certain contexts, such as
-Wreturn-type Warn whenever a function is defined with a return-type that
Give a warning whenever a function is used before being declared.
function with external linkage, returning two or three arguments of appropriate types.
the following example, the initializer for a is not fully bracketed, but that for b is fully bracketed.
int a[2][2] = { 0, 1, 2, 3 }; int b[2][2] = { { 0, 1 }, { 2, 3 } };
such constants are typographical errors. Since they have implementation-defined values, they should not be used in portable code. The following example illustrates the use of a multi-character character constant:
char xx(void) { return('xx'); }
when there is an assignment in a context where a truth value is expected, or when operators are nested whose precedence people often find confusing.
defaults to int. Also warn about any return-value in a function whose return-type is not void.
int, taking either zero,
return statement with no
DS51686E-page 66 2012 Microchip Technology Inc.
Compiler Command Line Driver
TABLE 3-8: WARNING AND ERROR OPTIONS IMPLIED BY ALL WARNINGS
Option Definition
-Wsequence-point Warn about code that may have undefined semantics because of violations of sequence point rules in the C standard. The C standard defines the order in which expressions in a C program are evaluated in terms of sequence points, which represent a partial ordering b etween t he executio n of pa rts of th e program: those executed before the sequence point and those executed after it. These occur after the evaluation of a full expression (one which is not part of a larger expression), after the evaluation of the first operand of a &&, ||, ? : or , (comma) operator , before a functi on is c alled (bu t after the eval uation of its arguments and the expre ssio n deno ting th e cal led fun ction ), and in certain other places. Other than as expressed by the sequence point rules, the orde r of evalu ati on of sube xp res si ons of an expression is not specified. All these rules describe only a partial order rather than a total order, since, for example, if two functions are called within one expression with no sequence point between them, the orde r in which the function s are called is not specified. However, the standards committee has ruled that function ca lls do not overlap. It is not specified when between sequence points modifications to the values of objects take effect. Programs whose behavior depends on this have undefined behavior. The C standard specifies that “Between the previous and next sequence point, an object shall have its stored value modified, at most once, by the evaluation of an expression. Furthermore, the prior value shall be read only to determine the value to be stored.” If a program breaks these rules, the results on any particular implementation are entirely unpredicta ble . Examples of code with undefined behavior are a = a++;, a[n] = b[n++] and a[i++] = i;. Some more complic ate d cases are not diagnosed by this option, and it may give an occasional false positive result, but in general it has been found fairly effective at detecting this sort of problem in programs.
-Wswitch Warn whenever a switch statement has an index of enumeral type and lacks a case f or one or more of the name d codes of that enumeration. (The presence of a default label prevents this warning.) case labels outside the enumeration range also provoke warnings when this option is used.
-Wsystem-headers Print warning messages for constructs found in system header files. Warnings from system headers are normally suppressed on the assumption that they usually do not indicate real problems and would only make the compiler output harder to read. Using this command line option tells the compiler to emit warnings from system headers as if they occurred in user code. However, note that using -Wall in conjunction with this option does not warn about unknown pragmas in system headers. For that, -Wunknown-pragmas must also be used.
-Wtrigraphs Warn if any trigraphs are encountered (assuming they are enabled).
2012 Microchip Technology Inc. DS51686E-page 67
MPLAB® XC32 C/C++ Compiler User’s Guide
TABLE 3-8: WARNING AND ERROR OPTIONS IMPLIED BY ALL WARNINGS
Option Definition
-Wuninitialized Warn if an automatic variable is used without first being initialized. These warnings are possi bl e only wh en op tim ization is enabled, because they require da ta flow informati on that is comp uted on ly when optimizing. These warnings occur only for variables that are candidates for register allocation. Therefore, they do not occur for a variable that is declared volatile, or whose a ddress is t ake n, or whose size is other than 1, 2, 4 or 8 bytes. Also, they do not occur for structures, unions or arrays, even when they are in registers. Note that there may be no warning about a variable that is used only to compute a value that itself is never used, because such computations may be deleted by data flow analysis before the warnings are printed.
-Wunknown-pragmas Warn when a #pragma directive is encountered which is not understood by the compiler. If this command line option is used, warnings will even be issued for unknown pragmas in system header files. This is not the case if the warnings were only enabled by the -Wall comm and line option.
-Wunused Warn whenever a variable is unused aside from its declaration, whenever a function is declared static but never defined, whenever a label is declared but not used, and whenever a statement computes a result that is explicitly not used. In order to get a warning about an unused function parameter, both -W and -Wunused must be specified. Casting an expression to void suppresses this warning for an expression. Similarly, the unused attribute suppresses this warning for unused variables, parameters and labels.
-Wunused-function Warn whenever a static function is declared but not defined or a non-inline static function is unused.
-Wunused-label Warn whenever a label is declared but not used. To suppress this warning, use the unused attribute.
-Wunused-parameter Warn whenever a function parameter is unused aside from its declaration. To suppress this warning, us e the unused attribute.
-Wunused-variable Warn wheneve r a local vari able or non-co nstant static va riable is unused aside from its declara tion. To suppress this warning, use the unused attribute.
-Wunused-value Warn whenever a statement computes a result that is explicitly not used. To suppress this warning, cast the expression to void.
The following -W options are not implied by -Wall. Some of them warn about constructions that users generally do not consider questionable, but which you might occasionally wish to check for. Others warn about constructions that are necessary or hard to avoid in some cases, and there is no simple way to modify the code to suppress the warning.
DS51686E-page 68 2012 Microchip Technology Inc.
Compiler Command Line Driver
TABLE 3-9: WARNING AND ERROR OPTIONS NOT IMPLIED BY ALL
WARNINGS
Option Definition
-W Print extra warning messages for these events:
• A nonvolatile automatic variable might be changed by a call to longjmp. These warnings are possible only in optimizing compilation. The compiler sees only the calls to setjmp. It cannot know where longjmp will be called. In fact, a signal handler could call it at any point in the code. As a result, a warning may be generated even when there is in fact no problem, because longjmp cannot in fact be called at the place that would cause a problem.
• A function could exit both via return return;. Completing the function body without passing any return statement is treated as return;.
• An expression-statement or the left-hand side of a comma expression contains no side effects. To suppress the warning, cast the unused expression to void. For example, an expression such as x[i,j] causes a warning, but x[(void)i,j] does not.
• An unsigned value is compared against zero with < or <=.
• A comparison like x<=y<=z appears, This is equivalent to (x<=y ? 1 : 0) <= z, which is a different interpretation from th at o f ordinary mathematical no t ati on.
• Storage-class specifier s like static are not the first things in a declaration. According to the C Standard, this usage is obsolescen t.
•If -Wall or -Wunused is also specified, warn about unused arguments.
• A comparison between signed and unsigned values could produce an incorrect result when the signed value is converted to unsigned. (But don’t warn if
-Wno-sign-compare is also specified.)
• An aggregate has a partly bracketed initializer. For example, the foll owing code wo uld evoke su ch a warning , because braces are missing around the initializer for
x.h: struct s { int f, g; };
struct t { struct s h; int i; }; struct t x = { 1, 2, 3 };
• An aggregate has an initializer that does not initialize all members. For example, the following code would cause such a warning, because x.h would be implicitly initialized to zero:
struct s { int f, g, h; }; struct s x = { 3, 4 };
-Waggregate-return Warn if any functions that return structures or unions are
defined or called.
-Wbad-function-cast Warn whenever a func tio n c al l is cast to a non-m atc hin g type. For example, warn if
-Wcast-align Warn whenever a pointer is cast, such that the required alignment of the target is increased. For example, warn if a
char * is cast to an
-Wcast-qual Warn whenever a pointer is cast, so as to remove a type
qualifier from the target type. For example, warn if a
const char * is cast to an ordinary char *.
int foof() is cast to anything *.
int *.
value; and
2012 Microchip Technology Inc. DS51686E-page 69
MPLAB® XC32 C/C++ Compiler User’s Guide
TABLE 3-9: WARNING AND ERROR OPTIONS NOT IMPLIED BY ALL
WARNINGS (CONTINUED)
Option Definition
-Wconversion Warn if a prototype causes a type conversion that is different from what would happen to the same argument in the absence of a prototype. This includes conversions of fixed point to floating and vice versa, and conversio ns changi ng the width or signedness of a fixed point argument, except when the same as the default promotion. Also, warn if a negative integer constant expression is implicitly converted to an unsigned type. For example, warn about the assignment x = -1 if x is unsigned. But do not warn about explicit casts like (unsigned) -1.
-Werror Make all warnings into errors.
-Winline Warn if a function can not be inlined, and either it was
declared as inline, or else the -finline-functions option was given.
-Wlarger-than-len Warn whenever an object of larger than len bytes is defined.
-Wlong-long
-Wno-long-long
-Wmissing-declarations Warn if a global function is defined without a previous
-Wmissing-
format-attribute
-Wmissing-noreturn Warn about functions that might be candidates for attribute
-Wmissing-prototypes Warn if a global function is defined without a previous
-Wnested-externs Warn if an extern declaration is encountered within a
-Wno-deprecated-
declarations
-Wpadded Warn if padding is included in a structure, either to align an
-Wpointer-arith Warn about anything that depends on the size of a function
-Wredundant-decls Warn if anything is declared more than once in the same
-Wshadow Warn whenever a local variable shadows another local
Warn if long long type is used. This is default. To inhibit the warning messages, use -Wno-long-long. Flags
-Wlong-long and -Wno-long-long are taken into account only when -pedantic flag is used.
declaration. Do so even if the definition itself provides a prototype.
If -Wformat is enabled, also warn about functions that might be candidates for format attributes. Note these are only possible candidates, not absolute ones. This option has no effect unless -Wformat is enabled.
noreturn. These are only possible candidates, not absolute ones. Care should be taken to manually verify functions. In fact, do not ever return befo re adding th e noreturn attribute , otherwise subtle code generation bugs could be introduced.
prototype declaration. This warning is issued even if the definition itse lf provide s a proto type. (Thi s option can be used to detect global functions that are not declared in header files.)
function. Do not warn about uses of functions, variables and types
marked as deprecated by using the deprecated attribut e.
element of t he structure or to align the whole structure.
type or of void. The compil er ass igns these t ypes a size o f 1, for convenience in calculations with void * pointers and pointers to functions.
scope, even in cases where multiple declaration is valid and changes not hing.
variable.
DS51686E-page 70 2012 Microchip Technology Inc.
Compiler Command Line Driver
TABLE 3-9: WARNING AND ERROR OPTIONS NOT IMPLIED BY ALL
WARNINGS (CONTINUED)
Option Definition
-Wsign-compare
-Wno-sign-compare
-Wstrict-prototypes Warn if a function is decla red or def ined withou t specify ing the
-Wtraditional Warn about certain constructs that behave differently in
-Wundef Warn if an undefined identifier is evaluated in an #if
-Wunreachable-code Warn if the compiler detects that code will never be exec uted.
-Wwrite-strings Give string const ants the ty pe const char[length] so that
Warn when a comparison between signed and unsigned values could produce an incorrect result when the signed value is converted to unsigned. This warning is also enabled by -W. To get the other warnings of -W without this warning, use -W -Wno-sign-compare.
argument types. (An old-style function definition is permitted without a warning if preced ed by a decla ration which specifies the argument types.)
traditional and ANSI C.
• Macro arguments occurring within string constants in the macro body. These would substitute the argument in traditional C, but are part of the constant in ANSI C.
• A function declared external in one block and then used after the end of the block.
• A switch statement has an operand of type long.
• A nonstatic function declar ati on fol lo ws a st atic one. This construct is not accepted by some traditional C compilers.
directive.
It is possible for this o pti on to produce a warni ng even though there are ci rcumstances under which part of the affected line can be executed, so care should be taken when removing apparently un reachable co de. For inst ance, when a function is inlined, a warning may mean that the line is unreachable in only one inlined copy of the function.
copying the address of one into a non-const char * pointer gets a warning. At co mp ile time, these warnings he lp you find code that you can try to write into a string constant, but only if you have been v ery care ful abou t using const in de claration s and prototypes. Otherwise, it’s just a nuisance, which is why
-Wall does not request these warnings.
2012 Microchip Technology Inc. DS51686E-page 71
MPLAB® XC32 C/C++ Compiler User’s Guide
3.9.6 Options for Debugging
The following options are used for debugging.

TABLE 3-10: DEBUGGING OPTIONS

Option Definition
-g Produce debugging informati on. The compiler support s the us e of -g with -O making it possible to debug optimized code. The shortcuts taken by optimized code may occasionally produce surprising results:
• Some declared variables may not exist at all
• Flow of control may briefly move unexpectedly
• Some statements may not be executed because they compute
constant results or their values were already at hand
• Some statements may execute in different places because they
were moved out of loops
Nevertheless it proves possible to debug optimized output. This makes it reasonable to use the optimizer for programs that might have bugs.
-Q Makes the compiler print out each function name as it is compiled, and print some statistics about each pass when it finishes.
-save-temps
-save-temps=cwd
-save-temps=obj Similar to -save-temps=cwd, but if the -o option is specified, the
Don’t delete intermediate files . Place them in the cur r ent dire ct ory and name them based on the source file. Thus, compiling foo.c with -c
-save-temps would produce the following files: foo.i (preprocessed file) foo.s (assembly language file) foo.o (object file)
temporary files are based on the object file. If the -o option is not specified, the -save-temps=obj switch behaves like –save-temps. For example:
xc32-gcc -save-temps=obj -c foo.c xc32-gcc -save-temps=obj -c bar.c -o dir/xbar.o xc32-gcc -save-temps=obj foobar.c -o dir2/yfoobar would create foo.i, foo.s, dir/xbar.i, dir/xbar.s, dir2/yfoobar.i, dir2/yfoobar.s, and dir2/yfoobar.o.
3.9.7 Options for Controlling Optimization
The following options control compiler optimizations.

TABLE 3-11: GENERAL OPTIMIZATION OPTIONS

Option Definition
-O0 Do not optimize. (This is the default.) Without -O, the compiler’s goal is to reduce the cost of compilation and to make debugging produce the expected res ults. S t atements are i ndependent: if y ou stop the program with a breakpoint between statements, you can then assign a new value to any variable or change the program counter to any other statement in the function and get exactly the results you would expect from the source code. The compiler only allocates variables declared register in registers.
-O
-O1
DS51686E-page 72 2012 Microchip Technology Inc.
Optimization level 1. Optimizing compilation takes somewhat longer, and a lot more host memory for a large function. With -O, the compiler tries to reduce code size and execution time. When -O is specified, the compiler turns on -fthread-jumps and
-fdefer-pop. The compiler turns on
-fomit-frame-pointer.
Compiler Command Line Driver
TABLE 3-11: GENERAL OPTIMIZATION OPTIONS (CONTINUED)
Option Definition
-O2 Optimization level 2. The compiler performs nearly all supported optimizations that do not involve a space-speed trade-off. -O2 turns on all optional optimizations except for loop unrolling (-funroll-loops), function inlining (-finline-functions), and strict aliasing optimizations (-fstrict-aliasing). It also turns on force copy of memory operands (-fforce-mem) and Frame Pointer elimin ation ( -fomit-frame-pointer). As compared to -O, this option i ncreases both com pilation time and the perfo rmance of the generated code.
-O3 Optimization level 3. -O3 turns on all optimizations specified by -O2 and also turns on the inline-functions option.
-Os Optimize for si ze. -Os ena bles all -O2 optimiza tions that do no t typica lly incre ase code size. It also performs further optimizations designed to reduce code size.
The following options control specific optimizations. The -O2 option turns on all of these optimizations except -funroll-loops, -funroll-all-loops and
-fstrict-aliasing. Y ou can use the following flags in the rare cases when “fine-tuning” of optimizations to
be performed is desired.

TABLE 3-12: SPECIFIC OPTIMIZATION OPTIONS

Option Definition
-falign-functions
-falign-functions= n
-falign-labels
-falign-labels=n
-falign-loops
-falign-loops=n
-fcaller-saves Enable values to be allocated i n registers that are clo bbered by
-fcse-follow-jumps In common subexpression elimination, scan through jump
Align the start of functions to the next power-of-two greater than n, skipping up to n bytes. For instance, -falign-functions=32 aligns functions to the next 32-byte boundary, but
-falign-functions=24 would align to the next 32-byte boundary only if this can be done by skipping 23 bytes or less.
-fno-align-functions and -falign-functions=1 are equivalent and mean that functions are not aligned. The assembler only su ppo rt s this flag when n is a power of two, so n is rounded up. If n is not specified, use a machine-dependent default.
Align all branch targets to a power-of-two boundary, skipping up to n bytes like -falign-functions. This option can easily make code slower , because it must insert dummy operati ons for when the branch target is reached in the usual flow of the code. If -falign-loops or -falign-jumps are applicable and are greater than this value, then their values are used instead. If n is not spec ified , use a m achin e-depen dent d efa ult whi ch i s ver y likely to be 1, meaning no alignment.
Align loops to a power-of-two boundary, skipping up to
-falign-functions. The hope is that the loop is executed many times, which makes up f or any exe cutio n of the dummy operati ons.
n is not specified, use a machine-dependent default.
If
function calls, by em itti ng ex tra ins truc tions to save and re sto r e t he registers around such calls. Such allocation is done only when it seems to result in better code than would otherwise be produced.
instructions when the t arget of the jump is not reac hed by any oth er path. For example, when CSE encou nters an if statement with an else clause, CSE follows the jump when the condition tested is false.
n bytes like
2012 Microchip Technology Inc. DS51686E-page 73
MPLAB® XC32 C/C++ Compiler User’s Guide
TABLE 3-12: SPECIFIC OPTIMIZATION OPTIONS (CONTINUED)
Option Definition
-fcse-skip-blocks This is similar to -fcse-follow-jumps, but causes CSE to follow jumps which conditionally skip over blocks. When CSE encounters a simple if stat em ent w ith no else clause,
-fcse-skip-blocks causes CSE to follow the jump around the body of the if.
-fexpensive-
optimizations
-ffunction-section
s
-fdata-sections
-fgcse Perform a global common subexpression elimination pass. This
-fgcse-lm When -fgcse-lm is enabled, global common subexpression
-fgcse-sm When -fgcse-sm is enabled, a store motion pass is run after
-fmove-all-movablesForces all invariant computations in loops to be moved outside the
-fno-defer-pop Always pop the arguments to each function call as soon as that
-fno-peephole
-fno-peephole2
-foptimize-
register-move
-fregmove
-freduce-all-givs Forces all general-induction variables in loops to be strength
-frename-registers Attempt to avoid false dependencies in scheduled code by making
-frerun-cse-after-
loop
-frerun-loop-opt Run the loop optimizer twice.
Perform a number of minor optimizations that are relatively expensive.
Place each function or data item into its own section in the output file. The name of the function or the name of the data item determines the section's name in the output file. Only use these opti ons when the re are sign ificant b enefits for doing so. When you specify these options, the assembler and linker may create larger object and executable files and is also slower.
pass also performs global constant and copy propagation.
elimination attempts to move loads which are only killed by stores into themselves. This allows a loop containing a load/store sequence to change to a load outside the loop, and a copy/store within the loop.
global common subexpression elimination. This pass attempts to move stores out of loops. When used in conjunction with
-fgcse-lm, loops cont aining a load /store sequenc e can change to a load before the loop and a store after the loop.
loop.
function returns. The comp iler norm ally let s argu ment s accum ulate on the stack for several function calls and pops them all at once.
Disable machine specific peephole optimizations. Peephole optimizations occur at various points during the compilation.
-fno-peephole disables peephole optimization on machine instructions, whi le -fno-peephole2 disables high leve l pe eph ole optimizations. To disable peephole entirely, use both options.
Attempt to reassign register numbers in move instructions and as operands of other simple instructions in order to maximize the amount of register tying.
-fregmove and -foptimize-register-moves are the same optimization.
reduced. These options may generate better or worse code. Results are highly dependent on the structure of loops within the source code.
use of registers left over after register allocation. This optimization most benefits processors with lots of registers. It can, however, make debugging impossible, since variables no longer stay in a “home register”.
Rerun common subexpression elimination after loop optimizations has been performed.
DS51686E-page 74 2012 Microchip Technology Inc.
Compiler Command Line Driver
TABLE 3-12: SPECIFIC OPTIMIZATION OPTIONS (CONTINUED)
Option Definition
-fschedule-insns Attempt to reorder instructions to eliminate instruction stalls due to required data being unavailable.
-fschedule-insns2 Similar to -fschedule-insns, but requests an ad dit ional p ass of instruction scheduling after register allocation has been done.
-fstrength-reduce Perform the optimizations of loop strength reduction and elimination of iteration variables.
-fstrict-aliasing Allows the compiler to assu me the s trictest aliasing rules a pplicable to the language being compiled. For C, this activates optimizations based on the type of expressions. In particular, an object of one type is assumed never to reside at the same add res s as an object of a different type, unless the types are almost the same. For example, an unsigned int can ali as an int, but not a void* or a double. A character type may alias any other type. Pay special attention to code like this:
union a_union { int i; double d; };
int f() { union a_union t; t.d = 3.0; return t.i; }
The practice of reading from a dif ferent un ion member than the one most recently written to (called “type-punning”) is common. Even with -fstrict-aliasing, type-punning is allowed, provided the memory is accessed through the union type. So, the code above works as expected. Howeve r, this code might not:
int f() { a_union t; int* ip; t.d = 3.0; ip = &t.i; return *ip; }
-fthread-jumps Perform optimizations where a check is made to see if a jump
branches to a lo cation whe re ano ther comp ariso n subsum ed by t he first is found. If so, the first branch is redirected to either the destination of the sec ond branc h or a point immed iately fol lowing it , depending on whether the condition is known to be true or false.
-funroll-loops Perform the optimization of loop unrolling. This is only done for loops whose number of iterations can be determined at compile time or run time. -funroll-loops implies both
-fstrength-reduce and -frerun-cse-after-loop.
-funroll-all-loops Perform the optimization of loop u nrol li ng. This is do ne for a ll l oo p s
and usually makes programs run more slowly.
-funroll-all-loops implies -fstrength-reduce, as well as
-frerun-cse-after-loop.
2012 Microchip Technology Inc. DS51686E-page 75
MPLAB® XC32 C/C++ Compiler User’s Guide
Options of the form -fflag specify machine-independent flags. Most flags have both positive and negative forms. The negative form of -ffoo would be -fno-foo. In the table below, only one of the forms is listed (the one that is not the default.)

TABLE 3-13: MACHINE-INDEPENDENT OPTIMIZATION OPTIONS

Option Definition
-fforce-mem Force memory operands to be copied into registers before doing arithmetic on them. This produces better code by making all memory re ferences pot ential comm on subexpressions. When they are not common subexpressions, in struction combinati on should elimi nate the separate register load. The -O2 option turns on this option.
-finline-functions Integrate all simple functions into their callers. The compiler heuristically decides whi ch fun cti ons are si mp le enough to be worth integrat in g in thi s way. If all calls to a given function ar e integrated, a nd the functi on is declared static, then the function is normally not output as assembler code in its own right.
-finline-limit=n By default, the compiler limits the size of functions that can be inlined. This flag allow s the contr ol of this limit for functions that are ex plici tly ma rked as inline (i.e., mar ked with the inline keyword). can be inlined in number of pseudo instructions (not counting parameter handling). The default value of n is
10000. Increasing this value can result in more inlined code at the cost of compilation time and memory consumption. Decreasing usually makes the compilation faster and less code is inlined (which presumably means slower programs). This opti on is particularly useful for pro gra ms that use inlining.
n is the size of functions that
Note: Pseudo instruction represents, in this particular context, an abstract measurement of function's size. In no way does it represent a count of assembly instructions and as such, its exact meaning might change from one release of the compiler to an another.
-fkeep-inline-functions Even if all calls to a given function ar e integrate d, and the function is declared static, output a separate run time callable version of the function. This switch does not affect extern inline functions.
-fkeep-static-consts Emit variables are declared static const when optimization isn't turned on, even if the variables are not referenced. The compiler enables this option by default. If you want to force the compiler to check if the variable was referenced, regardless of whether or not optimization is turned on, use the -fno-keep-static-consts option.
-fno-function-cse Do not put function addresses in registers. Make each instruction that calls a constant function contain the function's address explicitly. This option results in less efficient code, but some strange hacks that alter the assembler output may be confused by the optimizations performed when this option is not used.
DS51686E-page 76 2012 Microchip Technology Inc.
Compiler Command Line Driver
TABLE 3-13: MACHINE-INDEPENDENT OPTIMIZATION OPTIONS
Option Definition
-fno-inline Do not pay attention to th e inline keyword. Normally this option is used to keep the compiler from expanding any functions inline. If optimization is not enabled, no functions can be expanded inline.
-fomit-frame-pointer Do not keep the Frame Pointer in a register for functions that don't need one. This avoids the instructions to save, set up and restore Frame Pointers. It also makes an extra register available in many functions.
-foptimize-sibling-calls Optimize sibling and tail recursive calls.
2012 Microchip Technology Inc. DS51686E-page 77
MPLAB® XC32 C/C++ Compiler User’s Guide
3.9.8 Options for Controlling the Preprocessor
The following options control the compiler preprocessor.

TABLE 3-14: PREPROCESSOR OPTIONS

Option Definition
-C Tell the preprocessor not to discard comments. Used with the -E option.
-dD Tell the preprocessor to not remove macro definitions into the output, in their proper sequence.
-Dmacro Define macro macro with string 1 as its definition.
-Dmacro=defn Define macro macro as defn. All instances of -D on the command line are processed before any -U options.
-dM Tell the preprocessor to output only a list of the macro definitions that are in effect at the end of preprocessing. Used with the -E option.
-dN Like -dD except that the macro arguments and contents are omitted.
define name is included in the output.
Only #
-fno-show-column Do not print column numbers in diagnostics. This may be necessary if
diagnostics are being s canne d by a prog ram that do es not un derst and the column numbers, such as DejaGnu.
-H Print the name of each header file used, in addition to other normal activities.
-I- Any directories yo u spec ify with -I option s before th e -I- opti ons are searched only for the case of #include searched for #include If additional directories are specified with -I options after the -I-, these directories are searched for all #include direc tives . (Ordinarily all -I directories are used this way.) In addition, the -I- option inhibits the use of the current directory (where the current inp ut file came from) as the fi rst searc h dire ctory fo r
#include
With -I. you can specify searching the directory that was current when the compiler was invoked. That is not exactly the same as what the preprocessor does by default, but it is often satisfactory.
-I- does not inhibit the use of the standard system directories for header files. Thus, -I- and -nostdinc are indepe nde nt.
-Idir Add the directory dir to the head of the list of directories to be searched for header files. This can be used to override a system header file, substituting your own version, since these directories are searched before the system header file directories. If you use more than one -I option, the directories are scanned in left-to-right order. The standard system directories come after.
-idirafter dir Add the directory dir to the second include path. The directories on the second include path are searched when a header file is not found in any of the directories in the main include path (the one that -I adds to).
-imacros file Process file as input, discarding the resulting output, before processing the regular input file. Because the output generated from the file is dis car ded , th e o nly e ffect of -imacros file is to make the macros defined in file available for use in the main input. Any -D and -U options on the command line are always processed before -imacros written. All the -include and -imacros opt ions are p rocessed in the order in which they are written.
“file”. There is no way to override this effect of -I-.
<file>.
file, regardless of the order in which they are
“file”. They are not
DS51686E-page 78 2012 Microchip Technology Inc.
Compiler Command Line Driver
TABLE 3-14: PREPROCESSOR OPTIONS (CONTINUED)
Option Definition
-include file Process file as input before processing the regular input file. In effect, the contents of file are compiled first. Any command line are always processed before -include file, regardless of the order in which they are written. All the -include and -imacros options are processed in the order in which they are written.
-M Tell the preprocessor to output a rule suitable for dependencies of each object file. For each source file, the preprocessor outputs one make-rule whose target is the object file name for that source file and whose dependencies are all the #include header files it uses. This rule may be a single line or may be continued with \-newline if it is long. The list of rules is printed on standard output instead of the preprocessed C program.
-M implies -E (see Section 3.9.2 “Options for Controlling the Kind of Output”).
-MD Like -M but the dependency information is written to a file and compilation continues. The file containing the depe nde nc y i nformation is given the same name as the source file with a .d extension.
-MF file When used with -M or -MM, specifies a file in which to write the dependencies. If no -MF switch is given, the preprocessor sends the rules to the same place it would have sent preprocessed output. When used with the driver options, -MD or -MMD, -MF default dependency outp ut file .
-MG Treat missing header files as generated files and assume they live in the same directory as th e source file . If -MG is sp ecifi ed, th en ei ther -M or -MM must also be specified. -MG is not supported with -MD or -MMD.
-MM Like
-MMD Like -MD except mention only user header files, not system header
-MP This option instructs CPP to add a phony target for each dependency
-MQ Same as -MT, but it quotes any characters which are special to
-MT target Change the target of the rule emitted by dependency generation. By
-M but the output mentions only the user header files included
with #include <file> are omitted.
files.
other than the main file, causing each to depend on nothing. These dummy rules work around errors make gives if you remove header files without updating the make-file to match. This is typical output:
test.o: test.c test.h test.h:
-MQ '$(objpfx)foo.o'
The default target is automatically quoted, as if it were given with -MQ.
default, CPP takes the name of the mai n inp ut fil e, inc lu din g any p ath, deletes any file suffix such as .c, and appends the platform’s usual object suffix. The result is the target. An -MT option s ets th e ta rget to be exactly the str ing you s pecify. If you want multiple targets, you can specify them as a single argument to
-MT, or use multiple -MT options. For example:
-MT '$(objpfx)foo.o'
file”. System header files included with #include
gives $$(objpfx)foo.o: foo.c
might give $(objpfx)foo.o: foo.c
-D and -U options on the
make describing the
, overrides the
make.
2012 Microchip Technology Inc. DS51686E-page 79
MPLAB® XC32 C/C++ Compiler User’s Guide
TABLE 3-14: PREPROCESSOR OPTIONS (CONTINUED)
Option Definition
-nostdinc Do not search the standard system directories for header files. Only the directories you have specified with -I options (and the current directory, if appropriate) are searched. (See Section 3.9.11 “Options for Directory Search”) for information on -I. By using both -nostdinc and -I-, the include-file search path can be limited to only those directories explicitly specified.
-P Tell the preprocessor not to generate #line directives. Used with the
-E option (see Section 3.9.2 “Options for Controlling the Kind of
Output”).
-trigraphs Support ANSI C trigraphs. The -ansi option also has this effect.
-Umacro Undefine macro macro. -U options are evaluated after all -D options, but before any -include and -imacros options.
-undef Do not predefine any nonstandard macros (includin g architecture
flags).
DS51686E-page 80 2012 Microchip Technology Inc.
Compiler Command Line Driver
3.9.9 Options for Assembling
The following options control assembler operations.

TABLE 3-15: ASSEMBLY OPTIONS

Option Definition
-Wa,option Pass option as an option to the assembler. If option contains commas, it is split into multiple options at the commas.
3.9.10 Options for Linking
If any of the options -c, -S or -E are used, the linker is not run and object file names should not be used as arguments.

TABLE 3-16: LINKING OPTIONS

Option Definition
-fill=<options A memory-fill option to be passed on to the linker.
-Ldir Add directory dir to the list of directories to be searched for libraries
specified by the command line option -l.
-llibrary Search the library named library when linking.
The linker searches a s t an dard li st of d ire ctories for the library, which is actually a file named liblibrary.a. The lin ker then uses thi s file as if it had been specified precisely by name. It makes a difference where in the command you write this option. The linker processes libraries and object files in the order they are specified. Thus, foo.o -lz bar.o searches library z after file foo.o but before bar.o. If bar.o refers to functions in libz.a, those functions may not be loaded. The directories searched inc lu de sev eral standard system directories, plus any that you specify with -L. Normally the files found this way are library files (archive files whose members are object files). The linker handles an archive file by scanning through it for members which define symbols that have been referenced but not defined yet. But if the file found is an ordinary object file, it is linked in the usual fashion. The only difference between using an -l option (e.g., -lmylib) and specifying a file name (e.g., libmylib.a) is that -l searches several directories, as specified. By default the linker is directed to search:
<install-path>\lib
for libraries specified with the -l option. For a compiler installed into the default location, this would be:
Program Files\Microchip\mplab32\<version>\lib
This behavior can be overridden using the environment variables. See also the INPUT and OPTIONAL linker script directives.
-nodefaultlibs Do not use the standard system libraries when linking. Only the
libraries you specify are passed to the linker. The compiler may generate calls to memcmp, memset and memcpy. These entries are usually resolved by entries in the standard compiler libraries. These entry points should be supplied through some other mechanism when this option is specified.
-nostdlib Do not use the standard system start-up files or libraries when
linking. No start-up files and only the libraries you s pec ify a r e passed to the linker. The compiler may generate calls to memcmp, memset and memcpy. These entries are usually resolved by entries in standard compiler libraries. These entry points should be supplied through some other mechanism when this option is specified.
2012 Microchip Technology Inc. DS51686E-page 81
MPLAB® XC32 C/C++ Compiler User’s Guide
TABLE 3-16: LINKING OPTIONS (CONTINUED)
Option Definition
-s Remove all symbol table and relocation information from the executable.
-u symbol Pretend symbol is undefined to force linking of library modules to define the symbol. It is legitimate to use -u multiple times with different symbols to force loading of additional library modules.
-Wl,option Pass option as a n optio n to th e link er. If option contains commas, it is split into multiple options at the commas.
-Xlinker option Pass option as an option to the linker. You can use this to supply system-specific linker op tions tha t the comp iler do es not kno w how to recognize.
3.9.11 Options for Directory Search
The following options specify to the compiler where to find directories and files to search.

TABLE 3-17: DIRECTORY SEARCH OPTIONS

Option Definition
-Bprefix This option specifies where to find the executables, libraries,
include files and data files of the compiler itself. The compiler driver program runs one or more of the sub-programs xc32-cpp, xc32-as and xc32-ld. It tries prefix as a prefix for each program it tries to run. For each sub-program to be run, the compiler driver first tries the
-B prefix, if any. Lastly, the driver searches the current PATH environment variable for the subprogram.
-B prefixes that effectively specify directory names also apply to libraries in the linker, because the compiler translates these options into -L options for the linker. They also apply to include files in the preprocessor, because the compiler translates these options into -isystem options for the preprocessor. In this case, the compiler appends include to the prefix.
-specs=file Process file after the compiler reads in the standard specs file, in
order to override the defaults that the xc32-gcc driver program uses when determining what switches to pass to xc32-as, xc32-ld, etc. More than one -specs=file can be specified on the command line, and they are processed in order, from left to right.
DS51686E-page 82 2012 Microchip Technology Inc.
Compiler Command Line Driver
3.9.12 Options for Code Generation Conventions
Options of the form -fflag specify machine-independent flags. Most flags have both positive and negative forms. The negative form of -ffoo would be -fno-foo. In the table below, only one of the forms is listed (the one that is not the default).

TABLE 3-18: CODE GENERATION CONVENTION OPTIONS

Option Definition
-fargument-alias
-fargument-noalias
-fargument­ noalias-global
-fcall-saved-reg Treat the register named reg as an allocatable register saved by
-fcall-used-reg Treat the register named reg as an allocatable register that is
-ffixed-reg Treat the register named reg as a fixed register. Generated code
Specif y the poss ible relations hips among p arameters and b etween parameters and global data.
-fargument-alias specifies that arguments (para m eters) may alias each other and may alias global storage.
-fargument-noalias specifies that arguments do not alias each other, but may alias global storage.
-fargument-noalias-global specifies th at a r gum en t s do n ot alias each other and do not alias global storage. Each language automatically uses whatever option is required by the language standard. You should not need to use these options yourself.
functions. It may be allocated even for temporaries or variables that live across a call. Functions compiled this way saves and restores the register reg if they use it. It is an error to use this flag with the Frame Pointer or Stack Pointer. Use of this flag for other registers that have fixed pervasive roles in the m achine’s execu tion model produces disastrous results. A different sort of disaster results from the use of this flag for a register in which function values are returned. This flag should be used consistently through all modules.
clobbered by function calls. It may be allocated for temporaries or variables that do not live across a cal l. Functions com piled this wa y do not save and restore the register reg. It is an error to use this flag with the Frame Pointer or Stack Pointer. Use of this flag for other registers that have fixed pervasive roles in the m achine’s execu tion model produces disastrous results. This flag should be used consistently through all modules.
should never refer to it (except perhaps as a Stack Pointer, Frame Pointer or in some other fixed role). reg must be the name of a register (e.g., -ffixed-$0).
2012 Microchip Technology Inc. DS51686E-page 83
MPLAB® XC32 C/C++ Compiler User’s Guide
TABLE 3-18: CODE GENERATION CONVENTION OPTIONS (CONTINUED)
Option Definition
-finstrument-
functions
-fno-ident Ignore the #ident directive.
-fpack-struct Pack all structure members together without holes. Usually you
-fpcc-struct-
return
-fno-short-double By default, the c om pil er u ses a double type equivalent to float.
-fshort-enums Allocate to an enum type only as many bytes as it needs for the
-fverbose-asm
-fno-verbose-asm
-fvolatile Consider all memory references through pointers to be volatile.
-fvolatile-global Consider all memory references to external and global data items
-fvolatile-static Consider all memory references to static data to be volatile.
Generate instrumentation calls for entry and exit to functions. Just after function entry and just before function exit, the following profiling functions are called with the address of the current function and its call site.
void __cyg_profile_func_enter (void *this_fn, void *call_site); void __cyg_profile_func_exit (void *this_fn, void *call_site);
The first argument is the address of the start of the current function, which may be looked up exactly in the symbol table. The profiling functions should be provided by the user. Function instrumentation requires the use of a Frame Pointer. Some optimization levels disable the use of the Frame Pointer. Using -fno-omit-frame-pointer prevents this. This instrumentation is also done for functions expanded inline in other functions. The profiling calls indicates where, conceptually, the inline function is entered and exited. This means that addressable versions of such functions must be available. If all your uses of a function are expanded inline, this may mean an additional expansion of code size. If you use extern inline in your C code, an addressable version of such functions must be provided. A function may be given the attribute
no_instrument_function, in which case this instrumentation
is not done.
would not want to use this option, since it makes the code sub-optimal, and t he offs ets o f struct ure membe rs won’t agree wit h system libraries.
Return short struct and union values in memory like l onger ones, rather than in registers. This convention is less efficient, but it has the adv antage of a llowing c apabi lity between 32 -bit c ompiled files and files compiled with other compilers. Short structures and unions are those whose size and alignment match that of an integer type.
This option makes double equivalent to long double. Mixing this option across modules can have unexpected results if modules share double data either directly through argument passage or indirectly through shared buffer space. Libraries provided with the product function with either switch setting.
declared range of possible values. Specifically, the enum type is equivalent to the smallest integer type that has enough room.
Put extra commenta ry informa tion in the generated assembly c ode to make it more readable.
-fno-verbose-asm, the default, causes the extra information to be omitted and is useful when comparing two assembler files.
to be volatile. The use of this switch has no effect on static data.
DS51686E-page 84 2012 Microchip Technology Inc.

Chapter 4. Device-Related Features

4.1 INTRODUCTION

The MPLAB XC32 C/C++ Compiler supports a number of special features and exten­sions to the C/C++ language which are designed to ease the task of producing ROM-based applications. This chapter documents the special language features which are specific to these devices.
• Device Support
• Device Header Files
•Stack
• Using SFRs From C Code

4.2 DEVICE SUPPORT

MPLAB XC32 C/C++ Compiler aims to support all PIC32 devices. However, new devices in these families are frequently released. Check the readme document for a full list of all available devices.
MPLAB® XC32 C/C++ COMPILER
USER’S GUIDE

4.3 DEVICE HEADER FILES

There is one header file that is recommended be included into each source file you write. The file is <xc.h> and is a generic file that will include other device-specific header files when you build your project.
Inclusion of this file will allow access to SFRs via special variables, as well as #defines which allow the use of conventional register names from within assembly language files.

4.3.1 CP0 Register Definitions Header File

The CP0 register definitions header file (cp0defs.h) is a file that contains definitions for the CP0 registers and their fields. In addition, it contains macros for accessing the CP0 registers.
The CP0 register definitions header file is located in the pic32mx/include directory of your compiler installation directory. The CP0 register definitions header file is automatically included when you include the generic device header file, xc.h.
The CP0 register definitions header file was designed to work with either Assembly or C/C++ files. The CP0 register definitions header file is dependent on macros defined within the processor generic header file).
2012 Microchip Technology Inc. DS51686E-page 85
MPLAB® XC32 C/C++ Compiler User’s Guide

4.4 STACK

The PIC32 devices use what is referred to in this user’s guide as a “software stack”. This is the t ypical st ack arrangem ent employ ed by most com puters and is ordinary d ata memory accessed by a push-and-pop type instruction and a stack pointer register. The term “hardware stack” is used to describe the stack employed by Microchip 8-bit devices, which is only used for storing function return addresses.
The PIC32 devices use a dedicated stack pointer register sp (register 29) for use as a software Stack Pointer. All processor stack operations, including function calls, inter­rupts and exceptions, use the software stack. It points to the next free location on the stack. The stack grows downward, towards lower memory addresses.
By default, the size of the stack is 1024 bytes. The size of the stack may be changed by specifying the size on the linker command line using the
--defsym_min_stack_size linker command line option. An example of allocating a stack of 2048 bytes using the command line is:
xc32-gcc foo.c -Wl,--defsym,_min_stack_size=2048
The run-time stack grows downward from higher addresses to lower addresses. Two working registers are used to manage the stack:
• Register 29 (sp) – This is the Stack Pointer. It points to the next free location on the stack.
• Register 30 (fp) – This is the Frame Pointer. It points to the current function’s frame. No stack overflow detection is supplied. The C/C++ run-time start-up module initializes the stack pointer during the start-up and initialization sequence, see Section 12.3.2 “Initialize Stack Pointer and Heap”.

4.4.1 Configuration Bit Access

The PIC32 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.
The #pragma config directive specifies the processor-specific configuration settings (i.e., Configuration bits) to be used by the application. Refer to the “PIC32MX Configuration Settings” online help (found under MPLAB IDE>Help>Topics>Language Tools) for more information. (If using the compiler from the command line, this help file is located at the default location at:
Program Files/Microchip/<install-dir>/doc/hlpPIC32MXConfigSet.chm.)
Configuration settings may be specified with multiple #pragma config directives. The compiler verifies that the configuration settings specified are valid for the processor for which it is compiling. If a given setting in the Configuration word has not been specified in any #pragma config directive, the bits associated with that setting default to the unprogrammed value. Configuration settings should be specified in only
a single translation unit (a C/C++ file with all of its include files after preprocessing).
For each Configuration word for which a setting is specified with the #pragma config directive, the compiler generates a read-only data section named .config_address, where address is the hexadecimal representation of the address of the Configuration word. For example, if a configuration setting was specified for the Configuration word located at address 0xBFC02FFC, a read-only data section named .config_BFC02FFC would be created.
•Syntax
•Example
DS51686E-page 86 2012 Microchip Technology Inc.
Device-Related Features
4.4.1.1 SYNTAX The following shows the meta syntax notation for the different forms the pragma may
take. pragma-config-directive:
# pragma config setting-list setting-list:
setting | setting-list, setting setting: setting-name = value-name
The setting-name and value-name are device specific and can be determined by utilizing the PIC32MX Configuration Settings document.
All #pragma config directives should be placed outside of a function definition as they do not define executable code.
4.4.1.2 EXAMPLE The following example shows how the #pragma config directive might be utilized.
The example does the following:
• Enables the Watchdog Timer
• Sets the Watchdog Postscaler to 1:128
• Selects the HS Oscillator for the Primary Oscillator
#pragma config FWDTEN = ON, WDTPS = PS128 #pragma config POSCMOD = HS ... int main (void) { ... }
2012 Microchip Technology Inc. DS51686E-page 87
MPLAB® XC32 C/C++ Compiler User’s Guide

4.5 USING SFR S FR OM C CODE

The Special Function Registers (SFRs) are registers which control aspects of the MCU operation or that of peripheral modules on the device. These registers are memory mapped, which means that they appear at specific addresses in the device memory map. With some registers, the bits within the register control independent features.
Memory-mapped SFRs are accessed by special C variables that are placed at the addresses of the registers and use special attributes. These variables can be accessed like any ordinary C variable so that no special syntax is required to access SFRs.
The SFR variables are predefined in header files and will be accessible once the <xc.h> header file (see Section 4.3 “Device Header Files”) has been included into your source code. Structures are also defined by these header files to allow access to bits within the SFR.
The names given to the C variables, which map over the registers and bit variables, or bit fields, within the registers are based on the names specified in the device data sheet. The names of the structures that hold the bit fields will typically be those of the corresponding register followed by bits. For example, the following shows code that includes the generic header file, clears PORTB as a whole and sets bit 2 of PORTB using the structure/bit field definitions.
Note: The symbols PORTB and PORTBbits refer to the same register and resolve
to the same address. Writing to one register will change the values held by both.
#include <xc.h> int main(void) {
PORTB = 0x00; PORTBbits.RB2 = 1;
}
For use with assembly, the PORTB register is declared as: .extern PORTB. To confirm the names that are relevant for the device you are using, check the device
specific header file that <xc.h> will include for the definitions of each variable. These files will be loc ated in th e pic32mx/include/proc directory of the compiler and will have a name that represents the device. There is a one-to-one correlation between device and header file name that will be included by <xc.h>, e.g. when compiling for a PIC32MX360F512L device, the <xc.h> header file will include <p32mx360f512l.h>. Remember that you do not need to include this chip-specific file into your source code; it is automatically included by <xc.h>.
Some of the PIC32 SFRs have associated registers that allow the bits within the SFR to be set, cleared or toggled atomically. For example, the PORTB SFR has the write-only registers PORTBSET, PORTBCLR and PORTBINV associated with it. Writing a ‘1’ to a bit location in these registers sets, clears or toggles, respectively, the corresponding bit in the PORTB SFR. So to set bit 1 in PORTB, you can use the following code:
PORTBSET = 0x2;
or alternatively, using macros provided in the device header files:
PORTBSET = _PORTB_RB1_MASK;
The same operation can also be achieved using the peripheral library functions, for example
mPORTBSetBits(BIT_1);
Always ensure that you confirm the operation of peripheral modules from the device data sheet.
DS51686E-page 88 2012 Microchip Technology Inc.
Device-Related Features

4.5.1 CP0 Register Definitions

When the CP0 register definitions header file is included from an Assembly file, the CP0 registers are defined as:
#define _CP0_register_name $register_number, select_number
For example, the IntCtl register is defined as:
#define _CP0_INTCTL $12, 1
When the CP0 register definitions header file is included from a C file, the CP0 registers and selects are defined as:
#define _CP0_register_name register_number #define _CP0_register_name_SELECT select_number
For example, the IntCtl register is defined as:
#define _CP0_INTCTL 12 #define _CP0_INTCTL_SELECT 1

4.5.2 CP0 Register Field Definitions

When the CP0 register definitions header file is included from either an Assembly or a C/C++ file, three #defines exist for each of the CP0 register fields.
_CP0_register_name_field_name_POSITION – the starting bit location _CP0_register_name_field_name_MASK – the bits that are part of this field are
set _CP0_register_name_field_name_LENGTH – the number of bits that this field
occupies For example, the vector spacing field of the IntCtl register has the following defines:
#define _CP0_INTCTL_VS_POSITION 0x00000005 #define _CP0_INTCTL_VS_MASK 0x000003E0 #define _CP0_INTCTL_VS_LENGTH 0x00000005

4.5.3 CP0 Access Macros

When the CP0 register definitions header file is included from a C file, CP0 access macros are defined. Each CP0 register may have up to six different access macros defined:
_CP0_GET_register_name () Returns the value for register , register_name. _CP0_SET_register_name (val) Sets the register, register_name, to val, and
returns void. Only defined for registers that contain a writable field.
_CP0_XCH_register_name (val) Sets the register, register_name, to val, and
returns the previous register value. Only defined for registers that contain a writable field.
_CP0_BIS_register_name (set) Sets the register, register_name, to (reg |= set),
and returns the previous register value. Only defined for registers that contain writable bit fields.
_CP0_BIC_register_name (clr) Sets the register , register_name, to (reg &= ~clr),
and returns the previous register value. Only defined for registers that contain writable bit fields.
_CP0_BCS_register_name (clr, set)
Sets the register, register_name, to (reg = (reg & ~clr) | set), and returns the previous register value. Only defined for registers that contain writable bit fields.
2012 Microchip Technology Inc. DS51686E-page 89
MPLAB® XC32 C/C++ Compiler User’s Guide

4.5.4 Address Translation Macros

System code may need to translate between virtual and physical addresses, as well as between kernel segment addresses. Macros are provided to make these translations easier and to determine the segment an address is in.
KVA_TO_PA(v) Translate a kernel virtual address to a physical address. PA_TO_KVA0(pa) Translate a physical address to a KSEG0 virtual address. PA_TO_KVA1(pa) Translate a physical address to a KSEG1 virtual address. KVA0_TO_KVA1(v) Translate a KSEG0 virtual address to a KSEG1 virtual address. KVA1_TO_KVA0(v) Translate a KSEG1 virtual address to a KSEG0 virtual address. IS_KVA(v) Evaluates to 1 if the address is a kernel segment virtual address, zero
otherwise.
IS_KVA0(v) Evaluate to 1 if the address is a KSEG0 virtual add ress, zero oth erwise. IS_KVA1(v) Evaluate to 1 if the address is a KSEG1 virtual add ress, zero oth erwise. IS_KVA01(v) Evaluate to 1 if the address is either a KSEG0 or a KSEG1 virtual
address, zero otherwise.
DS51686E-page 90 2012 Microchip Technology Inc.
MPLAB® XC32 C/C++ COMPILER

Chapter 5. ANSI C Standard Issues

This compiler conforms to the ANS X3.159-1989 Standard for programming languages. This is commonly called the C89 Standard. It is referred to as the ANSI C Standard in this manual. Some features from the later standard C99 are also supported.
• Divergence from the ANSI C Standard
• Extensions to the ANSI C Standard
• Implementation-defined behavior

5.1 DIVERGENCE FROM THE ANSI C STANDARD

There are no divergences from the ANSI C standard.

5.2 EXTENSIONS TO THE ANSI C STANDARD

C/C++ code for the MPLAB XC32 C/C++ Compiler differs from the ANSI C standard in these areas: keywords, statements and expressions.

5.2.1 Keyword Differences

USER’S GUIDE
The new keywords are part of the base GCC implementation and the discussions in the referenced sections are based on the standard GCC documentation, tailored for the specific syntax and semantics of the 32-bit compiler port of GCC.
• Specifying Attributes of Variables – Section 6.12 “Variable Attributes”
• Specifying Attributes of Functions – Section 10.2 “Function Attributes and
Specifiers”
• Inline Functions – Section 10.9 “Inline Functions”
• Variables in Specified Registers – Section 6.12 “ Variable Attributes”
• Complex Numbers – Section 6.8 “Complex Data Types”
• Referring to a Type with typeofSection 6.10 “Standard Type Qualifiers”

5.2.2 Statement Differences

The statement differences are part of the base GCC implementation, and the discus­sions in the referenced sections are based on the standard GCC documentation, tailored for the specific syntax and semantics of the 32-bit compiler port of GCC.
• Labels as Values – Section 8.4 “Labels as Values”
• Conditionals with Omitted Operands – Section 8.5 “Conditional Operator Oper-
ands”
• Case Ranges – Section 8.6 “Case Ranges”

5.2.3 Expression Differences

Expression differences are:
• Binary constants – Section 6.9 “Constant Types and Formats”.
2012 Microchip Technology Inc. DS51686E-page 91
MPLAB® XC32 C/C++ Compiler User’s Guide

5.3 IMPLEMENTATION-DEFINED BEHAVIOR

Certain features of the ANSI C standard have implementation-defined behavior. This means that the exact behavior of some C code can vary from compiler to compiler. The exact behavior of the MPLAB XC32 C/C++ Compiler is detailed throughout this docu­mentation, and is fully summarized in Appendix 18. “Implementation-Defined Behavior”.
DS51686E-page 92 2012 Microchip Technology Inc.

Chapter 6. Supported Data Ty pe s and Variables

6.1 INTRODUCTION

The MPLAB XC32 C/C++ Compiler supports a variety of data types and attributes. These data types and variables are discussed here. For information on where variables are stored in memory, see Chapter 7. “Memory Allocation and Access”.
• Data Representation
• Integer Data Types
• Floating-Point Data Types
• Structures and Unions
• Pointer Types
• Complex Data Types
• Constant Types and Formats
• Standard Type Qualifiers
• Compiler-Specific Qualifiers
• Variable Attributes
MPLAB® XC32 C/C++ COMPILER
USER’S GUIDE

6.2 IDENTIFIERS

A C/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 pro­grams. Such is not the case for assembly domain identifiers, which often begin with an underscore
Identifiers are case sensiti ve , so main is different than Main. All characters are significant in an identifier, although identifiers longer than 31 charac-
ters in length are less portable.

6.3 DAT A REPR ES EN TATION

The compiler stores multibyte values in little-endian format. That is, the Least Significant Byte is stored at the lowest address.
For example, the 32-bit value 0x12345678 would be stored at address 0x100 as:
Address Data
0x100 0x101 0x102 0x103 0x78 0x56 0x34 0x12
2012 Microchip Technology Inc. DS51686E-page 93
MPLAB® XC32 C/C++ Compiler User’s Guide

6.4 INTEGER DATA TYPES

Integer values in the compiler are represented in 2’s complement and vary in size from 8 to 64 bits. These values are available in compiled code via limits.h.
Type Bits Min Max
char, signed char 8 -128 127 unsigned char short, signed short 16 -32768 32767 unsigned short int, signed int, long, signed long 32 -2 unsigned int, unsigned long 32 0 2 long long, signed long long 64 -2 unsigned long long
6.4.1 Signed and Unsigned Character Types
80255
16 0 65535
64 0 264-1
31
63
231-1
32
-1
263-1
By default, values of type plain char are signed values. This behavior is implementation-defined by the C standard, and some environments
1
define a plain C/C++ char value to be unsigned. The command line option -funsigned-char can be used to set the default type to unsigned for a given translation unit.
6.4.2 limits.h
The limits.h header file defines the ranges of values which can be represented by the integer types.
Macro name Value Description
CHAR_BIT
SCHAR_MIN
SCHAR_MAX
UCHAR_MAX
CHAR_MIN
CHAR_MAX
MB_LEN_MAX
SHRT_MIN
SHRT_MAX
USHRT_MAX
8 The size, in bits, of the smallest non-bit field
object.
-128 The minimum value possible for an object of
signed char.
type
127 The maximum value possible for an object of
type
signed char.
255 The maximum value possible for an object of
unsigned char.
type
-128 (or 0, see
Section 6.4.1 “Signed and Unsigned Character Types”)
127 (or 255, see
Section 6.4.1 “Signed and Unsigned Character Types”)
16 The maximum length of multibyte character in
-32768 The minimum value possible for an object of
32767 The maximum value possible for an object of
65535 The maximum value possible for an object of
The minimum value possible for an object of
char.
type
The maximum value possible for an object of
char.
type
any locale.
short int.
type
short int.
type
type
unsigned short int.
1. Notably, PowerPC and ARM.
DS51686E-page 94 2012 Microchip Technology Inc.
Supported Data Types and Variables
Macro name Value Description
31
INT_MIN
INT_MAX
UINT_MAX
LONG_MIN
LONG_MAX
ULONG_MAX
LLONG_MIN
LLONG_MAX
ULLONG_MAX
-2
231-1 The maximum value possible for an object of
232-1 The maximum value possible for an object of
31
-2
231-1 The maximum value possible for an object of
232-1 The maximum value possible for an object of
63
-2
263-1 The maximum value possible for an object of
264-1 The maximum value possible for an object of
The minimum value possible for an object of
int.
type
type
int.
unsigned int.
type The minimum value possible for an object of
long.
type
type
long.
unsigned long.
type The minimum value possible for an object of
long long.
type
type
long long.
unsigned long long.
type
2012 Microchip Technology Inc. DS51686E-page 95
MPLAB® XC32 C/C++ Compiler User’s Guide

6.5 FLOATING-POINT DATA TYPES

The compiler uses the IEEE-754 floating-point format. Detail regarding the implementation limits is available to a translation unit in float.h.
Type Bits
float double long double
Variables may be declared using the float, double and long double keywords, respectively, to hold values of these types. Floating-point types are always signed and the unsigned keyword is illegal when specifying a floating-point type. All floating-point values are represented in little endian format with the Least Significant Byte at the lower address.
This format is described in Table 6-1, where:
• Sign is the sign bit which indicates if the number is positive or negative
• For 32-bit floating point values, the exponent is 8 bits which is stored as excess
127 (i.e. an exponent of 0 is stored as 127).
• For 64-bit floating point values, the exponent is 11 bits which is stored as excess
1023 (i.e. an exponent of 0 is stored as 1023).
• Mantissa is the mantissa, which is to the right of the radix point. There is an
implied bit to the left of the radix point which is always 1 except for a zero value,
where the implied bit is zero. A zero value is indicated by a zero exponent. The value of this number for 32-bit floating point values is: (-1)
sign
(exponent-127)
x 2
x 1. mantissa and for 64-bit values (-1)
sign
(exponent-1023)
x 2
x 1. mantissa.
Here is an example of the IEEE 754 32-bit format shown in Table 6-1. Note that the Most Significant bit 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).
32 32 64

TABLE 6-1: FLOATING-POINT FORMAT EXAMPLE IEEE 754

Format Number Biased exponent 1.mantissa Decimal
32-bit 7DA6B69Bh 11111011b 1.0100110101101101
0011011b
(251) (1.302447676659)
2.77000e+37
The example in Table 6-1 can be calculated manually as follows. The sign bit is zero; the biased exponent is 251, so the exponent is 251-127=124. Take
the binary number to the right of the decimal point in the mantissa. Convert this to dec­imal and divide it by 2
23
where 23 is the number of bits taken up by the mantissa, to give 0.302447676659. Add 1 to this fraction. The floating-point number is then given by:
02124
-1
1.302447676659 which becomes: 12.126764793256e+371.302447676659 which is approximately equal to:
2.77000e+37
DS51686E-page 96 2012 Microchip Technology Inc.
Supported Data Types and Variables
Binary floating-point values are sometimes misunderstood. It is important to remember that not every floating-point value can be represented by a finite sized floating-point number. The size of the exponent in the number dictates the range of values that the number can hold, and the size of the mantissa relates to the spacing of each value that can be represented exactly. Thus the 64-bit floating-point format allows for values with a larger range of values and that can be more accurately represented.
So, for example, if you are using a 32-bit wide floating-point type, it can exactly store the value 95000.0. However, the next highest number it can represent is (approxi­mately) 95000.00781 and it is impossible to represent any value in between these two in such a type as it will be rounded. This implies that C/C++ code which compares float­ing-point type may not behave as expected. For example:
volatile float myFloat; myFloat = 95000.006; if(myFloat == 95000.007) // value will be rounded
LATA++; // this line will be executed!
in which the result of the if() expression will be true, even though it appears the two values being compared are different.
The characteristics of the floating-point formats are summarized in T able 6-2. The sym­bols in this table are preprocessor macros which are available after including
<float.h> in your source code. 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. DBL_MAX
represents the same values for the double type. As the size and format of float­ing-point 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.

TABLE 6-2: RANGES OF FLOATING-POINT TYPE VALUES

Symbol Meaning 32-bit Value 64-bit Value
XXX_RADIX Radix of exponent representation 2 2 XXX_ROUNDS Rounding mode for addition 1 XXX_MIN_EXP
XXX_MIN_10_E
XP
XXX_MAX_EXP
XXX_MAX_10_E
XP
XXX_MANT_DIG
XXX_EPSILON
Min. n such that FL T_RADIX a normalized float value
Min. n such that 10n is a normalized float value
Max. n such that FLT_RADIX is a normalized float value
Max. n such that 10n is a normalized float value
Number of FLT_RADIX mantissa digits
The smallest number which added to 1.0 does not yield 1.0
n-1
is
-125 -1021
-37 -307
n-1
128 1024
38 308
24 53
1.1920929e-07 2.22044604925 03131e-16
2012 Microchip Technology Inc. DS51686E-page 97
MPLAB® XC32 C/C++ Compiler User’s Guide

6.6 STRUCTURES AND UNIONS

MPLAB XC32 C/C++ Compiler supports struct and union types. Str uctures and unions only differ in the memory offset applied to each member.
These types will be at least 1 byte wide. Bit fields are fully supported. No padding of structure members is added. Structures and unions may be passed freely as function arguments and function return
values. Pointers to structures and unions are fully supported.

6.6.1 Structure and Union Qualifiers

The MPLAB XC32 C/C++ Compiler supports the use of type qualifiers on structures. When a qualifier is applied to a structure, all of its members will inherit this qualification. In the following example the structure is qualified const.
const struct { int number; int *ptr; } record = { 0x55, &i };
In this case, the entire structure will be placed into the program memory and each member will be read-only . Remember that all members are usually initialized if a struc­ture is const as they cannot be initialized at runtime.
If the members of the structure were individually qualified const, but the structure was not, then the structure would be positioned into RAM, but each member would be read-only. Compare the following structure with the above.
struct { const int number; int * const ptr; } record = { 0x55, &i};

6.6.2 Bit Fields in Structures

MPLAB XC32 C/C++ Compiler fully supports bit fields in structures. Bit fields are always allocated within 8-bit storage units, even though it is usual to use
the type unsigned int in the definition. Storage units are aligned on a 32-bit bound­ary, although this can be changed using the packed attribute.
The first bit defined will be the Least Significant bit 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; other­wise, a new byte is allocated within the structure. Bit fields can never cross the bound­ary between 8-bit allocation units. For example, the declaration:
struct { unsigned lo : 1; unsigned dummy : 6; unsigned hi : 1; } foo;
will produce a structure occupying 1 byte. If foo was ultimately linked at address 10H, the field lo will be bit 0 of address 10H; hi will be bit 7 of address 10H. The Least Sig­nificant bi t of dummy will be bit 1 of address 10H and the Most Significant bit of dummy will be bit 6 of address 10h.
DS51686E-page 98 2012 Microchip Technology Inc.
Supported Data Types and Variables
Unnamed bit fields may be declared to pad out unused space between active bits in control registers. For example, if dummy is never referenced, the structure above could have been declared as:
struct { unsigned lo : 1; unsigned : 6; unsigned hi : 1; } foo;
A structure with bit fields may be initialized by supplying a comma-separat e d li st of i ni ­tial values for each field. For example:
struct { unsigned lo : 1; unsigned mid : 6; unsigned hi : 1; } foo = {1, 8, 0};
Structures with unnamed bit fields may be initialized. No initial value should be supplied for the unnamed members, for example:
struct { unsigned lo : 1; unsigned : 6; unsigned hi : 1; } foo = {1, 0};
will initialize the members lo and hi correctly. The MPLAB XC compiler supports anonymous unions. These are unions with no iden-
tifier 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;
int main(void) {
aaa.x = 99; // ...}
Here, the union is not named and its members accessed as if they are part of the struc­ture. Anonymous unions are not part of any C Standard and so their use limits the por­tability of any code.
2012 Microchip Technology Inc. DS51686E-page 99
MPLAB® XC32 C/C++ Compiler User’s Guide

6.7 POINTER TYPES

There are two basic pointer types supported by the MPLAB XC32 C/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.

6.7.1 Combining Type Qualifiers and Pointers

It is helpful to first review the ANSI C/C++ standard conventions for definitions of pointer types.
Pointers can be qualified like any other C/C++ object, but care must be taken when doing so as there are two quantities associated with pointers. The first is the actual pointer itself, which is treated like any ordinary C/C++ variable and has memory reserved for it. The second is the target, or targets, that the pointer references, or to which the pointer points. The general form of a pointer definition looks like the following:
target_type_&_qualifiers
Any qualifiers to the right of the * (i.e. next to the pointer’s name) relate to the pointer variable itself. The type and any qualifiers to the left of the * relate to the pointer’s tar­gets. This makes sense since it is also the * operator that dereferences a pointer, which allows you to get from the pointer variable to its current target.
Here are three examples of pointer definitions using the volatile qualifier. The fields in the definitions have been highlighted with spacing:
volatile int * vip ; int * volatile ivp ; volatile int * volatile vivp ;
The first example is a pointer called vip. It contains the address of int objects that are qualified volatile. The pointer itself — the variable that holds the address — is not volatile; however, the objects that are accessed when the pointer is derefer- enced are treated as being volatile. In other words, the target objects accessible via the pointer may be externally modified.
The second example is a pointer called ivp which also contains the address of int objects. In this example, the pointer itself is volatile, that is, the address the pointer contains may be externally modified; however, the objects that can be accessed when dereferencing the pointer are not volatile.
The last example is of a pointer called vivp which is itself qualified volatile, and which also holds the address of volatile objects.
Bear in mind that one pointer can be assigned the addresses of many objects; for example, a pointer that is a parameter to a function is assigned a new object address every time the function is called. The definition of the pointer must be valid for every target address assigned.
* pointer’s_qualifiers pointer’s_name;
Note: Care must be taken when describing pointers. Is a “const pointer” a pointer
that points to const objects, or a poi nter t hat is const itself? You can talk about “pointers to const” and “const pointers” to help clarify the definition, but such terms may not be universally understood.
6.7.2 Data Pointers
Pointers in the compiler are all 32 bits in size. These can hold an address which can reach all memory locations.
DS51686E-page 100 2012 Microchip Technology Inc.
Loading...