MPLAB® XC32 C/C++ Compiler Guide Datasheet by Microchip Technology

View All Related Products | Download PDF Datasheet
6‘ MICRDCHIP
2012-2016 Microchip Technology Inc. DS50001686J
MPLAB® XC32 C/C++ Compiler
Users Guide
YSTEM
DS50001686J-page 2 2012-2016 Microchip Technology Inc.
Information contained in this publication regarding device
applications and the like is provided only for your convenience
and may be superseded by updates. It is your 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 support and/or safety applications is entirely at
the buyer’s risk, and the buyer agrees to defend, indemnify and
hold harmless Microchip from any and all damages, claims,
suits, or expenses resulting from such use. No licenses are
conveyed, implicitly or otherwise, under any Microchip
intellectual property rights unless otherwise stated.
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.
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® MCUs and dsPIC® DSCs, KEELOQ® code hopping
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.
QUALITYMANAGEMENTS
YSTEM
CERTIFIEDBYDNV
== ISO/TS16949==
Trademarks
The Microchip name and logo, the Microchip logo, AnyRate,
dsPIC, FlashFlex, flexPWR, Heldo, JukeBlox, KEELOQ,
KEELOQ logo, Kleer, LANCheck, LINK MD, MediaLB, MOST,
MOST logo, MPLAB, OptoLyzer, PIC, PICSTART, PIC32 logo,
RightTouch, SpyNIC, SST, SST Logo, SuperFlash and UNI/O
are registered trademarks of Microchip Technology
Incorporated in the U.S.A. and other countries.
ClockWorks, The Embedded Control Solutions Company,
ETHERSYNCH, Hyper Speed Control, HyperLight Load,
IntelliMOS, mTouch, Precision Edge, and QUIET-WIRE are
registered trademarks of Microchip Technology Incorporated
in the U.S.A.
Analog-for-the-Digital Age, Any Capacitor, AnyIn, AnyOut,
BodyCom, chipKIT, chipKIT logo, CodeGuard, dsPICDEM,
dsPICDEM.net, Dynamic Average Matching, DAM, ECAN,
EtherGREEN, In-Circuit Serial Programming, ICSP, Inter-Chip
Connectivity, JitterBlocker, KleerNet, KleerNet logo, MiWi,
motorBench, MPASM, MPF, MPLAB Certified logo, MPLIB,
MPLINK, MultiTRAK, NetDetach, Omniscient Code
Generation, PICDEM, PICDEM.net, PICkit, PICtail,
PureSilicon, RightTouch logo, REAL ICE, Ripple Blocker,
Serial Quad I/O, SQI, SuperSwitcher, SuperSwitcher II, Total
Endurance, TSHARC, USBCheck, VariSense, ViewSpan,
WiperLock, Wireless DNA, 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.
Silicon Storage Technology is a registered trademark of
Microchip Technology Inc. in other countries.
GestIC is a registered trademarks of Microchip Technology
Germany II GmbH & Co. KG, a subsidiary of Microchip
Technology Inc., in other countries.
All other trademarks mentioned herein are property of their
respective companies.
© 2012-2016, Microchip Technology Incorporated, Printed in
the U.S.A., All Rights Reserved.
ISBN: 978-1-5224-0679-2
Q MICROCHIP
MPLAB® XC32 C/C++ COMPILER
USERS GUIDE
2012-2016 Microchip Technology Inc. DS50001686J-page 3
Table of Contents
Preface ........................................................................................................................... 9
Document Layout .................................................................................................. 9
Conventions Used ............................................................................................... 11
Recommended Reading...................................................................................... 12
Chapter 1. Compiler Overview
1.1 Introduction ................................................................................................... 15
1.2 Device Description ....................................................................................... 15
1.3 Compiler Description and Documentation .................................................... 15
1.4 Compiler and Other Development Tools ...................................................... 17
Chapter 2. Common C Interface
2.1 Introduction ................................................................................................... 19
2.2 Background – The Desire for Portable Code ............................................... 19
2.3 Using the CCI ............................................................................................... 22
2.4 ANSI Standard Refinement .......................................................................... 23
2.5 ANSI Standard Extensions ........................................................................... 31
2.6 Compiler Features ........................................................................................ 46
Chapter 3. How To’s
3.1 Introduction ................................................................................................... 47
3.2 Installing and Activating the Compiler .......................................................... 47
3.3 Invoking the Compiler ................................................................................... 49
3.4 Writing Source Code .................................................................................... 52
3.5 Getting My Application to Do What I Want ................................................... 62
3.6 Understanding the Compilation Process ...................................................... 66
3.7 Fixing Code That Does Not Work ................................................................. 73
Chapter 4. XC32 Toolchain and MPLAB X IDE
4.1 Introduction ................................................................................................... 75
4.2 MPLAB X IDE and Tools Installation ............................................................ 75
4.3 MPLAB X IDE Setup .................................................................................... 76
4.4 MPLAB X IDE Projects ................................................................................. 77
4.5 Project Setup ................................................................................................ 79
4.6 Project Example ........................................................................................... 90
Chapter 5. Compiler Command Line Driver
5.1 Introduction ................................................................................................... 93
5.2 Invoking the Compiler ................................................................................... 93
5.3 The C Compilation Sequence ...................................................................... 97
5.4 The C++ Compilation Sequence ................................................................ 100
MPLAB® XC32 C/C++ Compiler User’s Guide
DS50001686J-page 4 2012-2016 Microchip Technology Inc.
5.5 Runtime Files ............................................................................................. 104
5.6 Start-Up and Initialization ........................................................................... 107
5.7 Compiler Output ......................................................................................... 109
5.8 Compiler Messages .................................................................................... 111
5.9 Driver Option Descriptions ......................................................................... 111
Chapter 6. ANSI C Standard Issues
6.1 Introduction ................................................................................................. 135
6.2 Divergence from the ANSI C Standard ...................................................... 135
6.3 Extensions to the ANSI C Standard ........................................................... 135
6.4 Implementation-Defined Behavior .............................................................. 136
Chapter 7. Device-Related Features
7.1 Introduction ................................................................................................. 137
7.2 Device Support ........................................................................................... 137
7.3 Device Header Files ................................................................................... 137
7.4 Stack .......................................................................................................... 138
7.5 Configuration Bit Access ............................................................................ 139
7.6 ID Locations ............................................................................................... 140
7.7 Using SFRs From C Code .......................................................................... 141
Chapter 8. Supported Data Types and Variables
8.1 Introduction ................................................................................................. 145
8.2 Identifiers .................................................................................................... 145
8.3 Data Representation .................................................................................. 145
8.4 Integer Data Types ..................................................................................... 146
8.5 Floating-Point Data Types .......................................................................... 148
8.6 Structures and Unions ................................................................................ 150
8.7 Pointer Types ............................................................................................. 152
8.8 Complex Data Types .................................................................................. 154
8.9 Constant Types and Formats ..................................................................... 154
8.10 Standard Type Qualifiers .......................................................................... 157
8.11 Compiler-Specific Qualifiers ..................................................................... 158
8.12 Variable Attributes .................................................................................... 158
Chapter 9. Memory Allocation and Access
9.1 Introduction ................................................................................................. 163
9.2 Address Spaces ......................................................................................... 163
9.3 Variables in Data Memory .......................................................................... 164
9.4 Auto Variable Allocation and Access .......................................................... 167
9.5 Variables in Program Memory .................................................................... 169
9.6 Variables in Registers ................................................................................ 170
9.7 Application-Defined Memory Regions ........................................................ 171
9.8 Dynamic Memory Allocation ....................................................................... 175
9.9 Memory Models .......................................................................................... 175
Chapter 10. Fixed-Point Arithmetic Support
10.1 Introduction ............................................................................................... 177
Table of Contents
2012-2016 Microchip Technology Inc. DS50001686J-page 5
10.2 Enabling Fixed-Point Arithmetic Support .................................................. 177
10.3 Data Types ............................................................................................... 178
10.4 External definitions ................................................................................... 180
10.5 SIMD Variables ........................................................................................ 181
10.6 Accessing Elements in SIMD Variables ................................................... 182
10.7 Array Alignment and Data Layout ............................................................ 184
10.8 C Operators .............................................................................................. 185
10.9 Operations on SIMD Variables ................................................................. 186
10.10 DSP Built-in Functions ........................................................................... 187
10.11 DSP Control Register ............................................................................. 187
10.12 Using Accumulators ............................................................................... 188
10.13 Mixed-mode operations .......................................................................... 188
10.14 Auto-Vectorization to SIMD .................................................................... 189
10.15 FIR Filter Example Project ..................................................................... 190
Chapter 11. Operators and Statements
11.1 Introduction ............................................................................................... 193
11.2 Integral Promotion .................................................................................... 193
11.3 Type References ...................................................................................... 195
11.4 Labels as Values ...................................................................................... 196
11.5 Conditional Operator Operands ............................................................... 197
11.6 Case Ranges ............................................................................................ 197
Chapter 12. Register Usage
12.1 Introduction ............................................................................................... 199
12.2 Register Usage ......................................................................................... 199
12.3 Register Conventions ............................................................................... 199
Chapter 13. Functions
13.1 Introduction ............................................................................................... 201
13.2 Writing Functions ...................................................................................... 201
13.3 Function Attributes and Specifiers ............................................................ 202
13.4 Allocation of Function Code ..................................................................... 206
13.5 Changing the Default Function Allocation ................................................ 206
13.6 Function Size Limits ................................................................................. 207
13.7 Function Parameters ................................................................................ 207
13.8 Function Return Values ............................................................................ 209
13.9 Calling Functions ...................................................................................... 209
13.10 Inline Functions ...................................................................................... 210
Chapter 14. Interrupts
14.1 Introduction ............................................................................................... 213
14.2 Interrupt Operation ................................................................................... 213
14.3 Writing an Interrupt Service Routine ........................................................ 214
14.4 Associating a Handler Function with an Exception Vector ....................... 219
14.5 Exception Handlers .................................................................................. 221
14.6 Interrupt Service Routine Context Switching ............................................ 222
MPLAB® XC32 C/C++ Compiler User’s Guide
DS50001686J-page 6 2012-2016 Microchip Technology Inc.
14.7 Latency ..................................................................................................... 222
14.8 Nesting Interrupts ..................................................................................... 222
14.9 Enabling/Disabling Interrupts ................................................................... 223
14.10 ISR Considerations ................................................................................ 223
Chapter 15. Main, Runtime Start-up and Reset
15.1 Introduction ............................................................................................... 225
15.2 The Main Function .................................................................................... 225
15.3 Runtime Start-up Code ............................................................................. 226
15.4 The On Reset Routine .............................................................................. 241
Chapter 16. Library Routines
16.1 Using Library Routines ............................................................................. 243
Chapter 17. Mixing C/C++ and Assembly Language
17.1 Introduction ............................................................................................... 245
17.2 Mixing Assembly Language and C Variables and Functions ................... 245
17.3 Using Inline Assembly Language ............................................................. 248
17.4 Predefined Macros ................................................................................... 252
Chapter 18. Optimizations
18.1 Introduction ............................................................................................... 255
Chapter 19. Preprocessing
19.1 Introduction ............................................................................................... 257
19.2 C/C++ Language Comments .................................................................... 257
19.3 Preprocessor Directives ........................................................................... 258
19.4 Pragma Directives .................................................................................... 260
19.5 Predefined Macros ................................................................................... 261
Chapter 20. Linking Programs
20.1 Introduction ............................................................................................... 265
20.2 Replacing Library Symbols ....................................................................... 265
20.3 Linker-Defined Symbols ........................................................................... 265
20.4 Default Linker Script ................................................................................. 266
Appendix A. Embedded Compiler Compatibility Mode
A.1 Introduction ................................................................................................ 285
A.2 Compiling in Compatibility Mode ................................................................ 285
A.3 Syntax Compatibility .................................................................................. 286
A.4 Data Type .................................................................................................. 287
A.5 Operator ..................................................................................................... 287
A.6 Extended Keywords ................................................................................... 288
A.7 Intrinsic Functions ...................................................................................... 289
A.8 Pragmas ..................................................................................................... 290
Appendix B. Implementation-Defined Behavior
B.1 Introduction ................................................................................................ 291
B.2 Highlights ................................................................................................... 291
B.3 Overview .................................................................................................... 291
B.4 Translation ................................................................................................. 292
Table of Contents
2012-2016 Microchip Technology Inc. DS50001686J-page 7
B.5 Environment ............................................................................................... 292
B.6 Identifiers ................................................................................................... 293
B.7 Characters ................................................................................................. 293
B.8 Integers ...................................................................................................... 294
B.9 Floating-Point ............................................................................................. 295
B.10 Arrays and Pointers ................................................................................. 296
B.11 Hints ......................................................................................................... 296
B.12 Structures, Unions, Enumerations, and Bit Fields ................................... 296
B.13 Qualifiers .................................................................................................. 297
B.14 Declarators ............................................................................................... 297
B.15 Statements ............................................................................................... 297
B.16 Pre-Processing Directives ........................................................................ 298
B.17 Library Functions ..................................................................................... 298
B.18 Architecture .............................................................................................. 302
Appendix C. Deprecated Features
C.1 Introduction ................................................................................................ 303
C.2 Variables in Specified Registers ................................................................ 303
Appendix D. Built-In Functions
D.1 Introduction ................................................................................................ 305
D.2 Built-In Function Descriptions .................................................................... 306
D.3 Built-In DSP Functions ............................................................................... 309
Appendix E. ASCII Character Set
Appendix F. Document Revision History
Document Revision History ............................................................................... 319
Support ...................................................................................................................... 323
Introduction........................................................................................................ 323
myMicrochip Personalized Notification Service................................................. 323
The Microchip Web Site .................................................................................... 324
Microchip Forums.............................................................................................. 324
Customer Support ............................................................................................. 324
Contact Microchip Technology .......................................................................... 324
Glossary ..................................................................................................................... 325
Index ........................................................................................................................... 345
Worldwide Sales and Service .................................................................................. 358
MPLAB® XC32 C/C++ Compiler User’s Guide
DS50001686J-page 8 2012-2016 Microchip Technology Inc.
NOTES:
Q MICROCHIP
MPLAB® XC32 C/C++ COMPILER
USERS GUIDE
2012-2016 Microchip Technology Inc. DS50001686J-page 9
Preface
MPLAB® XC32 C/C++ Compiler documentation and support information is discussed
in the sections below:
Document Layout
Conventions Used
Recommended Reading
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. How To’s – contains help and references for frequently encountered
situations when building projects.
Chapter 4. XC32 Toolchain and MPLAB X IDE – guides you through the toolchain
and IDE setup.
Chapter 5. Compiler Command Line Driver – describes how to use the compiler
from the command line.
Chapter 6. ANSI C Standard Issues – describes the differences between the
C/C++ language supported by the compiler syntax and the standard ANSI-89 C.
Chapter 7. Device-Related Features – describes the compiler header and register
definition files, as well as how to use them with the SFRs.
Chapter 8. Supported Data Types and Variables – describes the compiler integer
and pointer data types.
Chapter 9. Memory Allocation and Access – describes the compiler run-time
model, including information on sections, initialization, memory models, the
software stack and much more.
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® IDE or MPLAB X IDE
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 User’s Guide
DS50001686J-page 10 2012-2016 Microchip Technology Inc.
Chapter 10. Fixed-Point Arithmetic Support – describes the fixed-point types and
operations supported.
Chapter 11. Operators and Statements – discusses operators and statements.
Chapter 12. Register Usage – explains how to access and use SFRs.
Chapter 13. Functions – details available functions.
Chapter 14. Interrupts – describes how to use interrupts.
Chapter 15. Main, Runtime Start-up and Reset – describes important elements of
C/C++ code.
Chapter 16. Library Routines – explains how to use libraries.
Chapter 17. Mixing C/C++ and Assembly Language – provides guidelines for
using the compiler with 32-bit assembly language modules.
Chapter 18. Optimizations – describes optimization options.
Chapter 19. Preprocessing – details the preprocessing operation.
Chapter 20. Linking Programsexplains how linking works.
Appendix A. Embedded Compiler Compatibility Mode – discusses using the
compiler in compatibility mode.
Appendix B. Implementation-Defined Behavior – details compiler-specific
parameters described as implementation-defined in the ANSI standard.
Appendix C. Deprecated Features – details features that are considered obsolete.
Appendix D. Built-In Functions – lists the built-in functions of the C compiler.
Appendix E. ASCII Character Set – contains the ASCII character set.
Appendix F. Document Revision History – information on previous and current
revisions of this document.
Flie>Save
Preface
2012-2016 Microchip Technology Inc. DS50001686J-page 11
CONVENTIONS USED
The following conventions may appear in this documentation:
DOCUMENTATION CONVENTIONS
Description Represents Examples
Arial font:
Italic characters Referenced books MPLAB® X IDE User’s Guide
Emphasized text ...is the only compiler...
Initial caps A window the Output window
A dialog the Settings dialog
A menu selection select Enable Programmer
Quotes A field name in a window or dia-
log
“Save project before build”
Underlined, italic text with
right angle bracket
A menu path File>Save
Bold characters A dialog button Click OK
A tab Click the Power tab
Text in angle brackets < > A key on the keyboard Press <Enter>, <F1>
Courier font:
Plain Courier Sample source code #define START
Filenames autoexec.bat
File paths c:\mcc18\h
Keywords _asm, _endasm, static
Command-line options -Opa+, -Opa-
Bit values 0, 1
Constants 0xFF, ’A’
Italic Courier A variable argument file.o, where file can be
any valid filename
Square brackets [ ] Optional arguments mpasmwin [options] file
[options]
Curly brackets and pipe
character: { | }
Choice of mutually exclusive
arguments; an OR selection
errorlevel {0|1}
Ellipses... Replaces repeated text var_name [,
var_name...]
Represents code supplied by
user
void main (void)
{ ...
}
Sidebar Text
Device Dependent.
This feature is not supported on
all devices. Devices supported
will be listed in the title or text.
xmemory attribute
DD
MPLAB® XC32 C/C++ Compiler User’s Guide
DS50001686J-page 12 2012-2016 Microchip Technology Inc.
RECOMMENDED READING
The MPLAB® XC32 language toolsuite for PIC32 MCUs consists of a C compilation
driver (xc32-gcc), a C++ compilation driver (xc32-g++), an assembler (xc32-as), a
linker (xc32-ld), and an archiver/librarian (xc32-ar). This document 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 ref-
erence resources.
Release Notes (Readme Files)
For the latest information on Microchip tools, read the associated Release Notes
(HTML files) included with the software.
MPLAB® XC32 Assembler, Linker and Utilities Users Guide
(DS50002186)
A guide to using the 32-bit assembler, object linker, object archiver/librarian and various
utilities.
32-Bit Language Tools Libraries (DS50001685)
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,
References & Featured Links section.
PIC32 Configuration Settings
Lists the Configuration Bit settings for the Microchip PIC32 devices supported by the
#pragma config of the MPLAB XC32 C/C++ Compiler.
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
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 programs on a
variety of computing systems.
C++ Standards Information
Stroustrup, Bjarne, C++ Programming Language: Special Edition, 3rd Edition.
Addison-Wesley Professional; Indianapolis, Indiana, 46240.
Preface
2012-2016 Microchip Technology Inc. DS50001686J-page 13
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.
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, Second
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/
MPLAB® XC32 C/C++ Compiler User’s Guide
DS50001686J-page 14 2012-2016 Microchip Technology Inc.
NOTES:
Q MICROCHIP
MPLAB® XC32 C/C++ COMPILER
USERS GUIDE
2012-2016 Microchip Technology Inc. DS50001686J-page 15
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®, Linux® and Mac OS® X.
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.
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 5.9 “Driver Option Descriptions”.
Following this view, “compiler options” should be considered command-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.
MPLAB® XC32 C/C++ Compiler User’s Guide
DS50001686J-page 16 2012-2016 Microchip Technology Inc.
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,
language 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 18. “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.
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.
Note: Do not specify an MPLAB XC32 system include directory (e.g.,
/pic32mx/include/) in your project properties.The xc32-gcc compilation
drivers automatically select the XC libc and their respective include-file
directory for you. The xc32-g++ compilation drivers automatically select the
Dinkumware libc and their respective include-file directory for you. The Din-
kum C libraries can only be used with the C++ compiler. Manually adding a
system include file path may disrupt this mechanism and cause the incor-
rect 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.
Compiler Overview
2012-2016 Microchip Technology Inc. DS50001686J-page 17
1.3.7 Documentation
The C compiler is supported under both the MPLAB IDE v8.84 or higher, and the
MPLAB X IDE. For C++, MPLAB X IDE v1.50 or higher is required. For simplicity, both
IDEs are referred to throughout this book as simply MPLAB IDE.
Features that are unique to specific devices, and therefore specific compilers, are
noted with “DD” in the column (see the Preface), and text identifying the devices to
which the information applies.
1.4 COMPILER AND OTHER DEVELOPMENT TOOLS
The compiler works with many other Microchip tools including:
MPLAB XC32 assembler and linker - see the “MPLAB® XC32 Assembler, Linker
and Utilities User’s Guide” (DS50002186).
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
Note: Building an MPLAB XC32 C++ project and debugging C++ code requires
MPLAB X IDE v1.50 (or later). MPLAB IDE v8.xx does not support C++
projects.
MPLAB® XC32 C/C++ Compiler User’s Guide
DS50001686J-page 18 2012-2016 Microchip Technology Inc.
NOTES:
Q MICROCHIP
MPLAB® XC32 C/C++ COMPILER
USERS GUIDE
2012-2016 Microchip Technology Inc. DS50001686J-page 19
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
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.
You can only write code for one target device and only use one brand of compiler; but
if there is no regulation of the compiler’s operation, simply updating your compiler
version can 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.
MPLAB® XC32 C/C++ Compiler User’s Guide
DS50001686J-page 20 2012-2016 Microchip Technology Inc.
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 cannot allow the compiler to conform.1
But, if it is too weak, programmers would see wildly differing results within different
compilers and architectures, and the standard would lose its effectiveness.
The standard organizes source code whose behavior is not fully defined into groups
that include the following behaviors:
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 was 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 compiler is
being used, how that compiler is being used, and the device that is being targeted.
All the MPLAB XC compilers conform to the ANSI X3.159-1989 Standard for program-
ming languages (with the exception of the MPLAB XC8 compiler’s inability to allow
recursion, as mentioned in the footnote). This is commonly called the C89 Standard.
Some features from the later standard, C99, are also supported.
1. For example, the mid-range PIC® microcontrollers do not have a data stack. Because a compiler
targeting this device cannot implement recursion, it (strictly speaking) cannot conform to the ANSI
C Standard. This example illustrates a situation in which the standard is too strict for mid-range
devices and tools.
Implementation-defined
behavior
This is unspecified behavior in which each
implementation documents how the choice is made.
Unspecified behavior The standard provides two or more possibilities and
imposes no further requirements on which possibility is
chosen in any particular instance.
Undefined behavior This is behavior for which the standard imposes no
requirements.
Common C Interface
2012-2016 Microchip Technology Inc. DS50001686J-page 21
For freestanding implementations (or for what are typically call embedded applica-
tions), the standard allows non-standard extensions to the language, but obviously
does not enforce how they are specified or how they work. When working so closely to
the device hardware, a programmer needs a means of specifying device setup and
interrupts, as well as utilizing the often complex world of small-device memory
architectures. This cannot be offered by the standard in a consistent way.
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 implementation-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 uniform syntax. They replace keywords,
macros and attributes that are the native compiler implementa-
tion. The interpretation of the keyword can differ across each
compiler, and any arguments to the keywords can be device
specific.
Coding guidelines The CCI can indicate advice on how code should be written so
that it can be ported to other devices or compilers. While you
may choose not to follow the advice, it will not conform to the
CCI.
Use CCI Syntax
MPLAB® XC32 C/C++ Compiler User’s Guide
DS50001686J-page 22 2012-2016 Microchip Technology Inc.
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 can 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 X IDE widget Use CCI Syntax in your project, or use the
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.
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
indicated with these items.
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 a non-CCI feature has been used and the CCI is enabled.
Common C Interface
2012-2016 Microchip Technology Inc. DS50001686J-page 23
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 can be terminated using a line feed (\n) or carriage return (\r) that is immediately
followed by a line feed. Escaped characters can be used in character constants or
string literals to represent extended characters that are 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.
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 conforming include directives.
#include <usb_main.h>
#include "global.h"
MPLAB® XC32 C/C++ Compiler User’s Guide
DS50001686J-page 24 2012-2016 Microchip Technology Inc.
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 was compiled under other host operating systems.
Under the CCI, no directory separators should be used.
2.4.3.3 MIGRATION TO THE CCI
Any #include directives that use directory separators in the header file specifications
should be changed. Remove all but the header file name in the directive. Add the direc-
tory path to the compiler’s include search path or MPLAB X 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 X 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 that are detailed below.
Header files specified in angle bracket delimiters < > should be discoverable in the
search paths that are specified by -I options (or the equivalent MPLAB X IDE option),
or in the standard compiler include directories. The -I options are searched in the
order in which they are specified.
Header files specified in quote characters " " should be discoverable in the current
working directory or in the same directories that are searched when the header files are
specified in angle bracket delimiters (as above). In the case of an MPLAB X project, the
current working directory is the directory in which the C source file is located. If unsuc-
cessful, the search paths should be to the same directories searched when the header
file 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 speci-
fied by any -I options, or the standard compiler directories. A header file being located
elsewhere does not conform to the CCI.
Differences
The compiler operation under the CCI is not changed. This is purely a coding guideline.
2.4.4.2 MIGRATION TO THE CCI
Remove any option that specifies header file search paths other than the -I option (or
the equivalent MPLAB X 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.
Common C Interface
2012-2016 Microchip Technology Inc. DS50001686J-page 25
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 that states a lower number
of significant characters are used to identify an object.
2.4.5.1 EXAMPLE
The following example shows two poorly named variables, but names which are
considered unique under the CCI.
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
characters.
2.4.5.3 MIGRATION TO THE CCI
No action required. You can 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 clearly
indicated 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>.
MPLAB® XC32 C/C++ Compiler User’s Guide
DS50001686J-page 26 2012-2016 Microchip Technology Inc.
2.4.7 Plain char Types
The type of a plain char is unsigned char. It is generally recommended that all
definitions for the char type explicitly state the signedness of the object.
2.4.7.1 EXAMPLE
The following example
char foobar;
defines an unsigned char object called foobar.
2.4.7.2 DIFFERENCES
The 8-bit compilers have always treated plain char as an unsigned type.
The 16- and 32-bit compilers used signed char as the default plain char type. 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 can use the -funsigned-char option on MPLAB XC16 and XC32 to change the
type of plain char, but since this option is not supported on MPLAB 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
integer.
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.
Common C Interface
2012-2016 Microchip Technology Inc. DS50001686J-page 27
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 is truncated.
signed char destination;
unsigned int source = 0x12FE;
destination = source;
Under the CCI, the value of destination after the alignment is -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 Bitwise 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
operation.
signed char output, input = -13;
output = input & 0x7E;
Under the CCI, the value of output after the assignment is 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 example shows a negative quantity involved in a right-shift operation.
signed char output, input = -13;
output = input >> 3;
Under the CCI, the value of output after the assignment is -2 (i.e., the bit pattern
0xFE).
MPLAB® XC32 C/C++ Compiler User’s Guide
DS50001686J-page 28 2012-2016 Microchip Technology Inc.
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
conditions.
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 cor-
rect 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 is identical to that of one defined using
unsigned int. This is quite different from 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 that are
unsigned integers and with the size specified.
struct OUTPUTS {
int direction :1;
int parity :3;
int value :4;
};
Common C Interface
2012-2016 Microchip Technology Inc. DS50001686J-page 29
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
intention was for these to be signed quantities, then the type of these should be
changed to signed int. In the following example:
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
The standard indicates that implementations can determine whether bit-fields cross a
storage unit boundary. In the CCI, bit-fields do not straddle a storage unit boundary; a
new storage unit is allocated to the structure, and padding bits 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
compilers, 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 MPLAB XC8, the storage allocation unit is byte sized. The
bit-field second is 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, is 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 Bit-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 is the least significant bit (LSb) of the storage
unit in which it is allocated.
MPLAB® XC32 C/C++ Compiler User’s Guide
DS50001686J-page 30 2012-2016 Microchip Technology Inc.
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 is assigned the least significant bit of the storage unit assigned to the
structure foo. The bit-field mid is 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 by <stddef.h>; however, its definition is
implementation-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 converted 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 is 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.
Common C Interface
2012-2016 Microchip Technology Inc. DS50001686J-page 31
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>
previously used in 8-bit compiler code, or family-specific header files, for example,
from:
#include <p32xxxx.h>
#include <p30fxxxx.h>
#include <p33Fxxxx.h>
#include <p24Fxxxx.h>
#include "p30f6014.h"
to:
#include <xc.h>
2.5.2 Absolute Addressing
Variables and functions can be placed at an absolute address by using the __at() con-
struct. Stack-based (auto and parameter) variables 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.
2.5.2.3 MIGRATION TO THE CCI
Avoid making objects and functions absolute if possible.
MPLAB® XC32 C/C++ Compiler User’s Guide
DS50001686J-page 32 2012-2016 Microchip Technology Inc.
In MPLAB XC8, change absolute object definitions, for example, from:
int scanMode @ 0x200;
to:
int scanMode __at(0x200);
In MPLAB XC16 and XC32, change code, e.g., from:
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
MPLAB XC8, the __section() specifier is currently ignored.
2.5.3 Far Objects and Functions
The __far qualifier can be used to indicate that variables or functions are 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 usually 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 is 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.
Common C Interface
2012-2016 Microchip Technology Inc. DS50001686J-page 33
2.5.3.3 MIGRATION TO THE CCI
For 8-bit compilers, change any occurrence of the far qualifier, for example, from:
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, for exam-
ple, from:
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 can be used to indicate that variables or functions are 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. Expres-
sions involving near-qualified objects generally are 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 is 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.
MPLAB® XC32 C/C++ Compiler User’s Guide
DS50001686J-page 34 2012-2016 Microchip Technology Inc.
2.5.4.3 MIGRATION TO THE CCI
For 8-bit compilers, change any occurrence of the near qualifier to __near, for
example, from:
near char template[20];
to:
__near char template[20];
In 16- and 32-bit compilers, change any occurrence of the near attribute to __near,
e.g., from:
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 can 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 indi-
cate 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 to
__persistent, e.g., from:
persistent char template[20];
to:
__persistent char template[20];
For the 16- and 32-bit compilers, change any occurrence of the persistent attribute
to __persistent, for example, from:
int tblIdx __attribute__ ((persistent));
to
int __persistent tblIdx;
2.5.5.4 CAVEATS
None.
Common C Interface
2012-2016 Microchip Technology Inc. DS50001686J-page 35
2.5.6 X and Y Data Objects
The __xdata and __ydata qualifiers can be used to indicate that variables are located
in special memory regions. Exactly what constitutes X and Y memory is dependent on
the target device, but it is typically memory that can be accessed independently on sep-
arate 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 is 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 to __xdata, or __ydata respectively, e.g., from:
char __attribute__((space(xmemory)))template[20];
to:
__xdata char template[20];
2.5.6.4 CAVEATS
None.
2.5.7 Banked Data Objects
The __bank(num) qualifier can be used to indicate that variables are located in a par-
ticular 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 sub-
division 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 is 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;
MPLAB® XC32 C/C++ Compiler User’s Guide
DS50001686J-page 36 2012-2016 Microchip Technology Inc.
2.5.7.2 DIFFERENCES
The 8-bit compilers have used the four qualifiers bank0, bank1, bank2 and bank3 to
indicate the same, albeit more limited, memory placement.
Equivalent specifiers have never been defined for any other compiler.
2.5.7.3 MIGRATION TO THE CCI
For 8-bit compilers, change any occurrence of the bankx qualifiers to __bank(), e.g.,
from:
bank2 int logEntry;
to:
__bank(2) int logEntry;
2.5.7.4 CAVEATS
This feature is not yet implemented in MPLAB XC8.
2.5.8 Alignment of Objects
The __align(alignment) specifier can 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 2. 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 to
__align, e.g., from:
char __attribute__((aligned(4)))mode;
to:
__align(4) char mode;
2.5.8.4 CAVEATS
This feature is not yet implemented on MPLAB XC8.
Common C Interface
2012-2016 Microchip Technology Inc. DS50001686J-page 37
2.5.9 EEPROM Objects
The __eeprom qualifier can be used to indicate that variables should be positioned in
EEPROM.
Use the native keywords discussed in the Differences section to look up information on
the semantics of this qualifier.
Some devices may not implement EEPROM. Use of this qualifier for such devices gen-
erates 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 to __eeprom, e.g.,
from:
eeprom char title[20];
to:
__eeprom char title[20];
For 16-bit compilers, change any occurrence of the eedata space attribute to
__eeprom, e.g., from:
int mainSw __attribute__ ((space(eedata)));
to:
int __eeprom mainSw;
2.5.9.4 CAVEATS
MPLAB XC8 does not implement the __eeprom qualifiers for any PIC18 devices; this
qualifier works as expected for other 8-bit devices.
MPLAB® XC32 C/C++ Compiler User’s Guide
DS50001686J-page 38 2012-2016 Microchip Technology Inc.
2.5.10 Interrupt Functions
The __interrupt(type) specifier can 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:
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
generates a warning. If the argument to the __interrupt specifier does not make
sense for the target device, a warning or error is 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;
}
}
<empty> Implement the default interrupt function.
low_priority The interrupt function corresponds to the low priority interrupt
source.
(MPLAB XC8 - PIC18 only)
high_priority The interrupt function corresponds to the high priority interrupt
source.
(MPLAB XC8)
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 utilize 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)
Common C Interface
2012-2016 Microchip Technology Inc. DS50001686J-page 39
2.5.10.2 DIFFERENCES
The 8-bit compilers have used the interrupt and low_priority qualifiers to indicate
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, e.g., from:
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, e.g., from:
void _attribute_((interrupt(auto_psv,irq(52))))
_T1Interrupt(void);
to:
void __interrupt(auto_psv,irq(52))) _T1Interrupt(void);
For 32-bit compilers, the __interrupt() keyword takes two parameters, the vector
number and the (optional) IPL value. Change code that uses the interrupt attribute,
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.
MPLAB® XC32 C/C++ Compiler User’s Guide
DS50001686J-page 40 2012-2016 Microchip Technology Inc.
2.5.11 Packing Objects
The __pack specifier can 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 cannot pad structures with alignment gaps for some devices, and use
of this specifier for such devices is 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 that is with MPLAB 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 structure
member was not aligned with a memory gap.
2.5.11.3 MIGRATION TO THE CCI
No migration is required for MPLAB XC8.
For 16- and 32-bit compilers, change any occurrence of the packed attribute, e.g., from:
struct DOT
{
char a;
int x[2] __attribute__ ((packed));
};
to:
struct DOT
{
char a;
__pack int x[2];
};
Alternatively, you can pack the entire structure, if required.
2.5.11.4 CAVEATS
None.
2.5.12 Indicating Antiquated Objects
The __deprecate specifier can be used to indicate that an object has limited longevity
and should not be used in new designs. It is commonly used by the compiler vendor to
indicate that compiler extensions or features can become obsolete, or that better
features have been developed and should be used in preference.
Common C Interface
2012-2016 Microchip Technology Inc. DS50001686J-page 41
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 that 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 the different
spelling) 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 to
__deprecate, e.g., from:
int __attribute__(deprecated) intMask;
to:
int __deprecate intMask;
2.5.12.4 CAVEATS
None.
MPLAB® XC32 C/C++ Compiler User’s Guide
DS50001686J-page 42 2012-2016 Microchip Technology Inc.
2.5.13 Assigning Objects to Sections
The __section() specifier can be used to indicate that an object should be located in
the named section (or psect, using MPLAB XC8 terminology). This is typically used
when the object has special and unique linking requirements that 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 previously used the #pragma psect directive to redirect
objects to a new section, or psect. However, the __section() specifier is the
preferred method to perform this task, even if you are not using the CCI.
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 MPLAB 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, e.g.,
from:
int __attribute__((section("myVars"))) intMask;
to:
int __section("myVars") intMask;
2.5.13.4 CAVEATS
None.
2.5.14 Specifying Configuration Bits
The #pragma config directive can be used to program the Configuration bits for a
device. The pragma has the form:
#pragma config setting = state|value
where setting is a configuration setting descriptor (e.g., WDT), state is a descriptive
value (e.g., ON) and value is a numerical value.
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.
Common C Interface
2012-2016 Microchip Technology Inc. DS50001686J-page 43
#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
settings.
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, e.g.,
__CONFIG(WDTEN & XT & DPROT)
to the #pragma config directive, e.g.,
#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() mac-
ros attribute, e.g., from:
_FOSC(CSW_FSCM_ON & EC_PLL16);
to:
#pragma config FCKSMEM = CSW_ON_FSCM_ON, FPR = ECIO_PLL16
No migration is required for 32-bit code.
2.5.14.4 CAVEATS
None.
MPLAB® XC32 C/C++ Compiler User’s Guide
DS50001686J-page 44 2012-2016 Microchip Technology Inc.
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.
2.5.15.1 EXAMPLE
The following shows code that 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
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 that uses compiler-defined macros needs review. Old macros continue to
work as expected, but they are not compliant with the CCI.
2.5.15.4 CAVEATS
None.
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 enforcement is
enabled
__CCI__
__XC##__ The specific XC compiler used (## can be 8, 16 or
32)
__XC8__
__DEVICEFAMILY__ The family of the selected target device __dsPIC30F__
__DEVICENAME__ The selected target device name __18F452__
Common C Interface
2012-2016 Microchip Technology Inc. DS50001686J-page 45
2.5.16 In-line Assembly
The asm() statement can be used to insert assembly code in-line with C code. The
argument is a C string literal that 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, fe.g., from:
#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.
CCI Syntax
MPLAB® XC32 C/C++ Compiler User’s Guide
DS50001686J-page 46 2012-2016 Microchip Technology Inc.
2.6 COMPILER FEATURES
The following item details the compiler options used to control the CCI.
2.6.1 Enabling the CCI
It is assumed that 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.
If you are not using this IDE, then the command-line options are --EXT=cci for MPLAB
XC8 or -mcci for MPLAB XC16 and XC32.
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.
Q MICROCHIP
MPLAB® XC32 C/C++ COMPILER
USERS GUIDE
2012-2016 Microchip Technology Inc. DS50001686J-page 47
Chapter 3. How To’s
3.1 INTRODUCTION
This section contains help and references for situations that are frequently encountered
when building projects for Microchip 32-bit devices. Click the links at the beginning of
each section to assist finding the topic relevant to your question. Some topics are
indexed in multiple sections.
Start here:
Installing and Activating the Compiler
Invoking the Compiler
Writing Source Code
Getting My Application to Do What I Want
Understanding the Compilation Process
Fixing Code That Does Not Work
3.2 INSTALLING AND ACTIVATING THE COMPILER
This section details questions that might arise when installing or activating the compiler.
How Do I Install and Activate My Compiler?
How Can I Tell if the Compiler has Activated Successfully?
Can I Install More Than One Version of the Same Compiler?
3.2.1 How Do I Install and Activate My Compiler?
Installation and activation of the license are performed simultaneously by the XC com-
piler installer. The guide Installing and Licensing MPLAB XC C Compilers (DS52059)
is available on www.microchip.com. It provides details on single-user and network
licenses, as well as how to activate a compiler for evaluation purposes.
3.2.2 How Can I Tell if the Compiler has Activated Successfully?
If you think the compiler may not have installed correctly or is not working, it is best to
verify its operation outside of MPLAB X IDE to isolate possible problems. Try running
the compiler from the command line to check for correct operation. You do not actually
have to compile code.
From your terminal or command-line prompt, run the license manager xclm with the
option -status. This option instructs the license manager to print all MPLAB XC licenses
installed on your system and exit. So, under 32-bit Windows, for example, type the fol-
lowing line, replacing the path information with a path that is relevant to your installa-
tion.
"C:\Program Files\Microchip\xc32\v1.00\bin\xclm" -status
The license manager should run, print all of the MPLAB XC compiler license available
on your machine, and quit. Confirm that the your license is listed as activated (e.g.,
Product:swxc32-pro) Note: if it is not activated properly, the compiler will continue to
operate, but only in the Free mode. If an error is displayed, or the compiler indicates
Free mode, then activation was not successful.
MPLAB® XC32 C/C++ Compiler User’s Guide
DS50001686J-page 48 2012-2016 Microchip Technology Inc.
3.2.3 Can I Install More Than One Version of the Same Compiler?
Yes, the compilers and installation process has been designed to allow you to have
more than one version of the same compiler installed. For MPLAB X IDE, you can eas-
ily swap between version by changing options in the IDE (see Section 3.3.4 “How Can
I Select Which Compiler I Want to Build With?”.)
Compilers should be installed into a directory whose name is related to the compiler
version. This is reflected in the default directory specified by the installer. For example,
the MPLAB XC32 compilers v1.00 and v1.10 would typically be placed in separate
directories.
C:\Program Files\Microchip\xc32\v1.00\
C:\Program Files\Microchip\xc32\v1.10\
How To’s
2012-2016 Microchip Technology Inc. DS50001686J-page 49
3.3 INVOKING THE COMPILER
This section discusses how the compiler is run, both on the command-line and from the
IDE. It includes information about how to get the compiler to do what you want in terms
of options and the build process itself.
How Do I Compile from Within MPLAB IDE?
How Do I Compile on the Command-line?
How Do I Compile Using a Make Utility?
How Can I Select Which Compiler I Want to Build With?
How Can I Change the Compiler's Operating Mode?
How Do I Build Libraries?
How Do I Know What Compiler Options Are Available and What They Do?
How Do I Know What the Build Options in MPLAB IDE do?
What is Different About an MPLAB IDE Debug Build?
See also How Do I Stop the Compiler Using Certain Memory Locations?
See also What Do I Need to Do When Compiling to Use a Debugger?
See also How Do I Use Library Files In My Project?
See also What Optimizations Are Employed By The Compiler?
3.3.1 How Do I Compile from Within MPLAB IDE?
See the following documentation for information on how to set up a project:
Section 4.5 “Project Setup” - MPLAB X IDE
3.3.2 How Do I Compile on the Command-line?
The compiler driver is called xc32-gcc for all 32-bit devices; e.g., in Windows, it is
named xc32-gcc.exe. This application should be invoked for all aspects of compila-
tion. It is located in the bin directory of the compiler distribution. Avoid running the indi-
vidual compiler applications (such as the assembler or linker) explicitly. You can
compile and link in the one command, even if your project is spread among multiple
source files.
The driver is introduced in Section 5.2 “Invoking the Compiler”. See
Section 3.3.4 “How Can I Select Which Compiler I Want to Build With?” to ensure you
are running the correct driver if you have more than one installed. The command-line
options to the driver are detailed in Section 5.9 “Driver Option Descriptions”. The files
that can be passed to the driver are listed and described in Section 5.2.3 “Input File
Types.
3.3.3 How Do I Compile Using a Make Utility?
When compiling using a make utility (such as make), the compilation is usually per-
formed as a two-step process: first generating the intermediate files, and then the final
compilation and link step to produce one binary output. This is described in
Section 5.3.2 “Multi-step C Compilation”.
3.3.4 How Can I Select Which Compiler I Want to Build With?
The compilation and installation process has been designed to allow you to have more
than one compiler installed at the same time For MPLAB X IDE, you can create a proj-
ect and then build this project with different compilers by simply changing a setting in
the project properties.
File>Pm 'ect Progem'es
MPLAB® XC32 C/C++ Compiler User’s Guide
DS50001686J-page 50 2012-2016 Microchip Technology Inc.
In MPLAB X IDE, you select which compiler to use when building a project by opening
the Project Properties window (File>Project Properties) and selecting the Configuration
category (Conf: [default]). A list of MPLAB XC32 compiler versions is shown in the
Compiler Toolchain, on the far right. Select the MPLAB XC32 compiler you require.
Once selected, the controls for that compiler are then shown by selecting the XC32
global options, XC32 Compiler and XC32 Linker categories. These reveal a pane of
options on the right; each category has several panes which can be selected from a
pull-down menu that is near the top of the pane.
3.3.5 How Can I Change the Compiler's Operating Mode?
The compiler’s operating mode (Free, Evaluation, Standard or PRO) is based on its
level of optimizations (see Chapter 18. “Optimizations”) which can be specified as a
command line option (see Section 5.9.7 “Options for Controlling Optimization”.) If you
are building under MPLAB X IDE, go to the Project Properties window, click on the com-
piler name (xc32-gcc for C language projects or xc32-g++ for C++ language projects),
and select the Optimization option category to set optimization levels - see
Section 4.5.3 “xc32-gcc (32-bit C Compiler)”.
When building your project, the compiler will emit a warning message if you have
selected an option that is not available for your licensed operating mode. The compiler
will continue compilation with the option disabled.
3.3.6 How Do I Build Libraries?
When you have functions and data that are commonly used in applications, you can
make all the C source and header files available so other developers can copy these
into their projects. Alternatively, you can build these modules into object files and pack-
age them into library archives, which, along with the accompanying header files, can
then be built into an application.
Libraries can be more convenient because there are fewer files to manage. However,
libraries do need to be maintained. MPLAB XC32 uses *.a library archives. Be sure to
rebuild your library objects when you move your project to a new release of the com-
piler toolchain.
Using the compiler driver, libraries can begin to be built by listing all the files that are to
be included into the library on the command line. None of these files should contain a
main() function, nor settings for configuration bits or any other such data.
For information on how to create your own libraries, see Section 5.5.1.2 “User-defined
Libraries”.
How To’s
2012-2016 Microchip Technology Inc. DS50001686J-page 51
3.3.7 How Do I Know What Compiler Options Are Available and What
They Do?
A list of all compiler options can be obtained by using the --help option on the com-
mand line. Alternatively, all options are listed in Section 5.9 “Driver Option Descrip-
tions” in this user’s guide. If you are compiling in MPLAB X IDE, see
Section 4.5 “Project Setup”.
3.3.8 How Do I Know What the Build Options in MPLAB IDE do?
Most of the widgets and controls in the MPLAB X IDE Project Properties window, XC32
options, map directly to one command-line driver option or suboption. See
Section 4.5 “Project Setup” for a list of options and any corresponding command-line
options.
3.3.9 What is Different About an MPLAB IDE Debug Build?
The main difference between a command-line debug build and an MPLAB X IDE debug
build is the setting of a preprocessor macro called __DEBUG to be 1 when a debug is
selected. This macro is not defined if it is not a debug build.
You may make code in your source conditional on this macro using #ifdef directives,
etc (see Section 5.9.8 “Options for Controlling the Preprocessor”) so that you can have
your program behave differently when you are still in a development cycle. Some com-
piler errors are easier to track down after performing a debug build.
In MPLAB X IDE, memory will be reserved for your debugger only when you perform a
debug build. See Section 3.5.3 “What Do I Need to Do When Compiling to Use a
Debugger?”.
MPLAB® XC32 C/C++ Compiler User’s Guide
DS50001686J-page 52 2012-2016 Microchip Technology Inc.
3.4 WRITING SOURCE CODE
This section presents issues pertaining to the source code you write. It has been
subdivided into sections listed below.
C Language Specifics
Device-Specific Features
Memory Allocation
• Variables
• Functions
• Interrupts
Assembly Code
3.4.1 C Language Specifics
This section discusses source code issues that are directly relates to the C language
itself but which are commonly asked.
When Should I Cast Expressions?
Can Implicit Type Conversions Change the Expected Results of My Expressions?
How Do I Enter Non-English Characters Into My Program?
How Can I Use a Variable Defined in Another Source File?
How Do I Port My Code to Different Device Architectures?
3.4.1.1 WHEN SHOULD I CAST EXPRESSIONS?
Expressions can be explicitly cast using the cast operator -- a type in round brackets,
e.g., (int). In all cases, conversion of one type to another must be done with caution
and only when absolutely necessary.
Consider the example:
unsigned long l;
unsigned short s;
s = l;
Here, a long type is being assigned to a int type, and the assignment will truncate the
value in l. The compiler will automatically perform a type conversion from the type of
the expression on the right of the assignment operator (long) to the type of the lvalue
on the left of the operator (short).This is called an implicit type conversion. The com-
piler will typically produce a warning concerning the potential loss of data by the
truncation.
A cast to type short is not required and should not be used in the above example if a
long to short conversion was intended. The compiler knows the types of both oper-
ands and will perform the conversion accordingly. If you did use a cast, there is the
potential for mistakes if the code is later changed. For example, if you had:
s = (short)l;
the code will work the in the same way; but, if in future, the type of s is changed to a
long, for example, then you must remember to adjust the cast, or remove it, because
otherwise the contents of l will continue to be truncated by the assignment, which may
not be correct. Most importantly, the warning issued by the compiler will not be
produced if the cast is in place.
How To’s
2012-2016 Microchip Technology Inc. DS50001686J-page 53
Use a cast only in situations where the types used by the compiler are not the types
that you require. For example consider the result of a division assigned to a
floating-point variable:
int i, j;
float fl;
fl = i/j;
In this case integer division is performed, then the rounded integer result is converted
to a float format. So if i contained 7 and j contained 2, the division will yield 3 and
this will be implicitly converted to a float type (3.0) and then assigned to fl. If you
wanted the division to be performed in a float format, then a cast is necessary:
fl = (float)i/j;
(Casting either i or j will force the compiler to encode a floating-point division). The
result assigned to fl now be 3.5.
An explicit cast may suppress warnings that might otherwise have been produced. This
can also be the source of many problems. The more warnings the compiler produces,
the better chance you have of finding potential bugs in your code.
3.4.1.2 CAN IMPLICIT TYPE CONVERSIONS CHANGE THE EXPECTED
RESULTS OF MY EXPRESSIONS?
Yes! The compiler will always use integral promotion and there is no way to disable this
(see Section 11.2 “Integral Promotion”). In addition, the types of operands to binary
operators are usually changed so that they have a common type as specified by the C
Standard. Changing the type of an operand can change the value of the final expres-
sion so it is very important that you understand the type C Standard conversion rules
that apply when dealing with binary operators. You can manually change the type of an
operand by casting (see Section 3.4.1.1 “When Should I Cast Expressions?”).
3.4.1.3 HOW DO I ENTER NON-ENGLISH CHARACTERS INTO MY PROGRAM?
The ANSI standard and MPLAB XC C do not support extended characters set in char-
acter and string literals in the source character set. See Section 8.9 “Constant Types
and Formats” to see how these characters can be entered using escape sequences.
3.4.1.4 HOW CAN I USE A VARIABLE DEFINED IN ANOTHER SOURCE FILE?
Provided the variable defined in the other source file is not static (see
Section 9.3.2 “Static Variables”) or auto (see Section 9.4 “Auto Variable Allocation and
Access”), adding a declaration for that variable in the current file will allow you to
access it. A declaration consists of the keyword extern in addition to the type and
name of the variable as specified in its definition, e.g.
extern int systemStatus;
This is part of the C language and your favorite C text will give you more information.
The position of the declaration in the current file determines the scope of the variable,
i.e., if you place the declaration inside a function, it will limit the scope of the variable to
that function; placed outside of a function allows access to the variable in all functions
for the remainder of the current file.
Often, declarations are placed in header files and these are then #included into the C
source code (see Section 19.3 “Preprocessor Directives”).
MPLAB® XC32 C/C++ Compiler User’s Guide
DS50001686J-page 54 2012-2016 Microchip Technology Inc.
3.4.1.5 HOW DO I PORT MY CODE TO DIFFERENT DEVICE
ARCHITECTURES?
Microchip devices have three basic architectures: 8-bit, which is a Harvard architecture
with a separate program and data memory bus; 32-bit, which is a modified Harvard
architecture also with a separate program and data memory bus; and 32-bit, which is
a MIPS architecture. Porting code to different devices within an architectural family
requires a minimum update to application code. However, porting between architec-
tural families can require significant rewrite.
In an attempt to reduce the work to port between architectures, a Common C Interface,
or CCI, has been developed. If you use these coding styles, your code will more easily
migrate upward. For more on CCI, see Chapter 2. “Common C Interface”.
3.4.2 Device-Specific Features
This section discusses the code that needs to be written to set up or control a feature
that is specific to Microchip PIC devices.
How Do I Set the Configuration Bits?
How Do I Determine the Cause of Reset?
How Do I Access SFRs?
How Do I Stop the Compiler Using Certain Memory Locations?
See, also, the following linked information in other sections.
What Do I Need to Do When Compiling to Use a Debugger?
3.4.2.1 HOW DO I SET THE CONFIGURATION BITS?
These should be set in your code using either a macro or pragma. Earlier versions of
MPLAB IDE allowed you to set these bits in a dialog, but MPLAB X IDE requires that
they be specified in your source code. Config bits are set in source code using the con-
fig pragma. See Section 7.5 “Configuration Bit Access” for more information on the
config pragma.
3.4.2.2 HOW DO I DETERMINE THE CAUSE OF RESET?
The bits in the Reset Control (RCON) Register allow you to determine the cause of a
Reset. See the data sheet for your target device for a description of the RCON register.
3.4.2.3 HOW DO I ACCESS SFRS?
The compiler ships with header files, see Section 7.7 “Using SFRs From C Code”, that
define variables which are mapped over the top of memory-mapped SFRs. Since these
are C variables, they can be used like any other C variable and no new syntax is
required to access these registers.
Bits within SFRs can also be accessed. Bit-fields are available in structures which map
over the SFR as a whole. See Section 8.6.2 “Bit Fields in Structures”.
The name assigned to the variable is usually the same as the name specified in the
device data sheet. See Section 3.4.2.4 “How Do I Find The Names Used to Represent
SFRs and Bits?” if these names are not recognized.
How To’s
2012-2016 Microchip Technology Inc. DS50001686J-page 55
3.4.2.4 HOW DO I FIND THE NAMES USED TO REPRESENT SFRS AND BITS?
Special function registers and the bits within those are accessed via special variables
that map over the register, Section 3.4.2.3 “How Do I Access SFRs?”; however, the
names of these variables sometimes differ from those indicated in the data sheet for
the device you are using.
View the device-specific header file which allows access to these special variables.
Begin by searching for the data sheet SFR name. If that is not found, search on what
the SFR represents, as comments in the header often spell out what the macros under
the comment do.
3.4.3 Memory Allocation
Here are questions relating to how your source code affects memory allocation.
How Do I Position Variables at an Address I Nominate?
How Do I Position Functions at an Address I Nominate?
How Do I Place Variables in Program Memory?
How Do I Stop the Compiler Using Certain Memory Locations?
Why are Some Objects Positioned into Memory that I Reserved?
3.4.3.1 HOW DO I POSITION VARIABLES AT AN ADDRESS I NOMINATE?
The easiest way to do this is to make the variable absolute by using the address attri-
bute (see Section 8.12 “Variable Attributes”) or the __at() CCI construct (see
Section 2.5.2 “Absolute Addressing). This means that the address you specify is used
in preference to the variable’s symbol in generated code. Since you nominate the
address, you have full control over where objects are positioned, but you must also
ensure that absolute variables do not overlap.
See also Section 9.4 “Auto Variable Allocation and Access” for information on moving
auto variables, Section 9.3.1 “Non-auto Variable Allocation” for moving non-auto vari-
ables and Section 9.5 “Variables in Program Memory” for moving program-space vari-
ables.
3.4.3.2 HOW DO I POSITION FUNCTIONS AT AN ADDRESS I NOMINATE?
The easiest way to do this is to make the functions absolute, by using the address attri-
bute (see Section 13.3.1 “Function Attributes”). This means that the address you spec-
ify is used in preference to the function’s symbol in generated code. Since you
nominate the address, you have full control over where functions are positioned, but
must also ensure that absolute functions do not overlap.
3.4.3.3 HOW DO I PLACE VARIABLES IN PROGRAM MEMORY?
The const qualifier implies that the qualified variable is read only. See the
-membedded-data option in Section 5.9.1 “Options Specific to PIC32 Devices” for infor-
mation about allocating 'const' qualified variables to program memory (Flash). As a
consequence of this any variables, except for auto variables or function parameters,
qualified const are placed in program memory, thus freeing valuable data RAM (see
Section 9.5 “Variables in Program Memory”). Variables qualified const can also be
made absolute, so that they can be positioned at an address you nominate.
MPLAB® XC32 C/C++ Compiler User’s Guide
DS50001686J-page 56 2012-2016 Microchip Technology Inc.
3.4.3.4 HOW DO I STOP THE COMPILER USING CERTAIN MEMORY
LOCATIONS?
Concatenating an address attribute with the noload attribute can be used to block out
sections of memory. Also, you can use the option -mreserve. For more on variable
attributes and options, see the following sections in this user’s guide:
Section 8.12 “Variable Attributes”
Section 5.9.1 “Options Specific to PIC32 Devices”
See the MPLAB® XC32 Assembler, Linker and Utilities User’s Guide (DS50002186) for
details on linker scripts.
3.4.4 Variables
This examines questions that relate to the definition and usage of variables and types
within a program.
Why Are My Floating-point Results Not Quite What I Am Expecting?
How Can I Access Individual Bits of a Variable?
How Long Can I Make My Variable and Macro Names?
How Do I Share Data Between Interrupt and Main-line Code?
How Do I Position Variables at an Address I Nominate?
How Do I Place Variables in Program Memory?
How Can I Rotate a Variable?
How Do I Find Out Where Variables and Functions Have Been Positioned?
3.4.4.1 WHY ARE MY FLOATING-POINT RESULTS NOT QUITE WHAT I AM
EXPECTING?
First, make sure that if you are watching floating-point variables in MPLAB IDE that the
type and size of these match how they are defined. In MPLAB XC32, the float and
double types are 32-bit floating-point types by default. The long double type is a 64-bit
floating-point type.
The size of the floating point type can be adjusted for double types. See
Section 8.5 “Floating-Point Data Types”.
Since floating-point variables only have a finite number of bits to represent the values
they are assigned, they will hold an approximation of their assigned value. A float-
ing-point variable can only hold one of a set of discrete real number values. If you
attempt to assign a value that is not in this set, it is rounded to the nearest value. The
more bits used by the mantissa in the floating-point variable, the more values can be
exactly represented in the set and the average error due to the rounding is reduced.
Whenever floating-point arithmetic is performed, rounding also occurs. This can also
lead to results that do not appear to be correct.
How To’s
2012-2016 Microchip Technology Inc. DS50001686J-page 57
3.4.4.2 HOW CAN I ACCESS INDIVIDUAL BITS OF A VARIABLE?
There are several ways of doing this. The simplest and most portable way is to define
an integer variable and use macros to read, set or clear the bits within the variable
using a mask value and logical operations, such as the following.
#define testbit(var, bit) ((var) & (1 <<(bit)))
#define setbit(var, bit) ((var) |= (1 << (bit)))
#define clrbit(var, bit) ((var) &= ~(1 << (bit)))
These, respectively, test to see if bit number, bit, in the integer, var, is set; set the cor-
responding bit in var; and clear the corresponding bit in var. Alternatively, a union
of an integer variable and a structure with bit-fields (see Section 8.6.2 “Bit Fields in
Structures”) can be defined, e.g.
union both {
unsigned char byte;
struct {
unsigned b0:1, b1:1, b2:1, b3:1, b4:1, b5:1, b6:1, b7:1;
} bitv;
} var;
This allows you to access byte as a whole (using var.byte), or any bit within that vari-
able independently (using var.bitv.b0 through var.bitv.b7).
3.4.4.3 HOW LONG CAN I MAKE MY VARIABLE AND MACRO NAMES?
The C Standard indicates that only a number of initial characters in an identifier are sig-
nificant, but it does not actually state what this number is and it varies from compiler to
compiler. For MPLAB XC32, no limit is imposed, but for CCI there is a limit (see
Section 2.4.5 “The Number of Significant Initial Characters in an Identifier”). CCI Com-
pliant names are more portable across Microchip architectures.
If two identifiers only differ in the non-significant part of the name, they are considered
to represent the same object, which will almost certainly lead to code failure.
3.4.5 Functions
This section examines questions that relate to functions.
What is the Optimum Size For Functions?
How Can I Tell How Big a Function Is?
How Do I Know What Resources Are Being Used by Each Function?
How Do I Find Out Where Variables and Functions Have Been Positioned?
How Do I Use Interrupts in C?
How Do I Stop An Unused Function Being Removed?
How Do I Make a Function Inline?
MPLAB® XC32 C/C++ Compiler User’s Guide
DS50001686J-page 58 2012-2016 Microchip Technology Inc.
3.4.5.1 WHAT IS THE OPTIMUM SIZE FOR FUNCTIONS?
Generally speaking, the source code for functions should be kept small as this aids in
readability and debugging. It is much easier to describe and debug the operation of a
function which performs a small number of tasks. Also smaller-sized functions typically
have less side effects, which can be the source of coding errors. On the other hand, in
the embedded programming world, a large number of small functions, and the calls
necessary to execute them, may result in excessive memory and stack usage. There-
fore a compromise is often necessary.
Function size can cause issues with memory paging, as addressed in
Section 13.6 “Function Size Limits”. The smaller the functions, the easier it is for the
linker to allocate them to memory without errors.
3.4.5.2 HOW DO I STOP AN UNUSED FUNCTION BEING REMOVED?
The __attribute__((keep)) may be applied to a function. The keep attribute will pre-
vent the linker from removing the function with --gc-sections, even if it is unused. See
the “MPLAB® XC32 Assembler, Linker and Utilities User’s Guide” (DS50002186) for
more information on section garbage collection using the --gc-sections option.
3.4.5.3 HOW DO I MAKE A FUNCTION INLINE?
The XC32 compiler does not inline any functions when not optimizing.
By declaring a function inline, you can direct the XC32 compiler to make calls to that
function faster. One way XC32 can achieve this is to integrate that function's code into
the code for its callers. This makes execution faster by eliminating the function-call
overhead; in addition, if any of the actual argument values are constant, their known
values may permit simplifications at compile time so that not all of the inline function's
code needs to be included. The effect on code size is less predictable; object code may
be larger or smaller with function inlining, depending on the particular case.
To declare a function inline, use the inline keyword in its declaration, like this:
static inline int
inc (int *a)
{
return (*a)++;
}
When a function is both inline and static, if all calls to the function are integrated into
the caller, and the function's address is never used, then the function's own assembler
code is never referenced. In this case, XC32 does not actually output assembler code
for the function. Some calls cannot be integrated for various reasons (in particular, calls
that precede the function's definition cannot be integrated, and neither can recursive
calls within the definition). If there is a non-integrated call, then the function is compiled
to assembler code as usual. The function must also be compiled as usual if the pro-
gram refers to its address, because that can't be inlined.
Enable optimization level -O1 or greater to enable function inlining.
How To’s
2012-2016 Microchip Technology Inc. DS50001686J-page 59
3.4.6 Interrupts
Interrupt and interrupt service routine questions are discussed in this section.
How Do I Use Interrupts in C?
How Can I Make My Interrupt Routine Faster?
How Do I Share Data Between Interrupt and Main-line Code?
3.4.6.1 HOW DO I USE INTERRUPTS IN C?
First, be aware of what interrupt hardware is available on your target device. 32-bit
devices implement several separate interrupt vector locations and use a priority
scheme. For more information, see Section 14.2 “Interrupt Operation”.
In C source code, a function can be written to act as the interrupt service routine by
using the interrupt attribute. Such functions save/restore program context
before/after executing the function body code and a different return instruction is used.
For more on writing interrupt functions, see Section 14.3 “Writing an Interrupt Service
Routine”. To populate the interrupt vector table, use the vector or at_vector attribute.
An __ISR() macro is provided in the sys/attribs.h header file that simplifies the usage
of the interrupt and vector attributes.
Prior to any interrupt occurring, your program must ensure that peripherals are cor-
rectly configured and that interrupts are enabled. For details, see
Section 14.9 “Enabling/Disabling Interrupts”.
For all other interrupt related tasks, including specifying the interrupt vector, context
saving, nesting and other considerations, consult Chapter 14. “Interrupts”.
MPLAB® XC32 C/C++ Compiler User’s Guide
DS50001686J-page 60 2012-2016 Microchip Technology Inc.
3.4.7 Assembly Code
This section examines questions that arise when writing assembly code as part of a C
project.
How Should I Combine Assembly and C Code?
What do I need Other than Instructions in an Assembly Source File?
How Do I Access C Objects from Assembly Code?
How Can I Access SFRs From Within Assembly Code?
What Things Must I Manage When Writing Assembly Code?
3.4.7.1 HOW SHOULD I COMBINE ASSEMBLY AND C CODE?
Ideally, any hand-written assembly should be written as separate routines that can be
called. This offers some degree of protection from interaction between
compiler-generated and hand-written assembly code. Such code can be placed into a
separate assembly module that can be added to your project, as specified in
Section 17.2 “Mixing Assembly Language and C Variables and Functions”.
If necessary, assembly code can be added in-line with C code by using either of two
forms of the asm instruction; simple or extended. An explanation of these forms, and
some examples, are shown in Section 17.3 “Using Inline Assembly Language”.
Macros are provided which in-line several simple instructions, as discussed in
Section 17.4 “Predefined Macros”. More complex in-line assembly that changes
register contents and the device state should be used with caution. See Chapter
12. “Register Usage” for those registers used by the compiler.
3.4.7.2 WHAT DO I NEED OTHER THAN INSTRUCTIONS IN AN ASSEMBLY
SOURCE FILE?
Assembly code typically needs assembler directives as well as the instructions them-
selves. The operation of all the directives is described in the “MPLAB® XC32 Assem-
bler, Linker and Utilities User’s Guide” (DS50002186). Two common directives are
discussed below.
All assembly code must be placed in a section, using the .section directive, so it can
be manipulated as a whole by the linker and placed in memory. See the “Linker Pro-
cessing” chapter of the MPLAB® XC32 Assembler, Linker and Utilities User’s Guide
(DS50002186) for more information.
Another commonly used directive is .global which is used to make symbols accessi-
ble across multiple source files. Find more on this directive in the afore-mentioned
user’s guide.
3.4.7.3 HOW DO I ACCESS C OBJECTS FROM ASSEMBLY CODE?
Most C objects are accessible from assembly code. There is a mapping between the
symbols used in the C source and those used in the assembly code generated from
this source. Your assembly should access the assembly-equivalent symbols which are
detailed in Section 17.2 “Mixing Assembly Language and C Variables and Functions”.
Instruct the assembler that the symbol is defined elsewhere by using the .global
assembler directive. This is the assembly equivalent of a C declaration, although no
type information is present. This directive is not needed and should not be used if the
symbol is defined in the same module as your assembly code.
Any C variable accessed from assembly code will be treated as if it were qualified
volatile (see Section 8.10.2 “Volatile Type Qualifier”). Specifying the volatile
qualifier in C code is preferred as it makes it clear that external code may access the
object.
How To’s
2012-2016 Microchip Technology Inc. DS50001686J-page 61
3.4.7.4 HOW CAN I ACCESS SFRS FROM WITHIN ASSEMBLY CODE?
The safest way to gain access to SFRs in assembly code is to have symbols defined
in your assembly code that equate to the corresponding SFR address. For the XC32
compiler, the xc.h include file can be used from either preprocessed assembly code or
C/C++ code.
There is no guarantee that you will be able to access symbols generated by the
compilation of C code, even code that accesses the SFR you require.
3.4.7.5 WHAT THINGS MUST I MANAGE WHEN WRITING ASSEMBLY CODE?
If you are hand-writing assembly code there are several things that you must take
control of.
You must place any assembly code you write in a section. See the “Linker Pro-
cessing” chapter of the MPLAB® XC32 Assembler, Linker and Utilities User’s
Guide” (DS50002186) for more information.
Assembly code that is placed in-line with C code will be placed in the same sec-
tion as the compiler-generated assembly and you should not place this into a
separate section.
You must ensure that any registers you write to in assembly code are not already
in use by compiler-generated code. If you write assembly in a separate module,
then this is less of an issue as the compiler will, by default, assume that all regis-
ters are used by these routines (see Chapter 12. “Register Usage”, registers). No
assumptions are made for in-line assembly (see Section 17.2 “Mixing Assembly
Language and C Variables and Functions”) and you must be careful to save and
restore any resources that you use (write) and which are already in use by the
surrounding compiler-generated code.
MPLAB® XC32 C/C++ Compiler User’s Guide
DS50001686J-page 62 2012-2016 Microchip Technology Inc.
3.5 GETTING MY APPLICATION TO DO WHAT I WANT
This section provides programming techniques, applications and examples. It also
examines questions that relate to making an application perform a specific task.
What Can Cause Glitches on Output Ports?
How Do I Link Bootloaders and Downloadable Applications?
What Do I Need to Do When Compiling to Use a Debugger?
How Do I Share Data Between Interrupt and Main-line Code?
How Can I Prevent Misuse of My Code?
How Do I Use Printf to Send Text to a Peripheral?
How Can I Implement a Delay in My Code?
How Can I Rotate a Variable?
3.5.1 What Can Cause Glitches on Output Ports?
In most cases, this is caused by using ordinary variables to access port bits or the entire
port itself. These variables should be qualified volatile. See Section 8.10.2 “Volatile
Type Qualifier”.
The value stored in a variable mapped over a port (hence the actual value written to
the port) directly translates to an electrical signal. It is vital that the values held by these
variables only change when the code intends them to, and that they change from their
current state to their new value in a single transition. The compiler attempts to write to
volatile variables in one operation.
3.5.2 How Do I Link Bootloaders and Downloadable Applications?
Exactly how this is done depends on the device you are using and your project require-
ments, but the general approach when compiling applications that use a bootloader is
to allocate discrete program memory space to the bootloader and application so they
have their own dedicated memory. In this way the operation of one cannot affect the
other. This will require that either the bootloader or the application is offset in memory.
That is, the Reset and interrupt location are offset from address 0 and all program code
is offset by the same amount.
Typically the application code is offset, and the bootloader is linked with no offset so
that it populates the Reset and interrupt code locations. The bootloader Reset and
interrupt code merely contains code which redirects control to the real Reset and
interrupt code defined by the application and which is offset.
The contents of the Hex file for the bootloader can be merged with the code of the appli-
cation by using loadable projects in MPLAB X IDE. (See MPLAB X IDE documentation
for details.) This results in a single Hex file that contains the bootloader and application
code in the one image. Check for warnings from this application about overlap, which
may indicate that memory is in use by both bootloader and the downloadable
application.
See the PIC32 Bootloader Application Note (DS01388) on the Microchip website.
Pm err/es (File >Proiecl
How To’s
2012-2016 Microchip Technology Inc. DS50001686J-page 63
3.5.3 What Do I Need to Do When Compiling to Use a Debugger?
You can use debuggers - such as the PICkit™ 3 in-circuit debugger, the MPLAB ICD 3
in-circuit debugger or the MPLAB REAL ICE™ in-circuit emulator - to debug code built
with the MPLAB XC32 compiler. These debuggers use some of the data and program
memory of the device for its own use, so it is important that your code does not also
use these resources.
The command-line option -g (see Section 5.9.6 “Options for Debugging”) is used to tell
the compiler to generate debugging information. The compiler can then reserve the
memory used by the debugger so that your code will not be placed in these locations.
In the MPLAB X IDE, the appropriate debugger option is specified if you perform a
Debug Run. It will not be specified if you perform a regular Run, Build Project, or Clean
and Build.
Since some device memory is being reserved for use by the debugger, there is less
available for your program and it is possible that your code or data may no longer fit in
the device when a debugger is selected. For 32-bit devices, some boot flash memory
is required for debugging. In addition, some data memory (RAM) is used by the debug
tool and may impact the variable allocation in your application.
The specific memory locations used by the debuggers are attributes of MPLAB X, the
debug tool in use, and the target device. If you move a project to a new version of the
IDE, the resources required may change. For this reason, you should not manually
reserve memory for the debugger, or make any assumptions in your code as to what
memory is used. A summary of the debugger requirements is available in the MPLAB
IDE help files.
To verify that the resources reserved by the compiler match those required by the
debugger, you may view the boot-flash, application-flash, and data-memory usage in
the map file or memory-usage report.
To create a map file in MPLAB X IDE, open the Project Properties window (File>Project
Properties) and click on the linker category (xc32-ld). Under “Option Categories”, select
“Diagnostics”. Next to “Generate map file”, enter a path and name for the map file. The
logical place to put the map file is in the project folder.
Debug Run your code to generate the map file. View in your favorite text viewer.
See also Section 3.6.14 “Why are Some Objects Positioned into Memory that I
Reserved?”.
3.5.4 How Do I Share Data Between Interrupt and Main-line Code?
Variables accessed from both interrupt and main-line code can easily become cor-
rupted or mis-read by the program. The volatile qualifier (see
Section 8.10.2 “Volatile Type Qualifier”) tells the compiler to avoid performing optimiza-
tions on such variables. This will fix some of the issues associated with this problem.
The other issues relates to whether the compiler/device can access the data atomically.
With 32-bit PIC devices, this is rarely the case. An atomic access is one where the
entire variable is accessed in only one instruction. Such access is uninterruptible. You
can determine if a variable is being accessed atomically by looking at the assembler
list file (see the MPLAB® XC32 Assembler, Linker and Utilities User’s Guide,
DS50002186, for more information). If the variable is accessed in one instruction, it is
atomic. Since the way variables are accessed can vary from statement to statement it
is usually best to avoid these issues entirely by disabling interrupts prior to the variable
being accessed in main-line code, then re-enable the interrupts afterwards. See
Section 14.9 “Enabling/Disabling Interrupts” for more information. When writing to Spe-
cial Function Registers (SFRs), use the SET/CLR/INV registers as described in
Section 7.7 “Using SFRs From C Code”.
MPLAB® XC32 C/C++ Compiler User’s Guide
DS50001686J-page 64 2012-2016 Microchip Technology Inc.
3.5.5 How Can I Prevent Misuse of My Code?
First, many devices with flash program memory allow all or part of this memory to be
write protected. The device configuration bits need to be set correctly for this to take
place, so see Section 7.5 “Configuration Bit Access”, Section 2.5.14 “Specifying Con-
figuration Bits” for CCI, and your device data sheet.
Second, you can prevent third-party code being programmed at unused locations in the
program memory by filling these locations with a value rather than leaving them in their
default unprogrammed state. You can chose a fill value that corresponds to an instruc-
tion or set all the bits so as the values cannot be further modified. (Consider what will
happen if your program somehow reaches and starts executing from these filled val-
ues. What instruction will be executed?)
Use the --fill command to fill unused memory. Find usage information for this com-
mand in Section 5.9.10 “Options for Linking”.
3.5.6 How Do I Use Printf to Send Text to a Peripheral?
The printf function does two things: it formats text based on the format string and
placeholders you specify, and sends (prints) this formatted text to a destination (or
stream). You may choose the printf output go to an LCD, SPI module or USART, for
example.
For more on the ANSI C function printf, see the 32-bit Language Tool Libraries
manual (DS51685).
To check what is passed to the printf function, you may attempt to statically analyze
format strings passed to the function by using the -msmart-io option
(Section 5.9.1 “Options Specific to PIC32 Devices”). Also you may use the -Wformat
option to specify a warning when the arguments supplied to the function do not have
types appropriate to the format string specified (see Section 5.9.5 “Options for Con-
trolling Warnings and Errors”).
If you wish to create your own printf-type function, you will need to use the attributes
format and format_arg as discussed in Section 13.3.1 “Function Attributes”.
3.5.7 How Can I Implement a Delay in My Code?
If an accurate delay is required, or if there are other tasks that can be performed during
the delay, then using a timer to generate an interrupt is the best way to proceed.
Microchip does not recommend using a software delay on PIC32 devices as there are
many variables that can affect timing such as the configuration of the L1 cache,
prefetch cache, & Flash wait states. On PIC32 devices, you may choose to poll the core
timer, which increments every two instruction cycles.
How To’s
2012-2016 Microchip Technology Inc. DS50001686J-page 65
3.5.8 How Can I Rotate a Variable?
The C language does not have a rotate operator, but rotations can be performed using
the shift and bitwise OR operators. Since the 32-bit devices have a rotate instruction,
the compiler will look for code expressions that implement rotates (using shifts and
ORs) and use the rotate instruction in the generated output wherever possible.
If you are using CCI, you should consult Section 2.4.10 “Bitwise Operations on Signed
Values and Section 2.4.11 “Right-shifting Signed Values” if you will be using signed
variables.
For the following example C code:
int rotate_left (unsigned a, unsigned s)
{
return (a << s) | (a >> (32 - s));
}
the compiler may generate assembly instructions similar to the following:
rotate_left:
subu $2,$0,$5
jr $31
ror $2,$4,$2
MPLAB® XC32 C/C++ Compiler User’s Guide
DS50001686J-page 66 2012-2016 Microchip Technology Inc.
3.6 UNDERSTANDING THE COMPILATION PROCESS
This section tells you how to find out what the compiler did during the build process,
how it encoded output code, where it placed objects, etc. It also discusses the features
that are supported by the compiler.
What’s the Difference Between the Free, Standard and PRO Modes?
How Can I Make My Code Smaller?
How Can I Reduce RAM Usage?
How Can I Make My Code Faster?
How Does the Compiler Place Everything in Memory?
How Can I Make My Interrupt Routine Faster?
How Big Can C Variables Be?
What Optimizations Will Be Applied to My Code?
What Devices are Supported by the Compiler?
How Do I Know What Code the Compiler Is Producing?
How Can I Tell How Big a Function Is?
How Do I Know What Resources Are Being Used by Each Function?
How Do I Find Out Where Variables and Functions Have Been Positioned?
Why are Some Objects Positioned into Memory that I Reserved?
How Do I Know How Much Memory Is Still Available?
How Do I Use Library Files In My Project?
How Do I Customize the C Runtime Startup Code?
What Optimizations Are Employed By The Compiler?
Why Do I Get Out-of-Memory Errors When I Select a Debugger?
How Do I Set Up Warning/Error Messages?
How Do I Find the Code that Caused Compiler Errors Or Warnings in My Pro-
gram?
How Can I Stop Spurious Warnings from Being Produced?
Why Can’t I Even Blink an LED?
What Can Cause Corrupted Variables and Code Failure When Using Interrupts?
How Do I Build Libraries?
What is Different About an MPLAB IDE Debug Build?
How Do I Stop An Unused Function Being Removed?
How Do I Use Library Files In My Project?
3.6.1 What’s the Difference Between the Free, Standard and PRO
Modes?
These modes, or editions, mainly differ in the optimizations that are performed when
compiling (see Chapter 18. “Optimizations”). Compilers operating in Free and Standard
mode can compile for all the same devices as supported by the Pro mode. The code
compiled in Free, Standard or PRO modes can use all the available memory for the
selected device. What will be different is the size and speed of the generated compiler
output. Free mode output will be less efficient when compared to that produced in
Standard mode, which in turn will be less efficient than that produced when in Pro
mode.
How To’s
2012-2016 Microchip Technology Inc. DS50001686J-page 67
3.6.2 How Can I Make My Code Smaller?
There are a number of ways that this can be done, but results vary from one project to
the next. Use the assembly list file to observe the assembly code produced by the com-
piler to verify that the following tips are relevant to your code.For information on the list
file, see the MPLAB® XC32 Assembler, Linker and Utilities User’s Guide
(DS50002186).
Use the smallest data types possible as less code is needed to access these. (This also
reduces RAM usage.) For examples, a short integer type exists for this compiler. See
Chapter 8. “Supported Data Types and Variables” for all data types and sizes.
There are two sizes of floating-point type, as well, and these are discussed in the same
section. Replace floating-point variables with integer variables wherever possible. For
many applications, scaling a variable's value makes eliminating floating-point opera-
tions possible.
Use unsigned types, if possible, instead of signed types, particularly if they are used in
expressions with a mix of types and sizes. Try to avoid an operator acting on operands
with mixed sizes whenever possible.
Whenever you have a loop or condition code, use a “strong” stop condition, i.e., the
following:
for(i=0; i!=10; i++)
is preferable to:
for(i=0; i<10; i++)
A check for equality (== or !=) is usually more efficient to implement than the weaker <
comparison.
In some situations, using a loop counter that decrements to zero is more efficient than
one that starts at zero and counts up by the same number of iterations. So you might
be able to rewrite the above as:
for(i=10; i!=0; i--)
Ensure that you enable all the optimizations allowed for the edition of your compiler
(see Chapter 18. “Optimizations”). If you have a Pro edition, you can use the -Os option
(see Section 5.9.7 “Options for Controlling Optimization”) to optimize for size. Other-
wise, pick the highest optimization available.
Consider using the a compressed ISA mode such as MIPS16 or microMIPS if it is sup-
ported on your device. Use the -mips16 or -mmicromips option for your project to
make the compiler default to these modes. Use the mips16 or micromips function attri-
butes to change the mode at the function level. You may also choose the optimized and
compressed variants of the libraries in the linker options. Be aware of what optimiza-
tions the compiler performs so you can take advantage of them and don’t waste your
time manually performing optimizations in C code that the compiler already handles,
e.g., don’t turn a multiply-by-4 operation into a shift-by-2 operation as this sort of
optimization is already detected.
3.6.3 How Can I Reduce RAM Usage?
Consider using auto variables rather than global or static variables as there is the
potential that these may share memory allocated to other auto variables that are not
active at the same time. Memory allocation of auto variables is made on a stack,
described in Section 9.4 “Auto Variable Allocation and Access”.
Rather than pass large objects to, or from, functions, pass pointers which reference
these objects. This is particularly true when larger structures are being passed.
MPLAB® XC32 C/C++ Compiler User’s Guide
DS50001686J-page 68 2012-2016 Microchip Technology Inc.
Objects that do not need to change throughout the program can be located in program
memory using the const qualifier (see Section 9.5 “Variables in Program Memory”).
This frees up precious RAM, but slows execution.
3.6.4 How Can I Make My Code Faster?
To a large degree, smaller code is faster code, so efforts to reduce code size often
decrease execution time. To accomplish this, see Section 3.6.2 “How Can I Make My
Code Smaller?” and Section 3.6.6 “How Can I Make My Interrupt Routine Faster?”.
However, there are ways some sequences can be sped up at the expense of increased
code size.
Depending on your compiler edition (see Chapter 18. “Optimizations”), you may be
able to use the -O3 option (see Section 5.9.7 “Options for Controlling Optimization”) to
optimize for speed. This will use alternate output in some instances that is faster, but
larger.
Generally, the biggest gains to be made in terms of speed of execution come from the
algorithm used in a project. Identify which sections of your program need to be fast.
Look for loops that might be linearly searching arrays and choose an alternate search
method such as a hash table and function. Where results are being recalculated,
consider if they can be cached.
3.6.5 How Does the Compiler Place Everything in Memory?
In most situations, assembly instructions and directives associated with both code and
data are grouped into sections, and these are then positioned into containers which
represent the device memory. To see what sections objects are placed in, use the
option -ai to view this information in the assembler listing file.
The exception is for absolute variables, which are placed at a specific address when
they are defined and which are not placed in a section. For setting absolute variables,
use the address() attribute specified under Section 8.12 “Variable Attributes”.
3.6.6 How Can I Make My Interrupt Routine Faster?
Consider suggestions made in Section 3.6.2 “How Can I Make My Code Smaller?”
(code size) for any interrupt code. Smaller code is often faster code.
In addition to the code you write in the ISR, there is the code the compiler produces to
switch context. This is executed immediately after an interrupt occurs and immediately
before the interrupt returns, so must be included in the time taken to process an inter-
rupt. This code is optimal in that only registers used in the ISR will be saved by this
code. Thus, the fewer registers used in your ISR will mean potentially less context
switch code to be executed.
Generally simpler code will require fewer resources than more complicated expres-
sions. Use the assembly list file to see which registers are being used by the compiler
in the interrupt code. For information on the list file, see the MPLAB® XC32 Assembler,
Linker and Utilities User’s Guide (DS50002186).
Avoid calling other functions from the ISR. In addition to the extra overhead of the func-
tion call, the compiler also saves all general purpose registers that may or may not be
used by the called function. Consider having the ISR simply set a flag and return. The
flag can then be checked in main-line code to handle the interrupt. This has the advan-
tage of moving the complicated interrupt-processing code out of the ISR so that it no
longer contributes to its register usage. Always use the volatile qualifier (see
Section 8.10.2 “Volatile Type Qualifier” for variables shared by the interrupt and
main-line code, see Section 3.5.4 “How Do I Share Data Between Interrupt and
Main-line Code?”.
How To’s
2012-2016 Microchip Technology Inc. DS50001686J-page 69
3.6.7 How Big Can C Variables Be?
This question specifically relates to the size of individual C objects, such as arrays or
structures. The total size of all variables is another matter.
To answer this question you need to know in which memory space the variable will be
located. With the default -membedded-data option, objects qualified const will be
located in program memory; other objects will be placed in data memory. Program
memory object sizes are discussed in Section 9.5.1 “Size Limitations of const Vari-
ables”. Objects in data memory are broadly grouped into autos and non-autos and the
size limitations of these objects, respectively, are discussed in Section 9.3.1 “Non-auto
Variable Allocation” and Section 9.3.3 “Non-auto Variable Size Limits”.
3.6.8 What Optimizations Will Be Applied to My Code?
Code optimizations available depend on the edition of your compiler (see Chapter
18. “Optimizations”). A description of optimization options can be found under
Section 5.9.7 “Options for Controlling Optimization”.
3.6.9 What Devices are Supported by the Compiler?
New devices are usually added with each compiler release. Check the readme
document for a full list of devices supported by a compiler release.
3.6.10 How Do I Know What Code the Compiler Is Producing?
The assembly list file may be set up, using assembler listing file options, to contain a
great deal of information about the code, such as the assembly output for almost the
entire program, including library routines linked in to your program; section information;
symbol listings; and more.
The list file may be produced as follows:
On the command line, create a basic list file using the option:
-Wa, -a=projectname.lst.
For MPLAB X IDE, right click on your project and select “Properties”. In the Proj-
ect Properties window, click on “xc32-as” under “Categories”. From “Option cate-
gories”, select “Listing file options” and ensure “List to file” is checked.
By default, the assembly list file will have a .lst extension.
For information on the list file, see the “MPLAB® XC32 Assembler, Linker and Utilities
User’s Guide” (DS50002186).
3.6.11 How Can I Tell How Big a Function Is?
This size of a function (the amount of assembly code generated for that function) can
be determined from the assembly list file. See Section 3.6.10 “How Do I Know What
Code the Compiler Is Producing?” for more on creating an assembly listing file.
(Wmdow>Outgut>Ca/I Gmgh
MPLAB® XC32 C/C++ Compiler User’s Guide
DS50001686J-page 70 2012-2016 Microchip Technology Inc.
3.6.12 How Do I Know What Resources Are Being Used by Each
Function?
In the assembly list file there is information printed for every C function, including library
functions. See Section 3.6.10 “How Do I Know What Code the Compiler Is Producing?”
for more on creating an assembly listing file.
To see information on functions calls, you can view the Call Graph in MPLAB X IDE
(Window>Output>Call Graph). You must be in debug mode to see this graph. Right
click on a function and select “Show Call Graph” to see what calls this function and what
it calls.
Auto, parameter and temporary variables used by a function may overlap with those
from other functions as these are placed in a compiled stack by the compiler, see
Section 9.4 “Auto Variable Allocation and Access”.
3.6.13 How Do I Find Out Where Variables and Functions Have Been
Positioned?
You can determine where variables and functions have been positioned from either the
assembly list file (generated by the assembler) or the map file (generated by the linker).
Only global symbols are shown in the map file; all symbols (including locals) are listed
in the assembly list file.
There is a mapping between C identifiers and the symbols used in assembly code,
which are the symbols shown in both of these files. The symbol associated with a vari-
able is assigned the address of the lowest byte of the variable; for functions it is the
address of the first instruction generated for that function.
For more on assembly list files and linker map files, see the MPLAB® XC32 Assembler,
Linker and Utilities User’s Guide (DS50002186).
3.6.14 Why are Some Objects Positioned into Memory that I
Reserved?
Most variables and function are placed into sections that are defined in the linker script.
See the “MPLAB® XC32 Assembler, Linker and Utilities User’s Guide” (DS50002186)
for details on linker scripts. However, some variables and function are explicitly placed
at an address rather than being linked anywhere in an address range, as described in
3.4.3.1 “How Do I Position Variables at an Address I Nominate?” and 3.4.3.2 “How Do
I Position Functions at an Address I Nominate?”.
Check the assembly list file to determine the names of sections that hold objects and
code. Check the linker options in the map file to see if sections have been linked explic-
itly or if they are linked anywhere in a class. See the “MPLAB® XC32 Assembler, Linker
and Utilities User’s Guide” (DS50002186) for information on each of these files.
3.6.15 How Do I Know How Much Memory Is Still Available?
A memory usage summary is available from the compiler after compilation
(--report-mem option), from MPLAB X IDE in the Dashboard window. All of these sum-
maries indicate the amount of memory used and the amount still available, but none
indicate whether this memory is one contiguous block or broken into many small
chunks. Small blocks of free memory cannot be used for larger objects and so
out-of-memory errors may be produced even though the total amount of memory free
is apparently sufficient for the objects to be positioned.
Consult the linker map file to determine exactly what memory is still available in each
linker class. This file also indicates the largest contiguous block in that class if there are
memory page divisions. See the MPLAB® XC32 Assembler, Linker and Utilities User’s
Guide (DS50002186) for information on the map file.
Cawgonsi: > General n “mum/Mum um“ i w cam:[ml:llt] Dyna/151m mm: (u «2) me; mums v nun u 5mm om‘mmwmmmmmam mm v u wanna smmmm o uhmles 0 MM nbmumms m o X51(thal0p|nm) mm: summubnm J : Kins rmmmmum—m ram: . K12 H LlllkF‘lWSlSlhrancs ,w 1 )6?” m mlcm ms Mme”: mm m m \m 1 H? r mmmwwmmuq 1 Mammal 091mm: 0mm DENIM" renamed Eammandlme “Erwin/mils I! you men an mm m dssmpllm wnl x...“ mm Manage mum”:
How To’s
2012-2016 Microchip Technology Inc. DS50001686J-page 71
3.6.16 How Do I Use Library Files In My Project?
See Section 3.3.6 “How Do I Build Libraries?” for information on how you build your
own library files. The compiler will automatically include any applicable standard library
into the build process when you compile, so you never need to control these files.
To use one or more library files that were built by yourself or a colleague, include them
in the list of files being compiled on the command line. The library files can be specified
in any position in the file list relative to the source files, but if there is more than one
library file, they will be searched in the order specified in the command line.
For example:
xc32-gcc -mprocessor=32MZ2048ECH100 main.c int.c mylib.a
If you are using MPLAB IDE to build a project, add the library file(s) to the Libraries
folder that will shown in your project, in the order in which they should be searched. The
IDE will ensure that they are passed to the compiler at the appropriate point in the build
sequence.
3.6.17 How Do I Customize the C Runtime Startup Code?
Some applications may require an application-specific version of the C runtime startup
code. For instance, you may want to modify the startup code for an application loaded
by a bootloader.
To customize the startup code for your application:
1. Start with the default startup code, a copy of which is located in
<install-directory>/pic32-libs/libpic32/startup/crt0.S
Make a copy of this crt0.S file, rename it, and add it to your project.
2. Change your MPLAB X project to exclude the default startup code by enabling
the “Do not link startup code” under XC32 xc32-ld Option categories: Libraries
page as shown below. When you build your project, the MPLAB X will build your
new application-specific copy of the startup code rather than linking in the default
code.
FIGURE 3-1: STARTUP CODE PROPERTIES SETTING
MPLAB® XC32 C/C++ Compiler User’s Guide
DS50001686J-page 72 2012-2016 Microchip Technology Inc.
3. You can now edit the assembly code in your new copy of the crt0.S file. The
default source code uses macros defined in the device-specific header files,
which are included by xc.h. These macros define various device specific behav-
ior. Be sure to take this device-specific code into account when customizing your
copy of the code.
TABLE 3-1: DEVICE-SPECIFIC MACROS
3.6.18 What Optimizations Are Employed By The Compiler?
Code optimizations available depend on the edition of your compiler (see Chapter
18. “Optimizations”). A description of optimization options can be found under
Section 5.9.7 “Options for Controlling Optimization”.
3.6.19 Why Do I Get Out-of-Memory Errors When I Select a Debugger?
If you use a hardware tool debugger such as PICkit 3 in-circuit debugger, MPLAB ICD
3 in-circuit debugger, or MPLAB REAL ICE in-circuit emulator, memory is required for
the on-board debug executive.
Device-Specific Macro Description
__PIC32_SRS_SET_COUNT Defined to the number of Register Sets implemented on
the device. The default startup code uses this value to
determine how many register sets to use for $GP-register
initialization.
__PIC32_HAS_L1CACHE Defined if the device features an L1 cache.
__PIC32_HAS_MIPS32R2 Defined if the device supports the MIPS32r2 Instruction
Set.
__PIC32_HAS_MICROMIPS Defined if the device supports the microMIPS com-
pressed Instruction Set.
__PIC32_HAS_DSPR2 Defined if the device supports the DSPr2 Applica-
tion-Specific Extension.
__PIC32_HAS_FPU64 Defined if the device supports the single- and double-pre-
cision hardware Floating Point Unit.
__PIC32_HAS_SSX Defined if the device does not require initialization of the
bus matrix registers in order to support execution from
data memory.
__PIC32_HAS_MMU_MZ_FIXED Defined if the device features a Memory Management
Unit that should be pre-initialized to a standard SQI and
EBI mapping.
__PIC32_HAS_INIT_DATA Defined if the device requires data initialization by copy-
ing from a template located in Flash to RAM.
How To’s
2012-2016 Microchip Technology Inc. DS50001686J-page 73
3.7 FIXING CODE THAT DOES NOT WORK
This section examines issues relating to projects that do not build due to compiler
errors, or which build but do not work as expected.
How Do I Set Up Warning/Error Messages?
How Do I Find the Code that Caused Compiler Errors Or Warnings in My Program?
How Can I Stop Spurious Warnings from Being Produced?
Why Can’t I Even Blink an LED?
What Can Cause Corrupted Variables and Code Failure When Using Interrupts?
Invoking the Compiler
What Can Cause Corrupted Variables and Code Failure When Using Interrupts?
Why are Some Objects Positioned into Memory that I Reserved?
3.7.1 How Do I Set Up Warning/Error Messages?
To control message output, see Section 5.9.5 “Options for Controlling Warnings and
Errors”.
3.7.2 How Do I Find the Code that Caused Compiler Errors Or
Warnings in My Program?
In most instances, where the error is a syntax error relating to the source code, the
message produced by the compiler indicates the offending line of code. If you are com-
piling in MPLAB IDE, then you can double-click the message and have the editor take
you to the offending line. But identifying the offending code is not always so easy.
In some instances, the error is reported on the line of code following the line that needs
attention. This is because a C statement is allowed to extend over multiple lines of the
source file. It is possible that the compiler may not be able to determine that there is an
error until it has started to scan the next statement. Consider the following code:
input = PORTB // oops - forgot the semicolon
if(input>6)
// ...
The missing semicolon on the assignment statement will be flagged on the following
line that contains the if() statement.
In other cases, the error might come from the assembler, not the code generator. If the
assembly code was derived from a C source file, then the compiler will try to indicate
the line in the C source file that corresponds to the assembly that is at fault. If the
source being compiled is an assembly module, the error directly indicates the line of
assembly that triggered the error. In either case, remember that the information in the
error relates to some problem is the assembly code, not the C code.
Finally, there are errors that do not relate to any particular line of code at all. An error
in a compiler option or a linker error are examples of these. If the program defines too
many variables, there is no one particular line of code that is at fault; the program as a
whole uses too much data. Note that the name and line number of the last processed
file and source may be printed in some situations even though that code is not the direct
source of the error.
At the top of each message description, on the right in brackets, is the name of the
application that produced this message. Knowing the application that produced the
error makes it easier to track down the problem. The compiler application names are
indicated in Chapter 4. “XC32 Toolchain and MPLAB X IDE”.
MPLAB® XC32 C/C++ Compiler User’s Guide
DS50001686J-page 74 2012-2016 Microchip Technology Inc.
If you need to see the assembly code generated by the compiler, look in the assembly
list file. For information on where the linker attempted to position objects, see the map
file. See the MPLAB® XC32 Assembler, Linker and Utilities User’s Guide
(DS50002186) for information about the list and map files.
3.7.3 How Can I Stop Spurious Warnings from Being Produced?
Warnings indicate situations that could possibly lead to code failure. Always check your
code to confirm that it is not a possible source of error. In many situations the code is
valid and the warning is superfluous. In this case, you may:
Inhibit specific warnings by using the -Wno- version of the option.
Inhibit all warnings with the -w option.
In MPLAB X IDE, inhibit warnings in the Project Properties window under each
tool category. Also look in the Tool Options window, Embedded button,
Suppressible Messages tab.
See Section 5.9.5 “Options for Controlling Warnings and Errors” for details.
3.7.4 Why Can’t I Even Blink an LED?
Even if you have set up the port register and written a value to the port, there are
several things that can prevent such a seemingly simple program from working.
Make sure that the device’s configuration registers are set up correctly, as dis-
cussed in Section 7.5 “Configuration Bit Access”. Make sure that you explicitly
specify every bit in these registers and don’t just leave them in their default state.
All the configuration features are described in your device data sheet. If the con-
figuration bits that specify the oscillator source are wrong, for example, the device
clock may not even be running.
If the internal oscillator is being used, in addition to configuration bits there may be
SFRs you need to initialize to set the oscillator frequency and modes. See
Section 7.6 “ID Locations” and your device data sheet.
To ensure that the device is not resetting because of the watchdog time, either
turn off the timer in the configuration bits or clear the timer in your code. There are
library functions you can use to handle the watchdog timer, described in the 32-bit
Language Tool Libraries manual (DS51685). If the device is resetting, it may
never reach the lines of code in your program that blink the LED. Turn off any
other features that may cause device Reset until your test program is working.
The device pins used by the port bits are often multiplexed with other peripherals.
A pin might be connected to a bit in a port, or it might be an analog input, or it
might be the output of a comparator, for example. If the pin connected to your LED
is not internally connected to the port you are using, then your LED will never
operate as expected. The port function tables in your device data sheets will show
other uses for each pin which will help you identify peripherals to investigate.
3.7.5 What Can Cause Corrupted Variables and Code Failure When
Using Interrupts?
This is usually caused by having variables used by both interrupt and main-line code.
If the compiler optimizes access to a variable or access is interrupted by an interrupt
routine, then corruption can occur. See Section 3.5.4 “How Do I Share Data Between
Interrupt and Main-line Code?” for more information.
Q MICROCHIP
MPLAB® XC32 C/C++ COMPILER
USERS GUIDE
2012-2016 Microchip Technology Inc. DS50001686J-page 75
Chapter 4. XC32 Toolchain and MPLAB X IDE
4.1 INTRODUCTION
The 32-bit language tools may be used together under MPLAB X IDE to provide GUI
development of application code for the PIC32 MCU families of devices. The tools are:
MPLAB XC32 C/C++ Compiler
MPLAB XC32 Assembler
MPLAB XC32 Object Linker
MPLAB XC32 Object Archiver/Librarian and other 32-bit utilities
Topics covered in this chapter:
MPLAB X IDE and Tools Installation
MPLAB X IDE Setup
MPLAB X IDE Projects
Project Setup
Project Example
4.2 MPLAB X IDE AND TOOLS INSTALLATION
In order to use the 32-bit language tools with MPLAB X IDE, you must install:
MPLAB X IDE, which is available for free on the Microchip website.
MPLAB XC32 C/C++ Compiler, which includes all of the 32-bit language tools.
The compiler is available for free (Free and Evaluation editions) or for purchase
(Standard or Pro editions) on the Microchip website.
The 32-bit language tools will be installed, by default, in the directory:
Windows OS - C:\Program Files\Microchip\xc32\x.xx
Mac OS - Applications/microchip/xc32/x.xx
Linux OS - /opt/microchip/xc32/x.xx
where x.xx is the version number.
The executables for each tool will be in the bin subdirectory:
C Compiler - xc32-gcc.exe
Assembler - xc32-as.exe
Object Linker - xc32-ld.exe
Object Archiver/Librarian - xc32-ar.exe
Other Utilities - xc32-utility.exe
All device include (header) files are located in the /pic32mx/include/proc subdirectory.
These files are automatically incorporated when you #include the xc.h header file.
Code examples are located in the examples directory.
Tools>Og ns OD'Ion-s Genera‘ Edmr Fon‘sbco‘ws Keymw c/c++ mm Mmuanews 31:17:11: | Pmpaopml EmuKSEIW‘SSI sauna: Mw| m| Pom] Toddlan: HHECH PKCC (V133) [CN’mgr HHECH Prcc $9.32) [C2V’vugrs HK-TECN Pm: (yam) [cMugva szcn chc Mm) [CzV’vugrE rype: xcaz ”NEG“ PM (“W WWW Ba! mm: E:‘Pr0§vam Fw‘es‘McmdetSZWl uo‘bm nlJEflI PI((1HK0(V1.002 c may: CI‘Fvogvam Fdes‘McmdudeZh ma wnwzzmgw mm” CE‘ngIam FHes‘Maad’upudZWI uo‘bmbtdles.exa wk: Ommind: Ez‘Pmmm aBWumvwmms‘GnuMnazhh-de.m San (w and Tnds mm mm El cam Hdp
MPLAB® XC32 C/C++ Compiler User’s Guide
DS50001686J-page 76 2012-2016 Microchip Technology Inc.
4.3 MPLAB X IDE SETUP
Once MPLAB X IDE is installed on your PC, launch the application and check the
settings below to ensure that the 32-bit language tools are properly recognized.
1. From the MPLAB X IDE menu bar, select Tools>Options to open the Options dia-
log. Click on the “Embedded” button and select the “Build Tools” tab.
2. Click on “XC32” under “Toolchain”. Ensure that the paths are correct for your
installation.
3. Click OK.
FIGURE 4-1: XC32 TOOL SUITE LOCATIONS IN WINDOWS® OS
XC32 Toolchain and MPLAB X IDE
2012-2016 Microchip Technology Inc. DS50001686J-page 77
4.4 MPLAB X IDE PROJECTS
A project in MPLAB X IDE is a group of files needed to build an application, along with
their associations to various build tools. Below is a generic MPLAB X IDE project.
FIGURE 4-2: COMPILER PROJECT RELATIONSHIPS
In this MPLAB X IDE project, C source files are shown as input to the compiler. The
compiler will generate source files for input into the assembler. For more information on
the compiler, see the compiler documentation.
Assembly source files are shown as input to the C preprocessor. The resulting source
files are input to the assembler. The assembler will generate object files for input into
the linker or archiver. For more information on the assembler, see the assembler
documentation.
Object File Libraries
(*.a)
Assembler
Linker
C Source Files (*.c)
C++ Source Files (*.cpp, *.C)
C Compiler
Assembly Source
Files (*.S)
Debug File
(*.elf)
Archiver (Librarian)
Compiler
Driver
Program
MPLAB® X IDE
Debug Tool
Source Files (*.s)
Object Files
(*.o)
Command-Line
Simulator
Linker Script File(1)
(*.ld)
Executable File
(*.hex)
MPLAB® X IDE
Programmer
bin2hex Utility
Output File
(*.out)
Note 1: The linker can choose the correct linker script file for your project.
MPLAB® XC32 C/C++ Compiler User’s Guide
DS50001686J-page 78 2012-2016 Microchip Technology Inc.
Object files can be archived into a library using the archiver/librarian. For more
information on the archiver, see the archiver/librarian documentation.
The object files and any library files, as well as a linker script file (generic linker scripts
are added automatically), are used to generate the project output files via the linker.
The output files that may be generated by the linker are (1) a debug file (.elf) used by
the simulator and debug tools and (2) a production output file (.out) which may be
input into the bin2hex utility to produce an executable file (.hex). For more information
on linker script files and using the object linker, see the linker documentation.
For more on projects, and related workspaces, see MPLAB X IDE documentation.
(File>New Pro'ect File>Prolect Properties
XC32 Toolchain and MPLAB X IDE
2012-2016 Microchip Technology Inc. DS50001686J-page 79
4.5 PROJECT SETUP
To set up an MPLAB X IDE project for the first time, use the built-in Project Wizard
(File>New Project.) In this wizard, you will be able to select a language toolsuite that
uses the 32-bit language tools. For more on the wizard, and MPLAB X IDE projects,
see MPLAB X IDE documentation.
Once you have a project set up, you may then set up properties of the tools in MPLAB
X IDE.
1. From the MPLAB X IDE menu bar, select File>Project Properties to open a
window to set/check project build options.
2. Under “Conf:[default]”, select a tool from the tool collection to set up.
-XC32 (Global Options)
-xc32-as (32-bit Assembler)
-xc32-gcc (32-bit C Compiler)
-xc32-g++(32-bit C++ Compiler)
-xc32-ld (32-Bit Linker)
4.5.1 XC32 (Global Options)
Set up global options for all 32-bit language tools. See also “Options Page Features”.
TABLE 4-1: XC32 (GLOBAL OPTIONS) ALL OPTIONS CATEGORY
Option Description Command Line
Use legacy lib Check to use the Standard C library in the format before XC32
v1.12. Uncheck to use the HTC LIBC version. The legacy libc is
the default for new projects created in MPLAB X v3.15 and later.
-legacy-libc
&
-no-legacy-libc
Don’t delete intermediate
files
Don’t delete intermediate Files. Place them in the object directory
and name them based on the source file.
-save-temps=obj
Use Whole-Program and
Link-Time Optimizations
When this feature is enabled, the build will be constrained in the
following ways:
- The per-file build settings will be ignored
- The build will no longer be an incremental one (full build only)
-fwhole-program
-flto
Use GP relative
addressing threshold
Put definitions of externally-visible data in a small data section if
that data is no bigger than num bytes.
-G num
Common include dirs Directory paths entered here will be appended to the already
existing include paths of the compiler.
Relative paths are from the MPLAB X IDE project directory.
-I"dir"
MPLAB® XC32 C/C++ Compiler User’s Guide
DS50001686J-page 80 2012-2016 Microchip Technology Inc.
4.5.2 xc32-as (32-bit Assembler)
A subset of command-line options may be specified in MPLAB X IDE. Select a cate-
gory, and then set up assembler options. For additional options, see MPLAB XC32
Assembler documentation. See also “Options Page Features”.
TABLE 4-2: XC32-AS GENERAL OPTIONS CATEGORY
Option Description Command Line
Have symbols in produc-
tion build
Generate debugging information for source-level debugging in
MPLAB X.
--gdwarf-2
Keep local symbols Check to keep local symbols, i.e., labels beginning with .L
(upper case only).
Uncheck to discard local symbols.
--keep-locals
Exclude floating-point
library
Exclude support for floating-point operations reducing code
size for applications that do not require floating-point support.
-mno-float
Preprocessor macro defi-
nitions
Project-specific preprocessor macro defines passed via the
compiler's –D option.
Assembler symbols Define symbol 'sym' to a given 'value'. --defsym sym=value
Preprocessor Include
directories
Relative paths are from MPLAB X project directory.
Assembler Include direc-
tories
Relative paths are from MPLAB X project directory.
Add a directory to the list of directories the assembler
searches for files specified in .include directives.
You may add as many directories as necessary to include a
variety of paths. The current working directory is always
searched first and then -I directories in the order in which
they were specified (left to right) here.
-I
XC32 Toolchain and MPLAB X IDE
2012-2016 Microchip Technology Inc. DS50001686J-page 81
TABLE 4-3: XC32-AS OTHER OPTIONS CATEGORY
Option Description Command Line
Diagnostics level Select warnings to display in the Output window.
- Generate warnings
- Suppress warnings
- Fatal warnings
--warn
--no-warn
--fatal-warnings
Include source code Check for a high-level language listing. High-level listings
require that the assembly source code is generated by a com-
piler, a debugging option like -g is given to the compiler, and
assembly listings (-al) are requested.
Uncheck for a regular listing.
-ah
Expand macros Check to expand macros in a listing.
Uncheck to collapse macros.
-am
Include false conditionals Check to include false conditionals (.if, .ifdef) in a listing.
Uncheck to omit false conditionals.
-ac
Omit forms processing Check to turn off all forms processing that would be performed
by the listing directives .psize, .eject, .title and
.sbttl.
Uncheck to process by listing directives.
-an
Include assembly Check for an assembly listing. This -a suboption may be
used with other suboptions.
Uncheck to exclude an assembly listing.
-al
List symbols Check for a symbol table listing.
Uncheck to exclude the symbol table from the listing.
-as
Omit debugging
directives
Check to omit debugging directives from a listing. This can
make the listing cleaner.
Uncheck to included debugging directives.
-ad
List to file Use this option if you want the listing for a file. The list file will
have the same name as the asm file plus .lst.
-a=${CURRENT_QUOTE
D_IF_SPACED_OBJECT
_FILE_MINUS_EXTENS
ION}.lst
MPLAB® XC32 C/C++ Compiler User’s Guide
DS50001686J-page 82 2012-2016 Microchip Technology Inc.
4.5.3 xc32-gcc (32-bit C Compiler)
Although the MPLAB XC32 C/C++ Compiler works with MPLAB X IDE, it must be
acquired separately. The full version may be purchased, or a student (limited-feature)
version may be downloaded for free. See the Microchip website (www.microchip.com)
for details.
A subset of command-line options may be specified in MPLAB X IDE. Select a cate-
gory, and then set up compiler options. For additional options, see the MPLAB X IDE
User’s Guide (DS52027/DS50002027), also available on the Microchip website.
See also Section 4.5.6 “Options Page Features”.
TABLE 4-4: XC32-GCC GENERAL CATEGORY
Option Description Command Line
Have symbols in produc-
tion build
Build for debugging in a production build image. -g
Enable App IO Support the APPIN/APPOUT debugging feature with
REAL ICE
-mappio-debug
Isolate each function in a
section
This option is often used with the linker's --gc-sec-
tions option to remove unreferenced functions.
Check to place each function into its own section in the
output file. The name of the function determines the sec-
tion’s name in the output file.
Note: When you specify this option, the assembler and
linker may create larger object and executable files and
will also be slower.
Uncheck to place multiple functions in a section.
-ffunction-sections
Place data into its own
section
This option is often used with the linker's --gc-sec-
tions option to remove unreferenced statically-allocated
variables.
Place each data item into its own section in the output file.
The name of the data item determines the name of the
section. When you specify this option, the assembler and
linker may create larger object and executable files and
will also be slower.
-fdata-sections
Use indirect calls Enable full-range calls. -mlong-calls
Generate 16-bit code By default, generate code for the MIPS16 instruction set,
reducing code size.
-mips16
Exclude floating-point
library
Exclude support for floating-point operations reducing
code size for applications that do not require float-
ing-point support.
-mno-float
XC32 Toolchain and MPLAB X IDE
2012-2016 Microchip Technology Inc. DS50001686J-page 83
TABLE 4-5: XC32-GCC OPTIMIZATION CATEGORY
Option Description Command Line
Optimization Level Select an optimization level. Your compiler edition may
support only some optimizations. Equivalent to -On
option, where n is an option below:
0 - Do not optimize.The compiler’s goal is to reduce
the cost of compilation and to make debugging pro-
duce the expected results.
1 - Optimize. Optimizing compilation takes somewhat
longer, and a lot more host memory for a large func-
tion. The compiler tries to reduce code size and exe-
cution time.
2 - Optimize even more. The compiler performs
nearly all supported optimizations that do not involve
a space-speed trade-off.
3 - Optimize yet more favoring speed (superset of
O2).
s - Optimize yet more favoring size (superset of O2).
-On
Unroll loops This option often increases execution speed at the
expense of larger code size.
Check to 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.
Uncheck to not unroll loops.
-funroll-loops
Omit frame pointer Check to not keep the Frame Pointer in a register for
functions that don’t need one.
Uncheck to keep the Frame Pointer.
-fomit-frame-pointer
Pre-optimization instruc-
tion scheduling
Default for optimization level:
- Disable -fno-schedule-insns
- Enable -fschedule-insns
Post-optimization instruc-
tion scheduling
Default for optimization level:
- Disable -fno-schedule-insns2
- Enable -fschedule-insns2
TABLE 4-6: XC32-GCC PREPROCESSING AND MESSAGES CATEGORY
Option Description Command Line
Preprocessor macros Project-specific preprocessor macro defines passed via the
compiler's –D option.
Include directories Search these directories for project-specific include files.
Make warnings into
errors
Check to halt compilation based on warnings as well as
errors.
Uncheck to halt compilation based on errors only.
-Werror
Additional warnings Check to enable all warnings.
Uncheck to disable warnings.
-Wall
support-ansi Check to issue all warnings demanded by strict ANSI C.
Uncheck to issue all warnings.
-ansi
strict-ansi Issue all the warnings demanded by strict ISO C and ISO
C++; reject all programs that use forbidden extensions, and
some other programs that do not follow ISO C and ISO C++.
-pedantic
Use CCI syntax Enable support for the CCI syntax (see Chapter 2. “Common
C Interface).
-mcci
Use IAR syntax Enable support for syntax used by other toolchain vendors. -mext=IAR
MPLAB® XC32 C/C++ Compiler User’s Guide
DS50001686J-page 84 2012-2016 Microchip Technology Inc.
4.5.4 xc32-g++(32-bit C++ Compiler)
A subset of command-line options may be specified in MPLAB X IDE. Select a cate-
gory, and then set up linker options. For additional options, see MPLAB Object Linker
for 32-bit Devices documentation. See also Section 4.5.6 “Options Page Features”.
TABLE 4-7: XC32-G++ C++ SPECIFIC CATEGORY
Option Description Command Line
Generate run time type
descriptor information
Enable generation of information about every class with
virtual functions for use by the C++ runtime type identifi-
cation features ('dynamic_cast' and 'typeid'). If you don't
use those parts of the language, you can save some
space by disabling this option. Note that exception han-
dling 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 runtime type information, i.e.,
casts to void * or to unambiguous base classes.
-frtti
Enable C++ exception
handling
Enable exception handling. Generates extra code needed
to propagate exceptions.
-fexceptions
Check that the pointer
returned by operator
'new' is non-null
Check that the pointer returned by operator new is
non-null before attempting to modify the storage allo-
cated.
-fcheck-new
Generate code to check
for violation of exception
specification
Don't generate code to check for violation of exception
specifications at runtime. This option violates the C++
standard, but may be useful for reducing code size in pro-
duction builds.
-fenforce-eh-specs
TABLE 4-8: XC32-G++ GENERAL CATEGORY
Option Description Command Line
Have symbols in produc-
tion build
Build for debugging in a production build image. -g
Enable App IO Support the APPIN/APPOUT debugging feature with
REAL ICE.
-mappio-debug
Isolate each function in a
section
Place each function into its own section in the output file if
the target supports arbitrary sections. The name of the
function or the name of the data item determines the sec-
tion's name in the output file. This option is useful when
combined with the linker’s --gc-sections option to
remove unreferenced functions.
-ffunction-sections
Place data into its own
section
Place each data item into its own section in the output file
if the target supports arbitrary sections. The name of the
function or the name of the data item determines the sec-
tion's name in the output file. This option is useful when
combined with the linker’s --gc-sections option to
remove unreferenced variables.
-fdata-sections
Use indirect calls Enable full-range calls. -mlong-calls
Generate 16-bit code By default, generate code for the MIPS16 instruction set,
reducing code size.
-mips16
Exclude floating-point
library
Exclude support for floating-point operations reducing
code size for applications that do not require float-
ing-point support.
-mno-float
XC32 Toolchain and MPLAB X IDE
2012-2016 Microchip Technology Inc. DS50001686J-page 85
TABLE 4-9: XC32-G++ OPTIMIZATION CATEGORY
Option Description Command Line
Optimization Level Select an optimization level. Your compiler edition may
support only some optimizations. Equivalent to -On
option, where n is an option below:
0 - Do not optimize.The compiler’s goal is to reduce
the cost of compilation and to make debugging pro-
duce the expected results.
1 - Optimize. Optimizing compilation takes somewhat
longer, and a lot more host memory for a large func-
tion. The compiler tries to reduce code size and exe-
cution time.
2 - Optimize even more. The compiler performs
nearly all supported optimizations that do not involve
a space-speed trade-off.
3 - Optimize yet more favoring speed (superset of
O2).
s - Optimize yet more favoring size (superset of O2).
-On
Unroll loops Check to 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.
Uncheck to not unroll loops.
-funroll-loops
Omit frame pointer Check to not keep the Frame Pointer in a register for
functions that don’t need one.
Uncheck to keep the Frame Pointer.
-fomit-frame-pointer
Pre-optimization instruc-
tion scheduling
Default for optimization level:
- Disable -fno-schedule-insns
- Enable -fschedule-insns
Post-optimization instruc-
tion scheduling
Default for optimization level:
- Disable -fno-schedule-insns2
- Enable -fschedule-insns2
TABLE 4-10: XC32-G++ OPTIMIZATION CATEGORY
Option Description Command Line
Preprocessor macros Project-specific preprocessor macro defines passed via
the compiler’s –D option.
Include directories Search these directories for project-specific include files.
Make warnings into
errors
Check to halt compilation based on warnings as well as
errors.
Uncheck to halt compilation based on errors only.
-Werror
Additional warnings Check to enable all warnings.
Uncheck to disable warnings.
-Wall
support-ansi Check to issue all warnings demanded by strict ANSI C.
Uncheck to issue all warnings.
-ansi
strict-ansi Issue all the warnings demanded by strict ISO C and ISO
C++; reject all programs that use forbidden extensions,
and some other programs that do not follow ISO C and
ISO C++.
-pedantic
Use CCI syntax EnablesupportfortheCCIsyntax(Chapter
2. “Common C Interface”).
-mcci
Use IAR syntax Enable support for syntax used by other toolchain ven-
dors.
-mext=IAR
MPLAB® XC32 C/C++ Compiler User’s Guide
DS50001686J-page 86 2012-2016 Microchip Technology Inc.
4.5.5 xc32-ld (32-Bit Linker)
A subset of command-line options may be specified in MPLAB X IDE. Select a cate-
gory, and then set up linker options. For additional options, see MPLAB Object Linker
for 32-bit Devices documentation. See also Section 4.5.6 “Options Page Features”.
TABLE 4-11: XC32-LD GENERAL CATEGORY
Option Description Command Line
Heap Size (bytes) Specify the size of the heap in bytes. Allocate
a run-time heap of size bytes for use by C
programs. The heap is allocated from unused
data memory. If not enough memory is avail-
able, an error is reported.
--defsym=_min_heap_size=<size>
Minimum stack size
(bytes)
Specify the minimum size of the stack in
bytes. By default, the linker allocates all
unused data memory for the run-time stack.
Alternatively, the programmer may allocate
the stack by declaring two global symbols:
__SP_init and __SPLIM_init. Use this
option to ensure that at least a minimum
sized stack is available. The actual stack size
is reported in the link map output file. If the
minimum size is not available, an error is
reported.
--defsym=_min_stack_size=<size>
Allow overlapped
sections
Check to not check section addresses for
overlaps.
Uncheck to check for overlaps.
--check-sections
--no-check-sections
Remove unused sections Check to not enable garbage collection of
unused input sections (on some targets).
Uncheck to enable garbage collection.
--no-gc-sections
--gc-sections
Use response file to link Pass linker options in a file rather than on the
command line. On Windows systems, this
option allows you to properly link projects
with a large number of object files that would
normally overrun the command-line length
limitation of the Windows OS.
True
Additional driver options Type here any additional driver options not
existing in this GUI otherwise. The string you
introduce here will be emitted as is in the
driver invocation command.
XC32 Toolchain and MPLAB X IDE
2012-2016 Microchip Technology Inc. DS50001686J-page 87
TABLE 4-12: XC32-LD FILL FLASH MEMORY CATEGORY
Option Description Command Line
Which areas to fill Specify which area of Flash memory to fill.
No Fill - None (default).
Fill All Unused - Fill all unused memory.
Provide Range to fill - Fill a range of memory. Enter a
range under “Memory Address Range”.
How to fill it Specify how to fill Flash memory.
Provide sequence of values - provide a sequence
under the Sequence option.
Constant or incrementing value - provide a constant,
increment/decrement or increment/decrement constant
under the same-named option.
Sequence When Provide sequence of values is selected, enter a
sequence. The form is n1, n2, .... where n1 uses C
syntax. Example: 0x10, 25, 0x3F, 16.
--fill=sequence
Constant When Constant or incrementing value is selected,
enter a constant. Specify the constant using C syntax
(e.g., 0x for hex, 0 for octal). Example: 0x10 is the same
as 020 or 16.
--fill=constant
Increment/Decrement When Constant or incrementing value is selected, you
can select to increment or decrement the initial value of
“Constant” on each consecutive address.
No Incrementing - do not change constant value.
Increment Const - increment the constant value by the
amount specified under the option “Increment/Decrement
Constant”.
Decrement Const - decrement the constant value by the
amount specified under the option “Increment/Decrement
Constant”.
Increment/Decrement
Constant
When Increment Const or Decrement Const is
selected, enter a constant increment or decrement value.
Specify the constant using C syntax (e.g., 0x for hex, 0 for
octal). Example: 0x10 is the same as 020 or 16.
--fill=constant+=incr
--fill=constant-=decr
Memory Address Range When Provide Range to fill is selected, enter the range
here. Specify range as Start:End where Start and End use
C syntax. Example 0x100:0x1FF is the same as 256:511.
--fill=value@range
MPLAB® XC32 C/C++ Compiler User’s Guide
DS50001686J-page 88 2012-2016 Microchip Technology Inc.
TABLE 4-13: XC32-LD LIBRARIES CATEGORY
Option Description Command Line
Optimization level of
Standard Libraries
Select an optimization level. Your compiler edition may
support only some optimizations. Equivalent to -On
option, where n is an option below:
0 - Do not optimize.The compiler’s goal is to reduce
the cost of compilation and to make debugging pro-
duce the expected results.
1 - Optimize. Optimizing compilation takes somewhat
longer, and a lot more host memory for a large func-
tion. The compiler tries to reduce code size and exe-
cution time.
2 - Optimize even more. The compiler performs
nearly all supported optimizations that do not involve
a space-speed trade-off.
3 - Optimize yet more favoring speed (superset of
O2).
s - Optimize yet more favoring size (superset of O2).
-On
System Libraries Add libraries to be linked with the project files. You may
add more than one.
--library=name
Library directories Add a library directory to the library search path. You may
add more than one.
--library-path="name"
Exclude Standard Librar-
ies
Check to not use the standard system startup files or
libraries when linking. Only use library directories speci-
fied on the command line.
Uncheck to use the standard system startup files and
libraries.
-nostdlib
Do no link startup code Exclude the default startup code because the project pro-
vides application-specific startup code.
-nostartfiles
Generate 16-bit code Link the libraries precompiled for the MIPS16 instruction
set, reducing code size.
-mips16
Exclude floating-point
library
Exclude support for floating-point operations reducing
code size for applications that do not require float-
ing-point support.
-mno-float
TABLE 4-14: XC32-LD DIAGNOSTICS CATEGORY
Option Description Command Line
Generate map file Create a map file. -Map="file"
Display memory usage Check to print memory usage report.
Uncheck to not print a report.
--report-mem
Generate
cross-reference file
Check to create a cross-reference table.
Uncheck to not create this table.
--cref
Warn on section
realignment
Check to warn if start of section changes due to
alignment.
Uncheck to not warn.
--warn-section-align
Trace Symbols Add/remove trace symbols. --trace-symbol=symbol
XC32 Toolchain and MPLAB X IDE
2012-2016 Microchip Technology Inc. DS50001686J-page 89
4.5.6 Options Page Features
The Options section of the Properties page has the following features for all tools:
TABLE 4-15: XC32-LD SYMBOLS AND MACROS CATEGORY
Option Description Command Line
Linker symbols Create a global symbol in the output file containing the
absolute address (expr). You may use this option as
many times as necessary to define multiple symbols in
the command line. A limited form of arithmetic is sup-
ported for the expr in this context: you may give a hexa-
decimal constant or the name of an existing symbol, or
use + and - to add or subtract hexadecimal constants or
symbols.
--defsym=sym
Preprocessor macro defi-
nitions
Add linker macros. -Dmacro
Symbols Specify symbol information in the output.
- Keep all
- Strip debugging info --strip-debug (-S)
- Strip all symbol info --strip-all (-s)
TABLE 4-16: PAGE FEATURES OPTIONS
Reset Reset the page to default values.
Additional options Enter options in a command-line (non-GUI) format.
Option Description Click on an option name to see information on the option in this
window. Not all options have information in this window.
Generated Command
Line
Click on an option name to see the command-line equivalent of the
option in this window.
File>New Pm 'ect File>Pm 'ect Properties
MPLAB® XC32 C/C++ Compiler User’s Guide
DS50001686J-page 90 2012-2016 Microchip Technology Inc.
4.6 PROJECT EXAMPLE
In this example, you will create an MPLAB X IDE project with two C code files.
Run the Project Wizard
Set Build Options
Build the Project
Output Files
Further Development
4.6.1 Run the Project Wizard
In MPLAB X IDE, select File>New Project to launch the wizard.
1. Choose Project: Select “Microchip Embedded” for the category and “Stand-
alone Project” for the project. Click Next> to continue.
2. Select Device: Select the dsPIC30F6014. Click Next> to continue.
3. Select Header: There is no header for this device so this is skipped.
4. Select Tool: Choose a development tool from the list. Tool support for the
selected device is shown as a colored circle next to the tool. Mouse over the
circle to see the support as text. Click Next> to continue.
5. Select Compiler: Choose a version of the XC32 toolchain. Click Next> to
continue.
6. Select Project Name and Folder: Enter a project name, such as
MyXC32Project. Then select a location for the project folder. Click Finish to
complete the project creation and setup.
Once the Project Wizard has completed, the Project window should contain the project
tree. For more on projects, see the MPLAB X IDE documentation.
4.6.2 Set Build Options
Select File>Project Properties or right click on the project name and select “Properties”
to open the Project Properties dialog.
1. Under “Conf:[default]>XC32 (Global Options)”, select “xc32-gcc”.
2. Under “Conf:[default]>XC32 (Global Options)”, select “xc32-ld”.
3. Select “Diagnostics” from the “Option Categories”. Then enter a file name to
“Generate map file”, i.e., example.map.
4. Click OK on the bottom of the dialog to accept the build options and close the
dialog.
4.6.3 Build the Project
Right-click on the project name, “MyXC32Project”, in the project tree and select “Build”
from the pop-up menu. The Output window displays the build results.
If the build did not complete successfully, check these items:
1. Review the previous steps in this example. Make sure you have set up the
language tools correctly and have all the correct project files and build options.
2. If you modified the sample source code, examine the Build tab of the Output win-
dow for syntax errors in the source code. If you find any, click on the error to go
to the source code line that contains that error. Correct the error, and then try to
build again.
FIle>Ogen File File>OQen File File >Ogen File dist>default>gmductmn Debug>Debug Pro'ect
XC32 Toolchain and MPLAB X IDE
2012-2016 Microchip Technology Inc. DS50001686J-page 91
4.6.4 Output Files
View the project output files by opening the files in MPLAB X IDE.
1. Select File>Open File. In the Open dialog, find the project directory.
2. Under “Files of type” select “All Files” to see all project files.
3. Select File>Open File. In the Open dialog, select “example.map”. Click Open to
view the linker map file in an MPLAB X IDE editor window. For more on this file,
see the linker documentation.
4. Select File>Open File. In the Open dialog, return to the project directory and then
go to the dist>default>production directory. Notice that there is only one hex file,
“MyXC32Project.X.production.hex”. This is the primary output file. Click Open to
view the hex file in an MPLAB X IDE editor window. For more on this file, see the
Utilities documentation.
There is also another file, “MyXC32Project.X.production.elf”. This file contains
debug information and is used by debug tools to debug your code. For informa-
tion on selecting the type of debug file, see Section 4.5.1 “XC32 (Global
Options)”.
4.6.5 Further Development
Usually, your application code will contain errors and not work the first time. Therefore,
you will need a debug tool to help you develop your code. Using the output files
previously discussed, several debug tools exist that work with MPLAB X IDE to help
you do this. You may choose from simulators, in-circuit emulators or in-circuit
debuggers, either manufactured by Microchip Technology or third-party developers.
Please see the documentation for these tools to learn how they can help you. When
debugging, you will use Debug>Debug Project to run and debug your code. Please see
MPLAB X IDE documentation for more information.
Once you have developed your code, you will want to program it into a device. Again,
there are several programmers that work with MPLAB X IDE to help you do this. Please
see the documentation for these tools to see how they can help you. When
programming, you will use “Make and Program Device Project” button on the debug
toolbar. Please see MPLAB X IDE documentation concerning this control.
MPLAB® XC32 C/C++ Compiler User’s Guide
DS50001686J-page 92 2012-2016 Microchip Technology Inc.
NOTES:
Q MICROCHIP Build Ogtions
MPLAB® XC32 C/C++ COMPILER
USERS GUIDE
2012-2016 Microchip Technology Inc. DS50001686J-page 93
Chapter 5. Compiler Command Line Driver
5.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 com-
piler as it hides the complexity of all the internal applications used and provides a con-
sistent 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 dialog.
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
5.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.
5.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 XC32 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
MPLAB® XC32 C/C++ Compiler User’s Guide
DS50001686J-page 94 2012-2016 Microchip Technology Inc.
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 5.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. Typically
archive files are specified after source files. The file types are described in
Section 5.2.3 “Input File Types”.
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.
5.2.2 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.
Note: Command line options and file name extensions are case sensitive.
TABLE 5-1: COMPILER-RELATED ENVIRONMENT VARIABLES
Option Definition
XC32_C_INCLUDE_PATH
PIC32_C_INCLUDE_PATH
This variable’s value is a semicolon-separated list of directories, 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 appropriate
value based on the standard installation. By default, the following directories are
searched for include files:
<install-path>\pic32mx\include
XC32_COMPILER_PATH
PIC32_COMPILER_PATH
The value of PIC32_COMPILER_PATH is a semicolon-separated list of directories,
much like PATH. The compiler tries the directories thus specified when searching for
subprograms, if it can’t find the subprograms using PIC32_EXEC_PREFIX.
Compiler Command Line Driver
2012-2016 Microchip Technology Inc. DS50001686J-page 95
5.2.3 Input File Types
The compilation driver recognizes the following file extensions, which are case
sensitive.
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.
XC32_EXEC_PREFIX
PIC32_EXEC_PREFIX
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 name of a subprogram, but you can specify a prefix that ends with a slash if you
wish. If the compiler cannot find the subprogram using the specified prefix, it tries
looking in your PATH environment variable.
If the PIC32_EXEC_PREFIX environment variable is unset or set to an empty value, the
compiler driver chooses an appropriate 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 undefined and let the driver
locate subprograms itself.
XC32_LIBRARY_PATH
PIC32_LIBRARY_PATH
This variable’s value is a semicolon-separated list of directories, much like PATH. This
variable specifies a list of directories to be passed to the linker. The driver’s default eval-
uation of this variable is:
<install-path>\lib; <install-path>\pic32mx\lib.
TMPDIR If TMPDIR is set, it specifies the directory to use for temporary files. The compiler uses
temporary files to hold the output of one stage of compilation that is to be used as input
to the next stage: for example, the output of the preprocessor, which is the input to the
compiler proper.
TABLE 5-1: COMPILER-RELATED ENVIRONMENT VARIABLES (CONTINUED)
Option Definition
TABLE 5-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 source file.
file.S An assembly language source file that must be preprocessed.
other A file to be passed to the linker.
MPLAB® XC32 C/C++ Compiler User’s Guide
DS50001686J-page 96 2012-2016 Microchip Technology Inc.
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.
Compiler Command Line Driver
2012-2016 Microchip Technology Inc. DS50001686J-page 97
5.3 THE C COMPILATION SEQUENCE
5.3.1 Single-step C Compilation
A single command-line instruction can be used to compile one file or multiple files.
5.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 PIC32 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 PIC32 periph-
eral 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>
// Device - Specific Configuration - Bit settings
// SYSCLK = 80 MHz(8 MHz 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) {
x = 2;
y = 5;
z = add(x, y);
return 0;
}
MPLAB® XC32 C/C++ Compiler User’s Guide
DS50001686J-page 98 2012-2016 Microchip Technology Inc.
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.
5.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>
//Device - Specific Configuration - Bit settings
// SYSCLK = 80 MHz(8 MHz 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
#pragma config 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) {
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);
}
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.
Compiler Command Line Driver
2012-2016 Microchip Technology Inc. DS50001686J-page 99
5.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 inter-
mediate files (-c, see Section 5.9.2 “Options for Controlling the Kind of Output”). 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
MPLAB® XC32 C/C++ Compiler User’s Guide
DS50001686J-page 100 2012-2016 Microchip Technology Inc.
5.4 THE C++ COMPILATION SEQUENCE
5.4.1 Single-step C++ Compilation
A single command-line instruction can be used to compile one file or multiple files.
5.4.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/cpp - the directory for standard C++ header
files.
<install-dir>/pic32mx/include/proc - the directory for PIC32 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 PIC32 periph-
eral 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.
Compiler Command Line Driver
2012-2016 Microchip Technology Inc. DS50001686J-page 101
The following is a simple C++ program. Create the following program with any
plain-text editor and save it as ex2.cpp.
File 1
/* ex2.cpp */
#include <xc.h>
#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
#pragma config 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) {
//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: ");
// sortelements
sort(coll.begin(), coll.end());
print_elements(coll, "sorted: ");
//sorted reverse
sort(coll.begin(), coll.end(), greater < int >());
print_elements(coll, "sorted >: ");
while (1);
}
MPLAB® XC32 C/C++ Compiler User’s Guide
DS50001686J-page 102 2012-2016 Microchip Technology Inc.
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, 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.
5.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>
#include <iostream>
using namespace std;
//Device - Specific Configuration - bit settings
#pragma config FPLLMUL=MUL_20, FPLLIDIV=DIV_2, FPLLODIV=DIV_1
#pragma config 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;
//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:
while (1);
}
Compiler Command Line Driver
2012-2016 Microchip Technology Inc. DS50001686J-page 103
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 created.
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.
MPLAB® XC32 C/C++ Compiler User’s Guide
DS50001686J-page 104 2012-2016 Microchip Technology Inc.
5.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
5.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:
./.
./size
./speed
./mips16
./micromips
./no-float
./mips16/no-float
./micromips/no-float
./size/mips16
./size/micromips
./size/no-float
./size/mips16/no-float
./size/micromips/no-float
./speed/mips16
./speed/micromips
./speed/no-float
./speed/mips16/no-float
./speed/micromips/no-float
Note: Some PIC32 target devices allow you to select to boot in either the
MIPS32® or microMIPS™ ISA mode via a device configuration bit
(BOOTISA). On these devices, if your BOOTISA bit is set to microMIPS
mode, pass the -mmicromips mode to the xc32-gcc/g++ compilation driver
to tell it to link with the microMIPS variant of the runtime start-up code. If
your BOOTISA bit is set to MIPS32 mode, pass the -mno-micromips
option to the compilation driver so that the MIPS32 variant of the runtime
start-up code is linked.
Compiler Command Line Driver
2012-2016 Microchip Technology Inc. DS50001686J-page 105
The target libraries that are distributed with the compiler are built for the corresponding
command-line options:
Size vs speed (-Os vs. -O3)
MIPS16 vs MIPS32 vs microMIPS ISA mode (-mips16 vs. -mno-mips16 vs -mmi-
cromips)
Software floating-point vs no floating-point support (-msoft-float vs
-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 subdirectories are used.
5.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 16. “Library Routines.
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.
5.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.
MPLAB® XC32 C/C++ Compiler User’s Guide
DS50001686J-page 106 2012-2016 Microchip Technology Inc.
5.5.2 Peripheral Library Functions
Many of the peripherals of the PIC32 devices are supported by the peripheral library
functions provided with the compiler tools. Please refer to the MPLAB® Harmony
Libraries for new projects. For legacy support, these PLIB Libraries will be available for
download from http://www.microchip.com/pic32_peripheral_lib.
MPLAB Harmony includes a set of peripheral libraries, drivers and system services that
are readily accessible for application development. For access to the peripheral header
files (plib.h), go to the Microchip web site (www.microchip.com), click on the Design
Support tab and download MPLAB Harmony and MPLAB Code Configurator. The path
to the peripheral libraries is:
For Windows: C:\microchip\harmony\<version>\framework\peripheral
For Mac/Linux: ~\microchip\harmony\<version>\framework\peripheral
ForC: ForC++:
Compiler Command Line Driver
2012-2016 Microchip Technology Inc. DS50001686J-page 107
5.6 START-UP AND INITIALIZATION
The C/C++ runtime startup code is device specific. The xc32-gcc and xc32-g++
compilation drivers select the appropriate startup code when linking using the
-mprocessor=device option.
The startup code initializes the L1 cache when available.
It enables the DSPr2 engine when available.
It also initializes the Translation Lookaside Buffer (TLB) of the Memory Manage-
ment Unit (MMU) for the External Bus Interface (EBI) or Serial Quad Interface
(SQI) when available. The device-specific linker script creates a table of TLB
initialization values that the startup code uses to initialize the TLB at startup.
For C:
There is only one start-up module, which initializes the C runtime environment.
The source code for this is found in the following location:
<install-directory>/pic32-libs/libpic32/startup/crt0.S.
It is precompiled into the following library location:
<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 the following location:
<install-directory>/pic32-libs/libpic32/startup.
The PIC32 precompiled startup objects are located in the following location:
<install-directory>/pic32mx/lib/.
The files have the following names: cpprt0.o, crti.o, and crtn.o.
The GCC precompiled startup objects are located in the following location:
<install-directory>/lib/gcc/pic32mx/<gcc-version>/.
The files have the following names: crtbegin.o and crtend.o.
Note: Some PIC32 target devices allow you to select to boot in either the
MIPS32® or microMIPS™ ISA mode via a device configuration bit
(BOOTISA). On these devices, if your BOOTISA bit is set to microMIPS
mode, pass the -mmicromips mode to the xc32-gcc/g++ compilation driver
to tell it to link with the microMIPS variant of the runtime start-up code. If
your BOOTISA bit is set to MIPS32 mode, pass the -mno-micromips
option to the compilation driver so that the MIPS32 variant of the runtime
start-up code is linked.
Note: IMPORTANT: When your target MCU is configured to use the microMIPS
compressed ISA at startup (and for interrupts/exceptions), be sure to pass
the -mmicromips option to xc32-gcc when linking, and use the micromips
function attribute on all of your Interrupt Service Routines (ISRs). Using the
-mmicrimips option and the micromips attribute ensures that your startup
code and ISR code are compiled for the microMIPS ISA when the BOOTISA
Configuration bit is set to micromips. Likewise, be sure that you link
with the MIPS32 startup code, and your ISRs are not micromips attributed
when the BOOTISA bit is set to MIPS32.
MPLAB® XC32 C/C++ Compiler User’s Guide
DS50001686J-page 108 2012-2016 Microchip Technology Inc.
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 15.3 “Runtime Start-up Code”.
Compiler Command Line Driver
2012-2016 Microchip Technology Inc. DS50001686J-page 109
5.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.
5.7.1 Output Files
The compilation driver can produce output files with the following extensions, which are
case-sensitive.
The names of many output files use the same base name as the source file from which
they were derived. For example the source file input.c will create 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.
If you are using an IDE, such as MPLAB X 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.
The compiler is able to directly produce a number of the output file formats which are
used by Microchip development tools.
The default behavior of xc32-gcc and xc32-g++ is to produce an ELF output. To make
changes to the file’s output or the file names, see Section 5.9 “Driver Option
Descriptions”.
5.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®
XC32 Assembler, Linker and Utilities User’s Guide” (DS50002186). To pass the option
from the compiler, see Section 5.9.9 “Options for Assembling”.
TABLE 5-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 (intermediate file)
file.ii Preprocessed C++ file (intermediate file)
file.map Map file
Note: Throughout this manual, the term project name will refer to the name of the
project created in the IDE.
MPLAB® XC32 C/C++ Compiler User’s Guide
DS50001686J-page 110 2012-2016 Microchip Technology Inc.
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 listing 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 5.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 information relating to where objects were positioned in memory. 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 can be found in the MPLAB® XC32 Assembler, Linker and Utilities
User’s Guide (DS50002186). To pass the option from the compiler, see
Section 5.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.
Compiler Command Line Driver
2012-2016 Microchip Technology Inc. DS50001686J-page 111
5.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 may lead to a runtime failure of the code. The code
or situation that triggered the warning should be investigated; however, compila-
tion of the current module will continue, as will compilation of any remaining
modules.
Error Messages indicate source code that is illegal or that compilation of this
code cannot take place. Compilation will be attempted for the remaining source
code in the current module, but no additional modules will be compiled and the
compilation process will then conclude.
Fatal Error Messages indicate a situation that cannot allow compilation to pro-
ceed and which requires the compilation process to stop immediately.
For information on options that control compiler output of errors, warnings or
comments, see Section 5.9.4 “Options for Controlling the C++ Dialect”.
5.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 PIC32 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
MPLAB® XC32 C/C++ Compiler User’s Guide
DS50001686J-page 112 2012-2016 Microchip Technology Inc.
5.9.1 Options Specific to PIC32 Devices
These options are specific to the device, not the compiler.
TABLE 5-4: PIC32 DEVICE-SPECIFIC OPTIONS
Option Definition
-G num Put global and static items less than or equal to num 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 should be compiled with the same -G num value.
-mappio-debug Enable the APPIN/APPOUT debugging library functions for the MPLAB ICD 3
debugger and MPLAB REAL ICE in-circuit emulator. This feature allows you to
use the DBPRINTF and related functions and macros as described in the
32-bit Language 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.
-mcheck-zero-division
-mno-check-zero-division
Trap (do not trap) on integer division by zero. The default is
-mcheck-zero-division.
-membedded-data
-mno-embedded-data
Allocate variables to the read-only data section first if possible, then next in the
small data section if possible, otherwise in data. This gives slightly slower code
than the default, but reduces the amount of RAM required when executing,
and thus may be preferred for some embedded systems.
-mframe-header-opt Allows the compiler to omit a few instructions for each function that does not
use its incoming frame header. This feature usually improves both execution
speed and code size.
-mgen-pie-static Generate position-independent code suitable for statically linking into a
Position-Independent Executable (PIE). Such code access all constant
addresses through a Global Offset Table (GOT). A special ELF loader, running
on the target device, resolves the GOT entries and loads the final executable
image into memory. Pass this option to the xc32-gcc compilation driver when
compiling, assembling, and linking.
-minterlink-compressed Generate code that is link compatible with MIPS16 and microMIPS code.
-mips16
-mno-mips16
Generate (do not generate) MIPS16 code. This is only available in the PRO
edition.
-mjals
-mno-jals
Generate (do not generate) 'jals' for microMIPS by recognizing that the branch
delay slot instruction can be 16 bits. This implies that the function call cannot
switch the current mode during the linking stage because we don't have 'jals'
that supports 16-bit branch delay slot instructions. You man need to use
-mno-jals if you have link errors when attempting to link a microMIPS
object/library with a MIPS32 object/library.
-mlong-calls
-mno-long-calls
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.
-mmemcpy
-mno-memcpy
Force (do not force) the use of memcpy() for non-trivial block moves. The
default is -mno-memcpy, which allows GCC to inline most constant-sized
copies.
-mmicromips
-mno-micromips
Generate (do not generate) microMIPS™ instructions. This feature is available
only in the PRO edition.
When your device is configured to boot to the microMIPS compressed ISA
mode (e.g., #pragma config BOOTISA=MICROMIPS), use the
-mmicromips option when linking to specify the microMIPS startup code.
-mno-float Do not use software floating-point libraries.
ulL
Compiler Command Line Driver
2012-2016 Microchip Technology Inc. DS50001686J-page 113
-mno-peripheral-libs -mno-peripheral-libs is now the default. -mperipheral-libs is
optional. By default, the peripheral libraries are linked specified via the
device-specific linker script. Do not use the standard peripheral libraries when
linking.
-mprocessor Selects the device for which to compile.
(e.g., -mprocessor=32MX360F512L)
-mreserve When building a project for debugging in MPLAB X IDE, the IDE passes the
-mreserve option to the toolchain in order to reserve memory for use by the
debug executive. This mechanism replaces the hard-coded reserved memory
regions in the linker script.
-msmart-io=[0|1|2] This option attempts to statically analyze format strings 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 applications, 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.
-mtext="scn-name" Places text (program code) to be placed in a section named "scn-name",
rather than the default .text section. No white space should appear around the
'='. This command can be useful when developing a bootloader and you want
to map your code in a custom linker script. Example:
xc32-gcc bootloader.c
-mtext="MySectionName,address(0x9D00a000)"
-mprocessor=32MX795F512L
-muninit-const-in-rodata
-mno-uninit-const-in-rodata
Put uninitialized const variables in the read-only data section. This option is
only meaningful in conjunction with -membedded-data.
TABLE 5-4: PIC32 DEVICE-SPECIFIC OPTIONS (CONTINUED)
Option Definition
7x *ioro
MPLAB® XC32 C/C++ Compiler User’s Guide
DS50001686J-page 114 2012-2016 Microchip Technology Inc.
5.9.2 Options for Controlling the Kind of Output
The following options control the kind of output produced by the compiler.
TABLE 5-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:
-x language
Specify explicitly the language for the following input 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
-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 none, the compiler assumes all the input files are for the assembler.
--help Print a description of the command line options.
Compiler Command Line Driver
2012-2016 Microchip Technology Inc. DS50001686J-page 115
5.9.3 Options for Controlling the C Dialect
The following options define the kind of C dialect used by the compiler.
TABLE 5-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 in header files. This option is
silently 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 definitions, a K&R-style list of arguments followed
by their declarations is also provided, inside comments, after the declaration.
-fcheck-new /
-fno-check-new
(default)
Check that the pointer returned by operator new is non-null.
-fenforce-eh-specs
(default) /
-fno-enforce-eh-specs
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 exception specifications; the compiler will still optimize based on the
specifications, so throwing an unexpected exception will result in undefined
behavior.
-ffreestanding Assert that compilation takes place in a freestanding 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.
-fno-asm Do not recognize asm, inline or typeof as a keyword, so that code can use
these words as identifiers. You can use the keywords __asm__, __inline__ and
__typeof__ instead.
-ansi implies -fno-asm.
-fno-builtin
-fno-builtin-function
Don’t recognize built-in functions that do not begin with __builtin_ as prefix.
-fno-exceptions Disable C++ exception handling. This option disables the generation of extra code
needed to propagate exceptions.
-fno-rtti Enable/Disable runtime type-identification features. The -fno-rtti option dis-
ables 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 runtime type information, i.e., casts to void * or to unambiguous base
classes.
-fsigned-char Let the type char be signed, like signed char.
(This is the default.)
-fsigned-bitfields
-funsigned-bitfields
-fno-signed-bitfields
-fno-unsigned-bitfields
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.
-funsigned-char Let the type char be unsigned, like unsigned char.
-fwritable-strings Store strings in the writable data segment and do not make them unique.
MPLAB® XC32 C/C++ Compiler User’s Guide
DS50001686J-page 116 2012-2016 Microchip Technology Inc.
5.9.4 Options for Controlling the C++ Dialect
The following options define the kind of C++ dialect used by the compiler.
TABLE 5-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 functions declared
and/or defined in a translation unit, including those in header files. This option is
silently 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 definitions, a K&R-style list of arguments followed
by their declarations is also provided, inside comments, after the declaration.
-ffreestanding Assert that compilation takes place in a freestanding 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.
-fno-asm Do not recognize asm, inline or typeof as a keyword, so that code can use
these words as identifiers. You can use the keywords __asm__, __inline__ and
__typeof__ instead.
-ansi implies -fno-asm.
-fno-builtin
-fno-builtin-function
Don’t recognize built-in functions that do not begin with __builtin_ as prefix.
-fsigned-char Let the type char be signed, like signed char.
(This is the default.)
-fsigned-bitfields
-funsigned-bitfields
-fno-signed-bitfields
-fno-unsigned-bitfields
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.
-funsigned-char Let the type char be unsigned, like unsigned char.
-fwritable-strings Store strings in the writable data segment and do not make them unique.
Compiler Command Line Driver
2012-2016 Microchip Technology Inc. DS50001686J-page 117
5.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 5-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 forbid-
den 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 question-
able, and that are easy to avoid (or modify to prevent the warning), even in conjunction
with macros.
Note that some warning flags are not implied by -Wall. Some of them warn about con-
structions that users generally do not consider questionable, but which occasionally you
might 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. 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 address of a string literal, such as if (x == "abc").
Such uses typically indicate a programmer error: the address of a function always evalu-
ates to true, so their use in a conditional usually indicates that the programmer forgot the
parentheses in a function call; and comparisons against string literals result in unspeci-
fied 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.
-Wimplicit Equivalent to specifying both -Wimplicit-int and
-Wimplicit-function-declaration.
-Wimplicit-function-
declaration
Give a warning whenever a function is used before being declared.
-Wimplicit-int Warn when a declaration does not specify a type.
-Wmain Warn if the type of main is suspicious. main should be a function with external linkage,
returning int, taking either zero, two or three arguments of appropriate types.
-Wmissing-braces Warn if an aggregate or union initializer is not fully bracketed. In 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 } };
MPLAB® XC32 C/C++ Compiler User’s Guide
DS50001686J-page 118 2012-2016 Microchip Technology Inc.
-Wno-multichar Warn if a multi-character character constant is used. Usually, 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');
}
-Wparentheses Warn if parentheses are omitted in certain contexts, such as when there is an assign-
ment in a context where a truth value is expected, or when operators are nested whose
precedence people often find confusing.
-Wreturn-type Warn whenever a function is defined with a return-type that defaults to int. Also warn
about any return statement with no return-value in a function whose return-type is not
void.
-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 between the execution of
parts of the 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 function is called (but after the evaluation of its arguments
and the expression denoting the called function), and in certain other places. Other than
as expressed by the sequence point rules, the order of evaluation of subexpressions 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 order in which the functions are called is not
specified. However, the standards committee has ruled that function calls 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
unpredictable.
Examples of code with undefined behavior are a = a++;,
a[n] = b[n++] and a[i++] = i;. Some more complicated 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 for
one or more of the named 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).
TABLE 5-8: WARNING AND ERROR OPTIONS IMPLIED BY ALL WARNINGS (CONTINUED)
Option Definition
Compiler Command Line Driver
2012-2016 Microchip Technology Inc. DS50001686J-page 119
-Wuninitialized Warn if an automatic variable is used without first being initialized.
These warnings are possible only when optimization is enabled, because they require
data flow information that is computed only 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
address is taken, 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 command 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, use the unused attribute.
-Wunused-variable Warn whenever a local variable or non-constant static variable is unused aside from its
declaration. 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.
TABLE 5-8: WARNING AND ERROR OPTIONS IMPLIED BY ALL WARNINGS (CONTINUED)
Option Definition
MPLAB® XC32 C/C++ Compiler User’s Guide
DS50001686J-page 120 2012-2016 Microchip Technology Inc.
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.
TABLE 5-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 value; and 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 that of ordinary mathematical
notation.
Storage-class specifiers like static are not the first things in a declaration.
According to the C Standard, this usage is obsolescent.
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 following code
would evoke such 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 function call is cast to a non-matching type. For example, warn if
int foof() is cast to anything *.
-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 int *.
-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 *.
-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 conversions changing 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.
Compiler Command Line Driver
2012-2016 Microchip Technology Inc. DS50001686J-page 121
-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
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.
-Wmissing-declarations Warn if a global function is defined without a previous declaration. Do so even if the
definition itself provides a prototype.
-Wmissing-
format-attribute
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.
-Wmissing-noreturn Warn about functions that might be candidates for attribute noreturn. These are
only possible candidates, not absolute ones. Care should be taken to manually verify
functions. In fact, do not ever return before adding the noreturn attribute, otherwise
subtle code generation bugs could be introduced.
-Wmissing-prototypes Warn if a global function is defined without a previous prototype declaration. This
warning is issued even if the definition itself provides a prototype. (This option can be
used to detect global functions that are not declared in header files.)
-Wnested-externs Warn if an extern declaration is encountered within a function.
-Wno-deprecated-
declarations
Do not warn about uses of functions, variables and types marked as deprecated by
using the deprecated attribute.
-Wpadded Warn if padding is included in a structure, either to align an element of the structure or
to align the whole structure.
-Wpointer-arith Warn about anything that depends on the size of a function type or of void. The
compiler assigns these types a size of 1, for convenience in calculations with void *
pointers and pointers to functions.
-Wredundant-decls Warn if anything is declared more than once in the same scope, even in cases where
multiple declaration is valid and changes nothing.
-Wshadow Warn whenever a local variable shadows another local variable.
-Wsign-compare
-Wno-sign-compare
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.
-Wstrict-prototypes Warn if a function is declared or defined without specifying the argument types. (An
old-style function definition is permitted without a warning if preceded by a
declaration which specifies the argument types.)
-Wtraditional Warn about certain constructs that behave differently in 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 declaration follows a static one. This construct is not
accepted by some traditional C compilers.
-Wundef Warn if an undefined identifier is evaluated in an #if directive.
TABLE 5-9: WARNING AND ERROR OPTIONS NOT IMPLIED BY ALL WARNINGS (CONTINUED)
Option Definition
MPLAB® XC32 C/C++ Compiler User’s Guide
DS50001686J-page 122 2012-2016 Microchip Technology Inc.
5.9.6 Options for Debugging
The following options are used for debugging.
-Wunreachable-code Warn if the compiler detects that code will never be executed.
It is possible for this option to produce a warning even though there are
circumstances under which part of the affected line can be executed, so care should
be taken when removing apparently unreachable code. For instance, when a function
is inlined, a warning may mean that the line is unreachable in only one inlined copy of
the function.
-Wwrite-strings Give string constants the type const char[length] so that copying the address of
one into a non-const char * pointer gets a warning. At compile time, these warnings
help you find code that you can try to write into a string constant, but only if you have
been very careful about using const in declarations and prototypes. Otherwise, it’s
just a nuisance, which is why -Wall does not request these warnings.
TABLE 5-10: DEBUGGING OPTIONS
Option Definition
-g Produce debugging information.
The compiler supports the use 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
Don’t delete intermediate files. Place them in the current directory 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)
-save-temps=obj Similar to -save-temps=cwd, but if the -o option is specified, the 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 createfoo.i, foo.s, dir/xbar.i, dir/xbar.s, dir2/yfoobar.i,
dir2/yfoobar.s, and dir2/yfoobar.o.
TABLE 5-9: WARNING AND ERROR OPTIONS NOT IMPLIED BY ALL WARNINGS (CONTINUED)
Option Definition
Compiler Command Line Driver
2012-2016 Microchip Technology Inc. DS50001686J-page 123
5.9.7 Options for Controlling Optimization
The following options control compiler optimizations.
TABLE 5-11: GENERAL OPTIMIZATION OPTIONS
Option Edition Definition
-O0 All 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 results. Statements are independent: if you 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