Home
MPLAB C18 C Compiler User's Guide
Contents
1. Processor Value PIC18C242 0x8242 PIC18C252 0x8252 PIC18C442 0x8442 PIC18C452 0x8452 PIC18C658 0x8658 PIC18C858 0x8858 PIC18C601 0x8601 PIC18C801 0x8801 PIC18F242 0x242F PIC18F252 0x252F PIC18F442 0x442F PIC18F452 0x452F PIC18F248 0x8248 PIC18F258 0x8258 PIC18F448 0x8448 PIC18F458 0x8458 PIC18F1220 0xA122 PIC18F1320 0xA132 PIC18F2220 0xA222 PIC18F2320 0xA232 PIC18F4220 0xA422 PIC18F4320 0xA432 PIC18F6520 OxA652 PIC18F6620 OxA662 PIC18F6720 OxA672 PIC18F8520 0xA852 PIC18F8620 OxA862 PIC18F8720 0xA872 PIC18F6585 0x6585 PIC18F6680 0x6680 PIC18F8585 0x8585 PIC18F8680 0x8680 PIC18F6525 0x6525 PIC18F6621 OxA621 PIC18F8525 0x8525 PIC18F8621 0x8621 PIC18F4331 0x4331 PIC18F4431 0x4431 PIC18F2331 0x2331 PIC18F2431 0x2431 PIC18F2439 0x2439 PIC18F2539 0x2539 PIC18F4439 0x4439 PIC18F4539 0x4539 PIC18F2585 0x2585 PIC18F2680 0x2680 PIC18F2681 0x2681 PIC18F4585 0x4585 O 2004 Microchip Technology Inc DS51288C page 63 MPLAB C18 C Compiler User s Guide A 3 TABLE A 2 PROCESSOR TYPE CONTINUED PIC18F4680 0x4680 PIC18F4681 0x4681 PIC18F2515 0x2515 PIC18F2525 0x2525 PIC18F2610 0x2610 PIC18F2620 0x2620 PIC18F4515 0x4515 PIC18F4525 0x4525 PIC18F4610 0x4610 PIC18F4620 2 0x4620 PIC18F6410 0x6410 PIC18F6490 0x6490 PIC18F8410 0x8410 PIC18F8490 0x8490 Note 1 This is the processor uti
2. 97 99 Access Section 24 82 S E EEEE EA an matt ne 64 DIAQNOSIICS sasae e p aah 91 Predefined Macro 16 Selecting the Mode 9 10 82 Static Parameters 42 Storage Classes 13 14 81 Nop N rene een ne Et 34 O Optimizations ooooooocccccnicccccccncconancconnconnnnn cnn no nannn cnn 49 Banking criadas dao ia 49 50 Branche ss ane ete er rte 49 50 Code Straightening eee 49 51 52 Copy Propagation 49 53 55 Dead Code Removal 49 55 Duplicate String Merging ceeeeeeeeeee 49 Procedural Abstraction o oooc mo 49 55 56 Redundant Store Removal sse 49 54 Tail Merging oooocccccccnnoncccnccnnnancconcnannncnnnnnno 49 52 Unreachable Code Removal 49 53 WREG Content Tracking oooococcccnnnnncccccn 49 51 Output Files iii Sart AR es 8 OVET Lay A side there 13 14 97 98 2004 Microchip Technology Inc DS51288C page 109 MPLAB C18 C Compiler User s Guide P o E 34 Dt IO Ah ee AIR nr ne Le 47 PODATH id 47 BOTATU tada dada aida 47 Pointer A as Noirs 38 47 Initializing sites menti item 38 40 SIZES er nn ete eme n S 37 Slack sine ie ee E 38 47 Poi
3. STACK SIZE 0x100 RAM gpr5 To allocate a 512 byte stack in banks 4 and 5 these definitions should be replaced with DATABANK NAME stackregion START 0x400 END 0x5ff PROTECTED STACK SIZE 0x200 RAM stackregion If a stack larger than 256 bytes is used the 1s option must be given to the compiler There is a slight performance penalty that is incurred when using a large stack as both bytes of the frame pointer FSR2L and FSR2H must be incremented decremented when doing a push pop rather than just the low byte The size of the software stack required by an application varies with the complexity of the program When nesting function calls all auto parameters and variables of the calling function will remain on the stack Therefore the stack must be large enough to accommodate the requirements by all functions in a call tree MPLAB C18 supports parameters and local variables allocated either on the software stack or directly from global memory The static keyword places a local variable or a function parameter in global memory instead of on the software stack In general stack based local variables and function parameters require more code to access than static local variables and function parameters see Section 2 3 2 static Function Arguments Functions that use stack based variables are more flexible in that they can be reentrant and or recursive 3 2 3 Mixing C and Assembly 3 2 3 1 CALLING C FUNCTIONS FROM ASSEMBLY Wh
4. 53 4 8 Copy Propagation ivan et OA eee 53 4 9 Redundant Store Removal ooooccccccccccccccccnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnninnnino 54 4 10 Dead Code Removal iii 55 4 11 Procedural Abstracti0N srei ne ernen ea ne e a ee 55 Chapter 5 Sample Application Appendix A COFF File Format Al struct filehdr File Header vec zcscsccscciscess iii 61 A 1 1 unsigned short f Magina eeeniviivee tidied 61 AZ unsigned short E ns isan 61 A 1 3 nsigned Long E EIimMmdatis sus e 61 ATA unsigned Long E SM iii de 61 A 1 5 unsigned long E NS yMs uti eeeasievughapiavandee Mavis 61 AAG unsigned shorts Opt dE vis wii Laddo 61 Ad unsigned short Eladio 62 A 2 struct opthdr Optional File Header 62 AZ unsigned shore Magic Ate sere abso leads eee eee 62 A 2 2 unsigned short vst mp areren an lt ude ees 62 A23 unsigned Long prod ty P A 62 A 2 4 unsigned long rom width bits 64 A 2 5 unsigned long ram width bits 64 A 3 struct scnhdr Section Header iii 64 AS LS O A Ret nn A Non ns 65 A 3 2 unsigned Long s 6126 AA a 65 A 3 3 unsigned Vong 8 senpe ri pvc ante nent A rd 65 A SA unsigned long STE ine ai diel online eth 65 A 3 5 unsigned long s InnOptE viii 65 A 3 6 unsigned shorts onrel Olmedo da rd ana 65 ALC unsigned short s ninno nit ita 65 AaS unsigned long s flags ierisinensi reie lid 66 DS51288C page iv 2004 Microchip Technology Inc Table of Contents A 4 A 5 A 6 A 7 A
5. gt operator 2064 static function s not defined The function has been declared as static but there is no definition for the function present Common causes include a misspelled function name in the function definition 2065 static function s never referenced The static function has been defined but has not been referenced 2066 type qualifier mismatch in assignment Pointer assignment where the source and destination pointers point to objects of compatible type but the source pointer points to an object which is const or volatile qualified and the destination pointer does not 2067 type qualifier mismatch in argument d The argument expression is a pointer to a const or volatile qualified version of a compatible type to the parameter s type but the parameter is a pointer to a non const or volatile qualified version 2068 obsolete use of implicit int detected The ANSI standard allows a variable to be declared without a base type being specified e g extern x in which case a base type of int is implied This usage is deprecated by the standard as obsolete and therefore a diagnostic is issued to that effect 2069 enumeration value exceeds maximum range An enumeration value has been declared which is not expressible in a signed long format and the enumeration tag has negative enumeration values An unsigned long representation will be u
6. 2004 Microchip Technology Inc DS51288C page 77 MPLAB C18 C Compiler User s Guide B 4 INTEGERS ANSI C Standard A char a short int oran int bit field or their signed or unsigned varieties or an enumeration type may be used in an expression wherever an int or unsigned int may be used If an int can represent all values of the original type the value is converted to an int otherwise it is converted to an unsigned int These are called the integral promotions All other arithmetic types are unchanged by the integral promotions The integral promotions preserve value including sign 6 2 1 1 Implementation MPLAB C18 does not enforce this by default The Oi option can be used to require the compiler to enforce the ANSI defined behavior See Section 2 7 1 Integer Promotions ANSI C Standard The result of converting an integer to a shorter signed integer or the result of converting an unsigned integer to a signed integer of equal length if the value cannot be represented 6 2 1 2 Implementation When converting from a larger integer type to a smaller integer type the high order bits of the value are discarded and the remaining bits are interpreted according to the type of the smaller integer type When converting from an unsigned integer to a signed integer of equal size the bits of the unsigned integer are simply reinterpreted according to the rules for a signed integer of that size ANSI
7. A 6 5 unsigned long 1_fenndx Symbol table index of associated function if there is one A 7 struct aux file AUXILIARY SYMBOL TABLE ENTRY FOR A SOURCE FILE typedef struct aux file unsigned long x offset unsigned long x incline unsigned char x flags char _unused 9 j aux_file t A 7 1 unsigned long x offset String table offset for filename A 7 2 unsigned long x incline Line number at which this file was included If O file was not included O 2004 Microchip Technology Inc DS51288C page 71 MPLAB C18 C Compiler User s Guide A 8 A 9 A 7 3 unsigned char x flags Bit flags for the f ile entry Table A 9 lists the bit flags along with a description and respective values TABLE A 9 file ENTRY FLAGS Flag Description Value X FILE DEBUG ONLY This file entry was included for 0x01 debugging purposes only struct aux_scn AUXILIARY SYMBOL TABLE ENTRY FOR A SECTION typedef struct aux_scn unsigned long x scnlen unsigned short x nreloc unsigned short x nlinno char _unused 10 aux_scn t A 8 1 unsigned long x scnlen Section length A 8 2 unsigned short x nreloc Number of relocation entries A 8 3 unsigned short x nlinno Number of line numbers struct aux tag AUXILIARY SYMBOL TABLE ENTRY FOR A struct union enum TAGNAME typedef struct aux tag char _unused 6 unsigned short x size char _unused2 4 unsigned long x_endn
8. 2004 Microchip Technology Inc MICROCHIP MPLAB C18 C COMPILER USER S GUIDE DS51288C 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 reli
9. CPU Central Processing Unit E Endianness The ordering of bytes in a multi byte object Error File A file containing the diagnostics generated by the MPLAB C18 compiler Extended Mode In Extended mode the compiler will utilize the extended instructions i e ADDFSR ADDULNK CALLW MOVSF MOVSS PUSHL SUBFSR and SUBULNK and the indexed with literal offset addressing F Fatal Error An error that will halt compilation immediately No further messages will be produced Frame Pointer A pointer that references the location on the stack that separates the stack based arguments from the stack based local variables Free standing An implementation that accepts any strictly conforming program that does not use complex types and in which the use of the features specified in the library clause ANSI 89 standard clause 7 is confined to the contents of the standard headers lt float h gt lt iso646 h gt lt limits h gt lt stdarg h gt lt stdbool h gt lt stddef h gt and lt stdint h gt H Hexadecimal The base 16 numbering system that uses the digits 0 9 plus the letters A F or a f The digits A F represent decimal values of 10 to 15 The right most digit counts ones the next counts multiples of 16 then 16 256 etc High level Language A language for writing programs that is further removed from the processor than assembly l ICD In Circuit Debugger ICE In Circuit Emulator IDE Integrated Develo
10. and division operators require that their operands be of integer type Common causes include a missing dereference operator or a missing index operator 1136 integer operands required for shift operator The bitwise shift operators require that their operands be of integer type Common causes include a missing dereference operator or a missing index operator DS51288C page 86 2004 Microchip Technology Inc MPLAB C18 Diagnostics 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 integer types required for bitwise AND operator The amp and amp operators require that both operands be of integer type Common causes include a missing or operator integer types required for bitwise OR operator The and operators require that both operands be of integer type Common causes include a missing or operator integer types required for bitwise XOR operator The and operators require that both operands be of integer type Common causes include a missing or operator integer type required for bitwise NOT operator The operator requires that the operand be of integer type Common causes include a missing or operator integer type expected for pointer addition The addition operator requires that when one operand is of point
11. ANSI C Standard Implementation The type of integer required to hold the maximum size of an array that is the type of the sizeof operator size_t 6 3 3 4 7 1 1 size t is defined as an unsigned short long int The result of casting a pointer to an integer or vice versa 6 3 4 The integer will contain the binary value used to represent the pointer If the pointer is larger than the integer the representation will be truncated to fit in the integer The type of integer required to hold the difference between two pointers to elements of the same array ptrdiff t 6 3 6 7 1 1 ptrdiff tis defined as an unsigned long short The extent to which objects can actually be placed in registers by use of the register storage class specifier 6 5 1 The register storage class specifier is ignored B 8 STRUCTURES AND UNIONS ANSI C Standard Implementation ANSI C Standard Implementation B 9 BIT FIELDS ANSI C Standard Implementation ANSI C Standard Implementation ANSI C Standard Implementation A member of a union object is accessed using a member of a different type 6 3 2 3 The value of the member is the bits residing at the location for the member interpreted as the type of the member being accessed The padding and alignment of members of structures 6 5 2 1 Members of structures and unions are aligned on byte boundaries Whether a plain
12. _asm User assembly code MOVLW 10 Move decimal 10 to count MOVWF count 0 Loop until count is 0 start DECFSZ count 1 O GOTO done BRA start done _endasm It is generally recommended to limit the use of inline assembly to a minimum Any functions containing inline assembly will not be optimized by the compiler To write large fragments of assembly code use the MPASM assembler and link the modules to the C modules using the MPLINK linker DS51288C page 20 2004 Microchip Technology Inc Language Specifics 2 9 PRAGMAS 2 9 1 pragma sectiontype The section declaration pragmas change the current section into which MPLAB C18 will allocate information of the associated type A section is a portion of an application located at a specific address of memory Sections can contain code or data A section can be located in either program or data memory There are two types of sections for each type of memory program memory code contains executable instructions romdata contains variables and constants e data memory udata contains statically allocated uninitialized user variables idata contains statically allocated initialized user variables Sections are absolute assigned or unassigned An absolute section is one that is given an explicit address via the address of the section declaration pragma An assigned section is one that is ascribed to a specific section via the SECTION dire
13. enumeration value of s does not match previous When the same enumeration constant name is used in multiple enumeration tags the value of the enumeration constant must be the same in each enumeration cannot locate a parameter in program memory s Since all parameters are located on the stack it is not possible to locate a parameter in program memory Common causes include a mis typed pointer to program memory declaration local s in program memory can not be auto A local variable which is located in program memory must be declared as static or extern as auto local variables must be located on the stack static parameter detected in function pointer s Function pointers require parameters be passed via the stack When compiling with static locals enabled declare parameters for function pointers and for functions whose addresses are assigned to function pointers explicitly to auto the sign was already specified A type may include only one signed or unsigned cannot reference the address of a bitfield The address of a bitfield member of a structure cannot be referenced directly cannot dereference a pointer to void type The dereference operator requires a pointer to a non void object as its operand call of non function The operand of the function call post fix operator must be of type pointer to function Most commonly this is a function ide
14. int bit field is treated as a signed int oras an unsigned int bit field 6 5 2 1 A plain int bit field is treated as a signed int bit field The order of allocation of bit fields within a unit 6 5 2 1 Bit fields are allocated from least significant bit to most significant bit in order of occurrence Whether a bit field can straddle a storage unit boundary 3 5 2 1 A bit field cannot straddle a storage unit boundary O 2004 Microchip Technology Inc DS51288C page 79 MPLAB C18 C Compiler User s Guide B 10 ENUMERATIONS ANSI C Standard Implementation B 11 SWITCH STATEMENT ANSI C Standard Implementation The integer type chosen to represent the values of an enumeration type 6 5 2 2 The smallest type capable of representing all values in the enumeration type The maximum number of case values in a switch statement 6 6 4 2 The maximum number of values is limited only by target memory B 12 PREPROCESSING DIRECTIVES ANSI C Standard Implementation ANSI C Standard Implementation ANSI C Standard Implementation The method for locating includable source files 6 8 2 See Section 2 5 1 System Header Files The support for quoted names for includable source files 6 8 2 See Section 2 5 2 User Header Files The behavior on each recognized pragma directive 6 8 6 See Section 2 9 Pragmas DS51288C page 80 O
15. int i 5 int u void main void If an object s definition has an explicit far qualifier see Section 2 4 Storage Qualifiers the object is located in non access memory Similarly an explicit near qualifier see Section 2 4 Storage Qualifiers tells the compiler that the object is located in access memory If an object s definition has neither the near or far qualifier the compiler looks at whether the 0a option was specified on the command line DS51288C page 24 2004 Microchip Technology Inc Language Specifics 2 9 1 4 SECTION ATTRIBUTES The pragma sectiontype directive may optionally include two section attributes access Or overlay 2 9 1 4 1 access The access attribute tells the compiler to locate the specified section in an access region of data memory see the device data sheets or the PiCmicro 18C MCU Family Reference Manual DS39500 for more on access data memory Data sections with the access attribute will be placed into memory regions that are defined as ACCESSBANK in the linker script file These regions are those accessed via the access bit of an instruction i e no banking is required see the device data sheet Variables located in an access section must be declared with the near keyword For example pragma udata access my_access all accesses to these will be unbanked near unsigned char avl av2 2 9 1 4 2 overlay The overlay attribute permits other sections
16. register should be saved using a save PROD qualifier on the interrupt pragma directive For example pragma interruptlow low_interrupt_service routine save PROD If an interrupt service routine uses math library functions or calls a function that returns 24 or 32 bit data the math data section which is named MATH DATA should be saved using a save section MATH DATA qualifier on the interrupt pragma directive For example pragma interrupt high interrupt service routine save section MATH DATA All previous examples show a single value being saved Multiple variables and sections may be saved using the same save qualifier If an interrupt service routine used the PROD file register the tmpdata section the myint variable and the mydata section these should be saved using the save PROD section tmpdata myint section mydata qualifier on the interrupt pragma directive For example pragma interrupt isr save PROD section tmpdata myint section mydata DS51288C page 30 2004 Microchip Technology Inc Language Specifics 2 9 2 5 LATENCY The time between when an interrupt occurs and when the first ISR instruction is executed is the latency of the interrupt The three elements that affect latency are 1 Processor servicing of interrupt The amount of time it takes the processor to recognize the interrupt and branch to the first address of the interrupt vector To determine this value refer to the proces
17. that is for x y the expression x y must be valid x y is functionally equivalent to x y 1130 pointer operand required for operator The dereference operator requires a pointer to a non void object as its operand 1131 type mismatch in assignment The assignment operators require that the result of the right hand expression be of compatible type with the type of the result of the left hand expression Common causes include a missing or operator 1132 integer type expected for right hand operand of operator The operator requires that the right hand side by of integer type when the left hand side is of pointer type Common causes include a missing or operator 1133 type mismatch in operator The types of the operands of the operator must be such that for x y the expression x x y is valid 1134 arithmetic operands required for multiplication operator The and multiplication operators require that their operands be of arithmetic type Common causes include a missing dereference operator or a missing index operator 1134 arithmetic operands required for division operator The 7 and division operators require that their operands be of arithmetic type Common causes include a missing dereference operator or a missing index operator 1135 integer operands required for modulus operator The
18. void foo void static int foo ui static char foo_uc void bar void static int bar ii 5 static char bar_ic Z DS51288C page 22 2004 Microchip Technology Inc Language Specifics TABLE 2 6 OBJECTS SECTION LOCATION Object Section Location ri romdata re romdata foobar_ri romdata foobar_rc romdata ui udata uc udata foo_ui udata foo_uc udata ii idata ic idata bar ii idata bar_ic idata foo code bar code foobar code 2 9 1 3 DEFAULT SECTIONS A default section exists for each section type in MPLAB C18 see Table 2 7 TABLE 2 7 DEFAULT SECTION NAMES Section Type Default Name code code filename romdata romdata_filename udata udata_filename idata idata_filename Note filename is the name of the object file being generated For example mcc18 foo c fo fo0 o will produce an object file with a default code section named code_foo o Specifying a section name that has been previously declared causes MPLAB C18 to resume allocating data of the associated type into the specified section The section attributes must match the previous declaration otherwise an error will occur see Appendix D 1 Errors O 2004 Microchip Technology Inc DS51288C page 23 MPLAB C18 C Compiler User s Guide A section pragma directive with no name resets the allocation of data of the associated type to
19. 2004 Microchip Technology Inc MPLAB C18 C COMPILER MICROCHIP USER S GUIDE Appendix C Command line Summary Usage mcc18 options file options TABLE C 1 COMMAND LINE SUMMARY Option Description Reference help Displays the help screen 1 2 I lt path gt Add path to include path 2 5 1 2 5 2 fo lt name gt Object file name 1 2 1 fe lt name gt Error file name 1 2 1 k Set plain char type to unsigned char 2 1 ls Large stack can span multiple banks 3 2 2 ms Set compiler memory model to small model 2 6 3 1 default ml Set compiler memory model to large model 2 6 3 1 0 O Enable all optimizations default 4 0 Disable all optimizations 4 Od Enable dead code removal default 4 10 Od Disable dead code removal 4 10 Oi Enable integer promotion 2 7 1 Oi Disable integer promotion default 2 7 1 Om Enable duplicate string merging default 4 1 Om Disable duplicate string merging 4 1 On Enable banking optimizer default 4 3 On Disable banking optimizer 4 3 Op Enable copy propagation default 4 8 4 10 Op Disable copy propagation 4 8 4 10 Or Enable redundant store elimination default 4 9 Or Disable redundant store elimination 4 9 Ou Enable unreachable code removal default 4 7 Ou Disable unreachable code removal 4 7 Os Enable code straightening default 45 Os Disa
20. 452 should be used The command line option p18cxx explicitly specifies that the source is being compiled for a generic PIC18 PICmicro microcontroller 1 2 5 Selecting the Mode The compiler can operate in one of two different modes Extended or Non extended When operating in the Extended mode the compiler will utilize the extended instruc tions i e ADDFSR ADDULNK CALLW MOVSF MOVSS PUSHL SUBFSR and SUBULNK and the indexed with literal offset addressing which generally requires fewer instruc tions for accessing stack based variables resulting in a smaller program memory image When operating in Non extended mode the compiler will not utilize the extended instructions nor the indexed with literal offset addressing The extended and no extended command line options tell the compiler the mode in which to operate Table 1 2 outlines the mode in which the compiler will operate based on the command line options specified 2004 Microchip Technology Inc DS51288C page 9 MPLAB C18 C Compiler User s Guide TABLE 1 2 MODE SELECTION No Processor p extended p no extended pl8cxx Specified extended Extended Error Extended Extended no extended Non extended Non extended Non extended Non extended Not Specified Non extended Non extended Non extended Non extended Note If the compiler is invoked with mcc18 help the help displayed will be for the compiler operating in the
21. 8 A 9 A 10 A 12 A 13 A 14 struct reloc Relocation Entry lc a ctl 66 A41 unsigned Long Y vaddi aor eana A E AR EA 66 A42 unsigned long 1s ymndx osie iia rerni EE E ATR 66 A43 Short ir OF ESEG ehre le nits ae ert a 66 A 4 4 unsigned short TYPE ta lib 67 struct syment Symbol Table Entry ains cia 68 ACS Union Maa ea tei ate 68 A 5 2 unsigned Long n value ss 68 AS 3 Short senum it tilo calla Ud Seatac 69 A 5 4 unsigned Short n Eype iii 69 AS char islas iia iia 70 RN ue ste thant Mas ett de Saati antenne ish detente ane sn 70 struct coff Lineno Line Number Entry iris 71 AGI nsigned Long 1 SORA 71 A 6 Z unsigned short L Innatia ih iia 71 A 6 3 unsigned long L paddr onoaiia in a a a E 71 A 6 4 unsigned short L_flags non ronca nana n nn nn nnnnnnnnn 71 A b 5 uns Ig ed longL Fonade dada Hastie Seed aed 71 struct aux file Auxiliary Symbol Table Entry for a Source File 71 ATA unsigned long x OLf8etiniiiacai a ed 71 AT unsigned Long x IMC 71 A T 3 unsigned char x ElagS iii dad 72 struct aux_scn Auxiliary Symbol Table Entry for a Section 72 A 8 1 unsigned long x scnlen sis 72 A 8 2 unsigned short x nrel e s times Aan ihe 72 A8 S unsigned shore MTA NNO ieia este ika nt Mat eau 72 struct aux tag Auxiliary Symbol Table Entry for a struct union enum Tagname E RA 72 AD un
22. Road 07 02 Prime Centre Singapore 188980 Tel 65 6334 8870 Fax 65 6334 8850 Taiwan Kaohsiung Branch 30F 1 No 8 Min Chuan 2nd Road Kaohsiung 806 Taiwan Tel 886 7 536 4818 Fax 886 7 536 4803 Taiwan Taiwan Branch 11F 3 No 207 Tung Hua North Road Taipei 105 Taiwan Tel 886 2 2717 7175 Fax 886 2 2545 0139 EUROPE Austria Durisolstrasse 2 A 4600 Wels Austria Tel 43 7242 2244 399 Fax 43 7242 2244 393 Denmark Regus Business Centre Lautrup hoj 1 3 Ballerup DK 2750 Denmark Tel 45 4420 9895 Fax 45 4420 9910 France Parc d Activite du Moulin de Massy 43 Rue du Saule Trapu Batiment A ler Etage 91300 Massy France Tel 33 1 69 53 63 20 Fax 33 1 69 30 90 79 Germany Steinheilstrasse 10 D 85737 Ismaning Germany Tel 49 89 627 144 0 Fax 49 89 627 144 44 Italy Via Quasimodo 12 20025 Legnano MI Milan Italy Tel 39 0331 742611 Fax 39 0331 466781 Netherlands P A De Biesbosch 14 NL 5152 SC Drunen Netherlands Tel 31 416 690399 Fax 31 416 690340 United Kingdom 505 Eskdale Road Winnersh Triangle Wokingham Berkshire England RG41 5TU Tel 44 118 921 5869 Fax 44 118 921 5820 02 17 04 DS51288C page 114 2004 Microchip Technology Inc
23. Tower No 88 TIDU Street Chengdu 610016 China Tel 86 28 86766200 Fax 86 28 86766599 China Fuzhou Unit 28F World Trade Plaza No 71 Wusi Road Fuzhou 350001 China Tel 86 591 7503506 Fax 86 591 7503521 China Hong Kong SAR Unit 901 6 Tower 2 Metroplaza 223 Hing Fong Road Kwai Fong N T Hong Kong Tel 852 2401 1200 Fax 852 2401 3431 China Shanghai Room 701 Bldg B Far East International Plaza No 317 Xian Xia Road Shanghai 200051 Tel 86 21 6275 5700 Fax 86 21 6275 5060 China Shenzhen Rm 1812 18 F Building A United Plaza No 5022 Binhe Road Futian District Shenzhen 518033 China Tel 86 755 82901380 Fax 86 755 8295 1393 China Shunde Room 401 Hongjian Building No 2 Fengxiangnan Road Ronggui Town Shunde District Foshan City Guangdong 528303 China Tel 86 757 28395507 Fax 86 757 28395571 China Qingdao Rm B505A Fullhope Plaza No 12 Hong Kong Central Rd Qingdao 266071 China Tel 86 532 5027355 Fax 86 532 5027205 India Divyasree Chambers 1 Floor Wing A A3 A4 No 11 O Shaugnessey Road Bangalore 560 025 India Tel 91 80 22290061 Fax 91 80 22290062 Japan Benex S 1 6F 3 18 20 Shinyokohama Kohoku Ku Yokohama shi Kanagawa 222 0033 Japan Tel 81 45 471 6166 Fax 81 45 471 6122 Korea 168 1 Youngbo Bldg 3 Floor Samsung Dong Kangnam Ku Seoul Korea 135 882 Tel 82 2 554 7200 Fax 82 2 558 5932 or 82 2 558 5934 Singapore 200 Middle
24. a pointer to a string as its argument but that string must be in data memory rom char mystring Send me to the USART void foo void char strbuffer 21 str2ram strbuffer mystring putsUSART strbuffer Alternatively the library routine can be modified to read from a string located in program memory The only changes required to the library routine are to change the name so the new routine does not conflict with the original routine and to add the rom qualifier to the parameter void putsUSART rom static const rom char data Send characters up to the null do while BusyUSART 1 Write a byte to the USART putcUSART data while data DS51288C page 18 2004 Microchip Technology Inc Language Specifics 2 8 LANGUAGE EXTENSIONS 2 8 1 Anonymous Structures MPLAB C18 supports anonymous structures inside of unions An anonymous structure has the form struct member list An anonymous structure defines an unnamed object The names of the members of an anonymous structure must be distinct from other names in the scope in which the structure is declared The members are used directly in that scope without the usual member access syntax For example union foo struct int a int b dE char c bar char c bar a c a is a member of the anonymous structure located inside bar A structure for wh
25. be overridden explicitly with the static or overlay keywords or implicitly with either the scs static local variables or sco overlay local variables command line option For completeness MPLAB C18 also supports the sca command line option This option allows the storage class for local variables to be explicitly specified as auto 2 3 2 static Function Arguments Function parameters can have storage class auto or static An auto parameter is placed on the software stack enabling reentrancy A static parameter is allocated globally enabling direct access for generally smaller code static parameters are valid only when the compiler is operating in Non extended mode see Section 1 2 5 Selecting the Mode The default storage class for function parameters is auto This can be overridden explicitly with the static keyword or implicitly with the scs command line option The sco command line option will also implicitly override function parameters storage class with static 2 4 STORAGE QUALIFIERS In addition to the ANSI standard storage qualifiers const volatile the MPLAB C18 compiler introduces storage qualifiers of far near rom and ram Syntactically these new qualifiers bind to identifiers just as the const and volatile qualifiers do in ANSI C Table 2 4 shows the location of an object based on the storage qualifiers specified when it was defined The default storage qualifiers for an object defined without explicit stora
26. bytes are assumed to be an offset into the string table This is a bit nasty as it is not strictly conforming to the ANSI specification i e type munging is undefined behavior by the standard but it is effective and it maintains binary compatibility with the System V layout which other options would not do This implementation has the advantage of mirroring the standard System V structure used for long symbol names A 3 1 1 char s name 8 In place section name If the section name is fewer than eight characters long then the section name is stored in place A 3 1 2 struct ss Section name is stored in the string table If the first four characters of the section name are zero then the last four form an offset into the string table to find the name of the section A 3 1 2 1 unsigned long _s zeroes First four characters of the section name are zero A 3 12 2 unsigned long _s offset Offset of section name in the string table A 3 1 3 unsigned long s paddr Physical address of the section A 3 1 4 unsigned long s vaddr Virtual address of the section Always contains the same value as s_paddr A 3 2 unsigned long s size Size of this section A 3 3 unsigned long s scnptr Pointer to the raw data in the COFF file for this section A 3 4 unsigned long s relptr Pointer to the relocation information in the COFF file for this section A 3 5 unsigned long s lnnoptr Pointer to the line number information in the COFF file for this s
27. characters long and so takes 80 bytes of program memory table2 is declared as an array of pointers to program memory The rom qualifier after the places the array of pointers in program memory as well All of the strings in table2 are 9 bytes long and the array is four elements long so table2 takes 9 4 4 2 44 bytes of program memory Accesses to table2 may be less efficient than accesses to table however because of the additional level of indirection required by the pointer An important consequence of the separate address spaces for MPLAB C18 is that pointers to data in program memory and pointers to data in data memory are not compatible Two pointer types are not compatible unless they point to objects of compatible types and the objects they point to are located in the same address space For example a pointer to a string in program memory and a pointer to a string in data memory are not compatible because they refer to different address spaces 2004 Microchip Technology Inc DS51288C page 17 MPLAB C18 C Compiler User s Guide A function to copy a string from program to data memory could be written as follows void str2ram static char dest static char rom src while dest src 0 The following code will send a string located in program memory to the USART ona PIC18C452 using the PICmicro MCU C libraries The library function to send a string to the USART putsUSART const char str takes
28. file and add the code to the beginning of the entry function To customize the startup files if using Non extended mode 1 Goto the c mcci8 src traditional startup directory where c mcc18 is the directory where the compiler is installed 2 Edit either c018 c c018i corc018iz c to add any customized startup code desired 3 Compile the updated startup file to generate either cO18 0 c018i o or co18iz o 4 Copy the startup module to c mcc18 11b where c 1mcc1g is the directory where the compiler is installed To customize the startup files if using Extended mode 1 Gotothe c mcec18 src extended startup directory where c mcc18 is the directory where the compiler is installed 2 Edit either c018 e c c018i e corc018iz e c to add any customized startup code desired 3 Compile the updated startup file to generate either co18_e o co18i_e oor c018iz e o 4 Copy the startup module to c mcc18 1ib where C mcc18 is the directory where the compiler is installed 3 4 COMPILER MANAGED RESOURCES Certain special function registers and data sections of the PIC18 PlCmicro microcontrollers are used by MPLAB C18 and are not available for general purpose user code Table 3 4 indicates each of these resources their primary use by the compiler and whether the compiler automatically saves the resource when entering an ISR AA EEE 2 SE SS DS51288C page 46 2004 Microchip Technology Inc Run time Model TABLE 3 4 COMPILE
29. filehdr FILE HEADER The filehar structure holds information regarding the file It is the first entry in a COFF file It is used to denote where the optional file header symbol table and section headers begin typedef struct filehdr unsigned short f magic unsigned short f nscns unsigned long f timdat unsigned long f_symptr unsigned long f nsyms unsigned short f opthdr unsigned short f flags filehdr t A 1 1 unsigned short f magic The magic number is used to identify the implementation of COFF that the file follows For Microchip PICmicro MCU COFF files this number is 0x1234 A 1 2 unsigned short f nscns The number of sections in the COFF file A 1 3 unsigned long f timdat The time and date stamp when the COFF file was created this value is a count of the number of seconds since midnight January 1 1970 A 1 4 unsigned long f symptr A pointer to the symbol table A 1 5 unsigned long f nsyms The number of entries in the symbol table A 1 6 unsigned short f opthdr The size of the optional header record O 2004 Microchip Technology Inc DS51288C page 61 MPLAB C18 C Compiler User s Guide A 1 7 unsigned short f flags Information on what is contained in the COFF file Table A 1 shows the different file header flags along with a description and respective values TABLE A 1 FILE HEADER FLAGS Flag Description Value F_RELFLG Relocation information
30. has been stripped from the 0x0001 COFF file F_EXEC The file is executable and has no unresolved external 0x0002 symbols F_LNNO Line number information has been stripped from the 0x0004 COFF file L_SYMS Local symbols have been stripped from the COFF file 0x0080 F_EXTENDED18 The COFF file was produced utilizing the Extended 0x4000 mode F_GENERIC The COFF file is processor independent 0x8000 A 2 struct opthdr OPTIONAL FILE HEADER The opthdr structure contains implementation dependent file level information For Microchip PlCmicro MCU COFF files it is used to specify the name of the target pro cessor version of the compiler assembler and to define relocation types Note that the layout of this header is specific to the implementation i e the Microchip optional header is not the same format as the System V optional header typedef struct opthdr unsigned short magic unsigned short vstamp unsigned long proc_type unsigned long rom width bits unsigned long ram width bits opthdr t A 2 1 unsigned short magic The magic number can be used to determine the appropriate layout A 2 2 unsigned short vstamp Version stamp A 2 3 unsigned long proc type Target processor type Table A 2 shows the processor type along with the associated value stored in this field DS51288C page 62 O 2004 Microchip Technology Inc COFF File Format TABLE A 2 PROCESSOR TYPE
31. is operating in Extended mode the total size of local variables is limited to 96 bytes per function as compared to 120 bytes when the compiler is operating in Non extended mode E 1 2 static Parameters static parameters are not supported when the compiler is operating in the Extended mode A warning diagnostic will be issued when the compiler is operating in the Extended mode and a static parameter is seen In addition the compiler will act as if the code explicitly specified an auto parameter The parameter will now be stored on the stack instead of being allocated globally Since the total size of stack space for auto parameters is limited to 120 bytes per function the application may result in a parameter frame too large diagnostic being issued that does not occur when the compiler is operating in Non extended mode To resolve this the function will need to be modified to take fewer parameters E 1 3 overlay Keyword The overlay keyword is not supported when the compiler is operating in the Extended mode A warning diagnostic will be issued when the compiler is operating in the Extended mode and the overlay keyword is seen In addition the compiler will act as if the code explicitly specified the auto keyword Similar to static parameters the overlay local variable will now be stored on the stack instead of being allocated globally Since the total size of local variables is limited to 96 bytes per function the application may resul
32. the default section for the current module For example The following statement changes the current code section to the absolute section high vector Hpragma code high vector 0x08 The following statement returns to the default code section el Hpragma code When the MPLAB C18 compiler begins compiling a source file it has default data sections for both initialized and uninitialized data These default sections are located in either access or non access RAM depending on whether the compiler was invoked with a Oa option or not respectively The Oa command line option applies only when operating in Non extended mode see Section 1 2 5 Selecting the Mode When a pragma udata access name directive is encountered in the source code the current uninitialized data section becomes name which is located in access or non access RAM depending on whether the optional access attribute was specified The same is true for the current initialized data section when a pragma idata access name directive is encountered Objects are placed in the current initialized data section when an object definition with an explicit initializer is encountered Objects without an explicit initializer in their definition are placed in the current uninitialized data section For example in the following code snippet i would be located in the current initialized data section and u would be placed in the current uninitialized data section
33. variable void change asm variable void asm_variable 0x1234 AAA a DS51288C page 44 O 2004 Microchip Technology Inc Run time Model 3 3 STARTUP CODE 3 3 1 Default Behavior The MPLAB C18 startup begins at the reset vector address 0 The reset vector jumps to a function that initializes FSR1 and FSR2 to reference the software stack optionally calls a function to initialize idata sections data memory initialized data from program memory and loops on a call to the application s main function Whether the startup code initializes idata sections is determined by which startup code module is linked with the application The co18i o and c018i e o modules perform the initialization while the co18 o and c018 e o modules do not The default linker scripts provided by MPLAB C18 link with either the co18i o or c018i_e o module depending on whether Non extended mode or Extended mode is being utilized respectively The ANSI standard requires that all objects with static storage duration that are not initialized explicitly are set to zero With both the co18 0 c018_e o and c018i 0 c018i e o startup code modules this requirement is not met A third type of startup module c018iz oandc018iz e o is provided to meet this requirement If this startup code module is linked with the application then in addition to initializing idata sections all objects with static storage duration that are not initialized explicitly ar
34. will not utilize the extended instructions nor the indexed with literal offset addressing 2004 Microchip Technology Inc DS51288C page 103 MPLAB C18 C Compiler User s Guide O Object File A file containing object code It may be immediately executable or it may require linking with other object code files e g libraries to produce a complete executable program Object Code The machine code generated by an assembler or compiler Octal The base 8 number system that only uses the digits 0 7 The right most digit counts ones the next digit counts multiples of 8 then 82 64 etc P Pragma A directive that has meaning to a specific compiler R RAM Random Access Memory Random Access Memory A memory device in which information can be accessed in any order Read Only Memory Memory hardware that allows fast access to permanently stored data but prevents addition to or modification of the data ROM Read Only Memory Recursive Self referential e g a function that calls itself Reentrant A function that may have multiple simultaneously active instances This may happen due to either direct or indirect recursion or through execution during interrupt processing Relocatable An object whose address has not been assigned to a fixed memory location Run time Model Set of assumptions under which the compiler operates S Section A portion of an application located at a specific address of memory Se
35. with the PIC18F452 Microcontroller First Edition Pearson Education Inc Upper Saddle River New Jersey 07458 Focuses on Microchip Technology s PIC18FXXX family and writing enhanced application code Harbison Samuel P and Steele Guy L C A Reference Manual Fourth Edition Prentice Hall Englewood Cliffs New Jersey 07632 Covers the C programming language in great detail This book is an authoritative reference manual that provides a complete description of the C language the run time libraries and a style of C programming that emphasizes correctness portability and maintainability Kernighan Brian W and Ritchie Dennis M The C Programming Language Second Edition Prentice Hall Englewood Cliffs New Jersey 07632 Presents a concise exposition of C as defined by the ANSI standard This book is an excellent reference for C programmers Kochan Steven G Programming In ANSI C Revised Edition Hayden Books Indianapolis Indiana 46268 Another excellent reference for learning ANSI C used in colleges and universities Van Sickle Ted Programming Microcontrollers in C First Edition LLH Technology Publishing Eagle Rock Virginia 24085 Although this book focuses on Motorola microcontrollers the basic principles of programming with C for microcontrollers is useful DS51288C page 4 2004 Microchip Technology Inc Preface THE MICROCHIP WEB SITE Microchip provides on line support on the Microchip World
36. 000a 0x00000c fourth CALL sub4 0x0 0x00000e Code straightening should not affect the ability to debug source code 4 6 TAIL MERGING PS Tail merging attempts to combine multiple sequences of identical instructions into a single sequence For example given the following C source code fragment if user value PORTB 0x55 else PORTB 0x80 When compiled with tail merging disabled Ot a MOVWF PORTB 0x0 is generated in both cases of the if statement 0x000000 MOVF user value 0x0 0x0 0x000002 BZ Oxa 0x000004 MOVLW 0x55 0x000006 MOVWF PORTB 0x0 0x000008 BRA Oxe 0x00000a MOVLW 0x80 0x00000c MOVWF PORTB 0x0 0x00000e RETURN 0x0 However when compiled with tail merging enabled Ot only a single MOVWF PORTB 0x0 is generated and is used by both the if and else portions of the code 0x000000 MOVF user value 0x0 0x0 0x000002 BZ 0x8 0x000004 MOVLW 0x55 0x000006 BRA Oxa 0x000008 MOVLW 0x80 0x00000a MOVWF PORTB 0x0 0x00000c RETURN 0x0 When debugging source code compiled with this optimization enabled the incorrect source line may be highlighted because two or more source lines may share a single sequence of assembly code making it difficult for the debugger to identify which source line is being executed DS51288C page 52 O 2004 Microchip Technology Inc Optimizations 4 7 UNREACHABLE CODE REMOVAL Ou Ou Unreachable code will attempt to remove any code that can be provably demonst
37. 006 0x000008 RETURN 0x0 2004 Microchip Technology Inc DS51288C page 53 MPLAB C18 C Compiler User s Guide With copy propagation enabled Op instead of b being moved to c for the second instruction a is moved to c 0x000000 foo MOVFF a b 0x000002 0x000004 MOVFF a c 0x000006 0x000008 RETURN 0x0 Dead code removal would then delete the useless assignment of a to b see Section 4 10 Dead Code Removal Copy propagation may affect the ability to debug source code 4 9 REDUNDANT STORE REMOVAL Or Or When assignment of the form x y appears multiple times in an instruction sequence and the intervening code has not changed the value of x or y the second assignment may be removed This is a special case of common subexpression elimination An example where this may occur in C is char c void foo char a C ar Cc 3 With redundant store removal disabled Or the original code is mirrored in the generated assembly code 0x000000 foo MOVFF a c 0x000002 0x000004 MOVFF a c 0x000006 0x000008 RETURN 0x0 With redundant store removal enabled or the second assignment of c to a is not required 0x000000 foo MOVFF a c 0x000002 0x000004 RETURN 0x0 Redundant store removal may affect the ability to set breakpoints on certain lines of C source code HA A A DS51288C page 54 O 2004 Microchip Technology Inc Optimizations 4 10 DEAD CODE REMOVAL Od
38. 11 Short Long AWE sue A Merde i 11 SLQNEM ve rudes Heels AE 11 unsigned kiss dates 11 Internal Assembler c cccccceeeeeeeseeeeeeeeeeneeees 20 VS AMPASM ie sleet ot AR cede tb iris 20 Interrupt High priority cooooocccoccnnnocccccccononancconocanann cnn 27 31 Late a a 31 Low priority ee 27 31 Nesting 5 initia tte 31 Saving and Restoring Context 27 30 A O a A aE 29 interrupt pragma cooococcccccnononccnncconannncnncnnnnnncnnnnnnns 27 31 Interrupt Service Routine 27 31 46 103 interruptlow pragma ccccceeesseeeeeeeeteeeeeeees 27 31 K Keywords ASM inch Al Sek daaslat hia ees eine 20 CNG aS ties ioacc EE EE EE 20 QUO daa nent 13 14 38 40 41 91 Const ik Beever nee 14 84 Exte acess Murale Me Mecs sd 13 33 40 42 44 EST enr nn ae ee 14 15 24 37 MEAT nba 14 15 24 25 33 37 Overlay anus a UM Anime te 13 14 Se LUE e aos IO PT 14 15 TOG st CT eto Lh ees I MU rh A 13 TROT Steed sea E idas 14 15 17 18 22 26 Stati Crs ai 13 14 40 42 VP AER MAT were oa Se at eet sss 13 Yo Ee cri t ee ne Lien ete nn ct 14 33 L Large Memory Model 37 Linker Scripts ACCESSBANK iii ace eae 25 SECTION da 21 26 Little Endian vivos loe ie 12 103 long signed tia 11 a A EE Mere one ei E 11 TONG Short AE aces aed toi 11 Low priority Interrupt c cceeeeeeeeeeeeeeeees 27 31 M Macros DIO toco dida 9 Inline Assembl
39. 288C page 110 S Sec dida 21 HOTELS RE ao 45 Stringtable titan 17 EMA traida 30 47 ADSOMUS cui tai 21 ASSIQNEG cistitis 21 Attributes sata torride 23 26 ACCESS in Shen ae ere EE 24 25 overlay sine rire eve 25 26 COAG A A AN 21 26 Default iii aia dida io tc 23 24 o TO 21 24 26 45 MATH DATA asiaani danara isa idake 30 47 LOMGACA MA EE 17 21 23 26 udata iaa tada 21 24 26 27 UE 21 Section Type Pragma 21 24 SFR See Special Function Registers Shadow Registers cccceeeeeeeeeeeeeeeeeteaees 27 31 short SAGO severe se ssadcss deed ecu ers rer Mr eda eis esse 11 Unsigned dut iii 11 Short Tong dais 11 o scheint ed alien al aes 11 UR TLONE Addis 11 Sizes POINEr ESA dao 37 SIS Spoil lr LUI MN rene EE E ren se tes 34 Small Memory Model 37 Software Stack 14 27 31 38 40 41 45 Large it 40 Special Function Registers 27 33 35 46 BSR a a 27 28 34 47 PORO lala tl ici ds 39 47 A see eeeee lees 38 45 47 A O aiae ni 38 40 45 47 Praia ein de ede hae fa 47 PELATHA 552 ie cortes doo thee diner si Ain oe 47 PRA e RM a 47 PORTA dildos 33 35 PROD a ide 47 PRODH ias rodada 39 PROD e o ne 39 STATUS rer dl 28 47 TABLAT co aa avetdecce 47 TBLPTR viii iia 47 WREG iia Ta 27 28 34 39 41 47 Stack Hardware erraien a a ai 38 Pointer enee aaa 38 47 Software coooonocccc
40. AB C18 C Compiler User s Guide 2 9 2 1 SYNTAX interrupt directive pragma interrupt function name tmp section name save Save list pragma interruptlow function name tmp section name save save list save list save specifier save list save specifier save specifier symbol name section section name funct ion name C identifier names the C function serving as an ISR tmp section name C identifier names the section in which to allocate the ISR s temporary data symbol name C identifier names the variable that will be restored following interrupt processing section name C identifier with the exception that the first character can be a dot names the section that will be restored following interrupt processing 2 9 2 2 INTERRUPT SERVICE ROUTINES An MPLAB C18 ISR is like any other C function in that it can have local variables and access global variables however an ISR must be declared with no parameters and no return value since the ISR in response to a hardware interrupt is invoked asynchronously Global variables that are accessed by both an ISR and mainline functions should be declared volatile ISR s should only be invoked through a hardware interrupt and not from other C functions An ISR uses the return from interrupt RETFTE instruction to exit from the function rather than the normal RETURN instruction Using a fast RETFTE instruction out of context can corrupt WREG BSR and ST
41. AS Corporate Office 2355 West Chandler Blvd Chandler AZ 85224 6199 Tel 480 792 7200 Fax 480 792 7277 Technical Support 480 792 7627 Web Address http www microchip com Atlanta 3780 Mansell Road Suite 130 Alpharetta GA 30022 Tel 770 640 0034 Fax 770 640 0307 Boston 2 Lan Drive Suite 120 Westford MA 01886 Tel 978 692 3848 Fax 978 692 3821 Chicago 333 Pierce Road Suite 180 Itasca IL 60143 Tel 630 285 0071 Fax 630 285 0075 Dallas 4570 Westgrove Drive Suite 160 Addison TX 75001 Tel 972 818 7423 Fax 972 818 2924 Detroit Tri Atria Office Building 32255 Northwestern Highway Suite 190 Farmington Hills MI 48334 Tel 248 538 2250 Fax 248 538 2260 Kokomo 2767 S Albright Road Kokomo IN 46902 Tel 765 864 8360 Fax 765 864 8387 Los Angeles 18201 Von Karman Suite 1090 Irvine CA 92612 Tel 949 263 1888 Fax 949 263 1338 San Jose 1300 Terra Bella Avenue Mountain View CA 94043 Tel 650 215 1444 Fax 650 961 0286 Toronto 6285 Northam Drive Suite 108 Mississauga Ontario L4V 1X5 Canada Tel 905 673 0699 Fax 905 673 6509 ASIA PACIFIC Australia Suite 22 41 Rawson Street Epping 2121 NSW Australia Tel 61 2 9868 6733 Fax 61 2 9868 6755 China Beijing Unit 706B Wan Tai Bei Hai Bldg No 6 Chaoyangmen Bei Str Beijing 100027 China Tel 86 10 85282100 Fax 86 10 85282104 China Chengdu Rm 2401 2402 24th Floor Ming Xing Financial
42. ATUS EEE DS51288C page 28 2004 Microchip Technology Inc Language Specifics 29 23 INTERRUPT VECTORS MPLAB C18 does not automatically place an ISR at the interrupt vector Commonly a GOTO instruction is placed at the interrupt vector for transferring control to the ISR proper For example include lt p18cxxx h gt void low_isr void void high _isr void For PIC18 devices the low interrupt vector is found at 00000018h The following code will branch to the low_interrupt_service routine function to handle interrupts that occur at the low vector pragma code low vector 0x18 void interrupt_at_low_vector void _asm GOTO low_isr endasm pragma code return to the default code section pragma interruptlow low_isr void low_isr void Re Rf For PIC18 devices the high interrupt vector is found at 00000008h The following code will branch to the high interrupt service routine function to handle interrupts that occur at the high vector xy pragma code high_vector 0x08 void interrupt_at_high vector void _asm GOTO high isr _endasm pragma code return to the default code section pragma interrupt high isr void high isr void fa see BE For a complete example see Chapter 5 Sample Application 2004 Microchip Technology Inc DS51288C page 29 MPLAB C18 C Compiler User s Guide 2 9 2 4 ISR CONTEXT SAVING MPLAB C18 wil
43. B C18 compiler s run time model e g return values must be returned in the locations specified in Table 3 2 The function is called from C using standard C function notation EXAMPLE 3 3 Given the following function written in assembly UDATA_ACS delay temp RES 1 CODE asm delay SETF delay temp not done DECF delay temp BNZ not done done RETURN GLOBAL asm delay export so linker can see it END to call the function asm_delay from a C source file an external prototype for the assembly function must be added and the function called using standard C function notation asm_delay is found in an assembly file extern void asm delay void void main void asm delay EEE DS51288C page 42 2004 Microchip Technology Inc Run time Model EXAMPLE 3 4 Given the following function written in assembly INCLUDE p18c452 inc CODE asm_timed delay not_done Figure 3 2 is what the stack looks like upon entry to this function i time is passed on the stack and must be gt 0 MOVLW Oxff DECF PLUSW1 0x1 0x0 BNZ not_done done RETURN export so linker can see it GLOBAL asm timed delay END to call the function asm timed delay from a C source file an external prototype for the assembly function must be added and the function called using standard C function notation asm_timed delay is found in an assembly file extern void asm_timed delay unsigned ch
44. C Standard The results of bitwise operations on signed integers 6 3 Implementation The bitwise operators are applied to the signed integer as if it were an unsigned integer of the same type i e the sign bit is treated as any other bit ANSI C Standard The sign of the remainder on integer division 6 3 5 Implementation The remainder has the same sign as the quotient ANSI C Standard The result of a right shift of a negative valued signed integral type 6 3 7 Implementation The value is shifted as if it were an unsigned integral type of the same size i e the sign bit is not propagated B 5 FLOATING POINT ANSI C Standard The representations and sets of values of the various types of floating point numbers 6 1 2 5 The direction of truncation when an integral number is converted to a floating point number that cannot exactly represent the original value 6 2 1 3 The direction of truncation or rounding when a floating point number is converted to a narrower floating point number 6 2 1 4 Implementation See Section 2 1 2 Floating point Types The rounding to the nearest method is used AA A A ___ gt gt a DS51288C page 78 O 2004 Microchip Technology Inc ANSI Implementation defined Behavior B 6 ARRAYS AND POINTERS ANSI C Standard Implementation ANSI C Standard Implementation ANSI C Standard Implementation B 7 REGISTERS
45. CT_SCNEND_LOW Address of the end of a section 28 RELOCT_SCNEND_HIGH 29 RELOCT SCNEND UPPER 30 RELOCT SCNEND LFSR1 Address of the end of a section on LFSR 31 RELOCT SCNEND LFSR2 32 2004 Microchip Technology Inc DS51288C page 67 MPLAB C18 C Compiler User s Guide A 5 struct syment SYMBOL TABLE ENTRY Symbols are created for all identifiers as well as sections function begins function ends block begins and block ends define SYMNMLEN 8 struct syment union char _n name SYMNMLEN struct unsigned long _n zeroes unsigned long _n offset nn char n nptr 2 _n unsigned long n value short n_scnum unsigned short n type char n sclass char n_numaux A 5 1 union n The symbol name may be stored directly as a string or it may be a reference to the string table Symbol names of fewer than eight characters are stored here with all others being stored in the string table It is from this structure that the inspiration comes for extending the section data structures to allow for section names to be stored in the symbol table A 5 1 1 char n name SYMNMLEN In place symbol name if fewer than eight characters long A5 1 2 struct no Symbol name is located in string table If the first four characters of the symbol name are zero then the last four form an offset into the string table to find the name of the symbol A 5 1 2 1 unsigned long _n zeros First four cha
46. Conditional Compilation 9 Configuration Bits See Configuration Words Configuration Words 35 36 CONS LR nr Ne tent sat te Mode 14 84 Customer Notification Service 5 Customer Support siinse dea ia nindi aane 6 D Data Memory Pointers See ram Pointers Default Section 23 24 Diagnostico Made uni 8 83 95 Level of Warning c ccceeeeeeteeeeeeeeeeteeeeeeees 8 SUPpTessiINO ici iaa 8 Documentation Conventions 2 double el lat tota ts 12 E EnNdiIanness italia dede 12 Extended Instructions ADDESR A E E e tee ie 9 98 ADDUENK icc nr nan ee fe 9 50 98 DS51288C page 108 CAT SEE A 9 98 MOVSF cocaina di 9 98 MOVOS ss red donne ner dr et cu 9 98 BUSH ida cai 9 98 SUBESR tisdale hdi 9 98 SUB LNK A 9 50 98 Extended Mode 97 99 COFRE cut An Er ne et 62 64 Diagnostics a aaaeeeaa aeaee 91 93 95 Predefined Macro 16 Selecting the Mode 9 10 82 ST E EEEE E 13 33 40 42 44 F O 14 15 24 37 ELA tt Grue een 12 Floating point Types ooocooccccconicocccocononannconccinannncnnnns 12 AGUS St E E ner 12 PVOAC Mi A es ee ee ee 12 VS IEEE 754 ccscscscsssssesccensesnensesenense
47. DS51281 Describes how to set up the MPLAB IDE software and use it to create projects and program devices MPASM User s Guide with MPLINK Linker and MPLIB Librarian DS33014 Describes how to use the Microchip PICmicro MCU assembler MPASM linker MPLINK and librarian MPLIB PICmicro 18C MCU Family Reference Manual DS39500 Focuses on the Enhanced MCU family of devices The operation of the Enhanced MCU family architecture and peripheral modules is explained but does not cover the specifics of each device PIC18 Device Data Sheets and Application Notes Data sheets describe the operation and electrical specifications of PIC18 devices Application notes describe how to use PIC18 devices To obtain any of the above listed documents visit the Microchip web site www microchip com to retrieve these documents in Adobe Acrobat pdf format O 2004 Microchip Technology Inc DS51288C page 3 MPLAB C18 C Compiler User s Guide C REFERENCES 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 ona variety of computing systems Beatman John B Embedded Design
48. E 14 93 99 HOM iii 9 10 O dido 14 93 99 Dinastia 9 ON iaa 14 93 99 EA eee 8 A ea e ssa aa nn ete 7 SE a A TAE E E T Mia dida 8 BW E E EE E E A A pre ee E 8 AT E iaa 15 2004 Microchip Technology Inc DS51288C page 107 MPLAB C18 C Compiler User s Guide A ne gt 11 77 O Ne rnb nie 40 RE Re 16 37 MM eatin ees 16 37 STW aude D de nr An Me fh iste Race died sd 8 DO tie E shies 49 At M Nimes 24 99 SO Men Den nca ner sn e et sean 49 50 BODE 2er A en ee 49 50 Od RU bed ee laa nt ME 49 55 SOS ME it Mie rot eS Aaa At ot tne Ae 49 55 A E ren 16 78 SOM cost A 49 SOM as E Seek tet ae cr od 49 SONS id 49 50 OTS lisa tds de mn ae oies 49 50 HOPE ad tele 49 53 55 AOD ni stocks Sou Mr tod teased 49 53 Opat Laden aea 49 55 56 SOPAS rada tapices 49 55 56 O A es 49 54 OE da teo ia saeta 49 54 A cei Tres td tee 49 51 52 A O AN A 49 51 OCH Rnb A ea hha aces 49 52 ORS Sint Abe donas an o AIR AA 49 52 O eo mr MM an PAE 49 53 QUA e red ir dci ic 49 53 SOWA ida 49 51 Mania 49 51 CPE ER NE A 9 16 34 59 SPAS n E A em Made as 56 HS GS renier ethan et abo di muet 14 93 99 CA lise ie 14 93 99 De OF ea ASE eee spre ten er 14 93 99 AWE r Oge a a th Ne MT de 7 SU RAM ne Per PERE OPE PRE ore nee Es 8 Command line Usage 7 81 Compiler Temporaries 27 28 30 47 Compiler managed Resources 46 47
49. Gta 15 _ENASM esse 20 ee ep ee en eee ee eee 11 77 A a o ner UV 40 ARA sia 14 24 33 E Sete TR ae DR see ou IE EL aie 16 37 e Sites coe ee 19 33 MS il An 16 37 A ssembler se A MC A LE ddl nes aura dt eee TN dede As e ne ao 20 ean PR AE AA NN EE TO TER O ES vs MPASM 222 20 o E a MPASM 99 SOD varia ee ada ta 49 50 Assembly DD At Radian eevee 49 50 odie oll E ne path eet 49 55 Mo ee ASTM ses aes dadas 20 OOS As os 49 55 ah O ee OA 16 78 e Ne 20 ps 3 49 Mixing with C ooooonocccccnconcccoccncccnnnancccncnnnnnnnos 40 44 RE A LE TR auto 19 14 38 40 41 91 OM ra TU nr ne errant iodo eue 49 AT 49 50 B A A e o cold 49 50 AS 27 28 34 47 el E OM NE 49 53 55 E A A 49 53 c Opaka te Mental mr e ties ot 49 55 56 GUAT E AANE 11 77 78 Opas tinn See das 49 55 56 o e den Men eae ei tes 11 77 A eee 49 54 unsigned miens in md ate eects 11 77 O nn unes 49 54 CLEAN aerar ited ale ee 34 TE nt re ne ace 49 51 52 OT COR NES PACS ee EEE 21 26 SOS MAMMA Nm M Nr PA se Ain vas 49 51 COFF File A EE ee PE TE 49 52 DIMGrENCES iii une tirant 99 OES Rhin nee aa 49 52 E 61 76 SOU data 49 53 Command line Options 7 81 82 OUTS en aer e ae 49 53 extended ossy iinei aia ikurri 9 10 le E 49 51 O T ed 7 OWE EE E dao E E EN 49 51 help message suisse 8 D De A eee ee 9 16 34 59 help message all ores 8 SSID il tata th ment esd uhh Ne eut 56 help message 1list conccnccccanananonnnnnncnnnnnnnnns 8 AS A
50. IARY SYMBOL TABLE ENTRY FOR FUNCTION CALL REFERENCES typedef struct aux fcn calls unsigned long x_calleendx unsigned long x is interrupt char _unused 10 aux fcn calls t A 12 1 unsigned long x calleendx Symbol index of the called function If call of a higher order function set to AUX_FCN CALLS HIGHERORDER define AUX _FCN CALLS HIGHERORDER unsigned long 1 A 12 2 unsigned longx is interrupt Specifies whether the function is an interrupt and if so the priority of the interrupt 0 not an interrupt 1 low priority 2 high priority A 13 struct aux arr AUXILIARY SYMBOL TABLE ENTRY FOR AN ARRAY define X_DIMNUM 4 typedef struct aux_arr unsigned long x_tagndx unsigned short x lnno unsigned short x size unsigned short x dimen X_DIMNUM aux arr t A 13 1 unsigned long x tagndx The symbol table index of the structure or union tagname associated with the array element type if the base type is structure or union A 13 2 unsigned short x size Size of array A 13 3 unsigned short x dimen X DIMNUM Size of first four dimensions AA AAA III A DS51288C page 74 O 2004 Microchip Technology Inc COFF File Format A 14 struct aux_eobf AUXILIARY SYMBOL TABLE ENTRY FOR THE END OF A BLOCK OR FUNCTION typedef struct aux_eobf char _unused 4 unsigned short x lnno char _unused2 12 aux_eobf t A 14 1 unsigned short x lnno C source line number of the end relative t
51. MPLAB C18 may be able to eliminate the second MOVLW instruction by determining that the value of WREG must already be 5 at this point 0x000000 MOVLW 0x5 0x000002 MOVWF a 0x1 0x000004 MOVWF b 0x1 WREG content tracking should not affect the ability to debug source code 4 5 CODE STRAIGHTENING Os Os Code straightening attempts to reorder code sequences so that they appear in the order in which they will be executed This can move or remove branching instructions so that code may be smaller and more efficient An example where this may occur in Cis first subl goto second third sub3 goto fourth second sub2 goto third fourth sub4 In this example the function calls will occur in numerical order namely sub1 sub2 sub3 and then sub4 With code straightening disabled Os the original flow of the code is mirrored in the generated assembly code 0x000000 first CALL subl1 0x0 0x000002 0x000004 BRA second 0x000006 third CALL sub3 0x0 0x000008 0x00000a BRA fourth 0x00000c second CALL sub2 0x0 0x00000e 0x000010 BRA third 0x000012 fourth CALL sub4 0x0 0x000014 O 2004 Microchip Technology Inc DS51288C page 51 MPLAB C18 C Compiler User s Guide With code straightening enabled 0s the code is reordered sequentially removing the branching instructions 0x000000 first CALL sub1 0x0 0x000002 0x000004 second CALL sub2 0x0 0x000006 0x000008 third CALL sub3 0x0 0x00
52. Migratable Memory MPASM MPLIB MPLINK MPSIM PICkit PICDEM PICDEM net PICLAB PICtail PowerCal Powerlnfo PowerMate PowerTool rfLAB rfPICDEM Select Mode Smart Serial SmartTel and Total Endurance are trademarks of Microchip Technology Incorporated in the U S A and other countries SQTP is a service mark of Microchip Technology Incorporated in the U S A All other trademarks mentioned herein are property of their respective companies 2004 Microchip Technology Incorporated Printed in the U S A All Rights Reserved gt Printed on recycled paper Microchip received ISO TS 16949 2002 quality system certification for its worldwide headquarters design and wafer fabrication facilities in Chandler and Tempe Arizona and Mountain View California in October 2003 The Company s quality system processes and procedures are for its PICmicro 8 bit MCUs 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 DS51288C page ii 2004 Microchip Technology Inc MPLAB C18 C COMPILER MICROCHIP USER S GUIDE Table of Contents Preta a 1 Chapter 1 Introduction T O A A 7 1 2 Invoking the Compiler se 7 1 2 1 Creating Output Files 8 1 2 2 Displaying Diagnostics cocoa nord 8 1 2 3 D fining Macros ooicc a 9 1 2 4 Selecting the P
53. Non extended mode however not all of the command line options are valid when the compiler is operating in the Extended mode The command line mcc18 extended help should be utilized to see help for the compiler operating in the Extended mode Note Other command line options are discussed throughout the User s Guide and a summary of all the command line options can be found in Appendix C A E E RR EL DS51288C page 10 2004 Microchip Technology Inc MPLAB C18 C COMPILER MICROCHIP USER S GUIDE Chapter 2 Language Specifics 2 1 DATA TYPES AND LIMITS 2 1 1 Integer Types The MPLAB C18 compiler supports the standard ANSI defined integer types The ranges of the standard integer types are documented in Table 2 1 In addition MPLAB C18 supports a 24 bit integer type short long int or long short int in both a signed and unsigned variety The ranges of this type are also documented in Table 2 1 TABLE 2 1 INTEGER DATA TYPE SIZES AND LIMITS Type Size Minimum Maximum char tr 8 bits 128 127 signed char 8 bits 128 127 unsigned char 8 bits 0 255 int 16 bits 32 768 32 767 unsigned int 16 bits 0 65 535 short 16 bits 32 768 32 767 unsigned short 16 bits 0 65 535 short long 24 bits 8 388 608 8 388 607 unsigned short long 24 bits 0 16 777 215 long 32 bits 2 147 483 648 2 147 483 647 unsigned long 32 bits 0 4 294 967 295 Note 1 A plain char is signed by def
54. Od Values computed in a function which are not used on any path to the function s exit are considered dead Instructions which compute only dead values are themselves considered dead Values stored to locations visible outside the scope of the function are considered used and therefore not dead since it is not determinable whether the value is used or not Using the same example as that shown in Section 4 8 Copy Propagation char c void foo char a char b b a c b With copy propagation enabled 0p and dead code removal disabled 0a the generated assembly code is that shown in Section 4 8 Copy Propagation 0x000000 foo MOVFF a b 0x000002 0x000004 MOVFF a c 0x000006 0x000008 RETURN 0x0 With copy propagation enabled Op and dead code removal enabled Od instead of b being moved to c for the second instruction a is moved to c thus making the assignment to b dead and able to be removed 0x000000 foo MOVFF a c 0x000002 0x000004 RETURN 0x0 The dead code removal optimization may affect the ability to set breakpoints on certain lines of C source code 4 11 PROCEDURAL ABSTRACTION Opa Opa MPLAB C18 like most compilers frequently generates code sequences that appear multiple times in a single object file This optimization reduces the size of the generated code by creating a procedure containing the repeated code and replacing the copies with a call to the procedure Procedural ab
55. Pointer The frame pointer references the location on the stack that separates the stack based arguments from the stack based local variables Stack based arguments are located at negative offsets from the frame pointer and stack based local variables are located at positive offsets from the frame pointer Immediately upon entry into a C function the called function pushes the value of FSR2 onto the stack and copies the value of FSR1 into FSR2 thereby saving the context of the calling function and initializing the frame pointer of the current function Then the total size of stack based local variables for the function is added to the stack pointer allocating stack space for those variables References to stack based local variables and stack based arguments are resolved according to offsets from the frame pointer Figure 3 3 shows a software stack following a Call to a C function DS51288C page 38 2004 Microchip Technology Inc Run time Model FIGURE 3 3 EXAMPLE OF SOFTWARE STACK FOLLOWING A C FUNCTION CALL Unused Location _ FSR1 Stack Pointer Local Variable n Local Variable 2 Local Variable 1 _ FSR2 Frame Pointer Previous Frame Pointer Increasing Addresses Called Function Parameter 1 Called Function Parameter 2 Called Function Parameter n Caller Function s Context 3 2 1 Return Values The location of the return value is de
56. Promotions ISO mandates that all arithmetic be performed at int precision or greater By default MPLAB C18 will perform arithmetic at the size of the largest operand even if both operands are smaller than an int The ISO mandated behavior can be instated via the Oi command line option For example unsigned char a b unsigned i a i b 0x80 a b ISO requires that i 0x100 but in C18 i 0 Note that this divergence also applies to constant literals The chosen type for constant literals is the first one from the appropriate group that can represent the value of the constant without overflow For example define A 0x10 A will be considered a char unless Oi specified define B 0x10 B will be considered a char unless Oi specified Hdefine C A B unsigned i i C ISO requires that i 0x100 but in C18 i 0 2 7 2 Numeric Constants MPLAB C18 supports the standard prefixes for specifying hexadecimal 0x and octal 0 values and adds support for specifying binary values using the 0b prefix For example the value two hundred thirty seven may be denoted as the binary constant 0b11101101 DS51288C page 16 2004 Microchip Technology Inc Language Specifics 2 7 3 String Constants The primary use of data located in program memory is for static strings In keeping with this MPLAB C18 automatically places all string constants in program memory This type of a string constan
57. R RESERVED RESOURCES Compiler managed Primary Use s Automatically Resource Saved PC Execution control Y WREG Intermediate calculations Y STATUS Calculation results Y BSR Bank selection Y PROD Multiplication results return values intermediate calculations section tmpdata Intermediate calculations FSRO Pointers to RAM Y FSR1 Stack pointer Y FSR2 Frame pointer Y TBLPTR Accessing values in program memory TABLAT Accessing values in program memory PCLATH Function pointer invocation PCLATU Function pointer invocation section MATH_DATA Arguments return values and temporary locations for math library functions Note Compiler temporary variables are placed in a udata section named tmpdata Interrupt service routines each create a separate section for temporary data storage see Section 2 9 2 pragma interruptlow fname pragma interrupt fname 2004 Microchip Technology Inc DS51288C page 47 MPLAB C18 C Compiler User s Guide NOTES DS51288C page 48 2004 Microchip Technology Inc MPLAB C18 C COMPILER MICROCHIP USER S GUIDE Chapter 4 Optimizations The MPLAB C18 compiler is an optimizing compiler It performs optimizations that are primarily intended to reduce code size All of the optimizations that can be performed by the MPLAB C18 compiler are enabled by default but can be completely disabled using the O command
58. RTB 0 38 39 OpenTimerO TIMER_INT_ON amp TO SOURCE INT amp TO_16BIT 40 INTCONbits GIE 1 fe ale 42 while 1 43 44 45 DS51288C page 58 2004 Microchip Technology Inc Sample Application Line 1 Line 10 Line 13 Line 16 Line 18 Line 19 20 Line 24 Line 30 Line 36 37 Line 39 Line 40 This line includes the generic processor header file The correct processor is selected via the p command line option See Section 2 5 1 System Header Files and Section 2 10 Processor specific Header Files For PIC18 devices the low interrupt vector is found at 000000018h This line of code changes the default code section to the absolute code section named low_vector located at address 0x18 See Section 2 9 1 pragma sectiontype and Section 2 9 2 3 Interrupt Vectors This line contains inline assembly that will jump to the ISR See Section 2 8 2 Inline Assembly and Section 2 9 2 3 Interrupt Vectors This line returns the compiler to the default code section See Section 2 9 1 pragma sectiontype and Table 2 7 This line specifies the function timer_isr as a low priority interrupt service routine This is required in order for the compiler to generate a RETFTE instruc tion instead of a RETURN instruction for the timer_isr function In addition it ensures that PROD special function register will be sa
59. TOMER SUPPORT Users of Microchip products can receive assistance through several channels e Distributor or Representative e Local Sales Office e Field Application Engineer FAE Corporate Applications Engineer CAE e Hotline Customers should call their distributor representative or field application engineer FAE for support Local sales offices are also available to help customers See the back cover for a list of sales offices and locations Corporate Applications Engineers CAEs may be contacted at 480 792 7627 In addition there is a Systems Information and Upgrade Line This line provides system users a list of the latest versions of all of Microchip s development systems software products Plus this line provides information on how customers can receive any currently available upgrade kits The Hotline Numbers are 1 800 755 2345 for U S and most of Canada 1 480 792 7302 for the rest of the world DS51288C page 6 2004 Microchip Technology Inc MPLAB C18 C COMPILER MICROCHIP USER S GUIDE Chapter 1 Introduction 1 1 OVERVIEW The MPLAB C18 compiler is a free standing optimizing ANSI C compiler for the PIC18 PICmicro microcontrollers MCU The compiler deviates from the ANSI standard X3 159 1989 only where the standard conflicts with efficient PICmicro MCU support The compiler is a 32 bit Windows console application and is fully compatible with Microchip s MPLAB IDE allowing source leve
60. Wide Web WWW site The web site is used by Microchip as a means to make files and information easily available to customers To view the site you must have access to the Internet and a web browser such as Netscape Navigator or Microsoft Internet Explorer The Microchip web site is available by using your favorite Internet browser to reach http www microchip com The web site provides a variety of services Users may download files for the latest development tools data sheets application notes user s guides articles and sample programs A variety of information specific to the business of Microchip is also available including listings of Microchip sales offices distributors and factory representatives Technical Support e Frequently Asked Questions FAQ e On line Discussion Groups conferences for products development systems technical information and more e Microchip Consultant Program Member Listing e Links to other useful web sites related to Microchip products Engineer s Toolbox e Design Tips e Device Errata Other Available Information e Latest Microchip Press Releases e Listing of seminars and events e Job Postings DEVELOPMENT SYSTEMS CUSTOMER NOTIFICATION SERVICE Microchip started the customer notification service to help our customers keep current on Microchip products with the least amount of effort Once you subscribe you will receive e mail notification whenever we change update revise or
61. YPE STORAGE ENDIANNESS Endianness refers to the ordering of bytes in a multi byte value MPLAB C18 stores data in little endian format Bytes at lower addresses have lower significance the value is stored little end first For example pragma idata test 0x0200 long 1 0xAABBCCDD results in a memory layout as follows 0x0200 OxDD Address Content 0x0202 OxBB 0x0203 OxAA 0x0201 OxCC DS51288C page 12 2004 Microchip Technology Inc Language Specifics 2 3 STORAGE CLASSES MPLAB C18 supports the ANSI standard storage classes auto extern register static and typedef 2 3 1 Overlay The MPLAB C18 compiler introduces a storage class of overlay The overlay storage class applies only when the compiler is operating in Non extended mode see Section 1 2 5 Selecting the Mode The overlay storage class may be applied to local variables but not formal parameters function definitions or global variables The overlay storage class will allocate the associated symbols into a function specific static overlay section Such a variable will be allocated statically but initialized upon each function entry For example in void void overlay int x 5 X x will be initialized to 5 upon each function entry although its storage will be statically allocated If no initializer is present then its value upon function entry is undefined The MPLINK linker will attempt t
62. a macro CONFIG DECL and defines for each setting that allow the device configuration to be specified See Section 2 12 Configuration Words for more information In order to use the processor specific header file choose the header file that pertains to the device being used e g if using a PIC18C452 include lt p18c452 h gt inthe application source code The processor specific header files are located in the c mcc18 h directory where c mcc18 is the directory where the compiler is installed Alternatively include lt p18cxxx h gt will include the proper processor specific header file based on the processor selected on the command line via the p command line option TABLE 2 8 C MACROS PROVIDED FOR PlCmicro MCU INSTRUCTIONS Instruction Macro Action Nop Executes a no operation NOP Clrwat Clears the Watchdog Timer CLRWDT Sleep Executes a SLEEP instruction Reset Executes a device reset RESET Rlcf var dest access 2 3 Rotates var to the left through the carry bit Rincf var dest access 2 Rotates var to the left without going through the carry bit Rrcf var dest access 2 Rotates var to the right through the carry bit Rrncf var dest access 2 Rotates var to the right without going through the carry bit Swapf var dest access 2 3 Swaps the upper and lower nibble of var Note 1 Using any of these macros in a function affect
63. ar void main void asm_timed delay 0x80 3 2 3 3 USING C VARIABLES IN ASSEMBLY When using C variables in assembly e The C variable must have global scope in the C source file e The C variable must be declared as an extern symbol in the assembly file SSS aaa sss ES eee eee es 2004 Microchip Technology Inc DS51288C page 43 MPLAB C18 C Compiler User s Guide EXAMPLE 3 5 Given the following written in C unsigned int c variable void main void to modify the variable c_ variable from assembly an external declaration must be added for the variable in the assembly source file EXTERN c_variable defined in C module MYCODE CODE asm_function MOVLW Oxff put Oxffff in the C declared variable MOVWF c variable MOVWF c variable 1 done RETURN export so linker can see it GLOBAL asm_function END 3 2 3 4 USING ASSEMBLY VARIABLES IN C When using assembly variables in C The variable must be declared as global in the ASM module The variable must be declared as extern in the C module EXAMPLE 3 6 Given the following written in assembly MYDATA UDATA asm variable RES 2 2 byte variable export so linker can see it GLOBAL asm_variable END to change the variable asm_variable from a C source file an external declaration must be added for the variable in the C source file The variable can be used as if it were a C variable extern unsigned int asm
64. ault 2 Aplain char may be unsigned by default via the k command line option 2004 Microchip Technology Inc DS51288C page 11 MPLAB C18 C Compiler User s Guide 2 1 2 32 bit floating point types are native to MPLAB C18 using either the double or float data types The ranges of the floating point type are documented in Table 2 2 Floating point Types TABLE 2 2 FLOATING POINT DATA TYPE SIZES AND LIMITS Minimum Maximum Maximum Normalized Exponent Exponent Type Size Minimum Normalized float 32 bits 126 128 27126 1 17549435e 38 2128 2 2 15 6 80564693e 38 double 32 bits 126 128 27126 1 17549435e 38 2128 2 2 15 6 80564693e 38 The MPLAB C18 format for floating point numbers is a modified form of the IEEE 754 format The difference between the MPLAB C18 format and the IEEE 754 format consists of a rotation of the top nine bits of the representation A left rotate will convert from the IEEE 754 format to the MPLAB C18 format A right rotate will convert from the MPLAB C18 format to the IEEE 754 format Table 2 3 compares the two formats TABLE 2 3 MPLAB C18 FLOATING POINT VS IEEE 754 FORMAT Standard Exponent Byte Byte 0 Byte 1 Byte 2 IEEE 754 Sepe 1222304056 e7ddd dddd dddd dddd dddd dddd MPLAB C18 e0 1 2 3 4 5 6 7 sddd dddd dddd dddd dddd dddd Legend s sign bit d mantissa e exponent 2 2 DATA T
65. bank where PORTA is located and the starting address for that bank PORTA has two labels PORTAbits and PORTA both referring to the same location in this case 0xf 80 2 12 CONFIGURATION WORDS The default linker script for each part contains a section named CONFIG For example the p18c452 1kr script contains the following statements CODEPAGE NAME config START 0x300000 END 0x300007 PROTECTED SECTION NAME CONFIG ROM config The pragma romdata CONFIG directive is used to set the current romdata section to the section named CONFIG The configuration for the device can be specified using the CONFIG _DECL macro and the def ines located in the processor specific header file The following example specifies the configuration specified in Table 2 9 include lt p18c452 h gt Hpragma romdata CONFIG CONFIG DECL CP ON 1L OSCS ON 1H amp OSC LP 1H PWRT ON 2L amp BOR OFF 2L amp _BORV 42 2L WDT OFF 2H amp WDTPS 1 2H _CCP2MUX OFF 3H _CONFIG4L DEFAULT pragma romdata void main void 2004 Microchip Technology Inc DS51288C page 35 MPLAB C18 C Compiler User s Guide TABLE 2 9 EXAMPLE CONFIGURATION Setting Configuration Specified _CP ON 1L All of program memory is code protected _OSCS_ON_1H Oscillator system clock switch option is enabled oscillator switching is enabled _OSC_LP_1H LP oscillator _PWRT_ON 2L Power up timer enabled _BOR_OFF_2L Br
66. bject being initialized There are too many values in the initializer list 1219 integer constant expected A constant expression of integral type was expected but an expression of non integral type or a non constant expression was found 1220 initializer detected in typedef declaration of s A typedef declaration cannot include initializers 1221 empty initializer list detected An initializer list cannot be empty There must be one or more initializer values between the braces 1250 s operand s must be a literal The specified operand for the opcode must be a literal value not a symbol reference DS51288C page 90 O 2004 Microchip Technology Inc MPLAB C18 Diagnostics 1251 s operand count mismatch The number of operands found for the specified opcode does not match the number of operands expected Unlike the MPASM assembler the MPLAB C1x in line assembler expects all operands to be explicitly specified There are no default values for operands such as the access bit or destination bit 1252 invalid opcode s detected for processor s The opcode specified is not valid for the target processor Common causes include porting in line assembly code from a processor with a different instruction set e g PIC17CXX to PIC18CXX and typographical errors in the spelling of the opcode 1253 constant operand expected Operands to in line assembly opcodes must resolve to a constant expression where a cons
67. ble code straightening 4 5 Ot Enable tail merging default 4 6 Ot Disable tail merging 4 6 Ob Enable branch optimizations default 4 2 Ob Disable branch optimizations 4 2 sca Enable default auto locals default Valid for 2 3 Non extended mode only scs Enable default static locals Valid for 2 3 Non extended mode only sco Enable default overlay locals statically allocate 2 3 activation records Valid for Non extended mode only 2004 Microchip Technology Inc DS51288C page 81 MPLAB C18 C Compiler User s Guide DS51288C page 82 TABLE C 1 COMMAND LINE SUMMARY CONTINUED Option Description Reference Oa Enable default data in access memory Valid for 2 9 1 3 Non extended mode only Oa Disable default data in access memory default 2 9 1 3 Valid for Non extended mode only Ow Enable WREG tracking default 4 4 Ow Disable WREG tracking 4 4 Opa Enable procedural abstraction default 4 11 Opa Disable procedural abstraction 4 11 pa lt repeat count gt Set procedural abstraction repeat count 4 11 default 4 p lt processor gt Set processor default is generic 1 2 4 2 6 2 10 D lt macro gt text Define a macro 1 2 3 w 1 2 3 Set warning level default 2 1 2 2 nw lt n gt Suppress message lt n gt 1 2 2 verbose Operate verbosely show banner and other 1 2 information extended Generate Extende
68. censans 12 Frame Pointer ccccccccccecscceecccseueeseessueeeeeeeaeees 38 47 INHIalZINO torcidos 38 40 PSRO an tcc nt nn das aad dea tte 39 47 PORT Rs A El Res en 38 45 47 FORD sidi l distri EIS S 38 40 45 47 G Generic Processor ccccccccecccsssueeeeeeeeeees 9 59 64 99 Header Fil icono di Miss 34 H Hardware Stack 38 Header Files Generic Processor 34 Processor specific 33 34 SYST ME 2520828828 trapo ee l attestent ete 15 SOR asso meet cle E 15 High priority Interrupt c ccceeeeeeseeeeeeeeeeee 27 31 l o A A 21 24 26 45 IEEE 754 aie Rel i is 12 Inline Assembly 00 0 2 eee eeeeeeeeeeeeeteeeeeeteeeteeeeeeeeees 20 98 A ee ee a ee re 20 FONSI soit heures 20 Macros See Macros Inline Assembly Inline assembly eeeeeeceeeeeeeteeeeeeeeeeeeceetesseeeeees 20 int STONE Dieser A 11 16 unsigned snd esi Dont a ar 11 Integer Promotions 16 Integer Types cocoonoccccccccnonoccconnconancnnnnncnanncncnncnannnnncnn 11 CHAT ENS tte Ant en ns ee 11 77 78 STE sion eee awed ces certes 11 77 UNSTONE nee eee 11 77 int A earn 11 16 nsigned tadas 11 long o ssl uma de weeaeioeeecehes 11 unsigned tica tan 11 O 2004 Microchip Technology Inc Tong short Wnt ris eee 11 short SIM dia tad 11 unsigned rerien Nero dde
69. cncnnnnnos 14 27 31 38 40 41 45 Larges da le aay 40 Startup Code cooccccccnnnncnccconncononanananananononnonononononons 45 46 CUSTOMIZINQ nee 46 SEAL E A EET 13 14 40 42 97 98 STATUS ri til es 27 28 47 2004 Microchip Technology Inc Storage Classes una eet 13 14 T AUTO verter te teeteetetttteeetees 13 14 38 40 41 91 TABLAT Waun M NAN Au At 47 EXTEPN eencrnnnnnn ne nnnnn nn nnn nen nnnnos 13 33 40 42 44 TBLPTR ccccceccscsecesesseeseesceceeccescesccstcsescsaesaesaeeseeseeses 47 overlay Ls 13 14 97 98 Temporaries EEJISES E rata 13 Compiler ice russes 7 27 28 30 47 Static 13 14 40 42 97 98 ESPOSA AE 13 Eypede braille dial 13 Storage Qualifiers 14 15 U CONSERS A Sn ne ht des 14 84 data A i oN te ES 21 24 26 27 Elda li mae 14 15 24 37 v Nan Set Ro o BA oe 14 15 24 25 33 37 TO TO ART 14 15 Varlocate pragma cooococcccnoccccccccconnoncccnconnnnncnncnnnnns 31 32 IN AVE CO A RR Or 14 15 17 18 22 26 VOLaCI 6 tetra nate a A taire 14 33 volatile dri e pea mener 14 33 W Structures ANONYMOUS ere 19 33 WEES ease arenes ae tae Naa Swapl es nai ta diene nti ine 34 AAA EEE AAA O 2004 Microchip Technology Inc DS51288C page 111 MPLAB C18 C Compiler User s Guide NOTES DS51288C page 112 2004 Microchip Technology Inc Index NOTES 2004 Microchip Technology Inc DS51288C page 113 MICROCHIP WORLDWIDE SALES AND SERVICE AMERIC
70. ction Attribute A characteristic ascribed to a section e g an access section Special Function Register Registers that control I O processor functions I O status timers or other modes or peripherals DS51288C page 104 2004 Microchip Technology Inc Glossary Storage Class Determines the lifetime of the memory associated with the identified object Storage Qualifier Indicates special properties of the objects being declared e g const V Vector The memory locations that an application will jump to when either a reset or interrupt occurs AA EEE Sma O 2004 Microchip Technology Inc DS51288C page 105 MPLAB C18 C Compiler User s Guide NOTES DS51288C page 106 2004 Microchip Technology Inc MICROCHIP MPLAB C18 C COMPILER USER S GUIDE Index Symbols AMM tata 45 pragma See Pragmas Stringtable sca aceite lada 17 een A tee A Aiba eth at dd 9 10 Empdata sooi Morse ine idad 30 47 SET satire a rennes a aa Es 7 E 109 O ss 16 e UP messagera atan 8 EXTENDED 8 16 98 help message all mu 8 MARGE lo den datan 16 help message List vcecccccscccsssssessesseessesseseeeeees 8 PROCESSOR va stings ana 16 nO extended sise 9 10 SMALL sense 16 D a wart rt O 9 ___TRADITIONALIS8_ sssesssersrersirirsrerererennnnen 16 98 STONES a te st cr es 8 e Sierre terne sense ere A ent Tes Mes rss ete en rt 20 OA e de Aah 8 CONFIG DECI ss 34 35 Neg eae cea Ta Pe ide aa eae
71. ctive of the linker script An unassigned section is one that is neither absolute nor assigned 2 9 1 1 SYNTAX section directive pragma udata attribute list section name address pragma idata l attribute listl section name address pragma romdata overlay section name address pragma code overlay section name address attribute list attribute attribute list attribute attribute access overlay section name C identifier address integer constant a E S E ay 2004 Microchip Technology Inc DS51288C page 21 MPLAB C18 C Compiler User s Guide 2 9 1 2 SECTION CONTENTS A code section contains executable content located in program memory A romdata section contains data allocated into program memory normally variables declared with the rom qualifier For additional information on romdata usage e g for memory mapped peripherals see the MPLINK linker s portion of the MPASM User s Guide with MPLINK and MPLIB DS33014 A udata section contains uninitialized global data statically allocated into data memory An idata section contains initialized global data statically allocated into data memory Table 2 6 shows which section each of the objects in the following example will be located in rom int ri rom char rc A int ul char uc int ii 0 char ic A void foobar void static rom int foobar ri static rom char foobar_rc Z
72. d in PRODH PRODL see Table 3 2 i e EXTERN sub defined in C module MOVLW 0x65 MOVWF POSTINC1 MOVLW 0x12 MOVWF POSTINC1 y 0x1265 pushed onto stack MOVLW 0x61 MOVWF POSTINC1 MOVLW 0x78 MOVWF POSTINC1 X 0x7861 pushed onto stack CALL sub MOVFF PRODL result MOVFF PRODH result 1 result is returned in PRODH PRODL O 2004 Microchip Technology Inc DS51288C page 41 MPLAB C18 C Compiler User s Guide 3 2 3 1 2 static Parameters static parameters are allocated globally enabling direct access static parameters are valid only when the compiler is operating in Non extended mode see Section 1 2 5 Selecting the Mode The naming convention for static parameters is _ function name n where function name is replaced by the name of the function and n is the parameter position with numbering starting from 0 For example given the following prototype for a C function char add static char x static char y the value for y is accessed by using __add 1 and the value of x is accessed by using add 0 Note Since is not a valid character in the MPASM assembler s labels access ing static parameters in assembly functions is not supported 3 2 3 2 CALLING ASSEMBLY FUNCTIONS FROM C When calling assembly functions from C The function label must be declared as global in the ASM module The function must be declared as extern in the C module The function must maintain the MPLA
73. d mode code 1 2 5 no extended Generate Non extended mode code 1 2 5 help message list Display a list of all diagnostic messages 1 2 2 help message all_ Display help for all diagnostic messages 1 2 2 help message lt n gt Display help on diagnostic number lt n gt 1 2 2 2004 Microchip Technology Inc MPLAB C18 C COMPILER MICROCHIP USER S GUIDE Appendix D MPLAB C18 Diagnostics This appendix list errors warnings and messages generated by the MPLAB C18 compiler D 1 ERRORS 1002 syntax error s expected The syntax of the pre processor construct was expecting the specified token Common causes include typographical errors missing required operands to the directive and mis matched parenthesis 1013 error in pragma directive MPLAB C18 was expecting the pragma being parsed to be complete but did not see a new line This would be caused by extra text following the pragma 1014 attribute mismatch in resumption of section s MPLAB C18 requires that a previously declared section s attribute must match those which are being specified in the current pragma sectiontype directive This error can also occur when the current pragma sectiontype directive specifies overlay or access multiple times 1016 integer constant expected for line directive The line number operand of the line preprocessor directive must be an integer constant 1017 symbol name expected in inte
74. declared without a base type being specified e g extern x in which case a base type of int is implied This usage is deprecated by the standard as obsolete and therefore a diagnostic is issued to that effect TABLE 1 1 WARNING LEVELS Warning Level Diagnostics Shown 1 Errors fatal and non fatal 2 Level 1 plus warnings 3 Level 2 plus messages A O Es DS51288C page 8 O 2004 Microchip Technology Inc Introduction 1 2 3 Defining Macros The D command line option allows a macro to be defined The D command line option can be specified in one of two ways Dname or Dname value Dname defines the macro name with 1 as its definition Dname value defines the macro name with value as its definition For example mcc18 DMODE defines the macro MODE to have a value of 1 whereas mcc18 DMODE 2 defines the macro MODE to have a value of 2 An instance of utilizing the D command line option is in conditional compilation of code For example if MODE X bo elif MODE X 0 else Xi T Hendif 1 2 4 Selecting the Processor By default MPLAB C18 compiles an application for a generic PIC18 PlCmicro microcontroller The object file can be limited to a specific processor with the pprocessor command line option where processor specifies the particular processor to utilize For example to limit an object file for use with only the PIC18F452 the command line option p18
75. does not need to generate a second MOVLB instruction when using c4 immediately after c3 AAA III A A DS51288C page 32 O 2004 Microchip Technology Inc Language Specifics 2 10 PROCESSOR SPECIFIC HEADER FILES The processor specific header file is a C file that contains external declarations for the special function registers which are defined in the register definitions file see Section 2 11 Processor specific Register Definitions Files For example in the PIC18C452 processor specific header file PORTA is declared as extern volatile near unsigned char PORTA and as extern volatile near union struct unsigned RAO unsigned RA1 unsigned RA2 unsigned RA3 unsigned RA4 unsigned RAS unsigned RA6 struct unsigned ANO 1 unsigned AN1 1 unsigned AN2 1 unsigned AN3 1 unsigned TOCKI 1 unsigned SS 1 unsigned OSC2 1 struct unsigned 2 unsigned VREFM 1 unsigned VREFP 1 unsigned 1 unsigned AN4 1 unsigned CLKOUT 1 struct unsigned 5 unsigned LVDIN 1 Pa PORTAbits PPP Ppp The first declaration specifies that PORTA is a byte unsigned char The extern modifier is needed since the variables are declared in the register definitions file The volatile modifier tells the compiler that it cannot assume that PORTA retains values assigned to it The near modifier specifies that the port is located in access RAM The second declaration specifies that PORTAbits i
76. dx char _unused3 2 aux tag t A 9 1 unsigned short x size Size of structure union or enumeration A 9 2 unsigned long x endndx Symbol index of next entry beyond this structure union or enumerated tag DS51288C page 72 O 2004 Microchip Technology Inc COFF File Format A 10 struct aux_eos AUXILIARY SYMBOL TABLE ENTRY FOR AN END OF struct union enum typedef struct aux_eos unsigned long x_tagndx char _unused 2 unsigned short x size char _unused2 10 aux eos t A 10 1 unsigned long x tagndx Symbol index of a structure union or enumerated tag A 10 2 unsigned short x size Size of a structure union or enumeration A1 struct aux fcn AUXILIARY SYMBOL TABLE ENTRY FOR A FUNCTION NAME typedef struct aux fcn unsigned long x_tagndx unsigned long x_size unsigned long x_lnnoptr unsigned long x_endndx short x_actscnum aux_fcn t A 11 1 unsigned long x_tagndx The symbol table index of the structure or union tagname associated with the return value type if the return value base type is structure or union A 11 2 unsigned long x lInnoptr File pointer to line numbers for this function A 11 3 unsigned long x_endndx Symbol index of next entry beyond this function A 11 4 short x actscnum Section number of the static activation record data 2004 Microchip Technology Inc DS51288C page 73 MPLAB C18 C Compiler User s Guide A 12 struct aux fcn calls AUXIL
77. e pragma varlocate section name variable name 31 2 10 Processor specific Header Files ccccccccnccoocccnncncnnnncnoconononnnnnnnnnnnnnnnnnos 33 2 11 Processor specific Register Definitions Files 35 2 12 Configuration Words ss 35 2004 Microchip Technology Inc DS51288C page iii MPLAB C18 C Compiler User s Guide Chapter 3 Run time Model gT Memory Models shoe contes rea ae a a aaa ERA a aa eaa SERERE 37 3 2 Calling Conventions 38 3 2 1 Return Values ses 39 3 2 2 Managing the Software Stack narren 40 3 2 3 Mixing C and Assembly 40 Sor San COS e lake ered Can ann et tete de 45 3 3 1 Default Behnaviol noorena eapi ee e eaa e aeea EAN 45 3 3 2 Customization a in e in iets ld 46 3 4 Compiler Managed Resources 46 Chapter 4 Optimizations 4 1 Duplicate String Merging ooocccccccccccccnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn 49 42 Bra iia 50 4 3 BANKING A A OE dee ne 50 4 4 WREG Content Tracking ooocccccccccccccccnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnninnnin 51 4 5 Code Straightening ss 51 AiG Tail MOFQING crscselasscscre sense infinie nan etedauadevevdeusedtdeereaeeetahauadeds 52 4 7 Unreachable Code Removal
78. e application and describes the source code with references to the specific topics discussed in the User s Guide Appendix A COFF File Format Provides details of the Microchip COFF format Appendix B ANSI Implementation defined Behavior Discusses MPLAB C18 implementation defined behavior as required by the ANSI standard Appendix C Command line Summary Lists command line options along with references to sections that discuss each of the command line options Appendix D MPLAB C18 Diagnostics Lists errors warnings and messages Appendix E Extended Mode Discusses differences between Non extended and Extended modes 2004 Microchip Technology Inc DS51288C page 1 MPLAB C18 C Compiler User s Guide Conventions Used in this Guide This User s Guide uses the following documentation conventions DOCUMENTATION CONVENTION Description Represents Examples Code Courier font Courier font Sample source code distance time speed Filenames and paths c mcci8 h Keywords _asm endasm static Command line options Opa Opa Italic Courier Variable name argument file o where file can be any valid file name font Square Optional arguments mcc18 options file options brackets Ellipses Replaces repeated var_name var_name instances of text Represents code void main void supplied by user Oxnnnn A hexadecimal number OXFFFF 0x007A where n is a he
79. e set to zero To perform initialization of data memory the MPLINK linker creates a copy of initialized data memory in program memory that the startup code copies to data memory The cinit section is populated by the MPLINK linker to describe where the program memory images should be copied Table 3 3 describes the format of the cinit sec tion TABLE 3 3 FORMAT OF cinit Field Description Size num_init Number of sections 16 bit from_addr_0 Program memory start address of section 0 32 bit to addr 0 Data memory start address of section 0 32 bit size 0 Number of data memory bytes to initialize for section 0 32 bit from _addr_n Program memory start address of section nl 32 bit to addr nl Data memory start address of section n 1 32 bit size nl Number of data memory bytes to initialize for section nl 32 bit Note 1 n num init 1 After the startup code sets up the stack and optionally copies initialized data it calls the main function of the C program There are no arguments passed to main MPLAB C18 transfers control to main via a looped call i e loop Call the user s main routine main goto loop 2004 Microchip Technology Inc DS51288C page 45 MPLAB C18 C Compiler User s Guide 3 3 2 Customization To execute application specific code immediately after a device reset but before any other code generated by the compiler is executed edit the desired startup
80. ection A 3 6 unsigned short s nreloc The number of relocation entries for this section A 3 7 unsigned short s nlnno The number of line number entries for this section O 2004 Microchip Technology Inc DS51288C page 65 MPLAB C18 C Compiler User s Guide A 3 8 unsigned long s flags Section type and content flags The flags which define the section type and the section qualifiers are stored as bitfields in the s_ flags field Masks are defined for the bitfields to ease access Table A 3 shows the different section header flags along with a description and respective values TABLE A 3 SECTION HEADER FLAGS Flag Description Value STYP_TEXT Section contains executable code 0x00020 STYP_DATA Section contains initialized data 0x00040 STYP_BSS Section contains uninitialized data 0x00080 STYP DATA ROM Section contains initialized data for program 0x00100 memory STYP_ ABS Section is absolute 0x01000 STYP_SHARED Section is shared across banks 0x02000 STYP_OVERLAY Section is overlaid with other sections of the 0x04000 same name from different object modules STYP_ACCESS Section is available using access bit 0x08000 STYP_ACTREC Section contains the overlay activation record 0x10000 for a function A 4 struct reloc RELOCATION ENTRY Any instruction that accesses a relocatable identifier variable function etc must have a relocation entry This differs from the S
81. ef under that Act Information contained in this publication regarding device applications and the like is intended through suggestion only and may be superseded by updates It is your responsibility to ensure that your application meets with your specifications No representation or warranty is given and no liability is assumed by Microchip Technology Incorporated with respect to the accuracy or use of such information or infringement of patents or other intellectual property rights arising from such use or otherwise Use of Microchip s products as critical components in life support systems is not authorized except with express written approval by Microchip No licenses are conveyed implicitly or otherwise under any intellectual property rights QUALITY MANAGEMENT SYSTEM CERTIFIED BY DNV ISO TS 16949 2002 Trademarks The Microchip name and logo the Microchip logo Accuron dsPIC KEELOQ microID MPLAB PIC PICmicro PICSTART PRO MATE PowerSmart rfPIC and SmartShunt are registered trademarks of Microchip Technology Incorporated in the U S A and other countries AmpLab FilterLab MXDEV MXLAB PICMASTER SEEVAL SmartSensor and The Embedded Control Solutions Company are registered trademarks of Microchip Technology Incorporated in the U S A Analog for the Digital Age Application Maestro dsPICDEM dsPICDEM net dsPICworks ECAN ECONOMONITOR FanSense FlexROM fuzzyLAB In Circuit Serial Programming ICSP ICEPIC
82. eger constant variable name C identifier section name C identifier 2004 Microchip Technology Inc DS51288C page 31 MPLAB C18 C Compiler User s Guide 2 9 3 2 EXAMPLE USING pragma varlocate bank variable name In one file cl and c2 are explicitly assigned to bank 1 pragma udata bank1 0x100 signed char cl signed char c2 In a second file the compiler is told that both c1 and c2 are located in bank 1 pragma varlocate 1 cl extern signed char cl Hpragma varlocate 1 c2 extern signed char c2 void main void el 5 No MOVLB instruction needs to be generated here c2 5 When c1 and c2 are used in the second file the compiler knows that both variables are in the same bank and does not need to generate a second MOVLB instruction when using c2 immediately after c1 2 9 3 3 EXAMPLE USING pragma varlocate section name variable name In one file c3 and c4 are created in the udata section my_section pragma udata my section signed char c3 signed char c4 pragma udata In a second file the compiler is told that both c3 and c4 are located in the udata section my_section pragma varlocate my section c3 c4 extern signed char c3 extern signed char c4 void main void C3 5 No MOVLB instruction needs to be generated here c4 5 When c3 and c4 are used in the second file the compiler knows that both variables are in the same section and
83. emory and can therefore always be qualified with the near range qualifier Not specifying the near range qualifier will not cause incorrect code but may result in extraneous bank select instructions unknown pragma s The compiler has encountered a pragma directive which is not recognized As per ANSI ISO requirements the pragma is ignored Common causes include misspelled pragma names default overlay locals is unsupported in Extended mode sco ignored The overlay storage class is not supported in Extended mode default static locals is unsupported in Extended mode scs ignored The default storage class of static is not supported in Extended mode default auto locals is redundant in Extended mode sca ignored The default storage class for locals is always auto in Extended mode default static locals is unsupported in Extended mode Ol ignored The default storage class of static is not supported in Extended mode default access RAM is unsupported in Extended mode Oa ignored The default storage range of near is not supported in Extended mode unexpected return value A return of a value statement has been detected in a function declared to return no value The return value will be ignored return value expected A return with no value has been detected in a function declared to return a value The return value will be undefined suspicious pointer conversion A pointer has been used as an integer or an integer
84. en calling C functions from assembly e C functions are inherently global unless defined as static The C function name must be declared as an extern symbol in the assembly file A CALL or an RCALL must be used to make the function call 1 static parameters are valid only when the compiler is operating in Non extended mode see Section 1 2 5 Selecting the Mode DS51288C page 40 2004 Microchip Technology Inc Run time Model 3 2 3 1 1 auto Parameters auto parameters are pushed onto the software stack from right to left For multi byte data the low byte is pushed onto the software stack first EXAMPLE 3 1 Given the following prototype for a C function char add auto char x auto char y to call the function add with values x 0x61 and y 0x65 the value for y must be pushed onto the software stack followed by the value of x The return value since it is 8 bits will be returned in WREG see Table 3 2 i e EXTERN add defined in C module MOVLW 0x65 MOVWF POSTINCI y MOVLW 0x61 MOVWF POSTINC1 x CALL add MOVWF result result is returned in WREG 0x65 pushed onto stack 0x61 pushed onto stack EXAMPLE 3 2 Given the following prototype for a C function int sub auto int x auto int y to call the function sub with values x 0x7861 and y 0x1265 the value for y must be pushed onto the software stack followed by the value of x The return value since it is 16 bits will be returne
85. er type the other must be of integer type Common causes include a missing or operator type mismatch in operator The types of the operands of the operator must be such that one operand is of pointer type and the other is of integer type or both operands are of arithmetic type pointer difference requires pointers to compatible types When calculating the difference between two pointers the pointers must point to objects of compatible type Common causes include missing parentheses and a missing operator integer type required for pointer subtraction When the left hand operand of the subtraction operator is of pointer type the right hand operand must be of integer type Common causes include a missing or operator arithmetic type expected for subtraction operator When the left hand operand is not of pointer type the subtraction operator requires that both operands by of arithmetic type type mismatch in argument d The type of an argument to a function call must be compatible with the declared type of the corresponding parameter scalar type expected for increment operator The increment operators require that the operand be a modifiable lvalue of scalar type scalar type expected for decrement operator The decrement operators require that the operand be a modifiable Ivalue of scalar type arithmetic type expected for unary plus The unary plus operator requires that its
86. es MOVLB instruction in instances where it can be determined that the Bank Select register already contains the correct value For example given the following C source code fragment unsigned char a b a D b 5 If compiled with banking optimization disabled On MPLAB C18 will load the Bank register prior to each assignment 0x000000 MOVLB a 0x000002 MOVLW 0x5 0x000004 MOVWF a 0x1 0x000006 MOVLB b 0x000008 MOVWF b 0x1 When this same code is compiled with banking optimization enabled On MPLAB C18 may be able to eliminate the second MOVLB instruction by determining that the value of the Bank register will not change 0x000000 MOVLB a 0x000002 MOVLW 0x5 0x000004 MOVWF a 0x1 0x000006 MOVWF b 0x1 The banking optimization should not affect the ability to debug source code DS51288C page 50 2004 Microchip Technology Inc Optimizations 4 4 WREG CONTENT TRACKING Ow Ow WREG content tracking removes MOVLW instructions in instances where it can be determined that the Working register already contains the correct value For example given the following C source code fragment unsigned char a b a 5 b 5 If compiled with WREG content tracking disabled Ow MPLAB C18 will load a value of 5 into the Working register prior to each assignment 0x000000 MOVLW 0x5 0x000002 MOVWF a 0x1 0x000004 MOVLW 0x5 0x000006 MOVWF b 0x1 When this same code is compiled with WREG tracking enabled Ow
87. ficient to locate data in the code space as well To this purpose MPLAB C18 introduces the rom and ram qualifiers The rom qualifier denotes that the object is located in program memory whereas the ram qualifier denotes that the object is located in data memory Pointers can point to either data memory ram pointers or program memory rom pointers Pointers are assumed to be ram pointers unless declared as rom The size of a pointer is dependent on the type of the pointer and is documented in Table 2 5 Note When writing to a rom variable the compiler uses a TBLWT instruction however there may be additional application code that needs to be written based on the type of memory being utilized See the data sheet for more information TABLE 2 5 POINTER SIZES Pointer Type Example Size Data memory pointer char dmp 16 bits Near program memory pointer rom near char npmp 16 bits Far program memory pointer rom far char fpmp 24 bits 2 5 INCLUDE FILE SEARCH PATHS 2 5 1 System Header Files Source files included with include lt filename gt are searched for in the path specified in the MCC_ INCLUDE environment variable and the directories specified via the I command line option Both the MCC_ INCLUDE environment variable and the I values are a semi colon delimited list of directories to search If the included file exists in both a directory listed in the MCC_ INCLUDE environment variable and a d
88. fined A symbol has been referenced before it has been defined Common causes include a misspelled symbol name a missing header file that declares the symbol and a reference to a symbol valid only in an inner scope 1106 s is not a function A symbol must be a function name in order to be declared as an interrupt function 1107 interrupt functions must not take parameters When the processor vectors to an interrupt routine no parameters are passed so a function declared as an interrupt function should not expect parameters 1108 interrupt functions must not return a value Since interrupts are invoked asynchronously by the processor there will not be a calling routine to which a value can be returned DS51288C page 84 2004 Microchip Technology Inc MPLAB C18 Diagnostics 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 type mismatch in redeclaration of s The type of the symbol declared is not compatible with the type of a previous declaration of the same symbol Common causes include missing qualifiers or misplaced qualifiers auto symbol s not in function scope Variables may only be allocated off the stack within the scope of a function undefined label s in s The label has been referenced via a goto statement but has not been defined in the function Common causes include a mi
89. ge qualifiers are far and ram TABLE 2 4 LOCATION OF OBJECT BASED ON STORAGE QUALIFIERS rom ram far Anywhere in program memory Anywhere in data memory default near In program memory with address less In access memory than 64K 2 4 1 near far Data Memory Objects The far qualifier is used to denote that a variable that is located in data memory lives in a memory bank and that a bank switching instruction is required prior to accessing this variable The near qualifier is used to denote that a variable located in data memory lives in access RAM 2 4 2 near far Program Memory Objects The far qualifier is used to denote that a variable that is located in program memory can be found anywhere in program memory or if a pointer that it can access up to and beyond 64K of program memory space The near qualifier is used to denote that a variable located in program memory is found at an address less than 64K or ifa pointer that it can access only up to 64K of program memory space Ee DS51288C page 14 2004 Microchip Technology Inc Language Specifics 2 4 3 ram rom Qualifiers Because the PlCmicro microcontrollers use separate program memory and data memory address busses in their design MPLAB C18 requires extensions to distinguish between data located in program memory and data located in data memory The ANSI ISO C standard allows for code and data to be in separate address spaces but this is not suf
90. has been used as a pointer without an explicit cast expression is always false The control expression of a conditional statement evaluates to a constant false value expression is always true The control expression of a conditional statement evaluates to a constant true value possibly incorrect test of assignment An implicit test of an assignment expression e g if x y is often seen when an operator has been used when a operator was intended call of function without prototype A function call has been made without an in scope function prototype for the function being called This can be unsafe as no type checking for the function arguments can be performed 2004 Microchip Technology Inc DS51288C page 93 MPLAB C18 C Compiler User s Guide 2059 unary minus of unsigned value The unary minus operator is normally only applied to signed values 2060 shift expression has no effect Shifting by zero will not change the value being shifted 2061 shift expression always zero The number of bits that the value is being shifted by is greater than the number of bits in the value being shifted The result will always be zero 2062 _ gt operator expected not A struct union member access via a pointer to struct union has been performed using the operator 2063 operator expected not gt A direct struct union member access has been performed using the
91. have errata related to your specified product family or development tool of interest Go to the Microchip web site at http www microchip com and click on Customer Change Notification Follow the instructions to register The Development Systems product group categories are e Compilers e Emulators e In Circuit Debuggers e MPLAB IDE e Programmers 2004 Microchip Technology Inc DS51288C page 5 MPLAB C18 C Compiler User s Guide Here is a description of these categories Compilers The latest information on Microchip C compilers and other language tools These include the MPLAB C17 MPLAB C18 and MPLAB C30 C compilers MPASM and MPLAB ASM30 assemblers MPLINK and MPLAB LINK30 object linkers MPLIB and MPLAB LIB30 object librarians Emulators The latest information on Microchip in circuit emulators This includes the MPLAB ICE 2000 and MPLAB ICE 4000 In Circuit Debuggers The latest information on the Microchip in circuit debugger MPLAB ICD 2 MPLAB IDE The latest information on Microchip MPLAB IDE the Windows Integrated Development Environment for development systems tools This list is focused on the MPLAB IDE and MPLAB SIM simulators MPLAB IDE Project Manager and general editing and debugging features Programmers The latest information on Microchip device programmers These include the MPLAB PM3 and PRO MATE II device programmers and PICSTART Plus development programmer CUS
92. he Extended mode the compiler only supports default auto locals Default Data in Access Memory 0a 0a Since the amount of access RAM on an Extended mode device is limited the compiler does not support data being placed in access RAM by default when operating in the Extended mode E 3 COFF FILE DIFFERENCES E 3 1 Generic Processor The processor type proc_ type specified in the COFF file s optional file header when compiling for the generic processor p18cxx will be set to PIC18F4620 when the compiler is operating in the Extended mode and will be set to PIC18C452 when the compiler is operating in the Non extended mode E 3 2 File Header s flags Field When operating in Extended mode the COFF file that is generated will have the F_EXTENDED18 bit of the file header s _flags set This bit is not set when the compiler is operating in the Non extended mode SSS aaa ES ee eee eas 2004 Microchip Technology Inc DS51288C page 99 MPLAB C18 C Compiler User s Guide NOTES DS51288C page 100 2004 Microchip Technology Inc MPLAB C18 C COMPILER MICROCHIP USER S GUIDE Glossary A Absolute Section A section with a fixed address that cannot be changed by the linker Access Memory Special general purpose registers on the PIC18 PlCmicro microcontrollers that allow access regardless of the setting of the Bank Select Register BSR Address The code that identifies where a piece of information is st
93. he first 64k of program memory in the small model In the large memory model 24 bits are used Applications using more than 64k of program memory must use the large memory model The memory model setting can be overridden on a case by case basis by using the near or far qualifier when declaring a pointer into program space Pointers to near memory use 16 bits as in the small memory model and pointers to far memory use 24 bits as in the large memory model The following example creates a pointer to program memory that can address up to and beyond 64k of program memory space even when the small memory model is being used far rom pgm_ptr The following example creates a function pointer that can address up to and beyond 64k of program memory space even when the small memory model is being used far rom void fp void If the same memory model is not used for all files in a project all global pointers to program memory should be declared with explicit near or far qualifiers so that they are accessed correctly in all modules The pre compiled libraries distributed with MPLAB C18 can be used with either the small or large memory models Following the use of a far data pointer in a small memory model program the TBLPTRU byte must be cleared by the user MPLAB C18 does not clear this byte 2 Following the use of a far function pointer in a small memory model program the PCLATU byte must be cleared by the user MPLAB C18 doe
94. ich objects or pointers are declared is not an anonymous structure For example union foo struct int a int b ptr char c bar char c bar a cC error bar ptr gt a c ok The assignment to bar a is illegal since the member name is not associated with any particular object 2004 Microchip Technology Inc DS51288C page 19 MPLAB C18 C Compiler User s Guide 2 8 2 Inline Assembly MPLAB C18 provides an internal assembler using a syntax similar to the MPASM assembler The block of assembly code must begin with _asm and end with endasm The syntax within the block is label lt instruction gt larg1 arg2 arg3 The internal assembler differs from the MPASM assembler as follows e No directive support Comments must be C or C notation Full text mnemonics must be used for table reads writes i e TBLRD TBLRDPOSTDEC TBLRDPOSTINC TBLRDPREINC TBLWT TBLWTPOSTDEC TBLWTPOSTINC TBLWTPREINC No defaults for instruction operands all operands must be fully specified Default radix is decimal Literals are specified using C radix notation not MPASM assembler notation For example a hex number should be specified as 0x1234 not H 1234 Label must include colon Indexed addressing syntax i e is not supported must specify literal and access bit e g specify as CLRF 2 0 notCLRF 2 For example
95. iler does not support explicit initialization of block scope objects with extern storage class 1511 ran out of internal memory for temps The compiler cannot support the allocation of any more temporary variables 1512 redefinition of label s The same label may not have multiple definitions in the same function 1513 redefinition of member s A structure or union may only have a single member with a given name 1514 cast of a pointer to floating point is undefined The requested cast is illegal This error may be caused by omitting an array subscript on assignment 1515 redefinition of case value ld A switch statement may only have a single case statement for a given value 1516 array size must be greater than zero The constant value given for the array size must be greater than zero 1900 s processor core not supported The compiler does not currently support the specified processor core Commonly caused by a misspecification of processor name or an invocation of the incorrect compiler executable EEE DS51288C page 92 2004 Microchip Technology Inc MPLAB C18 Diagnostics D 2 WARNINGS 2001 2002 2025 2026 2027 2028 2029 2052 2053 2054 2055 2056 2057 2058 non near symbol s declared in access section s Statically allocated variables declared into an access qualified section will always be placed by the linker into access data m
96. ip Technology Inc DS51288C page 7 MPLAB C18 C Compiler User s Guide 1 2 1 Creating Output Files By default the compiler will generate an output object file named file o where file is the name of the source file specified on the command line minus the extension The output object file name can be overridden with the o command line option For example mcc18 fo bar o foo c If the source file contains errors then the compiler generates an error file named file err Where file is the name of the source file specified on the command line minus the extension The error file name can be overridden using the fe command line option For example mcc18 fe bar err foo c 1 2 2 Displaying Diagnostics Diagnostics can be controlled using the w and nw command line options The w command line option sets the level of warning diagnostics 1 2 or 3 Table 1 1 shows the level of warning diagnostics and the type of diagnostics that are shown The nw command line option suppresses specific messages Appendix D or the help message list command line option lists all messages generated by the compiler Help on all messages can be seen using the help message all command line option For help on a specific diagnostic the help message command line option can be used For example mcc18 help message 2068 displays the following results 2068 obsolete use of implicit int detected The ANSI standard allows a variable to be
97. irectory listed in a I command line option the file will be included from the directory listed in the I command line option This allows the MCC_INCLUDE environment variable to be overridden with a I command line option 2 5 2 User Header Files Source files included with include filename are searched for in the directory containing the including file If not found the file is searched for as a system header file see Section 2 5 1 System Header Files 2004 Microchip Technology Inc DS51288C page 15 MPLAB C18 C Compiler User s Guide 2 6 PREDEFINED MACRO NAMES In addition to the standard predefined macro names MPLAB C18 provides the following predefined macros ___18CXxX The constant 1 intended to indicate the MPLAB C18 compiler ___PROCESSOR The constant 1 if compiled for the particular processor For example __18C452 would be defined as the constant 1 if compiled with the p18c452 command line option and __ 18F258 would be defined as the constant 1 if compiled with the p18 258 command line option __ SMALL The constant 1 if compiled with the ms command line option _ LARGE _ The constant 1 if compiled with the m1 command line option _ TRADITIONAL18__ The constant 1 if the Non extended mode is being used see Section 1 2 5 Selecting the Mode __ EXTENDED18__ The constant 1 if the Extended mode is being used see Section 1 2 5 Selecting the Mode 2 7 ISO DIVERGENCES 2 7 1 Integer
98. ived types along with a description and respective values TABLE A 6 DERIVED TYPES Derived Type Description Value DT_NON no derived type 0 DT_PTR pointer 1 DT_FCN function 2 DT_ARY array 3 2004 Microchip Technology Inc DS51288C page 69 MPLAB C18 C Compiler User s Guide A 5 5 charn sclass Storage class of the symbol Table A 7 lists the storage classes along with a description and respective values TABLE A 7 STORAGE CLASSES Storage Class Description Value C_EFCN Physical end of function OxFF C_ NULL Null 0 C_AUTO Automatic variable 1 C_ EXT External symbol 2 C_STAT Static 3 C_REG Register variable 4 C_EXTDEF External definition 5 C_ LABEL Label 6 C_ULABEL Undefined label 7 C_MOS Member of structure 8 C_ARG Function argument 9 C_STRTAG Structure tag 10 C_MOU Member of union 11 C_UNTAG Union tag 12 C_TPDEF Type definition 13 C_USTATIC Undefined static 14 C_ENTAG Enumeration tag 14 C_MOE Member of enumeration 16 C_REGPARM Register parameter 17 C_FIELD Bit field 18 C_AUTOARG Automatic argument 19 C_LASTENT Dummy entry end of block 20 C_BLOCK bb or eb 100 C_FCN bf or ef 101 C_EOS End of structure 102 C FILE File name 103 C LINE Line number reformatted as symbol table entry 104 C_ALIAS Duplicate tag 105 C_HIDDEN Externa
99. l debugging with the MPLAB ICE in circuit emulator the MPLAB ICD 2 in circuit debugger or the MPLAB SIM simulator The MPLAB C18 compiler has the following features e ANSI 89 compatibility Integration with the MPLAB IDE for easy to use project management and source level debugging Generation of relocatable object modules for enhanced code reuse Compatibility with object modules generated by the MPASM assembler allowing complete freedom in mixing assembly and C programming in a single project Transparent read write access to external memory Strong support for inline assembly when total control is absolutely necessary Efficient code generator engine with multi level optimization Extensive library support including PWM SPI CT UART USART string manipulation and math libraries Full user level control over data and code memory allocation 1 2 INVOKING THE COMPILER The MPLAB C18 Getting Started Guide DS51295 describes how to use the compiler with the MPLAB IDE The compiler can also be invoked from the command line The command line usage is mcc18 options file options A single source file and any number of command line options can be specified The help command line option lists all command line options accepted by the compiler The verbose command line option causes the compiler to show a banner containing the version number and the total number of errors warnings and messages upon completion 2004 Microch
100. l preserve a basic context by default see Section 3 4 Compiler Managed Resources and the save clause allows additional arbitrary symbols to be saved and restored by the function To save a user defined global variable named myint the following pragma directive would be used pragma interrupt high interrupt service routine save myint In addition to variables entire data sections can also be named in the save clause For example to save a user defined section named mydata the following pragma directive would be used pragma interrupt high interrupt service routine save section mydata If an interrupt service routine calls another function the normal functions temporary data section which is named tmpdata should be saved using a save section tmpdata qualifier on the interrupt pragma directive For example pragma interrupt high interrupt service routine save section tmpdata If the ISR changes any file registers other than the basic context then they should be named in the save clause The generated code should be examined to determine which file registers are used and need to be saved If an ISR calls a function that returns a value less than or equal to 32 bits in size the locations associated with the return value see Section 3 2 1 Return Values should be specified in the save list of the interrupt pragma If an interrupt service routine calls a function that returns 16 bit data the PROD file
101. l symbol in dmert public library 106 C_EOF End of file 107 C_LIST Absolute listing on or off 108 C_SECTION Section 109 A 5 6 charn numaux The number of auxiliary entries for this symbol DS51288C page 70 O 2004 Microchip Technology Inc COFF File Format A 6 struct coff lineno LINE NUMBER ENTRY Any executable source line of code gets acoff_lineno entry in the line number table associated with its section For a Microchip PICmicro MCU COFF file this means that every instruction may have a coff_lineno entry since the debug information is often for debugging through the absolute listing file Readers of this information should note that the COFF file is not required to have an entry for every instruction though it typi cally does This information is significantly different from the System V format struct coff lineno unsigned long 1_srcndx unsigned short 1 _lnno unsigned long 1 paddr unsigned short 1 flags unsigned long 1 fcnndx coff lineno t A 6 1 unsigned long 1 srcndx Symbol table index of associated source file A 6 2 unsigned short 1 lnno Line number A 6 3 unsigned long 1 paddr Address of code for this line number entry A 6 4 unsigned short 1 flags Bit flags for the line number entry Table A 8 lists the bit flags along with a description and respective values TABLE A 8 LINE NUMBER ENTRY FLAGS Flag Description Value LINENO_HASFCN Set if 1_ cndx is valid 0x01
102. line option The MPLAB C18 compiler also allows optimizations to be enabled or disabled on a case by case basis Table 4 1 outlines each of the optimizations that can be performed by the MPLAB C18 compiler including the command line option to enable or disable it whether or not it affects debugging and the section where it is discussed Note Optimizations will not occur on any function containing inline assembly code TABLE 4 1 MPLAB C18 OPTIMIZATIONS Optimization To Enable To Disable Affects Section Debugging Duplicate String Merging Om Om 4 1 Branches Ob Ob 4 2 Banking On On 4 3 WREG Content Tracking Ow Ow 4 4 Code Straightening Os Os 45 Tail Merging Ot Ot Y 4 6 Unreachable Code Removal Ou Ou Y 4 7 Copy Propagation Op Op Y 4 8 Redundant Store Removal Or Or Y 4 9 Dead Code Removal Od Od Y 4 10 Procedural Abstraction Opa Opa Y 4 11 4 1 DUPLICATE STRING MERGING Om Om Duplicate string merging when enabled will take two or more identical literal strings and combine them into a single string table entry with a single instance of the raw data stored in program memory For example given the following when duplicate string merging is enabled Om only a single instance of the data for the string foo would be stored in the output object file and both a and b would reference this data const rom char a foo const rom cha
103. lized when compiling for the generic processor when the compiler is operating in Non extended mode 2 This is the processor utilized when compiling for the generic processor when the compiler is operating in Extended mode A 2 4 unsigned long rom width bits Width of program memory in bits A 2 5 unsigned long ram width bits Width of data memory in bits struct scnhdr SECTION HEADER The scnhdr structure contains information related to an individual section The Microchip PICmicro MCU COFF files make a slight departure from the normal COFF definition of the section name Since the Microchip PICmicro MCU COFF section names may be longer than eight characters the Microchip PICmicro9 MCU COFF files allow a string table entry for long names typedef struct scnhdr union char _s name 8 section name is a string struct unsigned long _s_ zeroes unsigned long _s offset _s_s _s unsigned long s_paddr unsigned long s_vaddr unsigned long s size unsigned long s_scnptr unsigned long s relptr unsigned long s_lnnoptr unsigned short s nreloc unsigned short s nlnno unsigned long s flags scnhdr t DS51288C page 64 2004 Microchip Technology Inc COFF File Format A 3 1 union s A string or a reference into the string table Strings of fewer than eight characters are stored directly and all others are stored in the string table If the first four characters of the string are 0 then the last four
104. make the source code compatible regardless of the mode in which the compiler is operating The __ EXTENDED18__ predefined macro will be the constant 1 when compiling for Extended mode whereas the__ TRADITIONAL18 _ predefined macro will be the constant 1 when compiling for Non extended mode Here are some examples of specific instances where this may be useful 1 Using the predefined macros to use static parameters in Non extended mode and auto parameters in Extended mode ifdef EXTENDED18 _ define SCLASS auto else define SCLASS static Hendif void foo SCLASS int bar 2 Using the predefined macros to utilize the overlay keyword in Non extended mode and the auto keyword in Extended mode ifdef EXTENDED18__ define SCLASS auto else define SCLASS overlay Hendif void foo void SCLASS int bar 3 Using the predefined macros to use only Non extended mode instructions in inline assembly in Non extended mode and to use Extended mode instructions in inline assembly in Extended mode _asm Hifdef EXTENDED18 _ PUSHL 5 Helse MOVLW 5 MOVWF POSTINC1 0 endif MOVF POSTDEC1 1 0 _endasm HA A AAA III A A DS51288C page 98 O 2004 Microchip Technology Inc Extended Mode E 2 COMMAND LINE OPTION DIFFERENCES The following command line options are not supported when the compiler is operating in the Extended mode Default Local Storage Class scs sco sca When operating in t
105. n Differences Rs 99 ES COFRE File Diff rences een a ik e Renee 99 E321 Generic ProceSsOn a dd y lo td ao de e 99 3 2 FileH ad rs flags Fieldin nets 99 GLOSSARY ii tie E 101 e O RE da eee 107 Worldwide Sales and Service cccsccceceeesseseeeeeeeeeaeseeneeseeeeseeeesseaesseeeeseneaneeeeeseaes 114 DS51288C page vi 2004 Microchip Technology Inc MPLAB C18 C COMPILER MICROCHIP USER S GUIDE Preface INTRODUCTION This document discusses the technical details of the MPLAB C18 compiler This document will explain all functionality of the MPLAB C18 compiler It assumes that the programmer already knows how to write C programs knows how to use the MPLAB Integrated Development Environment IDE to create and debug projects has read and understands the processor data sheet for which code is being written ABOUT THIS GUIDE Document Layout The document layout is as follows Chapter 1 Introduction Provides an overview of the MPLAB C18 compiler and information on invoking the compiler Chapter 2 Language Specifics Discusses how the MPLAB C18 compiler differs from the ANSI standard Chapter 3 Run time Model Discusses how the MPLAB C18 compiler utilizes the resources of the PIC18 PICmicro microcontrollers Chapter 4 Optimizations Discusses the optimizations that are performed by the MPLAB C18 compiler Chapter 5 Sample Application Provides a sampl
106. n enum 75 AMG unsigned long x tagnak cis e eds eme de 75 A 16 2 unsigned short x siZes sci dei eine iene 75 A 17 struct aux field Auxiliary Entry for a Bitfield 76 ANA uneigned Shore x SL lA less 76 Appendix B ANSI Implementation defined Behavior Bet Introductions 3 isc E E en ant fete nr arts dre rte entrants 77 B 2 Identifier iii e li bene js 77 aee Characters ALERT ero do dt lan A a 77 BA Integers israel manne a E Aa ai 78 B i5 Floating pOINT 5 8508 dates ae abl naiss intense 78 B 6 Arrays and Pointers ooccccccccccccccccicccinncnnncnnnnnnnnnnnn nn nn nn n rre rre nn nn nn nn nn nnnnnnnns 79 Ba AROUISI ti A A t 79 B 8 Structures and UNIONS LL 79 B 9 BES it e Lin es 79 B 10 En meratiOns 5 2245 rares cid it Ada bd 80 B11 SS Witch Statement 2 222 Selec he dia a ada 80 B 12 Preprocessing Directives 80 Appendix C Command line Summary Appendix D MPLAB C18 Diagnostics A SSSR EE onde une Len ne Anne 7 83 D 2 Waris 225 628 nn AAA E tr BL 93 D 3 MESSAGES ieccesdeiess dondegeederae dese irlanda obte 95 Appendix E Extended Mode E 1 Source Code Compatibility se 97 A 97 1 2 static Parametros 97 E 1 3 overlay Keyword mimica di 97 E 1 4 Inline Assembly het nantes di ins cei eee 98 E 1 5 Predefined Macros 98 E 2 Command line Optio
107. n file s The compiler was unable to open the named file Common causes include misspelled filename and insufficient access rights 1501 unable to locate file s The compiler was unable to locate the named file Common causes include misspelled filename and misconfigured include path 2004 Microchip Technology Inc DS51288C page 91 MPLAB C18 C Compiler User s Guide 1502 unknown option s The specified command line option is not a valid MPLAB C1X option 1503 multi bank stack supported only on 18CXX core The software stack can cross bank boundaries only on the 18CXX processors 1504 redefinition of s The same function name may not have multiple definitions 1505 redeclaration of s The same variable name may not have multiple defining declarations 1506 function s cannot have overlay storage class specifier The overlay storage class specifier may not be used with functions 1507 variable s of overlay storage class cannot have near qualifier The compiler does not currently support variables of overlay storage class in access ram 1508 inconsistent linkage for s The identifier has been given both internal and external linkage 1509 s cannot have extern storage class The extern storage class specifier may not be used with parameters 1510 s cannot have extern storage class block scope and an initializer The comp
108. nters AM a AST 15 17 OM des Mee dee ses ea dae 15 17 37 To Data memory See ram Pointers To Program Memory See rom Pointers PORTA diarias ed 33 35 Pragmas pragma interrupt ecmcnnnnnncncnonnnnnnnnnnnnnnns 27 31 pragma interruptlow oo 27 31 pragma sectiontype emmmcccccoooonnnnnnnnnnnos 21 24 pragma varlocate cccmmmnnnncnconononnnnnnnnnnnos 31 32 Predefined Macros TOCA sons tlt wie ee ee 16 A EXTENDEDIB scsi 16 98 ULARGE O unidad 16 PROCESSOR critica cto inensanteceees 16 SMA ie teats high aes it 16 TRADITIONAL18B_ niepo dee rii a 16 98 Processor Generic iii 9 59 64 99 Select ici iia 9 10 TYPO ii a 9 10 PROD does 47 PROD ii aha ar ea 39 PRODI iaa ed see De Soothes ee 39 Program Memory Pointer See rom Pointers R RAM ACCESS iia cele tee 14 24 33 Pa dd da Cr dead rss 14 15 PolMterS vc tosidiat da her de eck 15 17 register ii a aci 13 Register Definitions File 33 35 Reset Vector ivi is diia 45 Rese O O acs ete es eee 34 RETFIE See Return From Interrupt eee 27 Return from Interrupt ccccceeeeeeeeeeeeeeeeeees 27 28 Return Value LOCATION 215 SE nr A NE Te ae ne 39 R CE EE evens Lien ees M Enr ee ees 34 RACE MTS Male AL AR a Tes 34 OM ces ee a rd o 14 15 17 18 22 26 Pointers ss 15 17 37 OMAN Len is 17 21 23 26 RYCE Cr ante hie ee S 34 RENGE Cee ss tri 34 Run time Model 37 47 DS51
109. ntifier Common causes include missing scope parentheses too few arguments in function call To call a function the number of arguments passed must match exactly the number of parameters declared for the function too many arguments in function call To call a function the number of arguments passed must match exactly the number of parameters declared for the function unknown member s in s The structure or union tag does not have a member of the name requested Common causes include a misspelled member name and a missing member access operator for a nested structure unknown member s The structure or union type does not have a member of the name requested Common causes include a misspelled member name and a missing member access operator for a nested structure tag s is incomplete An incomplete struct or union tag cannot be referenced by the member access operators Common causes include a misspelled structure tag name in the symbol definition 2004 Microchip Technology Inc DS51288C page 89 MPLAB C18 C Compiler User s Guide 1208 pragma interrupt detected inside function body The interrupt pragma is only available at file level scope 1209 unknown function s in pragma interrupt The interrupt pragma requires that the function being declared as an interrupt have an active prototype when the pragma is encountered 1210 unknown symbol s in inter
110. o overlay local storage specified as overlay from functions that are guaranteed not to be active simultaneously For example in int void overlay int x 1 return x int g void overlay int y 2 return y If and g will never be active at the same time x and y become candidates for sharing the same memory location However in int void overlay int x 1 return x int g void overlay int y y f return y l N since f and g may be simultaneously active x and y will not be overlaid The advantage of using overlay locals is that they are statically allocated which means that in general fewer instructions are required to access them resulting in a smaller program memory image At the same time the total data memory allocation required for these variables may be less than what would be required had they been declared as static due to the fact that some of the variables may be overlaid 2004 Microchip Technology Inc DS51288C page 13 MPLAB C18 C Compiler User s Guide If the MPLINK linker detects a recursive function that contains a local variable of storage class overlay it emits an error and aborts If the MPLINK linker detects a call through a function pointer in any module and a local variable of storage class overlay in any and not necessarily the same module it emits an error and aborts The default storage class for local variables is auto This can
111. o start of block function A 15 struct aux bobf AUXILIARY SYMBOL TABLE ENTRY FOR THE BEGINNING OF A BLOCK OR FUNCTION typedef struct aux bobf char _unusedl 4 unsigned short x lnno char _unused2 6 unsigned long x_endndx char _unused3 2 aux_bobf t A 15 1 unsigned short x lnno C source line number of the beginning relative to start enclosing scope A 15 2 unsigned long x_endndx Symbol index of next entry past this block function A 16 struct aux var AUXILIARY SYMBOL TABLE ENTRY FOR A VARIABLE OF TYPE struct union enum typedef struct aux var unsigned long x_tagndx char _unused 2 unsigned short x_size char _unused2 10 aux var t A 16 1 unsigned long x tagndx Symbol index of a structure union or enumerated tag A 16 2 unsigned short x size Size of the structure union or enumeration AAA ah EEE O 2004 Microchip Technology Inc DS51288C page 75 MPLAB C18 C Compiler User s Guide A 17 struct aux field AUXILIARY ENTRY FOR A BITFIELD typedef struct aux field char _unused 6 unsigned short x size char _unused2 10 aux field t A 17 1 unsigned short x size The size of the bitfield in bits DS51288C page 76 2004 Microchip Technology Inc MPLAB C18 C COMPILER MICROCHIP USER S GUIDE Appendix B ANSI Implementation defined Behavior B 1 INTRODUCTION This section discusses MPLAB C18 implementation defined behavior The ISO standard for C req
112. ocontroller The command line used to build this application is mcc18 p 18c452 I c mcci8 h leds c where c mcc18 is the directory in which the compiler is installed This sample application was designed for use witha PICDEM 2 demo board This sample covers the following items 1 Interrupt handling pragma interruptlow interrupt vectors interrupt service routines and context saving System header files Processor specific header files pragma sectiontype Inline assembly Te oN 2004 Microchip Technology Inc DS51288C page 57 MPLAB C18 C Compiler User s Guide 1 include lt p18cxxx h gt 2 include lt timers h gt JA LS KT 4 define NUMBER OF LEDS 8 q LES 6 void timer isr void IE E 8 static unsigned char s count 0 JE STE 10 Hpragma code low_vector 0x18 11 void low interrupt void A 7 4 13 _asm GOTO timer isr _endasm 14 ESAS A 16 pragma code FEET A 18 pragma interruptlow timer_isr save PROD 19 void 20 timer_isr void 21 7 4 22 static unsigned char led display 0 RODS 7 24 INTCONbits TMROIF 0 25 26 s count s count NUMBER OF LEDS 1 27 28 led display 1 lt lt s_count 1 LALO ES 30 PORTB led display fx 34 1 7 32 33 void 34 main void 35 36 TRISB 0 37 PO
113. operand be of arithmetic type arithmetic type expected for unary minus The unary minus operator requires that its operand be of arithmetic type 2004 Microchip Technology Inc DS51288C page 87 MPLAB C18 C Compiler User s Guide 1151 struct or union object designator expected The member access operators and gt require operands of struct union and pointer to struct union respectively 1152 scalar or void type expected for cast An explicit cast requires that the type of the operand be of scalar type and the type being cast to be scalar type or void type 1153 cannot assign array type objects An object of array type may not be directly assigned Assignment is allowed only to array elements 1154 parameter d in s must have a name Parameters in a function definition must have an identifier declarator to name them The naming declarator is not required in prototypes but is ina definition 1160 conflicting storage classes specified A declaration may only specify a single storage class 1161 conflicting base types specified A declaration may only specify a single base type void int float et al Multiple instances of the same base type is also an error e g int int x 1162 both signed and unsigned specified A type may include only one of signed and unsigned 1163 function must be located in program memory All functions must be located in program mem
114. or the P operand of a PIC17 MOVFP 5 or MOVPF instruction RELOCT_BANKSEL Generate the appropriate instruction to bank switch for 6 a symbol RELOCT_PAGESEL Generate the appropriate instruction to page switch for 7 a symbol RELOCT_ALL 16 bits of an address 8 RELOCT_IBANKSEL Generate indirect bank selecting instructions 9 RELOCT_F 8 bits of address for the F operand of a PIC17 10 MOVFP or MOVPF instruction RELOCT_TRIS File register address for TRIS instruction 11 RELOCT_MOVLR MOVLR bank PIC17 banking instruction 12 RELOCT MOVLB MOVLB PIC17 and PIC18 banking instruction 13 RELOCT_GOTO2 Second word of an PIC18 GOTO instruction 14 RELOCT_CALL2 Second word of an PIC18 CALL instruction 14 RELOCT_FF1 Source register of the PIC18 MOVFF instruction 15 RELOCT_FF2 Destination register of the PIC18 MOVFF instruction 16 RELOCT_SF2 Destination register of the PIC18 MOVSF instruction 16 RELOCT_LFSR1 First word of the PIC18 LFSR instruction 17 RELOCT_LFSR2 Second word of the PIC18 LFSR instruction 18 RELOCT_BRA PIC18 BRA instruction 19 RELOCT_RCALL PIC18 RCALL instruction 19 RELOCT_CONDBRA PIC18 relative conditional branch instructions 20 RELOCT_UPPER Highest order 8 bits of a 24 bit address 21 RELOCT_ACCESS PIC18 access bit 22 RELOCT_PAGESEL WREG Selecting the correct page using WREG as scratch 23 RELOCT_PAGESEL BITS Selecting the correct page using bit set clear 24 instructions RELOCT_SCNSZ_LOW Size of a section 25 RELOCT_SCNSZ_HIGH 26 RELOCT_SCNSZ_UPPER 27 RELO
115. ored in memory Anonymous Structure An unnamed object ANSI American National Standards Institute Assembler A language tool that translates assembly source code into machine code Assembly A symbolic language that describes the binary machine code in a readable form Assigned Section A section that has been assigned to a target memory block in the linker command file Asynchronously Multiple events that do not occur at the same time This is generally used to refer to interrupts that may occur at any time during processor execution B Binary The base two numbering system that uses the digits 0 1 The right most digit counts ones the next counts multiples of 2 then 2 4 etc C Central Processing Unit The part of a device that is responsible for fetching the correct instruction for execution decoding that instruction and then executing that instruction When necessary it works in conjunction with the Arithmetic Logic Unit ALU to complete the execution of the instruction It controls the program memory address bus the data memory address bus and accesses to the stack Compiler A program that translates a source file written in a high level language into machine code 2004 Microchip Technology Inc DS51288C page 101 MPLAB C18 C Compiler User s Guide Conditional Compilation The act of compiling a program fragment only if a certain constant expression specified by a preprocessor directive is true
116. ormation test of floating point for equality detected Testing two floating point values for equality will not always yield the desired results as two expressions which are mathematically equivalent may evaluate to slightly different values when computed due to rounding error optimization skipped for s due to inline assembly Functions which contain inline assembly are not run through the optimizer since inline assembly may contain constructs which would result in the optimizer performing incorrectly comparison of a signed integer to an unsigned integer detected Comparing a signed integer value to an unsigned integer value may yield unexpected results when the signed value is negative To compare an unsigned integer to the binary equivalent representation of the signed value the signed value should first be explicitly cast to the unsigned type of the same size 2004 Microchip Technology Inc DS51288C page 95 MPLAB C18 C Compiler User s Guide NOTES DS51288C page 96 2004 Microchip Technology Inc MPLAB C18 C COMPILER MICROCHIP USER S GUIDE Appendix E Extended Mode This appendix details the differences between the Non extended and Extended modes The differences include Stack Frame Size static Parameters overlay Keyword Inline Assembly Predefined Macros Command line Option Differences COFF File Differences E 1 SOURCE CODE COMPATIBILITY E 1 1 Stack Frame Size When the compiler
117. ory as data memory is not executable 1165 reference to incomplete tag s A forward reference struct or union tag cannot be referenced directly ina declaration Only pointers to a forward referenced tag may be declared 1166 invalid type specification The type specification is not valid Common causes include typographic errors or misuse of a typedef type e g int enum myEnum xyz has an invalid type specification 1167 redefinition of enum tag s An enumeration tag may only be defined once Common causes include multiple inclusions of a header file which defines the enumeration tag 1168 reference to undefined enumeration tag s An enumeration tag must be defined prior to any declarations which reference it Unlike structure and union tags forward references to enumeration tags are not allowed 1169 anonymous members allowed in unions only An anonymous structure member may be declared only as a member of a union 1170 non integral type bitfield detected The type of a bitfield member of a structure must be an integral type 1171 bitfield width greater than 8 detected A bitfield must fit within a single storage unit which for MPLAB C18 is a byte Thus a bitfield must contain 8 or fewer bits DS51288C page 88 2004 Microchip Technology Inc MPLAB C18 Diagnostics 1172 1173 1174 1175 1176 1200 1201 1202 1203 1204 1205 1206 1207
118. own out reset disabled _BORV_42 2L VBOR set to 4 2V _WDT_OFF_2H Watchdog Timer disabled _WDTPS 1 2H Watchdog Timer postscale 1 1 _CCP2MUX_OFF_ 3H CCP2 input output is multiplexed with RB3 _CONFIG4L DEFAULT Default setting for this configuration byte stack full underflow will cause Reset AA EEE AAA gs AAA DS51288C page 36 O 2004 Microchip Technology Inc MPLAB C18 C COMPILER MICROCHIP USER S GUIDE Chapter 3 Run time Model This section discusses the run time model or the set of assumptions that the MPLAB C18 compiler operates including information about how the MPLAB C18 compiler uses the resources of the PIC18 PlCmicro microcontrollers 3 1 MEMORY MODELS MPLAB C18 provides full library support for both a small and a large memory model see Table 3 1 The small memory model is selected using the ms command line option and the large memory model using the m1 option If neither is provided the small memory model is used by default TABLE 3 1 MEMORY MODEL SUMMARY Memory Model Command line Default ROM Size of Pointers to Switch Range Qualifier Program Space small ms near 16 bits large ml far 24 bits The difference between the small and large models is the size of pointers that point to program memory In the small memory model both function and data pointers that point to program memory use 16 bits This has the effect of restricting pointers to addressing only t
119. pendent on the size of the return value Table 3 2 details the location of the return value based on its size TABLE 3 2 RETURN VALUES Return Value Size Return Value Location 8 bits WREG 16 bits PRODH PRODL 24 bits Non extended mode AARGB2 2 AARGB2 1 AARGB2 Extended mode __RETVAL2 RETVAL1 RETVALO 32 bits gt 32 bits Non extended mode AARGB3 3 AARGB3 2 AARGB3 1 AARGB3 Extended mode __RETVAL3 RETVAL2 RETVAL1 RETVALO on the stack and FSRO points to the return value O 2004 Microchip Technology Inc DS51288C page 39 MPLAB C18 C Compiler User s Guide 3 2 2 Managing the Software Stack The stack is sized and placed via the linker script with the STACK directive The STACK directive has two arguments SIZE and RAM to control the allocated stack size and its location respectively For example to allocate a 128 byte stack and place that stack in the memory region gpr3 STACK SIZE 0x80 RAM gpr3 MPLAB C18 supports stack sizes greater than 256 bytes The default linker scripts allocate one memory region per bank of memory so to allocate a stack larger than 256 bytes requires combining two or more memory regions as the stack section cannot cross memory region boundaries For example the default linker script for the PIC18C452 contains the definitions DATABANK NAME gpr4 START 0x400 END 0x4ff DATABANK NAME gpr5 START 0x500 END 0x5ff
120. pment Environment DS51288C page 102 2004 Microchip Technology Inc Glossary IEEE Institute of Electrical and Electronics Engineers Interrupt A signal to the CPU that suspends the execution of a running application and transfers control to an ISR so that the event may be processed Upon completion of the ISR normal execution of the application resumes Interrupt Service Routine A function that handles an interrupt ISO International Organization for Standardization ISR Interrupt Service Routine L Latency The time between when an event occurs and the response to it Librarian A program that creates and manipulates libraries Library A collection of relocatable object modules Linker A program that combines object files and libraries to create executable code Little Endian Within a given object the least significant byte is stored at lower addresses M Memory Model A description that specifies the size of pointers that point to program memory Microcontroller A highly integrated chip that contains a CPU RAM some form of ROM I O ports and timers MPASM Assembler Microchip Technology s relocatable macro assembler for PICmicro microcontroller families MPLIB Object Librarian Microchip Technology s librarian for PICmicro microcontroller families MPLINK Object Linker Microchip Technology s linker for PICmicro microcontroller families N Non extended Mode In Non extended mode the compiler
121. pression must be of scalar type i e an integer or a pointer scalar type expected in expression A operator control expression must be of scalar type i e an integer or a pointer scalar operand expected for operator The operator requires that its operand be of scalar type scalar operands expected for operator The logical OR operator requires scalar operands scalar operands expected for amp amp operator The logical AND operator amp amp requires scalar operands 2004 Microchip Technology Inc DS51288C page 85 MPLAB C18 C Compiler User s Guide 1125 preak must appear in a loop or switch statement A break statement must be inside a while do for or switch statement Common causes include a misplaced y 1126 continue must appear in a loop statement A continue statement must be inside a while do for or switch statement 1127 operand type mismatch in operator The types of the result operands of the operator must be either both scalar types or compatible types 1128 compatible scalar operands required for comparison A comparison operator must have operands of compatible scalar types 1129 operator requires a pointer and an integer as operands The array access operator requires that one operand be a pointer and the other be an integer
122. r b foo The Om command line option disables duplicate string merging Duplicate string merging should not affect the ability to debug source code 2004 Microchip Technology Inc DS51288C page 49 MPLAB C18 C Compiler User s Guide 4 2 BRANCHES Ob Ob The following branch optimizations are performed by the MPLAB C18 compiler when the Ob command line option is specified 1 A branch conditional or unconditional to an unconditional branch can be modified to target the latter s target instead 2 Anunconditional branch to a RETURN ADDULNK or SUBULNK instruction can be replaced by a RETURN ADDULNK or SUBULNK instruction respectively 3 A branch conditional or unconditional to the instruction immediately following the branch can be removed 4 Aconditional branch to a conditional branch can be modified to target the latter s target if both branches branch on the same condition 5 A conditional branch immediately followed by an unconditional branch to the same destination can be removed i e the unconditional branch is sufficient The Ob command line option disables branch optimizations Some of the branch optimizations save program space while others may expose unreachable code which can be removed by Unreachable Code Removal see Section 4 7 Unreachable Code Removal Branch optimization should not affect the ability to debug source code 4 3 BANKING On On Banking optimization remov
123. racters of the symbol name are zero A 5 1 2 2 unsigned long n offset Offset of symbol name in the string table A 5 13 char n nptr Allows for overlaying A 5 2 unsigned longn value Value of symbol Typically this is the address of the symbol within the section in which it resides For link time constants e g the Microchip symbol stksize the value is a literal value and not an address To the linker there is typically no difference The distinction is only in the usage in the application code DS51288C page 68 2004 Microchip Technology Inc COFF File Format A 5 3 short n_scnum References the section number where this symbol is located A 5 4 unsigned short n type Base type and derived type A 5 4 1 SYMBOL TYPES Table A 5 lists the base types along with a description and respective values TABLE A 5 BASE SYMBOL TYPES Type Description Value T_NULL null 0 T_VOID void 1 T_CHAR character 2 T_SHORT short integer 3 T_INT integer 4 T_LONG long integer 5 T_FLOAT floating point 6 T_DOUBLE double length floating point 7 T_STRUCT structure 8 T_UNION union 9 ENUM enumeration 10 MOE member of enumeration 11 T_UCHAR unsigned character 12 T_USHORT unsigned short 13 T_UINT unsigned integer 14 T_ULONG unsigned long 15 A 5 4 2 DERIVED TYPES Pointers arrays and functions are handled via derived types Table A 6 lists the der
124. rated to not execute during normal program flow An example where this may occur in C is Lfe 1 x 45 else XS 36 In this code it is obvious that the else portion of this code snippet can never be reached With unreachable code disabled Ou the generated assembly code will include the instructions necessary to move 6 to x and the instruction to branch around these instructions 0x000000 MOVLB x 0x000002 MOVLW 0x5 0x000004 BRA Oxa 0x000006 MOVLB x 0x000008 MOVLW 0x6 0x00000a MOVWF x 0x1 With unreachable code enabled Ou the generated assembly code will not include the instructions for the else 0x000000 MOVLB x 0x000002 MOVLW 0x5 0x000004 MOVWF x 0x1 The unreachable code optimization may affect the ability to set breakpoints on certain lines of C source code 4 8 COPY PROPAGATION Op Op Copy propagation is a transformation that given an assignment x lt y for some variables x and y replaces later uses of x with uses of y as long as intervening instructions have not changed the value of either x or y This optimization by itself does not save any instructions but enables dead code removal see Section 4 10 Dead Code Removal An example where this may occur in C is char c void foo char a char b b a c b With copy propagation disabled 0p the original code is mirrored in the generated assembly code 0x000000 foo MOVFF a b 0x000002 0x000004 MOVFF b c 0x000
125. rocessor 9 1 2 5 Selecting the Mode oooooooococococcccncccccconnnnnnnnnnnnconnnncconnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnno 9 Chapter 2 Language Specifics 2 1 Data Types and Limits sis 11 2 1 1 AAA 11 21 27 Floating point TYpes tua Baty ee Sad Rel ens 12 2 2 Data Type Storage Endianness nnnn nenn nnnn ennnen 12 23 Storage Classes ae a ae e aeaa a e Eae R aaaea hod eE ut 13 2 31 ON ETa e VAE E E ee E AN eee 13 2 3 2 static Function Arguments 14 2 4 Storage Qualifiers see 14 2 4 1 near far Data Memory Objects 14 2 4 2 near far Program Memory Objects 14 2 4 3 ram rom Qualifiers 15 2 5 Include File Search Paths se 15 2 5 1 System Header Files 15 2 5 2 User Header Files 15 2 6 Predefined Macro Names is 16 2 f ISO DiVergences is is imminente ae ane 16 2 7 1 Integer Promotions 16 2 7 2 Numeric Consta ivi rennes anti entierement te men e 16 2 1 3 String Constants 2 aa an a a e Ee a EE Uae 17 2 8 Language Extensions ss 19 2 8 1 Anonymous Structures 19 2 8 2 Inline ASSEMDl yee e ee ecg eet ce Re o de dud bas e 20 29 Pragmas A a ae woe Ss 21 29 1 fpragma SeCETONE YD fii Meur ra Mn teak ne sos cernes 21 2 9 2 pragma interruptlow fname pragma Interrupt fname iia a eyelet avian hares 27 2 9 3 pragma varlocate bank variable nam
126. rrupt pragma The save clause expects a comma delimited list of statically allocated in scope symbol names which are to be saved and restored by the interrupt function being specified Common causes include specifying a symbol which is not currently in scope not including a header file which declares the symbol being referenced and typographical errors in the symbol name 1018 function name expected in interrupt pragma The name of a function to be declared as an interrupt is expected as the first parameter to the interrupt pragma The function symbol must be currently in scope and must take no parameters and return no value Common causes include a missing prototype for the function being declared as an interrupt and typographical errors 1019 s is a compiler managed resource it should not appear in a save list The symbol named is not valid in a save clause of an interrupt declaration There are some locations which if saved restored via a save will produce aberrant code These locations do not need additional context save and can be safely removed from the save clause to correct the error 1020 unexpected input following s Extra information exists on the given preprocessor construct 2004 Microchip Technology Inc DS51288C page 83 MPLAB C18 C Compiler User s Guide 1050 section address permitted only at definition The absolute address in the location clause of the pragma section
127. rupt save list The interrupt pragma requires that symbols listed in the save list must be declared and in scope 1211 missing definition for interrupt function s The function was declared as an interrupt but was never defined The function definition of an interrupt function must be in the same module as the pragma declaring the function as an interrupt 1212 static function s referenced but not defined The function has been declared as static and has been referenced elsewhere in the module but there is no definition for the function present Common causes include a misspelled function name in the function definition 1213 initializer list expected The symbol being initialized requires a brace enclosed initializer list but a single value initializer was found 1214 constant expression expected in initializer The initializer value for a statically allocated symbol must be a constant expression 1215 initialization of bitfield members is not currently supported Bitfield structure members cannot currently be initialized explicitly 1216 string initializer used for non character array object A string literal initializer is only valid for initializing objects of type array of char or type pointer to char either can be unsigned char as well 1218 extraneous initializer values The count of initializer values does not agree with the number of expected values based on the type of the o
128. s a union of bit addressable anonymous structures see Section 2 8 1 Anonymous Structures Since individ ual bits in a special function register may have more than one function and hence more than one name there are multiple structure definitions inside the union all referring to the same register Respective bits in all structure definitions refer to the same bit in the register Where a bit has only one function for its position it is simply padded in other structure definitions For example bits 1 and 2 on PORTA are simply padded in the third and fourth structures because they only have two names whereas bit 6 has four names and is specified in each of the structures 2004 Microchip Technology Inc DS51288C page 33 MPLAB C18 C Compiler User s Guide Any of the following statements can be written to use the PORTA special function register PORTA 0x34 Assigns the value 0x34 to the port PORTAbits ANO 1 Sets the ANO pin high PORTAbits RAO 1 Sets the RAO pin high same as above statement In addition to register declarations the processor specific header file defines inline assembly macros These macros represent certain PICmicro MCU instructions that an application may need to execute from C code Although these instructions could be included as inline assembly instructions as a convenience they are provided as C macros see Table 2 8 Lastly the processor specific header file contains
129. s not clear this byte 2004 Microchip Technology Inc DS51288C page 37 MPLAB C18 C Compiler User s Guide 3 2 CALLING CONVENTIONS The MPLAB C18 software stack is an upward growing stack data structure on which the compiler places function arguments and local variables that have the storage class auto The software stack is distinct from the hardware stack upon which the PICmicro microcontroller places function call return addresses Figure 3 1 shows an example of the software stack FIGURE 3 1 EXAMPLE OF SOFTWARE STACK Unused Location lt a FSR1 Stack Pointer Increasing Function Context Addresses Local Variables and at FSR2 Frame Pointer Parameters The stack pointer FSR1 always points to the next available stack location MPLAB C18 uses FSR2 as the frame pointer providing quick access to local variables and parameters When a function is invoked its stack based arguments are pushed onto the stack in right to left order and the function is called The leftmost function argument is on the top of the software stack upon entry into the function Figure 3 2 shows the software stack immediately prior to a function call FIGURE 3 2 EXAMPLE OF SOFTWARE STACK IMMEDIATELY PRIOR TO FUNCTION CALL A Unused Location _ FSR1 Stack Pointer Function Parameter 1 Function Parameter 2 Function Parameter n Increasing Addresses Function Context lt lt FSR2 Frame
130. s the ability of the MPLAB C18 compiler to perform optimizations on that function 2 var must be an 8 bit quantity i e char and not located on the stack 3 If dest is 0 the result is stored in WREG and if dest is 1 the result is stored in var If access is 0 the access bank will be selected overriding the BSR value If access is 1 then the bank will be selected as per the BSR value DS51288C page 34 2004 Microchip Technology Inc Language Specifics 2 11 PROCESSOR SPECIFIC REGISTER DEFINITIONS FILES The processor specific register definitions file is an assembly file that contains definitions for all the special function registers on a given device The processor specific register definitions file when compiled will become an object file that will need to be linked with the application e g p18c452 asm compiles to p18c452 0 This object file is contained in p18xxxx 1lib g p18c452 0 is contained in pi8c452 1ib The source code for the processor specific register definitions files is found in both the c mcci8 src traditional proc and c mcc18 src extended proc directories Compiled object code is found in the c mcc18 1ib directory where c mcc18 is the directory where the compiler is installed For example PORTA is defined in the PIC18C452 processor specific register definitions file as SFR_UNBANKEDO UDATA ACS H f80 PORTA PORTAbits RES 1 0xf80 The first line specifies the file register
131. sed for the enumeration but relative comparisons of those enumeration constants which have negative representations may not behave as expected 2070 constant value d is too wide for bitfield and will be truncated The given value cannot fit into the bitfield Truncation by ANDing with the size of the bitfield was performed 2071 s cannot have overlay storage class replacing with static Parameters with overlay storage class are not permitted at this time When the default local storage class is overlay the static storage class will be assigned to parameters DS51288C page 94 2004 Microchip Technology Inc MPLAB C18 Diagnostics 2072 2073 2100 2101 D 3 MESSAGES 3000 3001 3002 invalid storage class specifier for s ignoring The storage class specifier used is not permitted for this declaration null terminated initializer string too long The null terminated initializer string cannot fit in the array object obsolete use of overlay for symbol s processing as auto The overlay storage class is not supported in extended mode the declaration will be processed as if storage class auto has been specified instead obsolete use of static storage for parameter s treating as auto When compiling in Extended mode MPLAB C18 requires all function parameters to be of automatic storage class See the MPLAB C18 User s Guide for more inf
132. should be placed in program memory The compiler will allocate this variable into the current romdata type section For example pragma romdata const table const rom char my_const_array 10 fo ty 2 Be Sy 6 7 8 9 Resume allocation of romdata into the default section Hpragma romdata The linker will enforce that romdata sections be placed in program memory regions and that udata and idata sections be placed in data memory regions however a data section can also be located in a specified memory region The SECTION directive of the linker script is used to assign a section to a specific memory region The following assigns udata section my_data to memory region gpr1 SECTION NAME my data RAM gprl1 DS51288C page 26 2004 Microchip Technology Inc Language Specifics 2 9 2 pragma interruptlow fname pragma interrupt fname The interrupt pragma declares a function to be a high priority interrupt service routine ISR the interruptlow pragma declares a function to be a low priority interrupt service routine An interrupt suspends the execution of a running application saves the current context information and transfers control to an ISR so that the event may be processed Upon completion of the ISR previous context information is restored and normal execution of the application resumes The minimal context saved and restored for an interrupt is WREG BSR and STATUS A high priority interrupt uses the shadow regis
133. signed short X s126 input 72 A9 2 unsigned Long Endodoncia 72 struct aux eos Auxiliary Symbol Table Entry for an End of SETUGE UM ON STU cs LS RD Une need ec rl batt x 73 A 10 1 unsigned long x Laia 73 A 10 2 unsigned short x S126 tt Senden aa eet 73 struct aux_f cn Auxiliary Symbol Table Entry for a Function Name 73 AJT T unsigned Tong tanda ida 73 A 11 2 unsigned long x_Innoptr ie 73 AA1 3 unsigned long x dai ad 73 ATTA Short ix dect sonatas atado 73 struct aux fcn calls Auxiliary Symbol Table Entry for Function Call References iccioicioior idear 74 A 12 1 unsigned long x calleend iii ii 74 A 12 2 unsigned lOngiX 18 INESTTUPL ri 74 struct aux arr Auxiliary Symbol Table Entry for an Array 74 AAS unsigned Tong tandil da ia telah 74 AA3 2 unsigned SHOT ERY BiZE ni este teas sebae gece enla AREE thane Ss 74 A 13 3 unsigned short x dimen X DIMNUM 000 eee eee eter rete 74 struct aux_eobf Auxiliary Symbol Table Entry for the End of a Block OF FUNGUO nr Es nt dels an nr a nl Sve tente Mr 75 A141 unsigned short x DANO ss die ta adsl 75 2004 Microchip Technology Inc DS51288C page v MPLAB C18 C Compiler User s Guide A 15 struct aux bobf Auxiliary Symbol Table Entry for the Beginning of a Block or Function 75 A l5 1 unsigned Shove x IO caida tt a TE 75 AMAS Z unsigned long Ren ties rd eii a 75 A 16 struct aux_var Auxiliary Symbol Table Entry for a Variable of Type struct unio
134. sor data sheet for the specific processor and interrupt source being used 2 Interrupt vector execution The amount of time it takes to execute the code at the interrupt vector that branches to the ISR 3 ISR prologue code The amount of time it takes MPLAB C18 to save the compiler managed resources and the data in the save list 2 9 2 6 NESTING INTERRUPTS Low priority interrupts may be nested since active registers are saved onto the software stack Only a single instance of a high priority interrupt service routine may be active at a time since these ISR s use the single level hardware shadow registers If nesting of low priority interrupts is desired a statement to set the GIEL bit can be added near the beginning of the ISR See the processor data sheet for details 2 9 3 pragma varlocate bank variable name pragma varlocate section name variable name The varlocate pragma tells the compiler where a variable will be located at link time enabling the compiler to perform more efficient bank switching The varlocate specifications are not enforced by the compiler or linker The sections that contain the variables should be assigned to the correct bank explicitly in the linker script or via absolute sections in the module s where they are defined 2 9 3 1 SYNTAX variable locate directive pragma varlocate bank variable name variable name pragma varlocate section name variable name variable name bank int
135. sspelled label identifier and a reference to an out of scope label i e a label defined in another function integer type expected in switch control expression The control expression for a switch statement must be an integer type Common causes include a missing operator and a missing operator integer constant expected for case label value The value for a case label must be an integer constant case label outside switch statement detected A case label is only valid inside the body of a switch statement Common causes include a misplaced multiple default labels in switch statement A switch statement can only have a single default label Common causes include a missing to close an inner switch type mismatch in return statement The type of the return value is not compatible with the declared return type of the function Common causes include a missing or operator scalar type expected in if statement An if statement control expression must be of scalar type i e an integer or a pointer scalar type expected in while statement A while statement control expression must be of scalar type i e an inte ger or a pointer scalar type expected in do while statement A do while statement control expression must be of scalar type i e an integer or a pointer scalar type expected in for statement A for statement control ex
136. straction is performed across all functions in a given code section Note Procedural abstraction generates a savings in program space at the potential expense of execution time For example given the following C source code fragment distance time speed position time speed 2004 Microchip Technology Inc DS51288C page 55 MPLAB C18 C Compiler User s Guide When compiled with procedural abstraction disabled Opa the code sequence generated for time speed is generated for each instruction listed above It is shown in bold below 0x000000 main MOVLB time 0x000002 MOVF time 0x0 0x1 0x000004 MULWF speed 0x1 0x000006 MOVF PRODL 0x0 0x0 0x000008 MOVWF PRODL 0x0 0x00000a CLRF PRODL 1 0x0 0x00000c MOVE WREG 0x0 0x0 0x00000e SUBWF distance 0x1 0x1 0x000010 MOVF PRODL 1 0x0 0x0 0x000012 SUBWFB distance 1 0x1 0x1 0x000014 MOVF time 0x0 0x1 0x000016 MULWF speed 0x1 0x000018 MOVF PRODL 0x0 0x0 0x00001a MOVWF PRODL 0x0 0x00001c CLRF PRODL 1 0x0 0x00001e MOVF WREG 0x0 0x0 0x000020 ADDWF position 0x1 0x1 0x000022 MOVF PRODL 1 0x0 0x0 0x000024 ADDWFC position 1 0x1 0x1 0x000026 RETURN 0x0 Whereas when compiled with procedural abstraction enabled Opa these two code sequences are abstracted into a procedure and the repeated code is replaced by a call to the procedure 0x000000 main MOVLB time 0x000002 CALL pa 0 0x0 0x000004 0x000006 SUBWF distance 0x1 0x1 0x000008 MOVF PRODL 1 0
137. t in a stack frame too large diagnostic being issued that does not occur when the compiler is operating in the Non extended mode To resolve this the function will need to be modified to contain fewer auto local variables One way to do this is to change the overlay variables to static Note Overlay sections pragma overlay are supported by the compiler regardless of the mode in which it is operating 2004 Microchip Technology Inc DS51288C page 97 MPLAB C18 C Compiler User s Guide E 1 4 Inline Assembly When operating in Extended mode the compiler will accept the extended instructions in inline assembly ADDFSR ADDULNK CALLW MOVSF MOVSS PUSHL SUBFSR and SUBULNK however when operating in Non extended mode the compiler will issue an error when it encounters an extended instruction in inline assembly In addition when operating in Extended mode the compiler will not recognize the bracketed syntax used by the MPASM assembler for indicating the indexed with literal offset addressing e g CLRF 2 Instead the compiler will recognize the indexed with literal offset addressing in inline assembly when the operand is less than or equal to Ox5F and the access bit operand a is set to zero e g CLRF 2 0 This same instruction will be interpreted as referencing access RAM when the compiler is operat ing in Non extended mode E 1 5 Predefined Macros The predefined macros can be utilized in source code to
138. t is array of char located in program memory const rom char The stringtable section is a romdata see Section 2 9 1 pragma sectiontype section that contains all constant strings For example the string hello in the following would be located in the stringtable section strcmppgm2ram Foo hello Due to the fact that constant strings are kept in program memory there are multiple versions of the standard functions that deal with strings For example the strcpy function has four variants allowing the copying of a string to and from data and program memory Copy string s2 in data memory to string sl in data memory char strcpy auto char sl auto const char s2 Copy string s2 in program memory to string s1 in data memory char strcpypgm2ram auto char s1 auto const rom char s2 Copy string s2 in data memory to string sl in program memory rom char strcpyram2pgm auto rom char s1 auto const char s2 Copy string s2 in program memory to string sl in program memory rom char strcpypgm2pgm auto rom char s1 auto const rom char s2 When using MPLAB C18 a string table in program memory can be declared as rom const char table 20 string 1 string 2 string 3 string 4 rom const char rom table2 string 1 string 2 string 3 string 4 The declaration of table declares an array of four strings that are each 20
139. tant expression is defined as a literal constant or a statically allocated symbol reference optionally plus or minus an integer constant Common causes include the use of a dynamically allocated symbol auto local variables and parameters as the operand to an in line assembly opcode 1300 stack frame too large The size of the stack frame has exceeded the maximum addressable size Commonly caused by too many local variables allocated as auto storage class in a single function 1301 parameter frame too large The size of the parameter frame has exceeded the maximum addressable size Commonly caused by too many parameters being passed to a single function 1302 old style function declarations not supported MPLAB C18 does not currently support the old K amp R style function definitions The in line parameter type declarations recommended by the ANSI standard should be used instead 1303 near symbol defined in non access qualified section Statically allocated variables allocated into a non access qualified section cannot be accessed via the access bit and therefore defining them with the near range qualifier would result in incorrect access to the location 1304 illegal use of obsolete overlay storage class for symbol s The overlay storage class is not supported in Extended mode Also note that in Non extended mode the overlay storage class is valid only for local variables 1500 unable to ope
140. ters to save and restore the minimal context while a low priority interrupt uses the software stack to save and restore the minimal context As a consequence a high priority interrupt terminates with a fast return from interrupt while a low priority interrupt terminates with a normal return from interrupt Two MOVFF instructions are required for each byte of context preserved via the software stack except for WREG which requires a MOVWF instruction and a MOVF instruction therefore in order to preserve the minimal context a low priority interrupt has an additional 10 word overhead beyond the requirements of a high priority interrupt Interrupt service routines use a temporary data section that is distinct from that used by normal C functions Any temporary data required during the evaluation of expressions in the interrupt service routine is allocated in this section and is not overlaid with the temporary locations of other functions including other interrupt functions The interrupt pragmas allow the interrupt temporary data section to be named If this section is not named the compiler temporary variables are created in a udata section named fname_tmp For example void foo void pragma interrupt foo void foo void perform interrupt function here The compiler temporary variables for interrupt service routine foo will be placed in the udata section foo tmp 2004 Microchip Technology Inc DS51288C page 27 MPL
141. to be located at the same physical address This can conserve memory by locating variables to the same location as long as both are not active at the same time The overlay attribute can be used in conjunction with the access attribute In order to overlay two sections four requirements must be met 1 Each section must reside in a different source file 2 Both sections must have the same name 3 Ifthe access attribute is specified with one section it must be specified with the other 4 Ifan absolute address is specified with one section the same absolute address must be specified with the other Code sections that have the overlay attribute can be located at an address that overlaps other overlay code sections For example file1 c pragma code overlay my overlay scn 0x1000 void void es file2 c pragma code overlay my overlay scn 0x1000 void g void ae 2004 Microchip Technology Inc DS51288C page 25 MPLAB C18 C Compiler User s Guide Data sections that have the overlay attribute can be located at an address that overlaps other overlay data sections This feature can be useful for allowing a single data range to be used for multiple variables that are never active simultaneously For example file1 c pragma udata overlay my overlay data 0x1fc 2 bytes will be located at Oxlfc and Oxlfe int int varl int var2 file2 c pragma udata overlay my overlay data 0x1fc 4 bytes
142. type directive may only be specified in the first pragma defining this section 1052 section overlay attribute does not match definition MPLAB C18 requires that a previously declared section s attribute must match those which are being specified in the current pragma sectiontype directive 1053 section share attribute does not match definition MPLAB C18 requires that a previously declared section s attribute must match those which are being specified in the current pragma sectiontype directive 1054 section type does not match definition MPLAB C18 has previously seen this section name but it was of a different type i e code idata udata romdata 1099 s source code error directive message 1100 syntax error Invalid function type definition 1101 Ivalue required An expression which designates an object is required Common causes include missing parentheses and a missing operator 1102 cannot assign to const modified object An object qualified with const is declared to be read only data and modifications to it are therefore not allowed 1103 unknown escape sequence s The specified escape sequence is not known to the compiler Check the User s Guide for a list of valid character escape sequences 1104 division by zero in constant expression The compiler cannot process a constant expression that contains a divide by or modulus by zero 1105 symbol s has not been de
143. uires that vendors document the specifics of implementation defined features of the language Note The section numbers in parenthesis e g 6 1 2 refer to the ANSI C standard X3 159 1989 Implementation defined behavior for the following sections is covered in section G 3 of the ANSI C Standard B 2 IDENTIFIERS ANSI C Standard The number of significant initial characters beyond 31 in an identifier without external linkage 6 1 2 The number of significant initial characters beyond 6 in an identifier with external linkage 6 1 2 Whether case distinctions are significant in an identifier with external linkage 6 1 2 Implementation All MPLAB C18 identifiers have at least 31 significant characters Case distinctions are significant in an identifier with external linkage B 3 CHARACTERS ANSI C Standard The value of an integer character constant that contains more than one character or a wide character constant that contains more than one multibyte character 6 1 3 4 Implementation The value of the integer character constant is the 8 bit value of the first character Wide characters are not supported ANSI C Standard Whether a plain char has the same range of values as signed char or unsigned char 6 2 1 1 Implementation A plain char has the same range of values as a signed char For MPLAB C18 this may be changed to unsigned char viaa command line switch k
144. ved Section 2 9 2 Hpragma interruptlow fname pragma interrupt fname and Section 2 9 2 4 ISR Context Saving These lines define the timer_isr function Notice that it does not take any parameters and does not return anything as required by ISRs See Section 2 9 2 2 Interrupt Service Routines This line clears the TMRO interrupt flag to stop the program from processing the same interrupt multiple times See Section 2 10 Processor specific Header Files This line demonstrates how to modify the special function register PORTB in C See Section 2 10 Processor specific Header Files These lines initialize the special function registers TRISB and PORTB See Section 2 10 Processor specific Header Files This line enables the TMRo interrupt setting up the timer as an internal 16 bit clock This line enables global interrupts See Section 2 10 Processor specific Header Files 2004 Microchip Technology Inc DS51288C page 59 MPLAB C18 C Compiler User s Guide NOTES DS51288C page 60 2004 Microchip Technology Inc MPLAB C18 C COMPILER MICROCHIP USER S GUIDE Appendix A COFF File Format The Microchip COFF specification is based upon the UNIX System V COFF format as described in Understanding and Using COFF Gintaras R Gircys 1988 O Reilly and Associates Inc Special mention is made where the Microchip format differs from that described there A 1 struct
145. will be located at Oxlfc long long var For more information on the handling of overlay sections see MPASM User s Guide with MPLINK and MPLIB DS33014 2 9 1 5 LOCATING CODE Following a pragma code directive all generated code will be assigned to the specified code section until another pragma code directive is encountered An absolute code section allows the location of code to a specific address For example pragma code my _code 0x2000 will locate the code section my_code at program memory address 0x2000 The linker will enforce that code sections be placed in program memory regions however a code section can be located in a specified memory region The SECTION directive of the linker script is used to assign a section to a specific memory region The following linker script directive assigns code section my_code1 to memory region pagel SECTION NAME my codel ROM pagel 2 9 1 6 LOCATING DATA Data can be placed in either data or program memory with the MPLAB C18 compiler Data that is placed in on chip program memory can be read but not written without additional user supplied code Data placed in external program memory can generally be either read or written without additional user supplied code For example the following declares a section for statically allocated uninitialized data udata at absolute address 0x120 pragma udata my new data_section 0x120 The rom keyword tells the compiler that a variable
146. x0 0x0 0x00000a SUBWFB distance 1 0x1 0x1 0x00000c CALL pa 0 0x0 0x00000e 0x000010 ADDWF position 0x1 0x1 0x000012 MOVF PRODL 1 0x0 0x0 0x000014 ADDWFC position 1 0x1 0x1 0x000016 RETURN 0x0 0x000018 _ pa 0 MOVF time 0x0 0x1 0x00001a MULWF speed 0x1 0x00001c MOVF PRODL 0x0 0x0 0x00001e MOVWF PRODL 0x0 0x000020 CLRF PRODL 1 0x0 0x000022 MOVF WREG 0x0 0x0 0x000024 RETURN 0x0 Not all matches are able to be abstracted in a single pass of procedural abstraction Procedural abstraction is performed until no more abstractions occur or a maximum of four passes The number of passes can be controlled via the pa n command line option Procedural abstraction can potentially add an additional 2 1 levels of function calls where n is the total number of passes If the hardware stack is a limited resource in an application the pa n command line option can be used to adjust the number of times procedural abstraction is performed When debugging source code compiled with this optimization enabled the incorrect source line may be highlighted because two or more source lines may share a single sequence of assembly code making it difficult for the debugger to identify which source line is being executed DS51288C page 56 2004 Microchip Technology Inc MPLAB C18 C COMPILER MICROCHIP USER S GUIDE Chapter 5 Sample Application The following sample application will flash LEDs connected to PORTB of a PIC18C452 micr
147. xadecimal digit Documents Arial font Italic characters Referenced books MPLAB User s Guide Documentation Updates All documentation becomes dated and this guide is no exception Since MPLAB C18 is constantly evolving to meet customer needs some tool descriptions may differ from those in this document Please refer to our web site to obtain the latest documentation available Documentation Numbering Conventions Documents are numbered with a DS number The number is located on the bottom of each page in front of the page number The numbering convention for the DS Number is DSXXXXXA where XXXXX A The document number The revision level of the document DS51288C page 2 2004 Microchip Technology Inc Preface PIC18 DEVELOPMENT REFERENCES readme c18 For the latest information on using MPLAB C18 C compiler read the readme c18 file ASCII text included with the software This readme file contains update information that may not be included in this document MPLAB C18 C Compiler Getting Started Guide DS51295 Describes how to install the MPLAB C18 compiler how to write simple programs and how to use the MPLAB IDE with the compiler MPLAB C18 C Compiler Libraries DS51297 Reference guide for MPLAB C18 libraries and precompiled object files Lists all library functions provided with the MPLAB C18 C compiler with detailed descriptions of their use MPLAB IDE V6 XX Quick Start Guide
148. y GLEN ai a IR 34 NA e eee a te TE 34 Rasta drid Ra eee 34 REG BAC afd pS intone te Foe vee os oh T 34 Rlncf A de Sale oc EESTI 34 RECE C2549 A A ne 34 Rrncf Y ri Sioa Soest 34 Seep indented Ae ie ie 34 SwWapt OEEO ENAA an eRe ee 34 Predefined TICK A tiuaten cheek ati ate ated aiere coter 16 EXTENDEDIS idos 16 98 LARGE adas 16 PROCESSOR Mati 16 SMALL dida 16 TRADITIONAL18B _ oocconinccnnnnnninnness 16 98 MATA DATA aaa nets 30 47 MCC INCLUDE Lira 15 Memory Models eesceeesteeeeeeeeeeseeetsneeeeeneeeeeaas 37 Detalla a aa ais 37 LIO att 37 OVerriding 52e 37 Small here sertie 37 Microchip Web Site ooooocccccconicccccccccconoccnnconananccnncnnnnns 5 Minimal Context 27 Modes Extended sereine dires trees 97 99 COR File ccoo aus mutants 62 64 Diagnostics 91 93 95 Non extended 97 99 Access Section 24 82 COFF File cccccecccccccccscsceeeeeeeeseseeeeeeeseneas 64 Diagnostics ee rie i aiarar 91 Static Parameters 42 Storage Classes 13 14 81 Predefined Macro 16 Selecting the Mode 9 10 82 MPASM viii ie eet 20 MPEINK insisi oen en add ia 13 14 20 45 N NE 14 15 24 25 33 37 Non extended Mode
149. ystem V relocation data where the offset is stored in the location being relocated to in that the offset to add to the base address of the symbol is stored in the relocation entry This is necessary because Microchip relocations are not restricted to just filling in an address offset value into the data stream but also do simple code modifications It is much more straightforward to store the offset here at the cost of a slightly increased file size typedef struct reloc unsigned long r_vaddr unsigned long r_symndx short r offset unsigned short r type reloc t A 4 1 unsigned long r vaddr Address of reference byte offset relative to start of raw data A 4 2 unsigned long r symndx Index into symbol table A 4 3 short r offset Signed offset to be added to the address of symbol r_symndx DS51288C page 66 O 2004 Microchip Technology Inc A 4 4 COFF File Format unsigned short r type Relocation type implementation defined values Table A 4 lists the relocation types along with a description and respective values TABLE A 4 RELOCATION TYPES Type Description Value RELOCT_CALL CALL instruction first word only on PIC18 1 RELOCT_GOTO GOTO instruction first word only on PIC 18 2 RELOCT_HIGH Second 8 bits of an address 3 RELOCT_LOW Low order 8 bits of an address 4 RELOCT_P 5 bits of address f
Download Pdf Manuals
Related Search
Related Contents
RIPEST - Universidad de Buenos Aires Samsung Flat Panel Television 430 User's Manual Compact Lightset MKII 1 - CNET Content Solutions 2.1chスピーカーシステム YSP-2021 取扱説明書 the great outdoors by Minka Lavery 8283-A61 Installation Guide Graco Inc. 308-532 Pressure Washer User Manual LMR100-spanish 771073210 Rev01 Android 4.2 Jelly Bean Copyright © All rights reserved.
Failed to retrieve file