Home

C Cross Compiler User's Guide for CORTEX-M

image

Contents

1. Function memcmp compares two text buffers character by character for lexical order in the character collating sequence The first buffer starts at s the second at s2 both buffers are n characters long Return Value memcmp returns a short integer greater than equal to or less than zero according to whether s is lexicographically greater than equal to or less than s2 Example To look for the string include in name if memcmp name include 7 0 doinclude See Also strcmp strncmp Notes memcmp is packaged in the integer library 2012 COSMIC Software Using The Compiler 123 Ei C Library memcpy memcpy Description Copy one buffer to another Syntax include lt string h gt void memcpy void s1 void s2 unsigned int n Function memcpy copies the first n characters starting at location s2 into the buffer beginning at s1 Return Value memcpy returns s1 Example To place first string second string in buf memcpy buf first string 12 memcpy buf 13 second string 15 See Also strcpy strncpy Notes memcpy is implemented as a builtin function 124 Using The Compiler 2012 COSMIC Software C Library memmove memmove Description Copy one buffer to another Syntax include lt string h gt void memmove void sl void s2 unsigned int n Function memmove copies the first n characters starting
2. dcb lt size gt lt count gt lt value gt Function The dcb directive allocates a memory block and initializes storage for constants The size area is the number of the specified value lt count gt of lt size gt The memory area can be initialized with the lt value gt specified The deb and deb b directives will allocate one byte per lt count gt The deb w directive will allocate one word per lt count gt The deb 1 directive will allocate one long word per lt count gt Example digit dcb b 10 5 allocate 10 bytes all initialized to 5 204 Using The Assembler 2012 COSMIC Software Assembler Directives dlist dlist Description Turn listing of debug directives on or off Syntax dlist on off Function The dlist directive controls the visibility of any debug directives in the listing It is effective if and only if listings are requested it is ignored otherwise 2012 COSMIC Software Using The Assembler 205 Assembler Directives ds Description Allocate variable s Syntax ds size lt space gt Function The ds directive allocates storage space for variables lt space gt must be an absolute expression Bytes created are set to the value of the filling byte defined by the f option The ds and ds b directives will allocate lt space gt bytes The ds w directive will allocate lt space gt words The ds l directive will allocate lt space gt lo
3. excorm cl mylist co myobj 1 mods acia c This command will compile the acia c file create a listing named acia ls in the mylist directory and an object file named acia o in the myobj directory 2012 COSMIC Software Tutorial Introduction Specifving Command Line Options cxcorm allows you to compile more than one file The input files can be C source files or assembly source files You can also mix all of these files If your application is composed with the following files two C source files and one assembly source file you would type cxcorm v start s acia c getchar c This command will assemble the start s file and compile the two C source files See Chapter 4 Using The Compiler for information on these and other command line options 28 Tutorial Introduction 2012 COSMIC Software CHAPTER 3 Programming Environments This chapter explains how to use the COSMIC program development system to perform special tasks required by various CORTEX M appli cations 2012 COSMIC Software Programming Environments 29 Introduction Introduction The COSMIC CORTEX M compiler is an ANSI C compiler that offers several extensions which support special requirements of embedded systems programmers This chapter provides details about Memory Models Modifying the Runtime Startup Initializing data in RAM The const and volatile Type Qualifiers Performing
4. w 139 Read formatted input cc cceceeeeeeeeeeseeceeceeceeeeeeeaeeaes 140 Save calling environment cceceseseeeeceeeeeeeseeteeteeneene 144 SI sesedadievisscuess E Riaeadecucsncensdesosavens E 146 Hyperbolic Sine ecececeeseesecseesecseeseeeeeeeeeeceeceeceeeeaeeasense 147 Output arguments formatted to buffer 148 Real square r00t eccesesseseeeeeeeeseeees 149 Seed pseudo random number generator 150 Read formatted input from a String eceeeeeeeeeeeeeeeee 151 Concatenate Strings cscsceecescsscesessesseeseeeeeeeeseeeeeeeeeees 152 Scan string for first occurrence of character ee 153 Compare two strings for lexical order cceeeeeeeeeeeees 154 Copy one string to another 0 0 0 ceeeeeeseeeees wilds Find the end of a span of characters in a set 156 Find length of a string 00 ec eeeeeeeeeeeeeees salo Concatenate strings of length n sssssessessesssesesseserssesseseese 158 Compare two n length strings for lexical order 159 Copy n length string cc ccceceesesesceeeeeeeeeeeeeeeeeeeeeeeeeeeees 160 Find occurrence in string of character in set 60 161 Scan string for last occurrence of character 162 Find the end of a span of characters not in set Scan string for first occurrence of string Convert buffer to double eee cceeseseeseeseeeeeteeeeeeeeeees Convert buffer to long c cc
5. OSMIC Version 4 1 Software C Cross Compiler User s Guide for CORTEX M Copyright COSMIC Software 1995 2012 All Trademarks are the property of their respective owners Table of Contents Organization of this Manual c ccceecceceeceseeseeseesecseeseeseeneees 1 Chapter 1 Tint Gut OMe ssf scscs veils letsenda cecwese EE AREE 4 Doctiment Conventions sinsear e ini 4 ype writer fOD sei cas ess cde veseseszessevactassvessgseoss ous dunaiedwesetsnavadee 4 Italics Brackets cccccccecccescesseseeseeeeeseeeeceeceeceeceaeeaeeaeeaeeaeeaeeaeenes CONVENTIONS cirian eet eee Command Line sesssccessuts con csiees Sesanededeneseaseenscoeceacsecuennsadestesdes PIAS 3 sas cib annon ons isisi eiiie ise adeactacnalasnsteseaesens Compiler Architecture Predefined Symbols sis 3 sesssstiessesscsntacaussasanoaselaess sends cvetensstevnasatee ENKHEE EE EAEE A rer reer reerecrer rece Programming Support Utilities eee eeseecseeeeeetereeseeeeeees 9 ListingS a 10 OPTIMIZATIONS sts cssscsstsscensenterssatseasscteassdecsasenseasisasedacassaecneasesdees 10 Acia c Example filessiisi isasiasaenaviseceecns tise cdssveedeeueseenss Default Compiler Operation Compiling and Linking ja Step 1 Compiling cece cececeseeseeseceeceececeeeesenseeeeeseeaeens Step 22 Assembler isisisi ssarsassis sisis sin ior rE PENEN Step 3 Linking me Step 4 Generating S Records file
6. Option Description b do not optimize branch instructions By default the assem bler replaces long branches by short branches wherever a shorter instruction can be used and short branches by long branches wherever the displacement is too large This opti mization also applies to jump and jump to subroutines instructions C produce cross reference information The cross reference information will be added at the end of the listing file This option enforces the l option d gt where has the form name value defines name to have the value specified by value This option is equivalent to using an equ directive in each of the source files e log errors from assembler in the text file instead of display ing the messages on the terminal screen ff use formfeed character to skip pages in listing instead of using blank lines ft output a title in listing date file name page By default no title is output f define the value of the filling byte used to fill any gap cre ated by the assembler directives Default is 0 ge produce error messages directly compatible with the Eclipse environment h include the file specified by before starting assembly It is equivalent to an include directive in each source file i gt define a path to be used by the include directive Up to 128 paths can be defined A path is a directory name and is not ended by any directory separator charact
7. 00 Command Line Options Warming Levels cccecceccessessesseeececsecsecsceceseeeeeeeeaeees Extra verifications ssssssssrssrssrssissreesssnsessrsosisrrsessrsresisorsross Return Status The cgcorm Code Generator Command Line Options Return Status The cocorm Assembly Language Optimizer Command Line Options Return Status ix Preface he Cross Compiler User s Guide for CORTEX M is a reference guide for programmers writing C programs for CORTEX M microcontroller environments It provides an overview of how the cross compiler works and explains how to compile assemble link and debug programs It also describes the programming support utilities included with the cross compiler and provides tutorial and reference information to help you configure executable images to meet specific requirements This manual assumes that you are familiar with your host operating sys tem and with your specific target environment Organization of this Manual This manual is divided into eight chapters and four appendixes Chapter 1 Introduction describes the basic organization of the C compiler and programming support utilities Chapter 2 Tutorial Introduction is a series of examples that demon strates how to compile assemble and link a simple C program Chapter 3 Programming Environments explains how to use the fea tures of C for CORTEX M to meet the requirements of y
8. 23 0 cleanup errmsg See Also memcmp strcmp Notes strncmp is packaged in the integer library 2012 COSMIC Software Using The Compiler 159 Ei C Library strncpy strncepy Description Copy n length string Syntax include lt string h gt char strncpy char sl char s2 unsigned int n Function strnepy copies the first n characters starting at location s2 into the buffer beginning at s n specifies the maximum number of characters to be copied unless the terminating NUL in s2 is encountered first In that case additional NUL padding is appended to s2 to copy a total of n characters Return Value strncpy returns s1 Example To make a copy of the string s2 in dest strncpy dest s2 n See Also memcpy strcpy Notes If the string s2 points at is longer than n characters the result may not be NUL terminated strncpy is packaged in the integer library 160 Using The Compiler 2012 COSMIC Software C Library strpbrk strpbrk Description Find occurrence in string of character in set Syntax include lt string h gt char strpbrk char s1 char s2 Function strpbrk scans the NUL terminated string starting at s for the first occurrence of a character in the NUL terminated set s2 Return Value strpbrk returns a pointer to the first character in s that is also contained in the set s2 or a NULL if none does Example To replace unprintable c
9. Initializing data in RAM movs r0 0 zbcl str r0 r1 4 subs r2 1 bne zbcl init ldr sp atabt 12 ldr r9 atab bl _main exit b exit align 4 atab dc l _ sdata dc l _ sram dc l __ eram dc l stack dc l _ idesc__ end to clear the bss clear memory count down and loop back initialize SP initialize DP execute main stay here init value of data pointer start of ram to clear end of ram to clear init value of stack pointer descriptor start address crtsi s performs the same function as described with the crts s but with one additional step Lines marked in bold in crtsi s include code to copy the contents of initialized static data which has been placed in the text section by the linker to the desired location in RAM For more information see Generating Automatic Data Initialization in Chapter 2 and Automatic Data Initialization in Chapter 6 36 Programming Environments 2012 COSMIC Software The const and volatile Type Qualifiers The const and volatile Type Qualifiers You can add the type qualifiers const and volatile to any base type or pointer type attribute Volatile types are useful for declaring data objects that appear to be in conventional storage but are actually represented in machine registers with special properties You use the type qualifier volatile to declare memory mapped input output control registers shared data objects and data objects accessed by
10. The clst utility The clst utility takes relocatable or executable files as arguments and creates listings showing the C source files that were compiled or linked to obtain those relocatable or executable files It is a convenient utility for finding where the source statements are implemented To use clst efficiently its argument files must have been compiled with the debug option clst can be instructed to limit its display to files occupying memory in a particular range of addresses facilitating debugging by excluding extra neous data clst will display the entire content of any files located between the endpoints of its specified address range Command Line Options clst accepts the following command line options each of which is described in detail below clst options gt file a list file alphabetically b display physical address f gt process selected file i gt source file directory 1 page length o output file name p suppress pagination r specify a line range Cist Option Usage Option Description a when set cause clst to list files in alphabetical order The default is that they are listed by increasing addresses b display physical address instead of logical address in the listing file f gt specify as the file to be processed Default is to process all the files of the application Up to 10 files can be specified 306 Debugging Support 2012 COSMIC S
11. abs Description Find absolute value Syntax include lt stdlib h gt int abs int i Function abs obtains the absolute value of i No check is made to see that the result can be properly represented Return Value abs returns the absolute value of i expressed as an int Example To print out a debit or credit balance printf balance d s n abs bal bal lt 0 CR W See Also labs fabs Notes abs is packaged in the integer library Using The Compiler 2012 COSMIC Software C Library acos acos Description Arccosine Syntax include lt math h gt double acos double x Function acos computes the angle in radians the cosine of which is x to full dou ble precision Return Value acos returns the closest internal representation to acos x expressed as a double floating value in the range 0 pi If x is outside the range 1 1 acos returns zero Example To find the arccosine of x theta acos x See Also asin atan atan2 Notes acos is packaged in the floating point library 2012 COSMIC Software Using The Compiler 75 76 E C Library asin asin Description Arcsine Syntax include lt math h gt double asin double x Function asin computes the angle in radians the sine of which is x to full double precision Return Value asin returns the nearest internal representation to asin x ex
12. toupper buf i See Also tolower Notes toupper is packaged in the integer library 2012 COSMIC Software Using The Compiler 171 Ei C Library va_arg va_arg Description Get pointer to next argument in list Syntax include lt stdarg h gt type va_arg va_list ap type Function The macro va_arg is an rvalue that computes the value of the next argument in a variable length argument list Information on the argu ment list is stored in the array data object ap You must first initialize ap with the macro va_start and compute all earlier arguments in the list by expanding va_arg for each argument The type of the next argument is given by the type name type The type name must be the same as the type of the next argument Remember that the compiler widens an arithmetic argument to int and converts an argument of type float to double You write the type after conversion Write int instead of char and double instead of float Do not write a type name that contains any parentheses Use a type def inition if necessary as in typedef int pfi pointer to function returning int fun_ptr va_arg ap pfi get function pointer argument Return Value va_arg expands to an rvalue of type type Its value is the value of the next argument It alters the information stored in ap so that the next expansion of va_arg accesses the argument following Example To write multiple strings to a
13. Return Value realloc returns a pointer to the start of the possibly moved cell if suc cessful Otherwise realloc returns NULL and the cell and ptr are unchanged The pointer returned may be assigned to an object of any type without casting Example To adjust p to be n doubles in size p realloc p n sizeof double See Also calloc free malloc Notes realloc is packaged in the integer library 138 Using The Compiler 2012 COSMIC Software C Library sbreak sbreak Description Allocate new memory Syntax no header file need be included void sbreak unsigned int size Function sbreak modifies the program memory allocation as necessary to make available at least size contiguous bytes of new memory on a storage boundary adequate for representing any type of data There is no guar antee that successive calls to sbreak will deliver contiguous areas of memory Return Value sbreak returns a pointer to the start of the new memory if successful otherwise the value returned is NULL Example To buy space for an array of symbols if p sbreak nsyms sizeof symbol remark not enough memory NULL Notes sbreak is packaged in the integer library sbreak is an extension to the ANSI C standard 2012 COSMIC Software Using The Compiler 139 Ei C Library scanf scanf Description Read formatted input Syntax include lt stdio h gt int scanf c
14. a simple return statement is used in a non void function strict missing switch test expression an expression in a switch instruction is needed but is not present missing while a while is expected and not found missing while test expression an expression in a while instruction is needed but none is present missing a is expected and not found missing a is expected and not found The parser reports such an error on the previous element as most of the time the is missing at the end of the declaration When this error occurs on top of a file or just after a file include the line number reported may not match the exact location where the problem is detected missing a is expected and not found missing a is expected and not found missing a is expected and not found 2012 COSMIC Software Compiler Error Messages 339 Parser cpcorm Error Messages missing a is expected and not found missing a is expected and not found missing in enum definition an enumeration list does not end with a P character missing in struct union definition a structure or union member list does not end with a character redeclared pragma attribute name lt name gt a pragma attribute object is already declared by another pragma attribute directive redeclared argument lt name gt a function argument has conflicting declarations
15. incompatible argument type the actual argument type does not match the corresponding type in the prototype incompatible compare type operands of comparison operators must be of scalar type incompatible operand types the operands of an arithmetic operator are not compatible incompatible pointer assignment assigned pointers must have the same type or one of them must be a pointer to void incompatible pointer operand a scalar type is expected when opera tors and are used on pointers incompatible pointer operation pointers are not allowed for that kind of operation incompatible pointer types the pointers of the assignment operator must be of equal or coercible type incompatible return type the return expression is not compatible with the declared function return type 332 Compiler Error Messages 2012 COSMIC Software Parser cpcorm Error Messages incompatible struct union assignment a structure or an union has been used as operand for an assignment operator and the other operand is not a structure or an union incompatible struct union operation a structure or an union has been used as operand of an arithmetic operator incompatible types in struct union assignment structure or union types must be identical for assignment incomplete elif expression a elif is followed by an incomplete expression incomplete if expression a if is followed by an incomplete expres sion incomplete ty
16. name 264 private 275 public 275 use of private name 290 register variables allocation 362 relative address 302 repeat directive 243 repeatl directive 244 restore directive 246 rexit directive 244 247 ROM 41 rotate vector through angle 88 runtime startup modifying 33 S save directive 248 sbreak function 139 scanf function 140 section bss 19 const 19 data 19 info 184 267 320 text 19 assembler directive 249 curly braces initiliazed data 40 definition 261 name 40 197 parenthesis code 40 pragma definition 40 pragma directive 40 predefinition 197 single 370 square brackets uninitialized data 40 switch to default 41 unused 270 user defined 40 sections default 40 predefined 40 relocation 278 segment debug 296 nfo 296 bsct start address 273 bss start address 273 build new 280 Index 9 control options 266 269 data start address 273 definition 261 fill 269 follow current 269 maximum size 270 name 271 overlap checking 272 278 overlapping 280 overlapping control 272 root 270 round up address 271 section overlap 273 space name 278 start new 269 text start address 273 zero size 265 separated address space 278 set directive 251 set new level 121 setjmp 118 setjmp function 144 share local variable 365 sin function 146 single precision option 281 sinh function 147 software interrupt 46 source files listing 306 source listings 306 space allocate on heap 120 for function 364
17. redeclared enum member lt name gt an enum element is already declared in the same scope redeclared external lt name gt an external object or function has con flicting declarations redeclared local lt name gt a local is already declared in the same scope redeclared proto argument lt name gt an identifier is used more than once in a prototype function declaration redeclared typedef lt name gt a typedef is already declared in the same scope redefined alias lt name gt an alias has been applied to an already declared object redefined label lt name gt a label is defined more than once in a func tion redefined member lt name gt an identifier is used more than once in structure member declaration redefined tag lt name gt a fag is specified more than once in a given scope 340 Compiler Error Messages 2012 COSMIC Software Parser cpcorm Error Messages repeated type specification the same type modifier occurs more than once in a type specification scalar type required type must be integer floating or pointer shift count out of range a constant shift count is larger than the shifted object size strict size unknown an attempt to compute the size of an unknown object has occurred space attribute conflict a space modifier attempts to redefine an already specified modifier space conflict with pragma attribute a space modifier declared with a pragma attribute mismatc
18. ter Default is la V be verbose The name of each module of the application is output to STDOUT lt file gt specifies one file which must be in executable format Return Status clabs returns success if no error messages are printed that is if all reads and writes succeed An error message is output if no relocatable listing files are found Otherwise it returns failure Examples The following command line clabs v acia cxm will output erts 1s acia ls vector 1ls and creates the following files crts la acia la vector la 2012 COSMIC Software Programming Support 315 8 The clabs Utility The following command line clabs r lst acia cxm will look for files with the suffix Ist The following command line clabs s 1x acia cxm will generate crts 1x acia lx vector 1x 316 Programming Support 2012 COSMIC Software The clib Utility The clib Utility clib builds and maintains object module libraries clib can also be used to collect arbitrary files in one place lt ibrary gt is the name of an exist ing library file or in the case of replace or create operations the name of the library to be constructed Command Line Options clib accepts the following command line options each of which is described in detail below clib options lt library gt lt files gt a accept absolute symbols e create a new library d delet
19. 01 return NOTPRIME sq isqrt n for div 3 div lt sq div 2 if n div return NOTPRIME return PRIME See Also Isqrt sqrt Notes isqrt is packaged in the integer library 2012 COSMIC Software Using The Compiler 109 Ei C Library isspace isspace Description Test for whitespace character Syntax include lt ctype h gt int isspace int c Function isspace tests whether c is a whitespace character Whitespace characters are horizontal tab t newline n vertical tab v form feed f carriage return r and space Return Value isspace returns nonzero if c is a whitespace character otherwise the value returned is zero Example To skip leading whitespace while isspace s s See Also iscntrl isgraph isprint ispunct Notes If the argument is outside the range 1 255 the result is undefined isspace is packaged in the integer library 110 Using The Compiler 2012 COSMIC Software C Library isupper isupper Description Test for upper case character Syntax no header file need be included int isupper int c Function isupper tests whether c is an upper case alphabetic character Return Value isupper returns nonzero if c is an upper case character otherwise the value returned is zero Example To convert to lower case if isupper c c a A
20. C Library Support This section describes the facilities provided by the C library The C cross compiler for CORTEX M includes all useful functions for pro grammers writing applications for ROM based systems How C Library Functions are Packaged The functions in the C library are packaged in four separate sub librar ies one for machine dependent routines the machine library one that does not support floating point the integer library and one that pro vides full floating point support the floating point library If your application does not perform floating point calculations you can decrease its size and increase its runtime efficiency by including only the integer library Inserting Assembler Code Directly Assembler instructions can be quoted directly into C source files and entered unchanged into the output assembly stream by use of the _asm function This function is not part of any library as it is recog nized by the compiler itself See Inserting Inline Assembly Instruc tions in Chapter 3 Linking Libraries with Your Program If your application requires floating point support you must specify the floating point library before the integer library in the linker command file Modules common to both libraries will therefore be loaded from the floating point library followed by the appropriate modules from the floating point and integer libraries in that order Integer Library Functions The following table
21. Depending on the context a string constant will be seen either as a series of bytes for a data initialization or as a numeric in which case the string constant should be reduced to only one character hexa de b 012345678 9ABCDEF start cmp r7 A ASCII value of A Expressions An expression consists of a number of labels and constants connected together by operators Expressions are evaluated to 32 bit precision Note that operators have the same precedence than in the C language A special label written is used to represent the current location address Note that when is used as the operand of an instruction it has the value of the program counter before code generation for that instruction The set of accepted operators is addition subtraction negation multiplication division remainder modulus amp bitwise and bitwise or bitwise exclusive or bitwise complement lt lt left shift gt gt right shift equality t difference lt less than lt less than or equal gt greater than gt greater than or equal amp amp logical and II logical or logical complement These operators may be applied to constants without restrictions but are restricted when applied to relocatable labels For those labels the addition and substraction operators only are accepted and only in the following cases label constant 192 Using The Assembler 2012 COSMI
22. _brk initialize on first call _brk heap_start obrk _brk old top _brk size new top if amp heap end lt brk brk lt amp heap start check boundaries _brk obrk restore old top return NULL return NULL pointer return obrk return new area start 54 Programming Environments 2012 COSMIC Software Heap Management Control with the C Compiler Note that it is possible to use this _sbreak function as a malloc equiva lent function with some restrictions The malloc function should be used when the allocated memory has to be released or if the application has no idea about the total amount of space needed If memory can be allocated and never released the free mechanism is not necessary nor the linked list of memory blocks built by malloc In that case simply rename the _sbreak function as malloc regardless of its implementa tion and you will get a very efficient and compact malloc mechanism You may do the renaming in the function itself which needs to be rec ompiled or by using a define at C level or by renaming the function at link time with a def directive such as tpri enter a private region tdef malloc _sbreak defines malloc as _sbreak new close region and forget malloc libi cxm load library containing _sbreak This sequence has to be placed just before loading libraries or before placing the module containing the _sbreak function The
23. a register is expected for this instruction missing string a character string is expected for this directive relocatable expression not allowed a constant is needed section name lt name gt too long a section name has more than 15 characters string constant too long a string constant is longer than 255 charac ters symbol lt name gt already defined attempt to redefine an existing symbol symbol lt name gt not defined a symbol has been used but not declared syntax error an unexpected identifier or operator has been found 346 Compiler Error Messages 2012 COSMIC Software Assembler cacorm Error Messages too many arguments a macro has been invoked with more than 9 arguments too many back tokens an expression is too complex to be evaluated unclosed if an if directive is not ended by an else or endif directive unknown instruction lt name gt an instruction not recognized by the processor has been specified value too large an operand is too large for the instruction type zero divide a divide by zero has been detected 2012 COSMIC Software Compiler Error Messages 347 Linker clnk Error Messages Linker clnk Error Messages a not allowed with b or o the after option cannot be specified if any start address is specified def symbol lt symbol gt multiply defined the symbol defined by a def directive is already defined bad address lt value gt for zero page symbol
24. for variable 364 space name definition 272 spe directive 252 sprintf function 148 sqrt function 149 square root unsigned int compute 109 unsigned long int compute 119 10 Index srand function 150 sscanf function 151 stack amount of memory 295 free space 97 need 295 pointer set 34 standard model 64 standard ANSI libraries 280 static data 304 strcat function 152 strchr function 153 stremp function 154 strcpy function 155 strespn function 156 strlen function 157 strncat function 158 strncmp function 159 strncpy function 160 strpbrk function 161 strrchr function 162 strspn function 163 strstr function 164 strtod function 165 strtol function 166 strtoul function 167 suffix assembly file 60 C file 60 input 315 output 315 suppress pagination 307 switch directive 253 symbol _ eram 34 _ sram 34 __ stack 34 alias 290 define 264 define alias 276 define new 276 definition 276 export 294 initialization image start equal 277 logical end value equal 276 logical start value equal 276 physical end value equal 277 physical start value equal 276 size value equal 277 sort alphabetically 267 sort by address 267 user defined 363 symbol table add 276 information 320 new 289 T tabs directive 254 tan function 168 tanh function 169 task entries 295 title directive 255 tolower function 170 toupper function 171 translate executable images 310 U uninitialized variables 64 unr
25. isprint s putchar s See Also iscntrl isgraph ispunct isspace Notes If the argument is outside the range 1 255 the result is undefined isprint is packaged in the integer library 2012 COSMIC Software Using The Compiler 107 Eg C Library ispunct ispunct Description Test for punctuation character Syntax include lt ctype h gt int ispunct int c Function ispunct tests whether c is a punctuation character Punctuation charac ters include any printing character except space a digit or a letter Return Value ispunct returns nonzero if c is a punctuation character otherwise the value returned is zero Example To collect all punctuation characters in a string into a buffer for i 0 s s if ispunct s buf it s See Also iscntrl isgraph isprint isspace Notes If the argument is outside the range 1 255 the result is undefined ispunct is packaged in the integer library 108 Using The Compiler 2012 COSMIC Software C Library isqrt isqrt Description Integer square root Syntax include lt stdlib h gt unsigned int isqrt unsigned int i Function isqrt obtains the integral square root of the unsigned int i Return Value isgrt returns the closest integer smaller or equal to the square root of i expressed as an unsigned int Example To use isgrt to check whether n gt 2 is a prime number if n amp
26. lt name gt a symbol declared in the zero page is allocated to an address larger than 8 bits bad file format an input file has not an object file format bad number in def the number provided in a def directive does not follow the standard C syntax bad number in spc lt segment gt the number provided in a spc directive does not follow the standard C syntax bad processor type an object file has not the same configuration information than the others bad reloc code an object file contains unexpected relocation informa tion bad section name in def the name specified after the in a def directive is not the name of a segment can t create map file lt file gt map file cannot be created can t create lt file gt output file cannot be created can t locate text segment for initialization initialized data segments have been found but no host segment has been specified can t locate shared segment shared datas have been found but no host segment has been specified can t open file lt file gt input file cannot be found 348 Compiler Error Messages 2012 COSMIC Software Linker clnk Error Messages file already linked an input file has already been processed by the linker function lt function gt is recursive a nostack function has been detected as recursive and cannot be allocated function lt function gt is reentrant a function has been detected as reentrant The
27. the input field consists of all charac ters up to the first character that is not in the set between the brackets if the first character after the left bracket is a circumflex the input field consists of all characters up to the first character that is in the set of the remaining characters between the brackets A NUL character will be appended to the input The conversion characters d i o u and x may be preceded by to indi cate that the subsequent argument is a pointer to long int rather than a pointer to int or by h to indicate that it is a pointer to short int Simi larly the conversion characters e and f may be preceded by I to indicate that the subsequent argument is a pointer to double rather than a pointer to float or by L to indicate a pointer to long double The conversion characters e g or x may be capitalized However the use of upper case has no effect on the conversion process and both upper and lower case input is accepted 142 Using The Compiler 2012 COSMIC Software C Library scanf If conversion terminates on a conflicting input character that character is left unread in the input stream Trailing white space including a newline is left unread unless matched in the control string The success of literal matches and suppressed assignments is not directly determina ble other than via the Yon conversion Return Value scanf returns the number of assigned input items which can be zero if there is an
28. 2012 COSMIC Software Linker Options Segment Control Options Usage cont Option Description n set the output name of the segment to Segment output names have at most 15 characters longer names are trun cated If no name is given with a n option the segment inheritates a default name equal to its assembler section name For example use this option when you want to generate the hex records for a particular PROM such as seg text b0x2000 n promi lt object_files gt seg text b0x4000 n prom2 lt object_files gt You can generate the hex records for prom1 by typing chex n promi file cxm For more information see The chex Utility in Chapter 8 0 set the logical start address of the segment to if b option is specified or the logical end address if e option is speci fied The default is to set the logical address equal to the physical address Options b and e cannot be specified both if o has been specified q enable a manual initialization mechanism by specifying a name of an empty segment which will host the initialization image of the current segment See Manual Segment Ini tialization on page 286 r round up the starting address of the segment and all the loaded sections The expression defines the power of two of the alignment value The option r3 will align the start address to an 8 bytes boundary This option has no effect if the st
29. CORTEX M Machine Library describes the assembly language routines that provide support for the C runtime library Appendix D Compiler Passes describes the specifics of the parser code generator and assembly language optimizer and the command line options that each accepts This manual also contains an Index 2012 COSMIC Software CHAPTER 1 Introduction This chapter explains how the compiler operates It also provides a basic understanding of the compiler architecture This chapter includes the following sections Introduction Document Conventions Compiler Architecture Predefined Symbol Linking Programming Support Utilities Listings Optimizations 2012 COSMIC Software Introduction 3 Introduction Introduction The C cross compiler targeting the CORTEX M microcontroller reads C source files assembly language source files and object code files and produces an executable file You can request listings that show your C source interspersed with the assembly language code and object code that the compiler generates You can also request that the compiler gen erate an object module that contains debugging information that can be used by COSMIC s C source level cross debugger or by other debug gers or in circuit emulators You begin compilation by invoking the cxcorm compiler driver with the specific options you need and the files to be compiled Document Conventions In
30. Index __ckdesc__ 1 287 _ eram symbol 21 __idesc__ 283 284 __ memory symbol 21 51 __sdata symbol 21 __sram symbol 21 _ stack symbol 21 _asm argument string size 44 assembly sequence 44 code optimization 369 in expression 45 return type 45 _asm function 72 inserting assembler function 68 _checksum function 84 _checksum 16 function 86 _checksum 16x function 87 _checksumx function 85 _fetcpy function 94 _Fract argument 133 _ sbreak function 51 Numerics 32 bits float 363 8 bit precision operation 11 A abort function 73 Index 1 abs function 74 absolute address 302 address in listing 314 full path name 366 hex file generator 9 listing file 314 listing utility 10 map section 182 path name 366 referencing address 41 section 240 249 section relocation 278 symbol 272 symbol in library 317 symbol table 267 symbol tables 294 symbol flagged 294 acos function 75 address default format 311 315 logical end 271 logical start segment 278 logical start set 271 paged format 311 315 physical 271 physical end 269 physical start 269 physical start segment 278 set logical 271 align directive 200 application embedded 262 non banked 312 system bootstrap 262 asin function 76 assembler branch shortening 198 C style directives 199 code inline 44 conditional directive 196 create listing file 183 2 Index endm directive 193 environment symbol 198 expression 192 filling byte 183 include directive
31. The Assembler 199 Assembler Directives align align Description Align the next instruction on a given boundary Syntax align lt expression gt lt fill_value gt Function The align directive forces the next instruction to start on a specific boundary The align directive is followed by a constant expression which must be positive The next instruction will start at the next address which is a multiple of the specified value If bytes are added in the section they are set to the value of the filling byte defined by the f option If lt fill_value gt is specified it will be used locally as the filling byte instead of the one specified by the f option Example align 3 next address is multiple of 3 ds b 1 See Also even 200 Using The Assembler 2012 COSMIC Software Assembler Directives base base Description Define the default base for numerical constants Syntax base lt expression gt Function The base directive sets the default base for numerical constants begin ning with a digit The base directive is followed by a constant expres sion which value must be one of 2 8 10 or 16 The decimal base is used by default When another base is selected it is no more possible to enter decimal constants Example base 8 7 select octal base mov r0 377 load SFF 2012 COSMIC Software Using The Assembler 201 Assembler Directives clist clist Description Turn
32. a section directive is not needed before to use them 2012 COSMIC Software Using The Assembler 197 Branch Optimization Section Description text executable code data initialized data bss uninitialized data Includes The include directive specifies a file to be included and assembled in place of the include directive The file name is written between double quotes and may be any character string describing a file on the host system If the file cannot be found using the given name it is searched from all the include paths defined by the i options on the command line and from the paths defined by the environment symbol CXLIB if such a symbol has been defined before the assembler invocation This symbol may contain several paths separated by the usual path separator of the host operating system for MSDOS and for UNIX The h option can specify a file to be included The file specified will be included as if the program had an include directive at its very top The specified file will be included before any source file specified on the command line Branch Optimization Branch instructions are by default automatically optimized to produce the shortest code possible This behaviour may be disabled by the b option This optimization operates on conditional branches on jumps and jumps to subroutine Old Syntax The m option allows the assembler to accept old constructs whic
33. accept a character string and may be repeated 0 accept a character string p simply a flag indicator pl accept a long integer value pn simply a flag indicator pp simply a flag indicator S simply a flag indicator W simply a flag indicator X accept a character string and may be repeated Compiler Architecture The C compiler consists of several programs that work together to translate your C source files to executable files and listings cxcorm controls the operation of these programs automatically using the options you specify and runs the programs described below in the order listed cpcorm the C preprocessor and language parser cpcorm expands directives in your C source and parses the resulting text 8 Introduction 2012 COSMIC Software Predefined Symbol cgcorm the code generator cgcorm accepts the output of cpcorm and generates assembly language statements cocorm the assembly language optimizer cocorm optimizes the assembly language code that cgcorm generates cacorm the assembler cacorm converts the assembly language out put of cocorm to a relocatable object module Predefined Symbol The COSMIC compiler defines the _ CSMC__ preprocessor symbol It expands to a numerical value whose each bit indicates if a specific option has been activated bit 2 set if unsigned char option specified pu bit 4 set if reverse bitfield option specified rev bit 5 set if no enu
34. add end r1 1 vl 2 vl 3 r r r add to register add to register add to register Using The Assembler 245 Assembler Directives restore restore Description Restore saved section Syntax restore Function The restore directive is used to restore the last saved section This is equivalent to a switch to the saved section Example switch bss var ds b var2 ds b save switch functionl 10S adds beq str function2 10 add subs bne bx restore var3 ds b var4 ds b switch add str end See Also save section 246 Using The Assembler text a E a 10 rl r9 var2 r1 r2 rl 2 10 ee text r1 3 ri r9 var4 2012 COSMIC Software Assembler Directives rexit rexit Description Terminate a repeat definition Syntax rexit Function The rexit directive is used to exit from a repeat definition before the endr directive is reached rexit is usually placed after a conditional assembly directive Example shift a value n times asln macro repeat 1 if l rexit endif slwi ri 1 endr endm 7 use of above macro asln 5 See Also endr repeat repeatl 2012 COSMIC Software Using The Assembler 247 Assembler Directives save save Description Save section Syntax save Function The save directive is used to save the current section so it may be restored later in the source file Exam
35. also see tolower See Also isalnum isalpha isdigit islower isxdigit tolower toupper Notes If the argument is outside the range 1 255 the result is undefined isupper is packaged in the integer library 2012 COSMIC Software Using The Compiler 111 Ei C Library isxdigit isxdigit Description Test for hexadecimal digit Syntax include lt ctype h gt int isxdigit int c Function isxdigit tests whether c is a hexadecimal digit ie in the set 0123456789abcdefA BCDEF Return Value isxdigit returns nonzero if c is a hexadecimal digit otherwise the value returned is zero Example To accumulate a hexadecimal digit for sum 0 isxdigit s s if isdigit s sum sum 10 s O else sum sum 10 tolower s 10 a See Also isalnum isalpha isdigit islower isupper tolower toupper Notes If the argument is outside the range 1 255 the result is undefined isxdigit is packaged in the integer library 112 Using The Compiler 2012 COSMIC Software C Library labs labs Description Find long absolute value Syntax include lt stdlib h gt long labs long 1 Function labs obtains the absolute value of No check is made to see that the result can be properly represented Return Value labs returns the absolute value of expressed as an long int Example To print out a debit or credit balance printf bala
36. case the compiler will use only default options to compile and 60 Using The Compiler 2012 COSMIC Software Invoking the Compiler assemble your program You can change the operation of the compiler by specifying the options you want when you run the compiler To specify options to the compiler type the appropriate option or options on the command line as shown in the first example above Options should be separated with spaces You must include the or that is part of the option name Compiler Command Line Options The excorm compiler accepts the following command line options each of which is described in detail below a gt ce cl co d gt e ec eg es ex cxcorm options lt files gt assembler options path for errors path for listings path for objects define symbol create error file all C files eclipse error messages all assembler files prefix executables configuration file code generator options path for include create listing do not use optimizer optimizer options parser options create only assembler file create only dependencies create only preprocessor file path for temporary files verbose do not execute select compiler options 2012 COSMIC Software Using The Compiler 61 Eg Invoking the Compiler Cxcorm Option Usage Option Description a gt specify assembler options Up to 128 options can be speci fied on the sam
37. cccccesessssseesceeceeceeceseesenseeeeeseeseess Allocate constant block 0 eeeeeeeeeeeeeeeee Turn listing of debug directives on or off Allocate variable s cecceceseseeteeteeteeeeee Conditional assembly c cccceeceeseeseeeceeceeceeceeeeeeeaeenes Conditional assembly cccceeseeeeseesceeceeceeceteeteeseeaeenee Stop the assembly End conditional assembly End conditional assembly End macro definition sissies inas End repeat Section cccceesescescesceeceseeseeseesecsecsecaeeneeaeens Give a permanent value to a symbol ceeeeeeeeeeeeee Assemble next byte at the next even address relative to the Start ofa Sectio cis sacri sci secedssidesananescods ses dedeversasutesedeseneisene 215 Generate error MESSAGE cceesesseeseeseeseeseeseeseeseeteteeeeeteees 216 Conditional assembly cccccceeseseeseeeceeceeceeceseeeeeeaeenes 217 Conditional assembly 0 cc ceceeeceeeseesceeseeeeeeeeerseeeeeaees 218 Conditional assembly c cccceeseeseeseesceeceeceeceseeeeeeseenes 219 Conditional assembly 0 00 0 ccccceseeeeseesceeceecesceeeeeeeaeenee 220 Conditional assembly cccccesceeeseesceeceeceeceteeteeeeaeenes 221 Conditional assembly cccceeceeesecseeseeseeneeeeeeeeeeeeeees 222 Conditional assembly ccscceecsecseceseseeseeneeseeeeeeeeeeees 223 Conditional assembly c escceseseeseeseesteseeneeeee
38. compiler pass 369 error log file 370 code optimizer compiler pass 372 code data no output 269 compiler ANSI checking 365 assembler 9 assembler options specification 62 C preprocessor and language parser 8 code generator 9 code generator option specification 62 code optimization 10 code optimizer 9 combination of options 354 command line options 60 configuration file 352 configuration file specification 62 configuration file predefined option 63 create assembler file only 63 debug information produce 64 default behavior 60 default configuration file 62 default operations 359 default options 60 352 driver 4 error files path specification 62 error message 60 exclusive options 354 flags 6 force single precision 65 generate error 327 generate error file 67 generate listing 67 include path definition 63 invoke 60 Index 3 listing file 63 listing file path specification 62 log error file 62 name 60 object file path specification 62 optimizer option specification 63 options 60 options request 60 parser option specification 63 predefined option selection 63 preprocessed file only 63 produce assembly file 17 programmable option 352 354 specific options 4 specify options 61 temporary files path 63 type checking 65 362 user defined preprocessor symbol 62 verbose mode 18 63 const data 37 qualifier 37 constant numeric 191 prefix character 191 string 191 string character 191 suffix character 191 constants unlimi
39. d b string text given as first operand endm endm mexit 2012 COSMIC Software Using The Assembler 233 Assembler Directives messg messg Description Send a message out to STDOUT Syntax messg lt text gt messg lt text gt Function The messg directive is used to send a message out to the host system s standard output STDOUT Example messg Test code for debug mov rl 2 strb rl r2 See Also title 234 Using The Assembler 2012 COSMIC Software Assembler Directives mexit mexit Description Terminate a macro definition Syntax mexit Function The mexit directive is used to exit from a macro definition before the endm directive is reached mexit is usually placed after a conditional assembly directive Example ctrace macro if tflag mexit endif bl 1 endm See Also endm macro 2012 COSMIC Software Using The Assembler 235 Assembler Directives mlist mlist Description Turn on or off listing of macro expansion Syntax mlist on off Function The mlist directive controls the parts of the program which will be writ ten to the listing file produced by a macro expansion It is effective if and only if listings are requested it is ignored otherwise The parts of the program to be listed are the lines which are assembled in a macro expansion See Also macro 236 Using The Assembler 2012 COSMIC S
40. data that is explicitly initialized to a non zero value char varl 25 which is generated into the data section and 2 data that is explicitly initialized to zero or left uninitialized char var2 which is generated into the bss section The first method to ensure that these values are correct consists in add ing code in your application that reinitializes them from a copy that you have created and located in ROM at each restart of the application The second method is to use the crtsi cxm start up file 1 that defines a symbol that will force the linker to create a copy of the initialized RAM in ROM 2 and that will do the copy from ROM to RAM The following link file demonstrates how to achieve automatic data ini tialization seg sconst b 0x2000 n sconst program start address seg text a const n text constant follow code 24 Tutorial Introduction 2012 COSMIC Software Generating Automatic Data Initialization seg data b0x20000000 crtsi cxm acia o modulel o libis cxm libm cxm def _ memory bss tdef stack 0x20010000 o 0x0 Se SH OSH E SHE SHE 000 data start address startup with auto init main program module program C library if needed machine library symbol used by library stack pointer initial value In the above example the text segment is located at address 0x2000 the data segment is located at address 0x20000000 immediately fol lowed by the bss segment th
41. de b 1 2 3 4 2012 COSMIC Software Using The Assembler 195 Assembly Language Syntax When invoking the macro table w will generate a table of word dc w 1 2 374 The directive mexit may be used at any time to stop the macro expan sion It is generally used in conjunction with a conditional directive A macro call may be used within another macro definition A macro definition cannot contain another macro definition If a listing is produced the macro expansion lines are printed if enabled by the mlist directive If enabled the invocation line is not printed and all the expanded lines are printed with all the parameters replaced by their corresponding arguments Otherwise the invocation line only is printed Conditional Directives A conditional directive allows parts of the program to be assembled or not depending on a specific condition expressed in an if directive The condition is an expression following the if command The expression cannot be relocatable and shall evaluate to a numeric result If the con dition is false expression evaluated to zero the lines following the if directive are skipped until an endif or else directive Otherwise the lines are normally assembled If an else directive is encountered the condition status is reversed and the conditional process continues until the next endif directive if debug add r0 r9 message bl print endif If the symbol debug is equal to 1 the nex
42. def _ramcode start ramcode tdef _image start image tdef _isize size image The linker symbol assignments are treated like addresses so the copy code would be the following extern char ramcode image isize memcpy amp ramcode amp image unsigned int amp isize 286 Using The Linker 2012 COSMIC Software Checksum Computation Checksum Computation This feature is activated by the detection of the symbol __ckdesc___ as an undefined symbol This is practically done by calling one of the pro vided checksum functions which uses that symbol and returns 0 if the checksum is correct These functions are provided in the integer library and are the following _checksum check a 8 bit checksum stored once for all the selected segments _checksumx check a 8 bit checksum stored for every selected segments This method allows a seg ment to be dynamically reloaded by updating the corresponding CRC byte _checksum16 check a 16 bit checksum stored once for all the selected segments _checksum16x check a 16 bit checksum stored for every selected segments This method allows a seg ment to be dynamically reloaded by updating the corresponding CRC word You then have to update the link command file in two ways 1 Mark the segments usually code segments you want to check by using the ck option on the seg line Note that you need only to mark the first segment of a hooked list mea
43. e integers longs floats and pointers are passed in registers r0 to r3 in that order from the leftmost argument if these registers are not already used by some other arguments e doubles are passed in register pairs r0 r1 to r2 r3 in that order from the leftmost argument if these registers are not already used by some other arguments Therefore a function called as func char argl long arg2 int arg3 will pass argument arg in register r0 argument arg in register rl and argument arg3 in register r2 As soon as an argument does not match these compatible types a struc ture for instance or if no register is available for the argument type this argument and those specified after it are passed onto the stack Except for returned value the registers r0 r3 and the conditions codes are undefined on return from a function call All other registers are pre served The returned value is in r0 char or short widened to int int long float pointer or r0 r1 double 2012 COSMIC Software Programming Environments 49 Register Usage Register Usage Stack frames are maintained by each C function using sp as a frame pointer On entry to a function the instruction sub sp lt n gt will reserve lt n gt bytes for automatics Control is returned via bx lr or a pop instruction including pe The r9 register is used as a base for data Registers r0 to r3 are used for argument passing return values and code gen
44. early conflict between an input character and the format or EOF if end of file is encountered before the first conflict or conversion Example To be certain of a dubious request printf are you sure if scanf c amp ans amp amp ans Y ans y scrog See Also sscanf Notes scanf is packaged in both the integer library and the floating point library The functionality of the integer only version of scanf is a subset of the functionality of the floating point version The integer only ver sion cannot read or manipulate floating point numbers If your pro grams call the integer only version of scanf the following conversion specifiers are invalid e f g and p The L flag is also invalid If an invalid conversion specifier is encountered it is ignored 2012 COSMIC Software Using The Compiler 143 Ei C Library setjmp setjmp Description Save calling environment Syntax include lt setjmp h gt int setjmp jmp_buf env Function setjmp saves the calling environment in env for later use by the longjmp function Since setjmp manipulates the stack it should never be used except as the single operand in a switch statement Return Value setjmp returns zero on its initial call or the argument to a longjmp call that uses the same env Example To call any event until it returns 0 or 1 and calls Jongjmp which will then start execution at the function event0 or even
45. eececeesesesseeseeseeseeeeeseeeeeeeeeees Convert buffer to unsigned long cceccseeseeseeseereeeeeees Tan ente eee EE REEE EENES Hyperbolic tangent 0 0 cceccseeseeseeseeeeeeeeees Convert character to lower case if necessary Convert character to upper case if necessary a Get pointer to next argument in Hist eee eere Stop accessing values in an argument list 0 0 eee Start accessing values in an argument list eee Output arguments formatted to stdout eects Output arguments formatted to buffer eee Chapter 5 Invoking cacorm 182 Object File DASE OS RENEE ERE EESE 186 Assembly Language Syntax cccceseseseeseseeeseesceneeseeeeeeeeess 187 Instructions ccceceeceees Labels cceeeeeee Temporary Labels Label Extensions cccccccecsscescesseceecesseeseseseeneeeeeesaeeees Constants ooa evento Meds ie sade see OTEA Expressions Macro Instructions Conditional Directives ccccccccscescessesseecsecsseeessenseeeees LEAS E E A A tess eludes siraan ask EE EEEIEE E Branch Optimization Old S yintaxes cists cieciscadcactset acta cisbelsdhalonnnecaeaeidataa a C Style Directives 00 ecceccescesessesceeeesecesceeceeceseeeeseteceeceeeees Assembler Directives cccccccsssssecsecsseesseeneeeseeeeeees Align the next instruction on a given boundary Define the default base for numerical constants Allocate constant S
46. equ directive 214 251 error assembler log file 183 file name 67 log file 267 message 10 message list 327 multiply defined symbol 189 293 undefined symbol 289 undefined symbol in listing 184 even directive 215 executable image 310 exit function 91 exp function 92 expression evaluation 193 high 193 low 193 page 193 relocatable 193 F fabs function 93 fail directive 216 file length restriction 302 file names 66 filling byte 200 206 215 240 float sprec option 281 calculation 363 single precision library 281 floating point library 68 Floating Point Library Functions 69 floor function 95 fmod function 96 format argument output to buffer 148 argument output to buffer 178 179 arguments output 130 ELF DWAREF 322 read input 140 read input from string 151 string conversion specifications 130 format description 140 free function 97 Freescale syntax 187 frexp function 98 function arguments 304 enforce prototype declaration 64 365 Index 5 in separate section 64 prototype declaration 64 365 recursive 295 returning int 71 suppress 370 suppress unused 64 function arguments 304 G generate bss section 48 const section 48 data section 48 Sbss section 48 sconst section 48 sdata section 48 text section 48 hex record 271 listing file 185 object file 185 getchar function 99 gets function 100 group option 264 H header files 70 heap allocate space 82 control 51 free space 97 location 5
47. for upper case character ccccecsescecesceecesceseeteeees 111 Test for hexadecimal digit Find long absolute value 113 Scale double exponent cceccseeseeseereee 114 Long divide with quotient and remainder ce ee 115 Natural logarithm ccccececsecsecsecneeeeeeeeeeeeeeeseeeeeeeeeeesees Common logarithm cccccsecscesseseeeeeeeeeeeeeceeceeceeceaeeaeenes Restore calling environmMent cceceseeseeteeseeteceeeeeneeee Long integer square root Allocate space on the heap Test for maximum x Scan buffer for character ceeesceessseeceseeceeseeeeeeerees Compare two buffers for lexical order eceeeeeeeeee 123 Copy one buffer to another ceeceeeecesceeceeceeceseeteeseenes 124 Copy one buffer to another cececeeeceeceeceeceteeteeeenes 125 Propagate fill character throughout buffer 00 126 Test fot MINIMUM coat vaes Sasess tasveseiencieistad scoatesenecte ne ceeees 127 iv Extract fraction and integer from double cee 128 Raise x to the y DOWEL cceecescescesceeeeeeeeeeeeceeceeceseeaeeaeenes 129 Output formatted arguments to stdout cece 130 Put a character to output stream eceeeeecesceeceseeeeeeeees 135 Put a text line to output stream ceeeeececeeceseeeeeeeeees 136 Generate pseudo random number a137 Reallocate space on the heap 138 Allocate new memory
48. line option 2 the two options d and d 2 are defined If the option dl1 is specified on the compiler command line the specific option l will be used for the parser and the specific option dl1 will be used for the code generator No specific option will be used for the optimizer and for the assembler The option d is also declared to be exclusive with the option d 2 meaning that d and dl2 will not be allowed together on the compiler command line The option d 2 is defined in the same way 354 Modifying Compiler Operation 2012 COSMIC Software Example Example The following command line cxcorm nobss hello c in combination with the previous configuration file directs the excorm compiler to execute the following commands cpcorm o 2 cxl u m0x3030 i cosmic hcorm hello c egcorm o 2 cx2 bss 2 cxl cocorm o 2 cxl 2 cx2 cacorm o hello o i cosmic hcorm 2 cx1 2012 COSMIC Software Modifying Compiler Operation 355 APPENDIX C CORTEX M Machine Library This appendix describes each of the functions in the Machine Library libm These functions provide the interface between the CORTEX M microcomputer hardware and the functions required by the code gener ator They are described in reference form and listed alphabetically Function Listing c_dadd c_dcmp c ddiv c_dmul c_dneg c_dsub c_dtof c_dtol c fadd c_fcmp c fdiv c_fmul c_fneg c_fsub double add
49. listing of conditionally excluded code on or off Syntax clist on off Function The clist directive controls the output in the listing file of conditionally excluded code It is effective if and only if listings are requested it is ignored otherwise The parts of the program to be listed are the program lines which are not assembled as a consequence of if else and endif directives See Also if else endif 202 Using The Assembler 2012 COSMIC Software Assembler Directives dc dc Description Allocate constant s Syntax dc size lt expression gt lt expression gt Function The de directive allocates and initializes storage for constants If lt expression gt is a string constant one byte is allocated for each charac ter of the string Initialization can be specified for each item by giving a series of values separated by commas or by using a repeat count The de and de b directives will allocate one byte per lt expression gt The de w directive will allocate one word per lt expression gt The de directive will allocate one long word per lt expression gt Example digit dc b 10 10123456789 dc w digit Note For compatibility with previous assemblers the directive feb is alias to de b and the directive fdb is alias to de w 2012 COSMIC Software Using The Assembler 203 Assembler Directives dcb dcb Description Allocate constant block Syntax
50. logic chooses the smallest possible jump branch instructions Jumps to jumps and jumps over jumps are eliminated as well e Integer and float constant expressions are folded at compile time e Redundant load and store operations are removed e enum is large enough to represent all of its declared values each of which is given a name The names of enum values occupy the same space as type definitions functions and object names The compiler provides the ability to declare an enum using the small est type char int or long e The compiler performs multiplication by powers of two as faster shift instructions e An optimized switch statement produces combinations of tests and branches jump tables for closely spaced case labels a scan table for a small group of loosely spaced case labels or a sorted table for an efficient search e The functions in the C library are packaged in three separate libraries one of them is built without floating point support If your application does not perform floating point calculations you can decrease its size and increase its runtime efficiency by linking with the non floating point version of the modules needed For information on using the compiler see Chapter 4 For information on using the assembler see Chapter 5 For information on using the linker see Chapter 6 For information on debugging support see Chapter 7 For information on using the programming utilities see Chapter 8 For in
51. looks like new lt public files gt pri lt private libraries gt Any symbols defined in lt public files gt are known outside this private name region Any symbols defined in lt private libraries gt are known only within this region hence they may safely be redefined as private to other regions as well NOTE All symbols defined in a private region are local symbols and will not appear in the symbol table of the output file Renaming Symbols At times it may be desirable to provide a symbol with an alias and to hide the original name i e to prevent its definition from being used by the linker as a DEF which satisfies REFs to that symbol name As an 290 Using The Linker 2012 COSMIC Software Special Topics example suppose that the function func in the C library provided with the compiler does not do everything that is desired of it for some special application There are three methods of handling this situation we will ignore the alternative of trying to live with the existing function s defi ciencies The first method is to write a new version of the function that performs as required and link it into the program being built before linking in the libraries This will cause the new definition of func to satisfy any refer ences to that function so the linker does not include the version from the library because it is not needed This method has two major draw backs first a new function must b
52. lt files gt The files in lt files gt not present in the library are added to it S list the symbols defined in the library with the module name to which they belong t list the files in the library V be verbose X extract the files in lt files gt that are present in the library into discrete files with the same names If no lt files gt are speci fied all files in the library are extracted At most one of the options c r t x may be specified at the same time If none of these is specified the t option is assumed Return Status clib returns success if no problems are encountered Otherwise it returns failure After most failures an error message is printed to STDERR and the library file is not modified Output from the t s options and verbose remarks are written to STDOUT Examples To build a library and check its contents clib c libc one o two o three o clib t libc will output 318 Programming Support 2012 COSMIC Software The clib Utility one o two o three o To build a library from a list file clib ci list libc six o seven o where ist contains files for the libc library one o two o three o four o five o 2012 COSMIC Software Programming Support 319 8 The cobj Utility The cobj Utility You use cobj to inspect relocatable object files or executable Such files may have been output by the assembler or by the linker co
53. lt stdarg h gt header file You can use it with any function that accepts a variable number of arguments by including lt stdarg h gt with your program 2012 COSMIC Software Using The Compiler 177 Ej C Library vprintf vprintf Description Output arguments formatted to stdout Syntax include lt stdio h gt include lt stdarg h gt int vprintf char s char fmt va_list ap Function vprintf writes formatted to the output stream using the format string at fmt and the arguments specified by pointer ap in exactly the same way as printf See the description of the printf function for information on the format conversion specifiers The va_start macro must be executed before to call the vprintf function vprintf uses putchar to output each character Return Value vprintf returns the numbers of characters transmitted Example To format a double at d into buf va_start aptr fmt vprintf fmt aptr See Also printf vsprintf Notes vprintf is packaged in both the integer library and the floating point library The functionality of the integer only version of vprintf is a sub set of the functionality of the floating point version The integer only version cannot print floating point numbers If your programs call the integer only version of vprintf the following conversion specifiers are invalid e E f g and G The L flag is also invalid 178 Using The Compiler 2012 COSMIC Software C Libr
54. option should be used carefully as such conversions are truncating addresses 364 Compiler Passes 2012 COSMIC Software The cpcorm Parser Parser Option Usage cont Option Description NS do not share independent local variables By default the compiler tries to overlay variables in the same memory location or register if they are not used concurrently 0 write the output to the file Default is STDOUT for output if e is specified Otherwise an output file name is required p enforce prototype declaration for functions An error mes sage is issued if a function is used and no prototype decla ration is found for it By default the compiler accepts both syntaxes without any error rb reverse the bitfield fill order By default bitfields are filled from less significant bit LSB to most significant bit MSB If this option is specified filling works from most significant bit to less significant bit rr reduce the number of register variables in order to fit with the MO accessible register set S do not reorder local variables By default the compiler sorts the local variables of a function in order to allocate the most used variables as close as possible to the frame pointer This allows to use the shortest addressing modes for the most used variables sa enforce a strict ANSI checking by rejecting any syntax or semantic extension This option also disables the enum size op
55. parenthesis indicating a code section name square brackets indicating uninitialized data name curly braces indicating initialized data A section name is a plain C identifier which does not begin with a dot character and which is no longer than 13 characters The compiler will prefix automatically the section name with a dot character when passing this information to the assembler It is possible to switch back to the default sections by omitting the section name in the lt qualified_name gt sequence Each pragma directive starts redirecting the selected component from the next declarations Redefining the bss section forces the compiler to produce the memory definitions for all the previous bss declarations before to switch to the new section 40 Programming Environments 2012 COSMIC Software Referencing Absolute Addresses The following directives pragma section code pragma section const string pragma section udata pragma section idata redefine the default sections or the previous one as following executable code is redirected to section code strings and constants are redirected to section string uninitialized variables are redirected to section udata initialized data are redirected to section idata Note that name and name are equivalent for constant section as it is considered as initialized The following directive pragma section switches back t
56. s2 Function stremp compares two text strings character by character for lexical order in the character collating sequence The first string starts at s the second at s2 The strings must match including their terminating NUL characters in order for them to be equal Return Value strcmp returns an integer greater than equal to or less than zero according to whether s is lexicographically greater than equal to or less than s2 Example To look for the string include if strcmp buf include 0 doinclude See Also memcmp strncmp Notes strcmp is packaged in the integer library 154 Using The Compiler 2012 COSMIC Software C Library strcpy strcpy Description Copy one string to another Syntax include lt string h gt char strcpy char s1 char s2 Function strcpy copies the NUL terminated string at s2 to the buffer pointed at by s1 The terminating NUL is also copied Return Value strcpy returns s1 Example To make a copy of the string s2 in dest strcpy dest s2 See Also memcpy strncpy Notes There is no way to specify the size of the destination area to prevent storage overwrites strcpy is implemented as a builtin function 2012 COSMIC Software Using The Compiler 155 Ei C Library strcspn strcspn Description Find the end of a span of characters in a set Syntax include lt string h gt unsigned int strcs
57. sets of libraries When using a memory model the application must be linked with the matching libraries The following table lists the memory models with their default setting Model Target Data Constants Floating Point mods M3 M4 4K r9 64K Libraries modsc M3 M4_ 4K r9 Unlimited Libraries modl M3 M4 Unlimited 64K Libraries modic M3 M4 Unlimited Unlimited Libraries mod0 MO Unlimited Unlimited Libraries 2012 COSMIC Software Programming Environments 31 When externing a variable which is accessed by a base pointer it is nec essary to properly specify if the variable is const or not otherwise the access may be implemented using the wrong base register When such information is not available it is always possible to extern the object with the ext extension forcing an extended 32 bit access When using a model with unlimited size for data and constants the code is larger and less efficient It is then more interesting when data or constants are exceeding the 64K efficient size to select the closest effi cient model and to explicitly declare with the ext modifier enough objects to obtain a set of efficient objects which can be located inside the based area and a set of less efficient objects allocated anywhere 32 Programming Environments 2012 COSMIC Software Modifying the Runtime Startup Modifying the Runtime Startup The runtime startup module perfor
58. signal handlers The compiler will not opti mize references to volatile data An expression that stores a value in a data object of volatile type stores the value immediately An expression that accesses a value in a data object of volatile type obtains the stored value for each access Your program will not reuse the value accessed earlier from a data object of volatile type NOTE The volatile keyword must be used for any data object variables that can be modified outside of the normal flow of the function Without the volatile keyword all data objects are subject to normal redundant code removal optimizations Volatile MUST be used for the following condi tions All data objects or variables associated with a memory mapped hard ware register e g volatile unsigned short SCRO 0xf352 All global variable that can be modified written to by an interrupt serv ice routine either directly or indirectly e g a global variable used as a counter in an interrupt service routine You use const to declare data objects whose stored values you do not intend to alter during execution of your program You can therefore place data objects of const type in ROM or in write protected program segments The cross compiler generates an error message if it encoun ters an expression that alters the value stored in a const data object 2012 COSMIC Software Programming Environments 37 The const and volatile Type Qualifiers If you decl
59. strspn returns the lowest possible value of i s1 i designates the termi nating null character if all of the characters in s1 are in s2 Example To check a string for characters other than decimal digits if str strspn str 0123456789 printf invalid number n See Also memchr strcspn strchr strpbrk strrchr Notes strspn is packaged in the integer library 2012 COSMIC Software Using The Compiler 163 Description Scan string for first occurrence of string Syntax include lt string h gt char strstr char s1 char s2 Function strstr looks for the first occurrence of a specific string s2 not including its terminating NUL in a NUL terminated target string s Return Value strstr returns a pointer to the first character that matches c or NULL if none does Example To look for a keyword in a string if t strstr buf LIST do_list t See Also memchr strcspn strpbrk strrchr strspn Notes strstr is packaged in the integer library 164 Using The Compiler 2012 COSMIC Software C Library strtod strtod Description Convert buffer to double Syntax include lt stdlib h gt double strtod char nptr char endptr Function strtod converts the string at nptr into a double The string is taken as the text representation of a decimal number with an optional fraction and exponent Leading whitespace is skipped and an optional sign
60. the I option Command Line Options clabs accepts the following command line options each of which is described in detail below clabs options file a process also library files zel listings files al restrict to local directory p use paged address format pn use paged address in bank only pp use paged address with mapping Sete relocatable listing suffix ihe absolute listing suffix v echo processed file names Clabs Option Usage Option Description a process also files located in libraries Default is to process only all the files of the application cl specify a path for the listing files By default listings are cre ated in the same directory than the source files l process files in the current directory only Default is to proc ess all the files of the application 314 Programming Support 2012 COSMIC Software The clabs Utility Clabs Option Usage cont Option Description p output addresses of banked segments using a paged for mat lt page_number gt lt logical_address gt instead of the default format lt physical gt pn behaves as p but only when logical address is inside the banked area pp behaves as p but uses paged addresses for all banked segments mapped or unmapped r specify the input suffix including or not the dot character Default is Is s specify the output suffix including or not the dot charac
61. the hyperbolic cosine of x to full double precision Return Value cosh returns the nearest internal representation to cosh x expressed as a double floating value If the result is too large to be properly repre sented cosh returns zero Example To use the Moivre s theorem to compute cosh x sinh x to the nth power demoivre cosh n x sinh n x See Also exp sinh tanh Notes cosh is packaged in the floating point library 2012 COSMIC Software Using The Compiler 89 90 Ei C Library div div Description Divide with quotient and remainder Syntax include lt stdlib h gt div_t div int numer int denom Function div divides the integer numer by the integer denom and returns the quo tient and the remainder in a structure of type div_t The field quot con tains the quotient and the field rem contains the remainder Return Value div returns a structure of type div_t containing both quotient and remainder Example To get minutes and seconds from a delay in seconds div_t result result div time 60 min result quot sec result rem See Also ldiv Notes div is packaged in the integer library Using The Compiler 2012 COSMIC Software C Library exit exit Description Exit program execution Syntax include lt stdlib h gt void exit int status Function exit stops the execution of a program by switching to the startup mod ule just
62. the magnitude to be printed is greater than or equal to 1E 100 addi tional exponent digits will be printed as necessary f the double argument is converted to decimal notation in the style ddd ddd where the number of digits following the decimal point is 132 Using The Compiler 2012 COSMIC Software C Library printf equal to the precision specification If the precision is missing it is taken as 6 If the precision is explicitly zero no decimal point appears If a decimal point appears at least one digit appears before it g G the double argument is printed in style f or e or in style E in the case of a G format code with the precision specifying the number of significant digits The style used depends on the value converted style e will be used only if the exponent resulting from the conversion is less than 4 or greater than the precision Trailing zeros are removed from the result a decimal point appears only if it is followed by a digit n the argument is taken to be an int pointer to an integer into which is written the number of characters written to the output stream so far by this call to printf No argument is converted p the argument is taken to be a void pointer to an object The value of the pointer is converted to a sequence of printable characters and printed as a hexadecimal number with the number of digits printed being determined by the field width r the _Fract argument is converted
63. the point For g and G conversions trailing zeros will not be removed from the result as they normally are For p conversion it designates hexadecimal output result of signed conversion will begin with a plus or minus sign result of conversion will be left justified within the field The lt conversion character gt is one of the following a is printed No argument is converted c the least significant byte of the int argument is converted to a char acter and printed d i 0 u X X the int argument is converted to signed decimal d or i unsigned octal 0 unsigned decimal u or unsigned hexadecimal notation x or X the letters abedef are used for x conversion and the letters ABCDEF are used for X conversion The precision specifies the minimum number of digits to appear if the value being converted can be represented in fewer digits it will be expanded with leading zeros The default precision is 1 The result of converting a zero value with precision of zero is no characters e E the double argument is converted in the style d ddde dd where there is one digit before the decimal point and the number of dig its after it is equal to the precision If the precision is missing six digits are produced if the precision is zero no decimal point appears The E format code will produce a number with E instead of e introducing the exponent The exponent always contains at least two digits However if
64. this documentation set we use a number of styles and typefaces to demonstrate the syntax of various commands and to show sample text you might type at a terminal or observe in a file The following is a list of these conventions Typewriter font Used for user input screen output Typewriter or courier font is used in the text and in examples to represent what you might type at a terminal command names directives switches literal filenames or any other text which must be typed exactly as shown It is also used in other examples to represent what you might see on a screen or in a printed listing and to denote executables To distinguish it from other examples or listings input from the user will appear in a shaded box throughout the text Output to the terminal or to a file will appear in a line box For example if you were instructed to type the compiler command that generates debugging information it would appears as cxcorm debug acia c Typewriter font enclosed in a shaded box indicates that this line is entered by the user at the terminal 4 Introduction 2012 COSMIC Software Document Conventions If however the text included a partial listing of the file acia c an example of text from a file or from output to the terminal then type writer font would still be used but would be enclosed in a line box defines the ACIA as a structure struct acia char status char data acia 0
65. to be declared directly in C Each entry must be declared as a function pointer and initialized with a function name The compiler will produce instead of an address con stant a branch instruction targeting the interrupt function to be reached Refer to the vectorc file provided with the compiler example for a more accurate implementation description A small C construct would be extern void handlerl handler2 handler3 void const vectab handlerl handler2 handler3 where handler and so forth are interrupt handlers which can be located anywhere in the code space Then in the linker command file include the following options on the directive line seg vector b0x0 vector o where vector o is the file which contains the vector table This file is provided in the compiler package 2012 COSMIC Software Programming Environments 47 Interfacing C to Assembly Language Interfacing C to Assembly Language The C cross compiler translates C programs into assembly language according to the specifications described in this section You may write external identifiers in both uppercase and lowercase The compiler prepends an underscore _ character to each identifier The compiler places function code in the text section Function code is not to be altered or read as data External function names are published via xdef declarations Literal data such as strings fl
66. you have initialized static variables which are located in RAM you need to perform their initialization before you start your C program The clnk linker will take care of that it moves the initialized data seg ments after the first text segment or the one you have selected with the it option and creates a descriptor giving the starting address destina tion and size of each segment The table thus created and the copy of the RAM are located in ROM by the linker and used to do the initialization An example of how to do this is provided in the ertsi s file located in the headers subdirectory 7 C STARTUP CODE WITH DATA INITIALIZATION Copyright c 2011 by COSMIC Software xdef exit _ stext xref 1 main __sdata _ sram _ eram _ stack __idesc__ __ stext ldr rl atabt 16 descriptor address skip ldr r4 r1 4 first image address dbols idr r2 x1 4 get flag word epz r2 zbss end continue fens 3 x1 4 ram start address ands r2 60 test for moveable code segment beq skip yes skip it dr r2 r1 pf code end address subs r block size lsrs r2 2 word size epel ay r0 r4 4 get and Str 0 x31 44 store subs 1r2 1 count down bne ebel and loop back b dbcl next segment zbss ldr rl atabt4 ldr r2 atabt8 subs r2 r1 beq LALE lsrs 1r2 2 2012 COSMIC Software get start of ram get end of ram byte size empty skip word size Programming Environments 35
67. 0 4 0 2 0 1 0 2 0 2 0 0 0 1 0 1 0 any 1 0 0 0 2 0 0 1 0 2 0 1 0 1 0 2 1 0 See Also exp Notes pow is packaged in the floating point library 2012 COSMIC Software Using The Compiler 129 Ei C Library printf printf Description Output formatted arguments to stdout Syntax include lt stdio h gt int printf char fmt Function printf writes formatted output to the output stream using the format string at fmt and the arguments specified by as described below printf uses putchar to output each character Format Specifiers The format string at fmt consists of literal text to be output interspersed with conversion specifications that determine how the arguments are to be interpreted and how they are to be converted for output If there are insufficient arguments for the format the results are undefined If the format is exhausted while arguments remain the excess arguments are evaluated but otherwise ignored printf returns when the end of the for mat string is encountered Each lt conversion specification gt is started by the character After the the following appear in sequence lt flags gt zero or more which modify the meaning of the conversion specification lt field width gt a decimal number which optionally specifies a mini mum field width If the converted value has fewer characters than the field width it is padded on the left or right if the left adjus
68. 00 to data Ox7 fff By default the banked mode is disable THIS FLAG IS CURRENTLY ONLY MEANINGFULL FOR THE HC12 HCS12 and HCS08 THIS FLAG IS NOT TO BE USED ON ANY S12X PAG ING BASED ON THE EXISTING GLOBAL ADDRESS MODE rb reverse bitfield from left to right SO add stack offset This option has to be selected when using debuggers using the SP value directly THIS FLAG IS CURRENTLY ONLY MEANINGFULL FOR THE HC08 HCS08 V select verbose mode cvdwarf will display information about its activity 324 Programming Support 2012 COSMIC Software The cvdwarf Utility Return Status cvdwarf returns success if no problems are encountered Otherwise it returns failure Examples Under MS DOS the command could be cvdwarf C test acia cxm and will produce C test acia elf and the following command cvdwarf o file C test acia cxm will produce file Under UNIX the command could be cvdwarf test acia cxm and will produce test acia elf 2012 COSMIC Software Programming Support 325 APPENDIX A Compiler Error Messages This appendix lists the error messages that the compiler may generate in response to errors in your program or in response to problems in your host system environment such as inadequate space for temporary inter mediate files that the compiler creates The first pass of the compiler generally
69. 198 listing process 314 listing stream 186 macro instruction 193 macro directive 193 macro parameter 194 object file 186 operator set 192 sections 197 special parameter 194 special parameter 195 232 special parameter 0 195 233 switch directive 197 assembleur debug information add line 184 label 185 assembly language code optimizer 372 atan function 77 atan2 function 78 atof function 79 atoi function 80 atol function 81 B bank automatic segment creation 272 default mode 324 size setting 269 switched system 278 base directive 201 bias segment parameter 278 setting 279 bitfield compiler reverse option 64 default order 365 filling 365 filling order 64 reverse order 365 sign check 362 bootloader 284 boundary round up 271 buffer convert to double 79 165 convert to integer 80 convert to long 81 166 convert to unsigned long 167 copy from one to another 124 125 C C interface to assembly language 48 underscore character prefix 48 C library builtin functions 70 floating point functions 69 integer functions 68 macro functions 69 package 68 C source lines merging 370 C99 compatible header file 71 calloc function 82 casting 362 ceil function 83 char signed 365 unsigned 365 checksum ck option 287 cre 287 functions 287 ik option 288 clabs utility 314 clib utillity 317 clist directive 202 217 219 220 221 222 223 224 225 226 227 clst utility 306 cobj utility 320 code generator
70. 3 pointer 51 space 82 start 51 top 51 help option 7 I IEEE Floating Point Standard 56 if directive 207 211 217 6 Index if directive 210 ifc directive 218 ifdef directive 219 ifeq directive 220 ifge directive 221 ifgt directive 222 ifle directive 223 iflt directive 224 ifne directive 225 ifndef directive 226 ifne directive 227 include assembler directive 228 directory names list 63 183 363 file 274 file before 363 module 280 object file 274 path specification 363 specify path 363 initialization automatic 283 define option 270 descriptor 283 descriptor address 284 descriptor format 283 first segment 283 initialized segments 283 marker 270 startup routine 284 inline pragma directive 43 assembly code 44 assembly instruction 43 block inside a function 43 block outside a function 43 with asm function 44 45 with pragma sequences 43 integer 90 library 281 interrupt function 47 function in map 295 handler 46 hardware 46 reset 33 vectors table 47 isalnum function 101 isalpha function 102 iscntrl 103 isdigit function 104 isgraph function 105 islower function 106 isprint function 107 ispunct function 108 isqrt function 109 isspace function 110 isupper function 111 isxdigit function 112 L label 189 labs function 113 Idexp function 114 Idiv function 115 library build and maintain 10 building and maintaining 317 create 317 delete file 317 double precision 280 extrac
71. 41 memory models 31 memset function 126 messg directive 234 mexit directive 233 235 min function 127 mlist directive 236 modf function 128 Motorola S Records format 311 standard behaviour 198 standard S record generating 22 moveable code section 284 code segment 94 function used 285 segment 94 8 Index movw movt instructions 64 N named syntax example 233 new segment control 264 start region 275 nolist directive 237 nopage directive 238 numbered syntax example 233 O object file location 27 image 261 module 262 module inspector 10 relocatable 320 relocatable file size 320 size 320 object code output 186 object file debug symbol in 186 offset segment parameter 278 setting 279 offset directive 239 old syntax support 198 optimization specific code 372 option global 266 org directive 240 output default format 311 file name 266 listing line number 363 override data bias 310 text bias 310 P page assembler directive 241 value 312 value assembler 193 paginating output 307 parser behaviour 364 compiler pass 360 error log file 363 plen directive 242 pointer narrow 364 pow function 129 prefix filename 366 modules 318 preprocessor define 360 include 360 run only 363 printf function 130 private name region use 290 processor select type 184 putchar function 135 puts function 136 R rand function 137 range specification 307 realloc function 138 redirect output 307 REFs 289 region
72. 56 Using The Assembler 2012 COSMIC Software Assembler Directives xref xref Description Declare symbol as being defined elsewhere Syntax xref identifier identifier Function Visibility of symbols between modules is controlled by the xref and xdef directives Symbols which are defined in other modules must be declared as xref A symbol may be declared both xdef and xref in the same module to allow for usage of common headers Example xref otherprog See Also xdef 2012 COSMIC Software Using The Assembler 257 CHAPTER 6 Using The Linker This chapter discusses the clnk linker and details how it operates It describes each linker option and explains how to use the linker s many special features It also provides example linker command lines that show you how to perform some useful operations This chapter includes the following sections e Introduction e Overview Linker Command File Processing e Linker Options e Section Relocation e Setting Bias and Offset e Linking Objects e Linking Library Objects e Automatic Data Initialization e Moveable Code 2012 COSMIC Software Using The Linker 259 e Manual Segment Initialization e Checksum Computation e DEFs and REFs e Special Topics Description of The Map File Linker Command Line Examples 260 Using The Linker 2012 COSMIC Software Introduction Introduction The linker combines relo
73. 6 Overview Overview You use the linker to build your executable program from a variety of modules These modules can be the output of the C cross compiler or can be generated from handwritten assembly language code Some modules can be linked unconditionally while others can be selected only as needed from function libraries All input to the linker regard less of its source must be reduced to object modules which are then combined to produce the program file The linker can be used to build freestanding programs such as system bootstraps and embedded applications It can also be used to make object modules that are loaded one place in memory but are designed to execute somewhere else For example a data segment in ROM to be copied into RAM at program startup can be linked to run at its actual target memory location Pointers will be initialized and address refer ences will be in place As a side effect of producing files that can be reprocessed clnk retains information in the final program file that can be quite useful The sym bol table or list of external identifiers is handy when debugging pro grams and the utility cobj can be made to produce a readable list of symbols from an object file Finally each object module has in its header useful information such as segment sizes In most cases the final program file created by clnk is structurally iden tical to the object module input to clnk The only difference is that t
74. C Software Assembly Language Syntax label constant labell label2 NOTE The difference of two relocatable labels is valid only if both symbols are not external symbols and are defined in the same section high expression upper byte low expression lower byte page expression page byte These special operators evaluate an expression and extract the appro priate information from the result The expression may be relocatable and may use the set of operators if allowed high extract the upper byte of the 16 bit expression low extract the lower byte of the 16 bit expression page extract the page value of the expression It is computed by the linker according to the bs option used This is used to get the address extension when bank switching is used Macro Instructions A macro instruction is a list of assembler commands collected under a unique name This name becomes a new command for the following of the program A macro begins with a macro directive and ends with a endm directive All the lines between these two directives are recorded and associated with the macro name specified with the macro directive signex macro sign extension mov r2 0 prepare MSW cmp rl 0 test sign bpl pos if not positive mvn r2 r2 invert MSW pos endm end of macro This macro is named signex and contains the code needed to perform a sign extension Whenever needed this macro can be expanded just by using its na
75. For more information see Linker Command Line Examples on page 298 Libraries Setup Search Paths The linker uses the environment variable CXLIB to search for objects and library files If you don t specify the full path to the objects and or libraries in the link command file AND they are not found in the local directory the linker will then search all paths specified by the CXLIB environment variable This allows you to specify just the names of the objects and libraries in your link command file For example setting the CXLIB environment variable to the C COSMIC LIB directory is done as follow C gt set CXLIB C COSMIC LIB 282 Using The Linker 2012 COSMIC Software Automatic Data Initialization Automatic Data Initialization The linker is able to configure the executable for an automatic data ini tialization This mechanism is initiated automatically when the linker finds the symbol __idesc___ in the symbol table as an undefined sym bol clnk first locates a segment behind which it will add an image of the data so called the host segment The default behaviour is to select the first text segment in the executable file but you can override this by marking one segment with the it option Then clnk looks in the executable file for initialized segments All the segments data and bsct are selected by default unless disabled explic itly by the ib option Otherwise renamed segments may also be sele
76. If an option requires additional information then the type of information is indicated by one of the following code displayed immediately after the option name Code Type of information i character string short integer HH long integer single character If the code is immediately followed by the character gt the option may be specified more than once with different values In that case the option name must be repeated for every specification For example the options of the chex utility are chex options file a absolute file start address b address bias e entry point address R output format h suppress header h specify header string m maximum data bytes per line n gt output only named segments o output file name p use paged address format pa use paged address for data pl page numbers for linear mapping pn use paged address in bank only pp use paged address with mapping s output increasing addresses wW output word addresses xe exclude named segment 2012 COSMIC Software Introduction Compiler Architecture chex accepts the following distinct flags Flag Function a accept a long integer value b accept a long integer value e accept a long integer value f accept a single character h simply a flag indicator h accept a character string m accept a short integer value n
77. Input Output in C Redefining Sections Referencing Absolute Addresses Inserting Inline Assembly Instructions Writing Interrupt Handlers Placing Addresses in Interrupt Vectors Interfacing C to Assembly Language Register Usage Heap Management Control with the C Compiler Data Representation 30 Programming Environments 2012 COSMIC Software Memory Models Memory Models The compiler implements several memory models allowing different efficiencies based on the maximum size of data and constant areas The CORTEX M processor does not allow direct access to global data objects so for a better efficiency the compiler allows these accesses to be based from a specific register The data area can be then based from register r9 using the dir modi fier allowing up to 4K data to be accessed more efficiently If more data is necessary the extended addressing mode can be selected using the ext modifier The constant area can be either located in the first 64K bytes of the address space allowing the compiler to load any address as a single 16 bit word Constants outside this range can be accessed using the ext modifier When using a memory model the compiler will default data and constant accesses to the selected configuration avoiding but not forbidding the explicit usage of any modifier When targetting the MO instruction set the based data access and the 64K constants access are no more available The compiler provides several
78. Objects ccceeseseneeneees Linking Library Objects c cccececesceseeseeseeeceeceecneeeeeeneeess Cibrar y Ordet ooe Gri reuda ae CEEE EEE Libraries Setup Search Paths Automatic Data Initialization Descriptor Format Moveable Code oo ce cececseseesecseseesessesessesessceaeseescsaeseeeceeeaceeens Manual Segment Initialization cccceceseeseeeeeeeeeeeeeeeeeeeeee Checksum Computation DEFs and REES sesteicessies cts stescstelehscucahsledatscoadatdeas Becds state Abdahns Special Topics ccececcecesesseeseeecseesceseeeeeseseeseeseseeseeeeeseeeeeees Private Name Regions Renaming Symbols Absolute Symbol Tables Description of The Map File eceseeseeseceecesenseneeeseeeeens Special Segments debug and info ec eeeeeeeeeeeeeees 296 Return Valers inie nesne Linker Command Line Examples Generating Debugging Information eseeseseerersrerererererereres Generating Line Number Information Generating Data Object Information The cprd Utility ccecceccecsesseescesceeceeceseeseeeeseceecececeseeaeeaes viii Command Line Options cecceeeeeeeeeeeceseeeeeeeeeeeeeeeeees 304 Examples sissscseiscschscescstcnscetetcntseeccsees ts dh dekh ease 30D The clst utility ceecceeeeeceeceeeeeeeseseeseesessestetecstertetsteeetes 306 Command Line Options ceeeeeeeeeseeseeteeeeeeeeeeeeeeeeees 306 Chapter 8 Theschex Ut
79. Option Subparts of the link command file can be included from other files by using the following option inc include the file specified by This is equivalent to expand ing the text file into the link file directly at the location of the inc line The linker searches the specified file using the provided list of directories unless specifying an absolute path 274 Using The Linker 2012 COSMIC Software Linker Options Example Include the file seg2 txt in the link file test 1k Test 1kf seg text b0x5000 seg data b0x100 filel o file2 o seg text b0x7000 inc seg2 txt seg2 txt modl1 o mod2 o0 mod3 0 Resultant link file seg text b0x5000 seg data b0x100 filel o file2 o seg text b0x7000 mod1l o mod2 0 mod3 o0 Private Region Options Options that control code regions are new start a new region A region is a user definable group of input object modules which may have both public and pri vate portions The private portions of a region are local to that region and may not access or be accessed by any thing outside the region By default a new region is given public access pub make the following portion of a given region public pri make the following portion of a given region private 2012 COSMIC Software Using The Linker 275 6 Linker Options Symbol Definition Option The option controlling symbol definition and
80. Syntax int _fctcpy char name Function _fcetepy copies a moveable code segment in RAM from its storage loca tion in ROM _fctcpy scans the descriptor built by the linker and looks for a moveable segment whose flag byte matches the given argument If such a segment is found it is entirely copied in RAM Any function defined in that segment may then be called directly For more informa tion see Moveable Code in Chapter 6 Return Value _fctcpy returns a non zero value if a segment has been found and cop ied It returns 0 otherwise Example if _fctcpy b flash 7 Notes _fctcpy is packaged in the integer library Using The Compiler 2012 COSMIC Software C Library floor floor Description Round to next lower integer Syntax include lt math h gt double floor double x Function floor computes the largest integer less than or equal to x Return Value floor returns the largest integer less than or equal to x expressed as a double floating value Example x floor x 5 1 5 0 5 0 5 0 0 0 0 0 5 0 5 0 5 1 6 0 See Also ceil Notes floor is packaged in the floating point library 2012 COSMIC Software Using The Compiler 95 96 Description Find double modulus Syntax include lt math h gt double fmod double x double y Function fmod computes the floating point remainder of x y to full double pre cision The return value of fis determine
81. Using The Assembler 2012 COSMIC Software Assembler Directives endif endif Description End conditional assembly Syntax if lt expression gt instructions endif Function The endif directive closes an if or else conditional directive The condi tional status reverts to the one existing before entering the if directive The endif directive applies to the closest previous if or else directive Example if offset gt 8 if offset too large add rl offset add offset else otherwise sub rl offset substract offset endif Note The endif and endc directives are equivalent and may used without dis tinction They are provided for compatibility with previous assemblers See Also if else clist 2012 COSMIC Software Using The Assembler 211 212 Using The Assembler Assembler Directives endm endm Description End macro definition Syntax label macro lt macro_body gt endm Function The endm directive is used to terminate macro definitions Example define a macro that places the length of a string in a byte prior to the string ltext macro ds b 2 l 1 ds b yT 2 endm See Also mexit macro 2012 COSMIC Software Assembler Directives endr endr Description End repeat section Syntax repeat lt macro_body gt endr Function The endr directive is used to terminate repeat sections Example shift a value
82. a b 0x100 crtsi cxm test o libis cxm libm cxm def _ memory bss The descriptor built by the linker is a list of entries followed by the expected CRC value only once if functions _checksum or _checksum16 are called or after each entry if functions _checksumx or _checksum16x are called An entry contains a flag byte a start address and an end address The flag byte is non zero and is or ed with 0x80 if the start address contains a bank value two words page first then start address otherwise it is just one word with the start address The end address is always one word The last entry is always followed by a nul byte seen as an ending flag and immediately followed by the expected CRC if functions _checksum or _checksum16 are called The linker compresses the list of entries by creating only one entry for contiguous segments as long as they are in the same space s option and in the same bank page The current linker implements only one algorithm Starting with zero the CRC byte word is first rotated one bit left a true bit rotation then xor ed with the code byte The CRC values stored in the checksum descriptor are the one s complement value of the expected CRC 288 Using The Linker 2012 COSMIC Software DEFs and REFs DEFs and REFs The linker builds a new symbol table based on the symbol tables in the input object modules but it is not a simple concatenation with adjust ments The
83. ader files needed to compile that file 2012 COSMIC Software Compiler Passes 363 D The cpcorm Parser Parser Option Usage cont Option Description m the value is used to configure the parser behaviour It is a two bytes value the upper byte specifies the default space for variables and the lower byte specifies the default space for functions A space byte is the or ed value between a size specifier and several optional other specifiers The allowed size specifiers are 0x10 tiny 0x20 near 0x30 far Allowed optional specifiers are 0x01 pack 0x04 nostack Note that all the combinations are not significant for all the target processors do not replace an access to an initialized const object by its value By default the usage of a const object whose value is known is replaced by its constant value do not optimize size of enum variables By default the com piler selects the smallest integer type by checking the range of the declared enum members This mechanism does not allow incomplete enum declaration When the ne option is selected all enum variables are allocated as int variables thus allowing incomplete declarations as the knowledge of all the members is no more necessary to choose the proper integer type allow pointer narrowing By default the compiler refuses to cast the pointer into any smaller object This
84. ader_name gt in your program where lt header_name gt is the name of the appropriate header file enclosed in angle brackets The required header file should be included before you refer to any function that it declares The names of the header files packaged with the C library and the func tions declared in each header are listed below lt assert h gt Header file for the assertion macro assert lt ctype h gt Header file for the character functions isalnum isalpha iscntrl isgraph isprint ispunct isspace isxdigit isdigit isupper islower tolower and toupper lt float h gt Header file for limit constants for floating point values lt io h gt Header file for input output registers Each register has an upper case name which matches the standard definition lt limits h gt Header file for limit constants of the compiler lt math h gt Header file for mathematical functions acos asin atan atan2 ceil cos cosh exp fabs floor fmod frexp Idexp log log10 modf pow sin sinh sqrt tan and tanh lt setjmp h gt Header file for nonlocal jumps setjmp and longjmp 70 Using The Compiler 2012 COSMIC Software Descriptions of C Library Functions lt stdarg h gt Header file for walking argument lists va_arg va_end and va_start Use these macros with any function you write that must accept a variable number of arguments lt stddef h gt Header file for types size_t w
85. after the call to the main function The status argument is not used by the current implementation Return Value exit never returns Example To exit in case of error if fatal_error exit See Also abort Notes exit is in the startup module 2012 COSMIC Software Using The Compiler 91 92 Ei C Library exp exp Description Exponential Syntax include lt math h gt double exp double x Function exp computes the exponential of x to full double precision Return Value exp returns the nearest internal representation to exp x expressed as a double floating value If the result is too large to be properly repre sented exp returns zero Example To compute the hyperbolic sine of x sinh exp x exp x 2 0 See Also log Notes exp is packaged in the floating point library Using The Compiler 2012 COSMIC Software C Library fabs fabs Description Find double absolute value Syntax include lt math h gt double fabs double x Function fabs obtains the absolute value of x Return Value fabs returns the absolute value of x expressed as a double floating value Example x fabs x 5 0 5 0 0 0 0 0 3 7 3 7 See Also abs labs Notes fabs is packaged in the floating point library 2012 COSMIC Software Using The Compiler 93 94 Ei C Library _fctcpy _fctcpy Description Copy a moveable code segment in RAM
86. aliases is def define new symbols to the linker The string can use dif ferent syntaxes ident constant where ident is a valid identifier and constant is a valid constant expressed with the standard C lan guage syntax This form is used to add ident to the symbol table as a defined absolute symbol with a value equal to constant ident1 ident2 where ident1 and ident2 are both valid identifiers This form is used to define aliases The symbol ident1 is defined as the alias for the symbol ident2 and goes in the symbol table as an external DEF a DEF is an entity defined by a given module If ident2 is not already in the symbol table it is placed there as a REF a REF is an entity referred to by a given module ident section where ident is a valid identifier and section is the name of a section specified as the first argument of a seg directive This form is used to add ident to the symbol table as a defined symbol whose value is the address of the next byte to be loaded in the specified section NOTE Whitespaces are not allowed aside the equal sign The following list of possible syntaxes uses a common construct The segment name must match the name of the segment specified by the n option These directives can be placed anywhere in the link command file even before the corresponding segment is defined ident start segment This form defines ident as the logical start address of the
87. an object has been assembled with the pl option local symbols are dis played just after the module description Stack Usage Describe the amount of memory needed for the stack Each function of the application is listed by its name fol lowed by a gt character indicating that this function is not called by any other one the main function interrupt func tions task entries The first number is the total size of the stack used by the function including all the internal calls The second number between braces shows the stack need for that function alone The entry may be flagged by the keyword Recursive meaning that this function is itself recursive or is calling directly or indirectly a recur sive function and that the total stack space displayed is not accurate The linker may detect potential but not actual recursive functions when such functions are called by pointer The linker displays at the end of the list a total stack size assuming interrupt functions cannot be them selves interrupted Interrupt frames and machine library calls are properly counted 2012 COSMIC Software Using The Linker 295 6 Description of The Map File Call Tree List all the functions sorted alphabetically followed by all the functions called inside The display goes on recursively unless a function has already been listed In such a case the name is followed by the line number where the func tion is expanded If a line becomes too
88. ar s2 Function strcat appends a copy of the NUL terminated string at s2 to the end of the NUL terminated string at s The first character of s2 overlaps the NUL at the end of s A terminating NUL is always appended to s Return Value strcat returns s1 Example To place the strings first string second string in buf buf 0 0 strcepy buf first string strcat buf second string See Also strncat Notes There is no way to specify the size of the destination area to prevent storage overwrites strcat is packaged in the integer library 152 Using The Compiler 2012 COSMIC Software C Library strchr strchr Description Scan string for first occurrence of character Syntax include lt string h gt char strchr char s int c Function strchr looks for the first occurrence of a specific character c in a NUL terminated target string s Return Value strchr returns a pointer to the first character that matches c or NULL if none does Example To map keystr characters into subst characters if t strchr keystr s s subst t keystr See Also memchr strcspn strpbrk strrchr strspn Notes strchr is packaged in the integer library 2012 COSMIC Software Using The Compiler 153 Ei C Library stremp strcmp Description Compare two strings for lexical order Syntax include lt string h gt int strcmp char s1 char
89. are a static data object of const type at either file level or at block level you may specify its stored value by writing a data initial izer The compiler determines its stored value from its data initializer before program startup and the stored value continues to exist unchanged until program termination If you specify no data initializer the stored value is zero If you declare a data object of const type at argument level you tell the compiler that your program will not alter the value stored in that argument data object by the function call If you declare a data object of const type and dynamic lifetime at block level you must specify its stored value by writing a data initializer If you specify no data initializer the stored value is indeterminate You may specify const and volatile together in either order A const volatile data object could be a Read only status register or a variable whose value may be set by another program Examples of data objects declared with type qualifiers are char const x const pointer to char int volatile y volatile pointer to int const float pi 355 0 113 0 pi is never changed 38 Programming Environments 2012 COSMIC Software Performing Input Output in C Performing Input Output in C You perform input and output in C by using the C library functions getchar gets printf putchar puts and sprintf They are described in chapter 4 The C source
90. arguments are zero atan2 returns zero Example To find the phase angle of a vector in degrees theta atan2 y x 180 0 pi See Also acos asin atan Notes atan2 is packaged in the floating point library Using The Compiler 2012 COSMIC Software C Library atof atof Description Convert buffer to double Syntax include lt stdlib h gt double atof char nptr Function atof converts the string at nptr into a double The string is taken as the text representation of a decimal number with an optional fraction and exponent Leading whitespace is skipped and an optional sign is permit ted conversion stops on the first unrecognizable character Acceptable inputs match the pattern d d e dd where d is any decimal digit and e is the character e or E No checks are made against overflow underflow or invalid character strings Return Value atof returns the converted double value If the string has no recogniza ble characters it returns zero Example To read a string from STDIN and convert it to a double at d gets buf d atof buf See Also atoi atol strtol strtod Notes atof is packaged in the floating point library 2012 COSMIC Software Using The Compiler 79 80 Description Convert buffer to integer Syntax include lt stdlib h gt int atoi char nptr Function atoi converts the string at nptr into an integer T
91. art address is explicitly defined by a b option and has no effect on the first object module 2012 COSMIC Software Using The Linker 271 6 Linker Options Segment Control Options Usage cont Option Description s define a space name for the segment This segment will be verified for overlapping only against segments defined with the same space name See Overlapping Control on page 278 V do not verify overlapping for the segment w set the window size for banked applications and activate the automatic bank segment creation X expandable segment Allow a segment to spill in the next segment of the same section type if its size exceeds the value given by the m option The next segment must be declared before the object causing the overflow This option has no effect if no m option is specified for the expendable segment Option e cannot be specified with option x Options defining a numerical value addresses and sizes can be entered as constant symbols or simple expression combined them with and operators Any symbol used has to be defined before to be used either by a def directive or loaded as an absolute symbol from a previ ously loaded object file The operators are applied from left to right without any priority and parenthesis are not allowed Such expres sions CANNOT contain any whitespace For example def START 0x1000 def MAXSIZE 0x2000 seg te
92. ary vsprintf vsprintf Description Output arguments formatted to buffer Syntax include lt stdio h gt include lt stdarg h gt int vsprintf char s char fmt va_list ap Function vsprintf writes formatted to the buffer pointed at by s using the format string at fmt and the arguments specified by pointer ap in exactly the same way as printf See the description of the printf function for infor mation on the format conversion specifiers A NUL character is written after the last character in the buffer The va_start macro must be exe cuted before to call the vsprintf function Return Value vsprintf returns the numbers of characters written not including the ter minating NUL character Example To format a double at d into buf va_start aptr fmt vsprintf buf fmt aptr See Also printf vprintf Notes vsprintf is packaged in both the integer library and the floating point library The functionality of the integer only version of vsprintfis a sub set of the functionality of the floating point version The integer only version cannot print floating point numbers If your programs call the integer only version of vsprintf the following conversion specifiers are invalid e E f g and G The L flag is also invalid 2012 COSMIC Software Using The Compiler 179 CHAPTER 5 Using The Assembler The cacorm cross assembler translates your assembly language source files into
93. ass of the C compiler It accepts a sequential file of flow graphs and parse trees from cpcorm and outputs a sequential file of assembly language statements As much as possible the compiler generates freestanding code but for those operations which cannot be done compactly it generates inline calls to a set of machine dependent runtime library routines Command Line Options cgcorm accepts the following options each of which is described in detail below cgcorm options file a optimize _asm code bss do not use bss cm constant in large mode d1 output line information e error file name f full listing display fp floating point mode ge eclipse error messages Sul output listing m0 select M0 target na do not xdef alias name no do not use optimizer o output file name sf split function sections v verbose Code generator Option Usage Option Description a optimize _asm code By default the assembly code inserted by a _asm call is left unchanged by the optimizer bss inhibit generating code into the bss section cm constant in large mode 2012 COSMIC Software Compiler Passes 369 D The cgcorm Code Generator Code generator Option Usage cont Option Description di produce line number information must be either 1 or 2 Line number information can be produced in two ways 1 function name and line number is obtained by specifying dl1 2 file name and l
94. at appends a copy of the NUL terminated string at s2 to the end of the NUL terminated string at s The first character of s2 overlaps the NUL at the end of s n specifies the maximum number of characters to be copied unless the terminating NUL in s2 is encountered first A ter minating NUL is always appended to s Return Value strncat returns s1 Example To concatenate the strings day and light strcpy s day strncat s 3 light 5 See Also strcat Notes strncat is packaged in the integer library 158 Using The Compiler 2012 COSMIC Software C Library strncmp strncmp Description Compare two n length strings for lexical order Syntax include lt string h gt int strncmp char s1 char s2 unsigned int n Function strnemp compares two text strings character by character for lexical order in the character collating sequence The first string starts at s the second at s2 n specifies the maximum number of characters to be com pared unless the terminating NUL in s or s2 is encountered first The strings must match including their terminating NUL character in order for them to be equal Return Value strncmp returns an integer greater than equal to or less than zero according to whether s is lexicographically greater than equal to or less than s2 Example To check for a particular error message if strncmp errmsg can t write output file
95. at contains uninitialized data The copy of the initialized data in ROM will follow the descriptor created by the linker after the code segment In case of multiple code and data segments a link command file could be seg sconst b 0x2000 n sconst program start address seg text a const crtsi cxm acia o modulel o seg text b0x4000 module2 o module3 o libis cxm libm cxm seg vector b 0x0 vector o tdef memory bss tdef stack 0x20010000 n or seg sconst b 0x2000 seg text a const n seg data b0x20000000 crtsi cxm acia o modulel o seg text b0x4000 it module2 o module3 o libis cxm 2012 COSMIC Software text n etext o 0x0 constant follow code startup with auto init main program module program new code segment module program module program C library if needed machine library vectors start address interrupt vectors symbol used by startup stack pointer initial value sconst program start address constant follow code 000 data start address startup with auto init main program module program sets the section attribute module program module program C library if needed Tutorial Introduction 25 Generating Automatic Data Initialization libm cxm machine library seg vector b 0x0 vectors start address vector o interrupt vectors def _ memory bss tdef stack 0x20010000 symbol used by startup stack pointe
96. at location s2 into the buffer beginning at s If the two buffers overlap the function performs the copy in the appropriate sequence so the copy is not corrupted Return Value memmove returns s1 Example To shift an array of characters memmove buf amp buf 5 10 See Also memcpy Notes memmove is packaged in the integer library 2012 COSMIC Software Using The Compiler 125 Description Propagate fill character throughout buffer Syntax include lt string h gt void memset void s int c unsigned int n Function memset floods the n character buffer starting at s with fill character c Return Value memset returns s Example To flood a 512 byte buffer with NULs memset buf 0 BUFSIZ Notes memset is packaged in the integer library 126 Using The Compiler 2012 COSMIC Software C Library min min Description Test for minimum Syntax include lt stdlib h gt min a b Function min obtains the minimum of its two arguments a and b Since min is implemented as a builtin function its arguments can be any numerical type and type coercion occurs automatically Return Value min is a numerical rvalue of the form a lt b a b suitably paren thesized Example To set a new minimum level nmove min space size See Also max Notes min is an extension to the ANSI C standard min is a builtin declared in the lt stdlib h gt hea
97. ation of options that the compiler will use edit the configuration file and add your specific options using the p for the parser g for the code generator o for the optimizer and a for the assembler options If you specify an invalid option or combination of options compilation will not proceed beyond the step where the error occurred You may define up to 128 such options Creating Your Own Options To create a programmable option edit the configuration file and define the parametrable option with the m option The string has the fol lowing format name popt gopt oopt aopt exclude The first field defines the option name and must be ended by a colon character The four next fields describe the effect of this option on the four passes of the compiler respectively the parser the generator the optimizer and the assembler These fields are separated by a comma character If no specific option is needed on a pass the field has to be specified empty The remaining fields if specified describe a exclusive relationship with other defined options If two exclusive options are specified on the command line the compiler will stop with an error message You may define up to 128 programmable options At least one field has to be specified Empty fields need to be specified only if a use ful field has to be entered after In the following example m dll 1 dl1 d12 dll line option 1 m d12 1 d12 d11 dll
98. be specified on the com mand line If there are several segments with the same name they will all be produced This option is used in com bination with the n option of the linker 0 write output module to file The default is STDOUT p output addresses of banked segments using a paged for mat lt page_number gt lt logical_address gt instead of the default format lt physical gt pa output addresses of banked data segments using a paged format lt page_number gt lt logical_address gt instead of the default format lt physical gt 2012 COSMIC Software Programming Support 311 8 The chex Utility Chex Option Usage cont Option Description pl specify the page value of the segment localized between 0x8000 and 0xc000 when using a linear non banked application This option enforces a paged format for this segment pn behaves as p but only when logical address is inside the banked area This option has to be selected when produc ing an hex file for the Noral debugger pp behaves as p but uses paged addresses for all banked segments mapped or unmapped This option has to be selected when producing an hex file for Promic tools S sort the output addresses in increasing order W output word addresses Addresses must be aligned on even addresses This option is useful for word processor type x gt do not output segments whose name is equal to the string Up to tw
99. bj can be used to check the size and configuration of relocatable object files or to output information from their symbol tables Command Line Options cobj accepts the following options described in detail below cobj options file d output data flows h output header l display info section n output sections TOS output file name e output relocation flows Ss output symbol table v display file addresses x output debug symbols lt file gt specifies a file which must be in relocatable format or executa ble format Cobj Option Usage Option Description d output in hexadecimal the data part of each section h display all the fields of the object file header i display the content of the info section in a readable format n display the name size and attribute of each section 0 write output module to file The default is STDOUT r output in symbolic form the relocation part of each section S display the symbol table V display seek addresses inside the object file X display the debug symbol table 320 Programming Support 2012 COSMIC Software The cobj Utility If none of these options is specified the default is hns Return Status cobj returns success if no diagnostics are produced i e if all reads are successful and all file formats are valid Examples For example to get the symbol table cobj s acia o symbols _
100. by the COS MIC s C source level cross debugger or another debugger or emulator The information produced about data objects includes their name scope type and address The address can be either absolute or relative to a stack offset 302 Debugging Support 2012 COSMIC Software Generating Debugging Information As with line number information alone you can generate debugging information about a single file or about all the files making up an exe cutable program cprd may be used to extract the debugging information from files com piled with the debug option as described below 2012 COSMIC Software Debugging Support 303 The cprd Utility The cprd Utility cprd extracts information about functions and data objects from an object module or executable image that has been compiled with the debug option cprd extracts and prints information on the name type storage class and address absolute or offset of program static data objects function arguments and automatic data objects that functions declare For automatic data the address provided is an offset from the frame pointer For function arguments the address provided is an offset from the stack pointer Command Line Options cprd accepts the following command line options each of which is described in detail below cprd options file fc select function name f 1 select file name o output file name ra recurse structure always SE recurse structu
101. c See Also putchar Notes getchar is packaged in the integer library 2012 COSMIC Software Using The Compiler 99 Ei C Library gets gets Description Get a text line from input stream Syntax include lt stdio h gt char gets char s Function gets copies characters from the input stream to the buffer starting at s Characters are copied until a newline is reached or end of file is reached If a newline is reached it is discarded and a NUL is written immediately following the last character read into s gets uses getchar to read each character Return Value gets returns s if successful If end of file is reached gets returns NULL If a read error occurs the array contents are indeterminate and gets returns NULL Example To copy input to output line by line while puts gets buf t See Also puts Notes There is no assured limit on the size of the line read by gets gets is packaged in the integer library 100 Using The Compiler 2012 COSMIC Software C Library isalnum isalnum Description Test for alphabetic or numeric character Syntax include lt ctype h gt int isalnum int c Function isalnum tests whether c is an alphabetic character either upper or lower case or a decimal digit Return Value isalnum returns nonzero if the argument is an alphabetic or numeric character otherwise the value returned is zero Example To test fo
102. catable object files selectively loading from libraries of such files made with clib to create an executable image for standalone execution or for input to other binary reformatters clnk will also allow the object image that it creates to have local symbol regions so the same library can be loaded multiple times for different segments and so that more control is provided over which symbols are exposed On microcontroller architectures this feature is useful if your executable image must be loaded into several noncontiguous areas in memory NOTE The terms segment and section refer to different entities and are carefully kept distinct throughout this chapter A section is a contigu ous subcomponent of an object module that the linker treats as indivisi ble The assembler creates several sections in each object module The linker combines input sections in various ways but will not break one up The linker then maps these combined input sections into output seg ments in the executable image using the options you specify A segment is a logically unified block of memory in the executable image An example is the code segment which contains the executable instructions For most applications the sections in an object module that the linker accepts as input are equivalent to the segments of the executable image that the linker generates as output 2012 COSMIC Software Using The Linker 261
103. cece ceeeeeseeteeteeeeee 22 Linking Your Application c cccceceseeseeseeecsecseceeeeeeeeeeeees 23 Generating Automatic Data Initialization eee 24 Specifying Command Line Options cccecesecsseeeseeeeeeeseees 27 Chapter 3 Miodu DON aeee a E SIR eset dete tee settee 30 Memory Models ccecceeeeeeee rest Modifying the Runtime Startup 0 a 33 Description of Runtime Startup Code 35439 Initializing data in RAM ERNE E EEEE OO The const and volatile Type Qualifiers RTE EERE 37 Performing Input Output in Co Redefining Sections 00 Referencing Absolute Addresses re Inserting Inline Assembly Instructions ccceseeeeeeseeneee 43 ii Tnlining with pragmas ccccceeecescescesceseeseeeeseeeeeeeenee Inlining With ast ccccceceseseesceeceeceeceseeaecsecseenseeeneeeee Writing Interrupt Handlers 2 0 0 0 eeeeeeescesceseeseeseeseeseeneesenee Placing Addresses in Interrupt Vectors c ceccesceseeseeseeseeee Interfacing C to Assembly Language cceeeseseeeeeeeeeeeees Register Usage s issiccsscccssccsetacuevsessvatessisseasaatenssascases Heap Management Control with the C Compiler Modifying The Heap Location ra Data Representation sssessssessesssesesstsessserstsetessesesteresrsessesesss Invoking the Compiler ccccccccecceceeceseeseeseesecnecnecaeeneeneenee Compiler Command Line Options File Naming Conventi
104. cess if it produces no diagnostics Example cgcorm usually follows cpcorm as follows cpcorm o 2 cxl u i cosmic hcorm file c cgcorm o 2 cx2 2 cx1 2012 COSMIC Software Compiler Passes 371 D The cocorm Assembly Language Optimizer The cocorm Assembly Language Optimizer cocorm is the code optimizing pass of the C compiler It reads source files of CORTEX M assembly language source code as generated by the cgcorm code generator and writes assembly language statements cocorm is a peephole optimizer it works by checking lines function by function for specific patterns If the patterns are present cocorm replaces the lines where the patterns occur with an optimized line or set of lines It repeatedly checks replaced patterns for further optimizations until no more are possible It deals with redundant load store opera tions constants stack handling and other operations Command Line Options cocorm accepts the following options each of which is described in detail below cocorm options lt file gt keep original lines as comments d disable specific optimizations o output file name v print efficiency statistics xX keep registers for debug Optimizer Option Usage Option Description C leave removed instructions as comments in the output file d specify a list of codes allowing specific optimizations func tions to be selectively disabled 0 write the output to
105. char_t and ptrdiff t lt stdint h gt C99 compatible header file for basic integer types lt stdio h gt Header file for stream input output getchar gets printf putchar puts and sprintf lt stdlib h gt Header file for general utilities abs abort atof atoi atol calloc div exit free isqrt labs Idiv Isqrt malloc rand realloc srand strtod strtol and strtoul lt string h gt Header file for string functions memchr memcmp mem cpy memmove memset strcat strchr strcmp strcpy strcspn strlen strncat strncmp strncpy strpbrk strrchr strspn and strstr Functions returning int C library functions that return int and can therefore be called without any header file since int is the function return type that the compiler assumed by default are isalnum isalpha iscntrl isgraph isprint ispunct isspace isxdigit isdigit isupper islower sbreak tolower and toupper Descriptions of C Library Functions The following pages describe each of the functions in the C library in quick reference format The descriptions are in alphabetical order by function name The syntax field describes the function prototype with the return type and the expected arguments and if any the header file name where this function has been declared 2012 COSMIC Software Using The Compiler 71 72 Ei C Library _asm _asm Description Syntax Generate inline assembly code no header file need b
106. code for these and all other C library functions is included with the distribution so that you can modify them to meet your specific needs Note that all input output performed by C library functions is supported by underlying calls to getchar and putchar These two func tions provide access to all input output library functions The library is built in such a way so that you need only modify getchar and putchar the rest of the library is independent of the runtime environment Function definitions for getchar and putchar are char getchar void char putchar char c 2012 COSMIC Software Programming Environments 39 Redefining Sections Redefining Sections The compiler uses by default predefined sections to output the various component of a C program The default sections are Section Description text executable code standard mode const text string and constants sconst dir constants data initialized variables in RAM bss uninitialized variables in RAM sdata initialized variables in short range R9 based sbss uninitialized variables in short range R9 based It is possible to redirect any of these components to any user defined section by using the following pragma definition pragma section lt attribute gt lt qualified_name gt where lt attribute gt is either empty or the keyword const and lt qualified_name gt is a section name enclosed as follows name
107. constants follow program seg sdata b0x10000 start data address cxcorm lib crts cxm startup object file filel o file2 o input object files cxcorm lib libis cxm integer lib cxcorm lib libm cxm machine lib def memory bss symbol used by startup Se SH H E SHE SHE SHE The following link command file is an example for an application that does not use floating point data types and does not require automatic initialization demo lkf link command WITHOUT automatic init seg const b 0x4000000 n const program start address seg vtext a const constants follow program seg sdata b0x10000 start data address seg vector a const m0x100000 r12 n vector int tables cxcorm lib crts cxm startup with NO INIT acia o main program modulel o module program cexcorm lib libis cxm integer lib cexcorm lib libm cxm machine lib vector o reset amp interrupt vectors tdef memory bss symbol used by library tdef stack 0x20000 stack pointer initial value 298 Using The Linker 2012 COSMIC Software Linker Command Line Examples The following link command file is an example for an application that uses single precision floating point data types and utilizes automatic data initialization demo lkf link command WITH automatic init seg const b 0x4000000 n const program start address seg vtext a const constants follow program seg sdata b0x10000 start data address seg vector a const
108. control character otherwise the value is Zero Example To map control characters to percent signs for 7 s7 s if iscntrl s g gt See Also isgraph isprint ispunct isspace Notes If the argument is outside the range 1 255 the result is undefined iscntrl is packaged in the integer library 2012 COSMIC Software Using The Compiler 103 a C Library isdigit isdigit Description Test for digit Syntax include lt ctype h gt int isdigit int c Function isdigit tests whether c is a decimal digit Return Value isdigit returns nonzero if c is a decimal digit otherwise the value returned is zero Example To convert a decimal digit string to a number for sum 0 isdigit s s sum sum 10 s O See Also isalnum isalpha islower isupper isxdigit tolower toupper Notes If the argument is outside the range 1 255 the result is undefined isdigit is packaged in the integer library 104 Using The Compiler 2012 COSMIC Software C Library isgraph isgraph Description Test for graphic character Syntax include lt ctype h gt int isgraph int c Function isgraph tests whether c is a graphic character i e any printing charac ter except a space 040 in ASCII Return Value isgraph returns nonzero if c is a graphic character Otherwise the value returned is zero Example To output only graphic characters fo
109. cted by using the id option The id option cannot be specified on a bss segment default or renamed Once all the selected segments are located clnk builds a descriptor containing the starting address and length of each such segment and moves the descriptor and the selected segments to the end of the host segment without relocating the content of the selected segments For more information see Generating Automatic Data Initialization in Chapter 2 and Initializing data in RAM in Chapter 3 Descriptor Format The created descriptor has the following format dc 1 start_ram_address starting address of the first image in prom for each segment dc 1 flag segment type dc 1 start_ram address start address of segment in ram dc 1 end_prom_address address of last data byte plus one in prom after the last segment dc 1 0 The flag word is used to detect the end of the descriptor and also to specify a type for the data segment The actual value is equal to the code of the first significant letter in the segment name If the RAM segment has been created using banked addresses b and 0 values the RAM start address is described using two words the first 2012 COSMIC Software Using The Linker 283 6 Moveable Code giving the page value for that segment and the second giving the match ing value for the start address in that space A segment description is displayed as dc 1 flag segment type
110. ction bad struct union operand a structure or an union has been used as operand for an arithmetic operator bad symbol definition the syntax of a symbol defined by the d option on the command line is not valid bad void argument the type void has not been used alone in a proto typed function declaration can t create lt name gt file lt name gt cannot be created for writing can t open lt name gt file lt name gt cannot be opened for reading can t redefine macro lt name gt macro lt name gt has been already defined can t undef macro lt name gt a undef has been attempted on a prede fined macro 330 Compiler Error Messages 2012 COSMIC Software Parser cpcorm Error Messages compare out of range a comparison is detected as beeing always true or always false strict const assignment a const object is specified as left operand of an assignment operator constant assignment in a test an assignment operator has been used in the test expression of an if while do for statements or a conditional expression strict duplicate pragma attribute name lt name gt two objects have been declared with the same lt name gt in pragma attribute directives duplicate case two case labels have been defined with the same value in the same switch statement duplicate default a default label has been specified more than once in a switch statement embedded usage of tag name lt name gt a struct
111. ction sinh computes the hyperbolic sine of x to full double precision Return Value sinh returns the closest internal representation to sinh x expressed as a double floating value If the result is too large to be properly repre sented sinh returns zero Example To obtain the hyperbolic sine of complex z typedef struct double x iy complex complex z Zx Sinh z x cos z iy z iy cosh z x sin z iy See Also cosh exp tanh Notes sinh is packaged in the floating point library 2012 COSMIC Software Using The Compiler 147 Eg C Library sprintf sprintf Description Output arguments formatted to buffer Syntax include lt stdio h gt int sprintf char s char fmt Function sprintf writes formatted to the buffer pointed at by s using the format string at fmt and the arguments specified by in exactly the same way as printf See the description of the printf function for information on the format conversion specifiers A NUL character is written after the last character in the buffer Return Value sprintf returns the numbers of characters written not including the ter minating NUL character Example To format a double at d into buf sprintf buf S10f n d See Also printf Notes sprintf is packaged in both the integer library and the floating point library The functionality of the integer only version of sprintf is a sub set of the functionalit
112. ction is not ending with a return statement missing prototype level 2 a function has been called without any previous prototype The pp option also produces this message missing return expression level 6 a return statement without expression is specified in a function with a non void return type shift count out of range level 2 a shift count is larger than the bit size of the shifted expression truncating assignment level 1 an expression is assigned to a varia ble and has a type larger than the variable one truncating constant cast level 1 a constant is cast to a smaller type which truncates its initial value unreachable code level 4 a code sequence cannot be reached due to previous optimizations value out of range level 2 a constant is assigned to a variable and is larger or smaller than the possible set of values for that type lt variable gt used before set level 7 a local variable has been used before beeing initialized by an explicit assignment Return Status cpcorm returns success if it produces no error diagnostics 2012 COSMIC Software Compiler Passes 367 D The cpcorm Parser Example cpcorm is usually invoked before cgcorm the code generator as in cpcorm o 2 cx1 u i cosmic hcorm file c cgcorm o 2 cx2 2 cx1 368 Compiler Passes 2012 COSMIC Software The cgcorm Code Generator The cgcorm Code Generator cgcorm is the code generating p
113. cts on the resulting code from the smallest 1 to the highest 7 The warn compiler option activates warning from level 1 To activate warnings from a different level the pw option can be used where is a starting level The list of warning messages is shared with the extra verifications ones described in the next paragraph along with their associated level dis played between parenthesis Extra verifications This paragraph describes the checkings done by the ck parser option strict compiler option or when warnings are enabled warn or pw compiler option according to the error message produced compare out of range level 2 a comparison is made with a constant larger or smaller than the possible values for the type of the compared expression constant assignment in a test level 4 a constant is assigned to a var iable in a test expression 366 Compiler Passes 2012 COSMIC Software The cpcorm Parser float value too large for integer cast level 1 a float constant is cast to an integer or a long but is larger than the maximum value of the cast type implicit int type in struct union declaration level 5 implicit int type in global declaration level 5 implicit int type in local declaration level 5 implicit int type in argument declaration level 5 an object is declared without an explicit type and is defaulted to int according to the ANSI standard missing explicit return level 6 a fun
114. d as externals and will be only displayed in the linker map file p mark all defined symbols as public This option has the same effect than adding a xdef directive for each label si suppress the info section produced automatically and containing the object name date and assembler options u produce an error message in the listing file for all occur rence of an undefined symbol This option enforces the l option V display the name of each file which is processed X add line debug information to the object file Xp do not prefix filenames in the debug information with any absolute path name Debuggers will have to be informed about the actual files location 184 Using The Assembler 2012 COSMIC Software Invoking cacorm Cacorm Option Usage cont Option Description XX add debug information in the object file for any label defin ing code or data This option disables the p option as only public or used labels are selected Each source file specified by lt files gt will be assembled separately and will produce separate object and listing files For each source file if no errors are detected cacorm generates an object file If requested by the l or c options cacorm generates a listing file even if errors are detected Such lines are followed by an error message in the listing 2012 COSMIC Software Using The Assembler 185 Object File Object File The object file produced by the assemb
115. d as a builtin function its arguments can be any numerical type and type coercion occurs automatically Return Value max is a numerical rvalue of the form a lt b b a suitably paren thesized Example To set a new maximum level hiwater max hiwater level See Also min Notes max is an extension to the proposed ANSI C standard max is a builtin declared in the lt stdlib h gt header file You can use it by including lt stdlib h gt with your program Because it is a builtin max cannot be called from non C programs nor can its address be taken 2012 COSMIC Software Using The Compiler 121 Description Scan buffer for character Syntax include lt string h gt void memchr void s int c unsigned int n Function memchr looks for the first occurrence of a specific character c in an n character buffer starting at s Return Value memchr returns a pointer to the first character that matches c or NULL if no character matches Example To map keybuf characters into subst characters if t memchr keybuf s KEYSIZ NULL s subst t keybuf See Also strchr strcspn strpbrk strrchr strspn Notes memchr is packaged in the integer library 122 Using The Compiler 2012 COSMIC Software C Library memcmp memcmp Description Compare two buffers for lexical order Syntax include lt string h gt int memcmp void sl void s2 unsigned int n
116. d checksum ce ceseseeseeeeeseereeeeeeeees 87 COSE scars cease wen tat cases E cee oases tee 88 Hyperbolic COSINE ececcecceseeseeseeeceeccesceeeceeseeeeeeeeeeeeeees 89 Divide with quotient and remainder ceeeeeeeereeeee 90 Exit program execution ceseesceseceeeseeeeceeeeeeeeeeeeeeeeeeeees 91 Exponential socne eenn 92 Find double absolute value ec ceceeseeeecseseeeeeeeeeeeteeees 93 Copy a moveable code segment in RAM eeeeeeeeeeees 94 Round to next lower integer ee ecesesseeeeeeeeeeeeeeeeeeeeeeeees 95 Find double modulus 0 cece seeseeseeeeeeseseceeeeeeeeeeeeees 96 Free space on the heap cccccceccscessesseesenseeseeeeeeeeeeeeeeeees 97 Extract fraction from exponent patt eee ceeeeeeee eee 98 Get character from input stream lt 9D Get a text line from input stream 100 Test for alphabetic or numeric character eee 101 Test for alphabetic character cccccecseseecesceeceseeseeteeees Test for control Character ccseeceseseceeceeeceeeeteeeeeeeeeees Test for digit 252 05235 cas ets ve csavesedecssetecstatacessdecaseds sunsentani esestaces Test for graphic character Test for lower case character Test for printing character Test for punctuation character 0 0 ccecceceeeeeeeceeceteeteeees Integer square TOOT 6 esoo inae i aia Test for whitespace character ececeeeteteeereeeee LLO Test
117. d using the formula f x i y where i is some integer fis the same sign as x and the absolute value of fis less than the absolute value of y Return Value jfmod returns the value of f expressed as a double floating value If y is zero fmod returns zero Example x y fmod x y 5 5 5 0 0 5 5 0 5 0 0 0 0 0 0 0 0 0 5 5 5 0 0 5 Notes Jmod is packaged in the floating point library Using The Compiler 2012 COSMIC Software C Library free free Description Free space on the heap Syntax include lt stdlib h gt void free void ptr Function free returns an allocated cell to the heap for subsequence reuse The cell pointer ptr must have been obtained by an earlier calloc malloc or realloc call otherwise the heap will become corrupted free does its best to check for invalid values of ptr A NULL value for ptr is explic itly allowed however and is ignored Return Value Nothing Example To give back an allocated area free pd See Also calloc malloc realloc Notes No effort is made to lower the system break when storage is freed so it is quite possible that earlier activity on the heap may cause problems later on the stack free is packaged in the integer library 2012 COSMIC Software Using The Compiler 97 98 Ei C Library frexp frexp Description Extract fraction from exponent part Syntax include lt math h gt double frexp double val int ex
118. d with a symbol Sym bols declared with set may be altered by a subsequent set The equ directive should be used for symbols that will have a constant value lt expression gt must be fully defined at the time the equ directive is assembled Example OFST set 10 See Also equ lit 2012 COSMIC Software Using The Assembler 251 Assembler Directives spc Description Insert a number of blank lines before the next statement in the listing file Syntax spe lt num_lines gt Function The spe directive causes lt num_lines gt blank lines to be inserted in the listing output before the next statement Example spc 5 title new file If listing is requested 5 blank lines will be inserted then the title will be output See Also title 252 Using The Assembler 2012 COSMIC Software Assembler Directives switch switch Description Place code into a section Syntax switch lt section_name gt Function The switch directive switches output to the section defined with the section directive lt section_name gt is the name of the target section and has to be already defined All code and data following the switch directive up to the next section switch or end directive are placed in the section lt section_name gt Example switch bss buffer ds b 512 xdef buffer This will place buffer into the bss section See Also section 2012 COSMIC Software Using The Ass
119. dc 1 start_ram_address start address of segment in ram dc 1 end prom address address of last data byte The end address in PROM of one segment gives also the starting address in prom of the following segment if any The address of the descriptor will be assigned to the symbol __idesec_ which is used by the crtsi s startup routine So all this mechanism will be activated just by linking the crtsi cxm file with the application or by referencing the symbol __idesc__ in your own startup file If the host segment has been opened with a m option giving a maxi mum size clnk will check that there is enough space to move all the selected segments Moveable Code The linker allows a code segment to be stored in the ROM part but linked at another address which is supposed to be located in RAM This feature is specially designed to allow an application to run FLASH pro gramming routines or bootloader from the RAM space This feature is sharing the same global mechanism than initialized data and the com mon descriptor built by the linker contains both record types The flag byte is used to qualify each entry In order to implement such a feature the link command file should contain a dedicated code segment marked with the ic option LINKER EXAMPLE FOR MOVEABLE CODE mark this segment with ic and link it at RAM address seg text b 0x100 n boot ic flash o seg text b 0x8000 n code application code file o 284 Usi
120. define macro is not a parameter bad directive lt name gt an unknown directive has been specified bad syntax is not followed by an identifier bad argument in macro lt name gt an argument of a operator in a define macro is missing bad asm directive a asm directive is not entered at a valid declara tion or instruction boundary bad define syntax a define is not followed by an identifier bad elif expression a elif is not followed by a constant expression bad else a e se occurs without a previous if ifdef ifndef or elif bad endasm directive a endasm directive is not closing a previous asm directive 328 Compiler Error Messages 2012 COSMIC Software Parser cpcorm Error Messages bad endif a endif occurs without a previous if ifdef ifndef elif or else bad if expression the expression part of a if is not a constant expression bad ifdef syntax extra characters are found after the symbol name bad ifndef syntax extra characters are found after the symbol name bad include syntax extra characters are found after the file name bad pragma attribute directive syntax for the pragma attribute directive is incorrect bad pragma section directive syntax for the pragma section direc tive is incorrect bad pragma space directive syntax for the pragma space directive is incorrect bad pragma unroll directive syntax for the pragma unroll direc tive
121. denote the tenth to 35th operand respectively Otherwise macro variables are denoted by their name prefixed by a character The macro variable name can also be enclosed by parenthesis to avoid unwanted concatenation with the remaining text In addition the macro variable contains the number of actual operands for a macro invoca tion The special parameter is expanded to the full list of passed arguments separated by commas 232 Using The Assembler 2012 COSMIC Software Assembler Directives macro The special parameter 0 corresponds to an extension lt ext gt which may follow the macro name separated by the period character For more information see Macro instructions A macro expansion may be terminated early by using the mexit direc tive which when encountered acts as if the end of the macro has been reached The sequence may be inserted in a label in order to allow a unique name expansion The sequence will be replaced by a unique number A macro can not be defined within another macro Example define a macro that places the length of a string in a byte in front of the string using numbered syntax r ltext 1 2 macro dc b 2 1 dc b l text given as first operand endm define a macro that places the length of a string in a byte in front of the string using named syntax ltext 1 2 See Also macro string dc b 2 1
122. der file You can use it by including lt stdlib h gt with your program Because it is a builtin min cannot be called from non C programs nor can its address be taken 2012 COSMIC Software Using The Compiler 127 Description Extract fraction and integer from double Syntax include lt math h gt double modf double val double pd Function modf partitions the double val into an integer portion which is deliv ered to pd and a fractional portion which is returned as the value of the function If the integer portion cannot be represented properly in an int the result is truncated on the left without complaint Return Value modf returns the signed fractional portion of val as a double floating value and writes the integer portion at pd Example val pd modf val pd Ss 5 0 1 5 0 5 0 0 4 9 4 0 9 0 0 0 0 0 1 4 1 0 4 See Also frexp ldexp Notes modf is packaged in the floating point library 128 Using The Compiler 2012 COSMIC Software C Library pow pow Description Raise x to the y power Syntax include lt math h gt double pow double x double y Function pow computes the value of x raised to the power of y Return Value pow returns the value of x raised to the power of y expressed as a dou ble floating value If x is zero and y is less than or equal to zero or if x is negative and y is not an integer pow returns zero Example x y pow x y 2 0 2
123. designated segment ident end segment This form defines ident as the logical end address of the designated segment ident pstart segment This form defines ident as the physical start address of the designated segment 276 Using The Linker 2012 COSMIC Software Linker Options ident pend segment This form defines ident as the physical end address of the designated segment ident size segment This form defines ident as the size of the desig nated segment ident init segment This form defines ident as the initialization image start address of the designated segment NOTE Whitespaces are not allowed aside the equal sign For more information about DEFs and REFs refer to the section DEF s and REFs on page 289 Reserve Space Option The following option is used to reserve space in a given segment spc lt segment gt lt value gt reserve lt value gt bytes of space at the current location in the segment named lt segment gt spc lt segment gt section reserve a space at the current location in the segment named lt segment gt equal to the current size of the opened segment where the given section is loaded The size is evaluated at once so if the reference segment grows after that directive there is no further modifi cation of the space reservation If such a directive is used to duplicate an exist ing section it has to be placed in the link command f
124. does not produce any map even if requested when used with the s option The basic sequence of commands looks like clnk o appli cxm m appli map appli 1kf clnk o appli sym s appli 1lkf The first link builds the application itself using the appli lkf command file The second link uses the same command file and creates an object file containing only an absolute symbol table This file can then be used as an input object file in any other link command file 294 Using The Linker 2012 COSMIC Software Description of The Map File Description of The Map File The linker can output a map file by using the m option The map file contains 4 sections the Segment section the Modules section the Stack Usage section and the Symbols section Segment Describe the different segments which compose the appli cation specifying for each of them the start address in hexa the end address in hexa the length in decimal and the name of the segment Note that the end value is the address of the byte following the last one of the segment meaning that an empty segment will have the same start and end addresses If a segment is initialized it is dis played twice the first time with its final address the sec ond time with the address of the image copy Modules List all the modules which compose the application giving for each the description of all the defined sections with the same format as in the Segment section If
125. e chex translate object module format clabs generate absolute listings clib build and maintains libraries cobj examine objects modules cvdwarf generate ELF DWARF format The assembler is described in Chapter 5 Using The Assembler The linker is described in Chapter 6 Using The Linker Support for debugging is described in Chapter 7 Debugging Support The description of each utility tells you what tasks it can perform the command line options it accepts and how you use it to perform some commonly required operations At the end of the chapter are a series of examples that show you how to combine the programming support util ities to perform more complex operations 2012 COSMIC Software Programming Support 309 a The chex Utility The chex Utility You use the chex utility to translate executable images produced by clnk to one of several hexadecimal interchange formats These formats are Motorola S record format and Intel standard hex format You can also use chex to override text and data biases in an executable image or to output only a portion of the executable The executable image is read from the input file lt file gt Command Line Options chex accepts the following command line options each of which is described in detail below a b e f s wW x gt chex options file absolute file start address address bias entry point addres
126. e The if directives may be nested The skipped lines may or may not in the listing depending on the clist directive status Example ife hello 2 if hello equals argument mov rl 45 load 45 elsec otherwise mov rl 0 endc See Also elsec endc clist 218 Using The Assembler 2012 COSMIC Software Assembler Directives ifdef ifdef Description Conditional assembly Syntax ifdef lt label gt or ifdef lt label gt instructions instructions endc elsec instructions endc Function The ifdef elsec and ende directives allow conditional assembly The ifdef directive is followed by a label lt abel gt If lt abel gt is defined the following instructions are assembled up to the next matching ende or elsec directive otherwise the following instructions up to the next matching endec or elsec directive are skipped lt abe gt must be first defined It cannot be a forward reference If the ifdef statement ends with an elsec directive the expression result is inverted and the same process applies to the following instructions up to the next matching endif So if the ifdef expression was not zero the instructions between elsec and endc are skipped otherwise the instruc tions between elsec and endc are assembled An elsec directive applies to the closest previous if directive The if directives may be nested The skipped lines may or may not be in the listing depending on the clist d
127. e use 7 use 7 use data structure library current build standard maths macros ports definition 2012 COSMIC Software Assembler Directives list list Description Turn on listing during assembly Syntax list Function The list directive controls the parts of the program which will be written to the listing file It is effective if and only if listings are requested it is ignored otherwise Example list expand source code until end or nolist dc b 1 2 4 8 16 end See Also nolist 2012 COSMIC Software Using The Assembler 229 Assembler Directives lit e lit Description Give a text equivalent to a symbol Syntax label lit string Function The lit directive is used to associate a text string to a symbol label This symbol is replaced by the string content when parsed in any assembler instruction or directive Example nor lit 5 add r0 nbr expand as addi r0 5 See Also equ set 230 Using The Assembler 2012 COSMIC Software Assembler Directives local Description Create a new local block Syntax local local Function The local directive is used to create a new local block When the local directive is used all temporary labels defined before the local directive will be undefined after the local label New local labels can then be defined in the new local block Local labels can only be referenced within t
128. e the right expression of a shift operator is not an integer invalid sizeof operand type the sizeof operator has been applied to a function invalid space for argument lt name gt an argument has been declared with a space modifier incompatible with the stack allocation invalid space for function a function has been declared with a space modifier incompatible with the function allocation invalid space for local lt name gt a local variable has been declared with a space modifier incompatible with the stack allocation invalid storage class storage class is not legal in this context invalid struct union operation a structure or an union has been used as operand of an arithmetic operator 336 Compiler Error Messages 2012 COSMIC Software Parser cpcorm Error Messages invalid switch test type the expression of a switch instruction must be of integer type invalid typedef usage a typedef identifier is used in an expression invalid void pointer a void pointer has been used as operand of an addition or a substraction invalid while test type the expression of a while instruction is not a testable expression misplaced pragma section directive a pragma section directive has been placed inside the body of a C function misplaced pragma attribute name a pragma attribute directive is not declaring any object missing argument in macro lt name gt an argument of a opera tor in a defin
129. e command line See Invoking cacorm in Chapter 5 for the list of all accepted options ce specify a path for the error files By default errors are cre ated in the same directory than the source files cl specify a path for the listing files By default listings are cre ated in the same directory than the source files co specify a path for the object files By default objects are created in the same directory than the source files d gt specify as the name of a user defined preprocessor sym bol define The form of the definition is dsymbol value the symbol is set to 1 if value is omitted You can specify up to 128 such definitions e log errors from parser in a file instead of displaying them on the terminal screen The error file name is defaulted to lt file gt err and is created only if there are errors eC treat all files as C source files eg produce error messages directly compatible with the Eclipse environment eS treat all files as assembler source files X use the compiler driver s path as prefix to quickly locate the executable passes Default is to use the path variable envi ronment This method is faster than the default behavior but reduces the command line length f specify as the name of a configuration file This file con tains a list of options which will be automatically used by the compiler If no file name is specified then the c
130. e compiler the acia lkf file contains the following information line 1 Link command file for test program line 2 Copyright c 2011 by COSMIC Software line 3 line 4 seg vector b0x0000 m0x1000 n vector int table line 5 seg sconst b0x1000 m0xf000 r2 n sconst con stants follow vectors line 6 seg text a sconst r2 it n text prog follow consts line 7 seg sdata b0x20000000 o0x0000 m0x1000 r2 id n sdata data start address line 8 seg sbss a sdata n sbss uninitialized data line 9 vector o interrupt vectors line 10 crts cxm line 11 acia o application program line 12 libis cxm integer library 2012 COSMIC Software Tutorial Introduction 19 Compiling and Linking line 13 libm cxm machine library line 14 def sram pstart sbss bss start address line 15 def eram pend sbss bss end address line 16 def stack 0x20010000 stack pointer init value line 17 def _ sdata pstart sdata data pointer value line 18 tdef _ memory end sbss symbol used by library You can create your own link command file by modifying the one pro vided with the compiler Here is the explanation of the lines in acia lkf lines 1 to 3 These are comment lines Each line can include comments They must be prefixed by the character line 4 seg vector b0x0000 m0x1000 n vector creates a text code segment located at 0x0 which is named vector line 5 seg sconst b0x1000
131. e data object designated by ap The argument parmN must be the identifier you declare as the name of the last specified argument in the variable length argument list for the function In the function prototype for the function parmN is the argument name you write just before the The type of parmN must be one of the types assumed by an argument passed in the absence of a prototype Its type must not be float or char Also parmN cannot have storage class register If you expand va_start you must expand the macro va_end before your program returns from the function containing the variable length argu ment list You must write an expansion of va_start as an expression statement containing a function call The call must be followed by a semicolon Return Value Nothing va_start expands to a statement not an expression Example To write multiple strings to a file include lt stdio h gt include lt stdarg h gt main 176 Using The Compiler 2012 COSMIC Software C Library va_start void strput strput pf This is one string n and this is another n char 0 void strput FILE pf void strput char ptr void strput ptr char ptr char ptr va_list va if ptr return else puts ptr va_start va ptr while ptr va_arg va char puts ptr va_end va See Also va_arg va_end Notes va_start is a macro declared in the
132. e floating value If the result is too large to be properly repre sented tanh returns zero Example To compute the hyperbolic tangent of x y tanh x See Also cosh exp sinh Notes tanh is packaged in the floating point library 2012 COSMIC Software Using The Compiler 169 Ei C Library tolower tolower Description Convert character to lower case if necessary Syntax include lt ctype h gt int tolower int c Function tolower converts an upper case letter to its lower case equivalent leav ing all other characters unmodified Return Value tolower returns the corresponding lower case letter or the unchanged character Example To accumulate a hexadecimal digit for sum 0 isxdigit s s if isdigit s sum sum 16 s O else sum sum 16 tolower s 10 a See Also toupper Notes tolower is packaged in the integer library 170 Using The Compiler 2012 COSMIC Software C Library toupper toupper Description Convert character to upper case if necessary Syntax include lt ctype h gt int toupper int c Function toupper converts a lower case letter to its upper case equivalent leav ing all other characters unmodified Return Value toupper returns the corresponding upper case letter or the unchanged character Example To convert a character string to upper case letters for i 0 i lt size i buf i
133. e included _asm lt string constant gt Function _asm generates inline assembly code by copying lt string constant gt and quoting it into the output assembly code stream If extra arguments are specified they are processed as for a standard function If argu ments are stacked they are popped off just after the inline code pro duced For more information see Inserting Inline Assembly Instructions in Chapter 3 Return Value Nothing unless _asm is used in an expression In that case normal return conventions must be followed See Register Usage in Chapter 3 Example The sequence mov r0 r1 mov r2 r3 may be generated by the follow ing call _asm mov r0 r1 n mov r2 r3 Notes _asm is not packaged in any library It is recognized and its argument passed unchanged by the compiler itself Using The Compiler 2012 COSMIC Software C Library abort abort Description Abort program execution Syntax include lt stdlib h gt void abort void Function abort stops the program execution by calling the exit function which is placed by the startup module just after the call to the main function Return Value abort never returns Example To abort in case of error if fatal_error abort See Also exit Notes abort is a macro equivalent to the function name evit 2012 COSMIC Software Using The Compiler 73 74 Ei C Library abs
134. e macro is missing missing gt in include a file name of a include directive begins with lt and does not end with gt missing in defined expansion a C does not have a balancing ina defined operator missing in argument declaration the declaration of a function argu ment does not end with missing in local declaration the declaration of a local variable does not end with missing in member declaration the declaration of a structure or union member does not end with missing test expression the test expression is missing in a ternary operator missing _asm argument the asm function needs at least one argu ment 2012 COSMIC Software Compiler Error Messages 337 Parser cpcorm Error Messages missing argument the number of arguments in the actual function call is less than that of its prototype declaration missing argument for macro lt name gt a macro invocation has fewer arguments than its corresponding declaration missing argument name the name of an argument is missing in a pro totyped function declaration missing array subscript an array element has been referenced with an empty subscript missing do test expression a do while instruction has been speci fied with an empty while expression missing enumeration member a member of an enumeration is not an identifier missing explicit return a return statem
135. e modules from library e accept empty module male object list filename al load all library at link p no pathname in modules Sis replace modules in library s list symbols in library zE list files in library v be verbose FR extract modules from library Clib Option Usage Option Description a include absolute symbols in the library symbol table C create a library containing lt files gt Any existing lt library gt of the same name is removed before the new one is created d delete from the library the zero or more files in lt files gt e accept module with no symbol i take object files from a list You can put several files per line or put one file per line Each lines can include com ments They must be prefixed by the character If the command line contains lt files gt then lt files gt will be also added to the library 2012 COSMIC Software Programming Support 317 8 The clib Utility Clib Option Usage cont Option Description l when a library is built with this flag set all the modules of the library will be loaded at link time By default the linker only loads modules necessary for the application p do not prefix module names in library with any path This option is only meaningfull with option c r in an existing library replace the zero or more files in lt files gt If no library lt library gt exists create a library contain ing
136. e written and debugged to provide something which basically already exists second the details of exactly what the function must do and how it must do it may not be available thus preventing a proper implementation of the function The second approach is to write a new function say my_func which does the extra processing required and then calls the standard function func This approach will generally work unless the original function func is called by other functions in the libraries In that case the extra function behavior cannot occur when func is called from library func tions since it is actually my_func that performs it The third approach is to use the aliasing capabilities of the linker Like the second method a new function will be written which performs the new behavior and then calls the old function The twist is to give the old function a new name and hide its old name Then the new function is given the old function s name and when it calls the old function it uses the new name or alias for that function The following linker script provides a specific example of this technique for the function func line 1 seg text b 0x1000 line 2 seg data b0 line 3 new line 4 Crts xx line 5 def _oldfunc _func line 6 pri func o line 7 new line 8 prog o newfunc o line 9 lt libraries gt 2012 COSMIC Software Using The Linker 291 The function name func as referenced here is the name as seen by the C prog
137. eachable code eliminate 11 uppercase mnemonic 45 y va_arg macro 172 va_end function 174 va_start macro 176 variable length argument list 174 176 reorder local 365 vers option 6 volatile data 37 memory mapped control registers 37 qualifier 37 using keyword 37 vprintf function 178 vsprintf function 179 W warnings 65 365 widen argument 172 to int 172 window set shift 267 322 size 272 X xdef directive 256 257 xref directive 256 257 Index 11
138. ead of logical address in the map file S create an output file containing only an absolute symbol table but still with an object file format The resulting file can then be used in another link to provide the symbol table of an existing application sa display symbols sort by address instead of alphabetic order in the map file S suppress the info segment content for compatibility with tools not supporting this segment yet sl output local symbols in the executable file 2012 COSMIC Software Using The Linker 267 6 Linker Options Global linker Options Option Description u display unused symbols Valid options are u1 display data symbols U2 display code and constant symbols u4 display absolute symbols located variables U8 display symbols defined in the link file Those values can be combined added or or ed to display several categories This option has no effect when the debug option has been set as symbols are at least referenced in the debug section Symbols defined in removed sections are of course not displayed V be verbose 268 Using The Linker 2012 COSMIC Software Linker Options Segment Control Options This section describes the segment control options that control the structure of individual segments of the output module A group of options to control a specific segment must begin with a seg option Such an
139. eaeenes 249 Give a resetable value to a symbol sssnssesseserseeseseeseeee 251 Insert a number of blank lines before the next statement in the listmg le monier inss ners r SEE 252 Place code into a section s ssessessesesessisersresirersrsrrsrseees 253 Specify the number of spaces for a tab character in the listing Pile R E E E E AAE EEE E Define default header ee csecsceseesceseeeeeeeeseeeeceeceeceaes Tirod Cti ON seson eaei e aiaa ia EE ER OVEIVIEW tuts a oeri AU TEAT A Linker Command File Processing Inserting comments in Linker commands 0 265 Linker Options cccccccescescesceseeseeseeeceeseeeeeeseeceececeeceseeaeenes 266 vi Global Command Line Options cccecceeseeeeesceeeeeeeees 267 Segment Control Options cceceseeseeseeseeseeneeeeeeeeeeees 269 Segment Grouping cececececceescesceseeeseeeeeeeeeeeeeeeseeeeaees 273 Linking Files on the Command line 0 0 eee eens 273 Symbol Definition Option Reserve Space Option cccccceccescssscseceecesceseesensenseeseeseees Section Relocation s sesse esenee sisse ar ia siaa aS Address Specification Overlapping Control Setting Bias and Offset Setting the Bi S sssssirsisresssresrrcsessasiecseseassrssisssnsibriars pasar aas Setting the Offset sesiis eceseeseesecsececeeeeeeseeseeeeeeeseeeeeees Using Default Placement Based Segment Configuration Linking
140. ed the subsequent argument must be an int pointer to an integer into which is written the number of characters read from the input stream so far by this call to scanf O an octal integer is expected the subsequent argument must be a pointer to integer 2012 COSMIC Software Using The Compiler 141 a C Library scanf p a pointer is expected the subsequent argument must be a void pointer The format of the input field should be the same as that pro duced by the p conversion of printf On any input other than a value printed earlier during the same program execution the behavior of the p conversion is undefined S a character string is expected the subsequent argument must be a char pointer to an array large enough to hold the string and a terminat ing NUL which will be added automatically The input field is termi nated by a space a horizontal tab or a newline which is not part of the field u an unsigned decimal integer is expected the subsequent argument must be a pointer to integer X a hexadecimal integer is expected a subsequent argument must be a pointer to integer a string that is not to be delimited by spaces is expected the subse quent argument must be a char just as for s The left bracket is fol lowed by a set of characters and a right bracket the characters between the brackets define a set of characters making up the string If the first character is not a circumflex
141. ed by typing a command line Command Line A command line is generally composed of three major parts program name lt flags gt lt files gt where lt program_name gt is the name of the program to run lt flags gt an optional series of flags and lt files gt a series of files Each element of a command line is usually a string separated by whitespace from all the others Flags Flags are used to select options or specify parameters Options are rec ognized by their first character which is always a or a followed by the name of the flag usually a single letter Some flags are simply yes or no indicators but some must be followed by a value or some additional information The value if required may be a character string a single character or an integer The flags may be given in any order and two or more may be combined in the same argument so long as the second flag can t be mistaken for a value that goes with the previ ous one Each utility can display its version number build date and host system by specifying the vers option The host name is ended by the F sequence if a license is necessary for executing the utility Introduction 2012 COSMIC Software Document Conventions It is possible for each utility to display a list of accepted options by specifying the help option Each option will be displayed alphabeti cally on a separate line with its name and a brief description
142. eeeeeeeeees 224 Conditional assembly c esccecesecseeseeseeeeeeeeeeeeeeeeeees 225 Conditional assembly cscceeeeeesecseeseeeeeeeeeeeeeeeeeees 226 Conditional assembly 0000 a221 Include text from another text file 228 Turn on listing during assembly we 229 Give a text equivalent to a symbol cceeeceseseeeeeeeeeee 230 Create a new local block cc cceceeseeseeeeseeseeseeseeeeeeeeeees 231 De ne a Matro 5 c5 ccd Sa cesseteesdcoieeisocsensend cunsedscecesteesesteatanes 232 Send a message out to STDOUT ceeceecseeeeeeeeeeeeeee 234 Terminate a macro definition 52 235 Turn on or off listing of macro expansion 236 Turn off listing 0 cceccecseeseeseeeeeeeeeeeeeees e237 Disable pagination in the listing file 0 eee eee 238 Creates absolute symbols c ccecceceseesseseeneeeeeeeeeeeeeeee 239 Sets the location counter to an offset from the beginning of a SOCH ON PRE EAE saa tondieaaetiies sate 240 Start a new page in the listing file 0 eee eeeeteeneeee 241 Specify the number of lines per pages in the listing file 242 Repeat a list of lines a number of times ceeeeeeee 244 Restore saved section cccsesseeseesseseeeeeeeeeeceeceeceeceseeaeeaes 246 Terminate a repeat definition cee ccecseeseeeeeeeeeeeeeeee 247 DAVE SCCU ON arris a tevin ieee tae cesta ete 248 Define a new section ccceceescesceseeeecesceececesceeeseee
143. embler 253 Assembler Directives tabs tabs Description Specify the number of spaces for a tab character in the listing file Syntax tabs lt tab _size gt Function The tabs directive sets the number of spaces to be substituted to the tab character in the listing output The minimum value of lt tab_size gt is 0 and the maximum value is 128 Example tabs 6 254 Using The Assembler 2012 COSMIC Software Assembler Directives title title Description Define default header Syntax title name Function The title directive is used to enable the listing pagination and to set the default page header used when a new page is written to the listing out put Example title My Application See Also page plen Note For compatibility with previous assemblers the directive ttl is alias to title 2012 COSMIC Software Using The Assembler 255 Assembler Directives xdef xdef Description Declare a variable to be visible Syntax xdef identifier identifier Function Visibility of symbols between modules is controlled by the xdef and xref directives A symbol may only be declared as xdef in one module A symbol may be declared both xdef and xref in the same module to allow for usage of common headers Example xdef sqrt allow sqrt to be called from another module sqrt routine to return a square root of a number gt zero See Also xref 2
144. ent is not ending a non void function strict missing exponent in real a floating point constant has an empty expo nent after the e or E character missing expression an expression is needed but none is present missing file name in include a include directive is used but no file name is present missing goto label an identifier is needed after a goto instruction missing if test expression an if instruction has been used with an empty test expression missing initialization expression a local variable has been declared with an ending character not followed by an expression missing initializer a simple object has been declared with an ending character not followed by an expression missing line number a line number is missing in a line directive 338 Compiler Error Messages 2012 COSMIC Software Parser cpcorm Error Messages missing local name a local variable has been declared without a name missing member declaration a structure or union has been declared without any member missing member name a structure or union member has been declared without a name missing name in declaration a variable has been declared without a name missing prototype a function has been used without a fully proto typed declaration strict missing prototype for inline function an inline function has been declared without a fully prototyped syntax missing return expression
145. ent of 0 otherwise Example if _checksumx abort Notes The descriptor is built by the linker only if the _checksumx function is called by the application even if there are segments marked with the ck option _checksumx is packaged in the integer library See Also _checksum _checksum16 _checksum16x 2012 COSMIC Software Using The Compiler 85 86 a C Library _checksum16 _checksum16 Description Verify the recorded checksum Syntax int _checksum16 Function _checksum16 scans the descriptor built by the linker and controls at the end that the computed 16 bit checksum is equal to the one expected For more information see Checksum Computation in Chapter 6 Return Value _checksum16 returns 0 if the checksum is correct or a value different of 0 otherwise Example if _checksum16 abort Notes The descriptor is built by the linker only if the _checksum16 function is called by the application even if there are segments marked with the ck option _checksum16 is packaged in the integer library See Also _checksum _checksumx _checksum16x Using The Compiler 2012 COSMIC Software C Library _checksum16x _checksum16x Description Verify the recorded checksum Syntax int _checksum1 6x Function _checksum16x scans the descriptor built by the linker and controls at the end that the computed 16 bit checksum is equal to the one e
146. enty different names may be specified on the com mand line If there are several segments with the same name they will not all be output Return Status chex returns success if no error messages are printed that is if all records are valid and all reads and writes succeed Otherwise it returns failure Examples The file hello c consisting of char p hello world when compiled produces the following the following Motorola S record format chex hello o SOOA000068656C6COF2ZE6F44 S 1110000020068656C6C6F20776F726C640090 S9030000FC 312 Programming Support 2012 COSMIC Software The chex Utility and the following Intel standard hex format chex fi hello o 0E000000020068656C6C6F20776F726C640094 00000001FF 2012 COSMIC Software Programming Support 313 8 The clabs Utility The clabs Utility clabs processes assembler listing files with the associated executable file to produce listing with updated code and address values clabs decodes an executable file to retrieve the list of all the files which have been used to create the executable For each of these files clabs looks for a matching listing file produced by the compiler ls file If such a file exists clabs creates a new listing file la file with abso lute addresses and code extracted from the executable file To be able to produce any results the compiler must have been used with
147. eplaced by a numeric value corresponding to the number of arguments actually found on the invocation line In order to operate directly in memory the previous macro may have been written using the numbered syntax signex macro sign extension mov r2 0 prepare MSW Lax v1 r9 1 4 load LSW bpl pos if not positive mvn bape ay invert MSW 194 Using The Assembler 2012 COSMIC Software Assembly Language Syntax pos str r2 r9 1 store MSW endm end of macro And called signex lword sign extend lword This macro may also be written using the named syntax signex macro value sign extension mov r2 0 prepare MSW ldr rl r9 walue 4 load LSW bpl pos if not positive mvn r2 xr2 invert MSW pos Str r2 r9 value store MSW endm end of macro The form of a macro call is name gt lt ext gt lt arguments gt The special parameter is replaced by a sequence containing the list of all the passed arguments separated by commas This syntax is useful to pass all the macro arguments to another macro or a repeatl directive The special parameter 0 corresponds to an extension lt ext gt which may follow the macro name separated by the period character An exten sion is a single letter which may represent the size of the operands and the result For example table macro dc 0 1 2 3 4 endm When invoking the macro table b will generate a table of byte
148. equal to x expressed as a double floating value Example x ceil x 5 1 6 0 5 0 5 0 0 0 0 0 5 0 5 0 5 1 5 0 See Also floor Notes ceil is packaged in the floating point library 2012 COSMIC Software Using The Compiler 83 84 Ei C Library _checksum checksum Description Verify the recorded checksum Syntax int _checksum Function _checksum scans the descriptor built by the linker and controls at the end that the computed 8 bit checksum is equal to the one expected For more information see Checksum Computation in Chapter 6 Return Value _checksum returns 0 if the checksum is correct or a value different of 0 otherwise Example if _checksum abort Notes The descriptor is built by the linker only if the checksum function is called by the application even if there are segments marked with the ck option _checksum is packaged in the integer library See Also _checksumx _checksum16 _checksum16x Using The Compiler 2012 COSMIC Software C Library _checksumx _checksumx Description Verify the recorded checksum Syntax int _checksumx Function _checksumx scans the descriptor built by the linker and controls at the end that the computed 8 bit checksum is equal to the one expected For more information see Checksum Computation in Chapter 6 Return Value _checksumx returns 0 if the checksum is correct or a value differ
149. er endc See Also elsec endc clist 220 Using The Assembler 2012 COSMIC Software Assembler Directives ifge ifge Description Conditional assembly Syntax ifge lt expression gt or ifge lt expression gt instructions instructions endc elsec instructions endc Function The ifge elsec and ende directives allow conditional assembly The ifge directive is followed by a constant expression If the result of the expression is greater or equal to zero the following instructions are assembled up to the next matching endc or elsec directive otherwise the following instructions up to the next matching endc or elsec direc tive are skipped If the ifge statement ends with an elsec directive the expression result is inverted and the same process applies to the following instructions up to the next matching endce So if the ifge expression is greater or equal to zero the instructions between elsec and endc are skipped otherwise the instructions between elsec and endc are assembled An elsec direc tive applies to the closest previous if directive The if directives may be nested The skipped lines may or may not in the listing depending on the clist directive status Example ifge offset 127 if offset too large addptr offset call a macro elsec otherwise add vl offset add to register endc See Also elsec endc clist 2012 COSMIC Software Using The Assembler 221 Assembler Directives if
150. er or a file con taining an unlimited list of directory names l create a listing file The name of the listing file is derived from the input file name by replacing the suffix by the s extension unless the I option has been specified create a listing file in the text file If both I and I are spec ified the listing file name is given by the option 2012 COSMIC Software Using The Assembler 183 Invoking cacorm Cacorm Option Usage cont Option Description m accept the old syntax md create only a list of make compatible dependencies con sisting for each source file in the object name followed by a list of included files needed to assemble that file mi accept label that is not ended with a character n select the processor type The default type is the Cortex M3 M4 processors The Cortex M0O processor is selected by option n0 0 write object code to the file If no file name is specified the output file name is derived from the input file name by replacing the rightmost extension in the input file name with the character o For example if the input file name is prog s the default output file name is prog o pe mark all symbols defined by an equ directive as public This option has the same effect than adding a xdef directive for each of those symbols pl put locals in the symbol table They are not publishe
151. eral directives are available to modify the listing display such as title for the page header plen for the page length page for starting a new page tabs for the tabulation characters expansion By default the listing file is not paginated Pagination is enabled by using at least one title directive in the source file or by specifying the ft option on the command line Otherwise the plen and page directives are simply ignored Some other directives such as clist mlist or dlist control the amount of information produced in the listing 186 Using The Assembler 2012 COSMIC Software Assembly Language Syntax A cross reference table will be appended to the listing if the e option has been specified This table gives for each symbol its value its attributes the line number of the line where it has been defined and the list of line numbers where it is referenced Assembly Language Syntax The assembler cacorm conforms to the Freescale syntax as described in the document Assembly Language Input Standard The assembly lan guage consists of lines of text in the form label command operands comment or comment where indicates the end of a label and defines the start of a com ment The end of a line terminates a comment The command field may be an instruction a directive or a macro call Instruction mnemonics and assembler directives may be written in upper or lower case The C compiler generates low
152. eration Registers r4 to r8 and r10 to r11 are used for register variables non volatile When used these registers are saved and restored on function entry and exit When targetting the MO instruction set registers r8 to r11 are not used restricting the register variables to registers r4 to r7 Register r12 is currently not used for EABI compliance 50 Programming Environments 2012 COSMIC Software Heap Management Control with the C Compiler Heap Management Control with the C Compiler The name heap designates a memory area in which are allocated and deallocated memory blocks for temporary usage A memory block is allocated with the malloc function and is released with the free function The malloc function returns a pointer to the allocated area which can be used until it is released by the free function Note that the free function has to be called with the pointer returned by malloc The heap allocation differs from a local variable allocation because its life is not limited to the life of the function performing the allocation In an embedded application the malloc free mechanism is available and automatically set up by the compiler environment and the library But it is possible to control externally the heap size and location The default compiler behaviour is to create a data area containing applica tion variables heap and stack in the following way initialized variables uninitialized va
153. ercase assembly lan guage A source file must end with the end directive All the following lines will be ignored by the assembler If an end directive is found in an included file it stops only the process for the included file Instructions 2012 COSMIC Software cacorm recognizes the following instructions adc itee mvn smlabt strexb adcs iteee mvns smlad strexd add iteet neg smladx strexh adds itet negs smlal strh addw itete nop smlalbb strht adr itett orn smlalbt strt and itt orns smlald sub ands itte orr smlaldx subs asr ittee orrs smlaltb subw asrs ittet pkhbt smlaltt svc b ittt pkhtb smlatb sxtab bal ittte pld smlatt sxtabl6 bee itttt pli smlawb sxtah Using The Assembler 187 Assembly Language Syntax bes lde beq ldc2 bfc ldmdb bfi ldmea bge ldmfd bgt ldmia bhi ldr bhs idro bic ldrbt bics ldrd bkpt ldrex bl ldrexb ble ldrexd blo ldrexh bls ldrh blt ldrht blx ldrsb bmi ldrsbt bne ldrsh bpl ldrsht bvc ldrt bvs isl bx lsls bxj tsr cbnz lsrs cbhz mcr cdp mcr2 cdp2 merr clrex mcrr2 clz mla cmn mls cmp mov cpsid movs cpsie movt cpy movw dbg mrc dmb mrc2 dsb mrre eor mrrc2 eors mrs isb msr it mul ite muls 188 Using The Assembler pop push qadd qadd16 qadd8 qasx qdadd qdsub qsax qsub qsub16 qsub8 roi rev revl6 revsh rfe rfedb rfeia ror rors Trx rrxs rsb rsbs sadd16 sadd8 sasx sbc sbcs sbfx sdiv sel setend sev shadd16 shadd8 shasx
154. es sharing the same name do have the same content or with conditional behav iours 322 Programming Support 2012 COSMIC Software The cvdwarf Utility Cvdwarf Option usage cont Option Description e specify either a symbol name or a numerical value defining the entry field in the elf header If a symbol name is speci fied it is searched in the assembler symbol table The value of symbol __stext is used by default loc location lists are used in place of location expressions whenever the object whose location is being described can change location during its lifetime THIS POSSIBILITY IS NOT SUPPORTED BY ALL DEBUGGERS 0 where is a filename is used to specify the output file for cvdwarf By default if o is not specified cvdwarf send its output to the file whose name is obtained from the input file by replacing the filename extension with elf 2012 COSMIC Software Programming Support 323 8 The cvdwarf Utility Cvdwarf Option usage cont Option Description page output addresses in paged mode where specifies the page type Valid usage for Paging Window 1 for All HC12 HCS12 and FLASH 0x8000 to banked HCS08 paged deriv Oxbfff code atives when Code Paging used 2 for Only for HC12A4 RAM 0x7000 to banked when Data Paging 0x7fff data used 3 both Only for HC12A4 FLASH 0x8000 to code when Data and Code Oxbfff and Paging used RAM 0x70
155. esent it is skipped before to convert If endptr is not a null pointer endptr is set to the address of the first unconverted character in the string nptr No checks are made against overflow or invalid character strings Return Value strtol returns the converted long integer If the string has no recogniza ble characters zero is returned Example To read a string from STDIN and convert it to a long gets buf 1 strtol buf NULL 0 See Also atof atoi strtoul strtod Notes strtol is packaged in the integer library 166 Using The Compiler 2012 COSMIC Software C Library strtoul strtoul Description Convert buffer to unsigned long Syntax include lt stdlib h gt unsigned long strtoul char nptr char endptr int base Function strtoul converts the string at nptr into a long integer Leading whitespace is skipped and an optional sign is permitted conversion stops on the first unrecognizable character If base is not zero charac ters a z or A Z represents digits in range 10 36 If base is zero a lead ing Ox or OX in the string indicates hexadecimal a leading 0 indicates octal otherwise the string is take as a decimal representation If base is 16 and a leading Ox or OX is present it is skipped before to convert If endptr is not a null pointer endptr is set to the address of the first unconverted character in the string nptr No checks are made aga
156. ession invalid function member a function has been declared within a struc ture or an union invalid function type the function call operator has been applied to an object which is not a function or a pointer to a function invalid if test type the expression of an if instruction is not a testa ble expression invalid indirection operand the operand of unary is not a pointer invalid line number the first parameter of a line directive is not an integer invalid local initialization the initialization of a local object is incom plete or ill formed invalid lvalue the left operand of an assignment operator is not a vari able or a pointer reference 2012 COSMIC Software Compiler Error Messages 335 Parser cpcorm Error Messages invalid narrow pointer cast a cast operator is attempting to reduce the size of a pointer invalid operand type the operand of a unary operator has an incom patible type invalid pointer cast operand a cast to a function pointer has been applied to a pointer that is not a function pointer invalid pointer initializer initializer must be a pointer expression or the constant expression 0 invalid pointer operand an expression which is not of integer type has been added to a pointer invalid pointer operation an illegal operator has been applied to a pointer operand invalid pointer types two incompatible pointers have been sub stracted invalid shift count typ
157. f 1 atol buf See Also atof atoi strtol strtod Notes atol is packaged in the integer library 2012 COSMIC Software Using The Compiler 81 82 Ei C Library calloc calloc Description Allocate and clear space on the heap Syntax include lt stdlib h gt void calloc int nelem int elsize Function calloc allocates space on the heap for an item of size nbytes where nbytes nelem elsize The space allocated is guaranteed to be at least nbytes long starting from the pointer returned which is guaranteed to be on a proper storage boundary for an object of any type The heap is grown as necessary If space is exhausted calloc returns a null pointer The pointer returned may be assigned to an object of any type without casting The allocated space is initialized to zero Return Value calloc returns a pointer to the start of the allocated cell if successful otherwise it returns NULL Example To allocate an array of ten doubles double pd pd calloc 10 sizeof double See Also free malloc realloc Notes calloc is packaged in the integer library Using The Compiler 2012 COSMIC Software C Library ceil ceil Description Round to next higher integer Syntax include lt math h gt double ceil double x Function ceil computes the smallest integer greater than or equal to x Return Value ceil returns the smallest integer greater than or
158. f the 1 appears with any other conversion character it is ignored L optionally specifies that the following e E f g and G conversion character applies to a long double argument If the L appears with any other conversion character it is ignored lt conversion character gt character that indicates the type of con version to be applied A field width or precision or both may be indicated by an asterisk instead of a digit string In this case an int argument supplies the field width or precision The arguments supplying field width must appear before the optional argument to be converted A negative field width argument is taken as a flag followed by a positive field width A nega tive precision argument is taken as if it were missing The lt flags gt field is zero or more of the following space a space will be prepended if the first character of a signed con version is not a sign This flag will be ignored if space and flags are both specified 2012 COSMIC Software Using The Compiler 131 a C Library printf result is to be converted to an alternate form For c d i s and u conversions the flag has no effect For o conversion it increases the precision to force the first digit of the result to be zero For p x and X conversion a non zero result will have Ox or OX prepended to it For e E f g and G conversions the result will contain a decimal point even if no digits follow
159. file 172 Using The Compiler 2012 COSMIC Software C Library va_arg include lt stdio h gt include lt stdarg h gt main void strput strput pf This is one string n and this is another n char 0 void strput FILE pf 7 void strput char ptr void strput ptr char ptr char ptr va_list va if ptr return else puts ptr va_start va ptr while ptr va_arg va char puts ptr va_end va See Also va_end va_start Notes va_arg is a macro declared in the lt stdarg h gt header file You can use it with any function that accepts a variable number of arguments by including lt stdarg h gt with your program 2012 COSMIC Software Using The Compiler 173 Ei C Library va_end va_end Description Stop accessing values in an argument list Syntax include lt stdarg h gt void va_end va_list ap Function va_end is a macro which you must expand if you expand the macro va_start within a function that contains a variable length argument list Information on the argument list is stored in the data object designated by ap Designate the same data object in both va_start and va_end You expand va_end after you have accessed all argument values with the macro va_arg before your program returns from the function that contains the variable length argument list After you expand va_end do not expand va_arg wit
160. flt directive is followed by a constant expression If the result of the expression is less than zero the following instructions are assembled up to the next matching endc or elsec directive otherwise the follow ing instructions up to the next matching endec or elsec directive are skipped If the iflt statement ends with an elsec directive the expression result is inverted and the same process applies to the following instructions up to the next matching endc So if the iflt expression was less than zero the instructions between elsec and endec are skipped otherwise the instructions between elsec and endec are assembled An elsec directive applies to the closest previous if directive The if directives may be nested The skipped lines may or may not in the listing depending on the clist directive status Example ifle offset 127 if offset small enough add rl offset add to register elsec otherwise addptr offset gt call a macro endc See Also elsec endc clist 224 Using The Assembler 2012 COSMIC Software Assembler Directives ifnc ifne Description Conditional assembly Syntax ifnc lt stringl gt string2 gt orifnc lt stringl gt lt string2 gt instructions instructions endc elsec instructions endc Function The ifne elsec and endec directives allow conditional assembly The ifne directive is followed by a constant expression If lt string gt and lt string2 gt are differents the fol
161. formation on the compiler passes see Appendix D 2012 COSMIC Software Introduction 11 CHAPTER 2 Tutorial Introduction This chapter will demonstrate step by step how to compile assemble and link the example program acia c which is included on your distri bution media Although this tutorial cannot show all the topics relevant to the COSMIC tools it will demonstrate the basics of using the com piler for the most common applications In this tutorial you will find information on the following topics Default Compiler Operation Compiling and Linking Linking Your Application Generating Automatic Data Initialization Specifying Command Line Options 2012 COSMIC Software Tutorial Introduction 13 Acia c Example file Acia c Example file The following is a listing of acia c This C source file is copied during the installation of the compiler EXAMPLE PROGRAM WITH INTERRUPT HANDLING Copyright c 2008 by COSMIC Software Each character received is copied in a buffer by the interrupt routine The main program reads characters from the buffer and echoes them include lt io05516 h gt define SIZE512 buffer size define TDRE0Ox8000000 transmit ready bit define RDRF0x2000000 receive data bit Authorize interrupts 7 define cli _asm wrteei 1 Some variables ay char buffer SIZE reception buffer char ptlec read p
162. function is both called in an interrupt function and in the main code incomplete def directive the def directive syntax is not correct incomplete seg directive the seg directive syntax is not correct incomplete spc directive the spc directive syntax is not correct init segment cannot be initialized the host segment for initialization cannot be itself initialized invalid argument the syntax of an optional input file is not correct invalid i option the i directive is followed by an unexpected charac ter missing command file a link command file must be specified on the command line missing output file the o option must be specified missing in def the def directive syntax is not correct missing in spe lt segment gt the spce directive syntax is not cor rect named segment lt segment gt not defined a segment name does not match already existing segments no default placement for segment lt segment gt a segment is missing a or b option 2012 COSMIC Software Compiler Error Messages 349 Linker clnk Error Messages prefixed symbol lt name gt in conflict a symbol beginning by f for a banked function also exists without the f prefix read error an input object file is corrupted segment lt segment gt and lt segment gt overlap a segment is overlap ping an other segment segment lt segment gt size overflow the size of a segment is la
163. functions which if they do not return inf are declared in header files and defined in a separate object module that is linked in with your program later functions implemented as macros are defined using define preprocessor directives in the header file that declares them Macros can therefore be used independently of any library by including the header file that defines and declares them with your program as explained below The functions in the C library that are implemented as macros are max min va_arg va_end and va_start Functions Implemented as Builtins A few functions of the C library are actually implemented as builtins The code for those functions is directly inlined instead of passing argu Using The Compiler 69 Ei C Library Support ments and calling a function Arguments are built directly in registers and the code is produced to match exactly the function behaviour Those functions are also provided in the library to allow them to be called through pointers The functions in the C library that are imple mented as builtins are abs fabs and labs Including Header Files If your application calls a C library function you must include the header file that declares the function at compile time in order to use the proper return type and the proper function prototyping so that all the expected arguments are properly evaluated You do this by writing a preprocessor directive of the form include lt he
164. g Cosmic supplied utilities cvdwarf and cv695 The debug segment information may also be extracted in text format using the Cosmic cprd utility included with the compiler info segment The info segment is generated automatically by the compiler and it contains the component version and 296 Using The Linker 2012 COSMIC Software Return Value options used to compile and link the application This information can be extracted into a text file using the cobj utility with the i option and o options This segment may also be suppressed by the linker using the linker command line option si This option is useful for compatibility with older debuggers and utilities Return Value clnk returns success if no error messages are printed to STDOUT that is if no undefined symbols remain and if all reads and writes succeed Otherwise it returns failure 2012 COSMIC Software Using The Linker 297 6 Linker Command Line Examples Linker Command Line Examples This section shows you how to use the linker to perform some basic operations A linker command file consists of linker options input and output file and libraries The options and files are read from a command file by the linker For example to create an CORTEX M file from file o you can type at the system prompt clnk o myapp myapp 1kf where myapp lkf contains seg const b 0x4000000 n const program start address seg vtext a const
165. g REF in the linker s internal sym bol table Thus the simplest use of clnk is to combine two files and check that no unused references remain The executable file created by the linker must have no REFs in its sym bol table Otherwise the linker emits the error message undefined sym bol and returns failure 2012 COSMIC Software Using The Linker 289 6 Special Topics Special Topics This section explains some special linker capabilities that may have limited applicability for building most kinds of microcontroller applica tions Private Name Regions Private name regions are used when you wish to link together a group of files and expose only some to the symbol names that they define This lets you link a larger program in groups without worrying about names intended only for local usage in one group colliding with identi cal names intended to be local to another group Private name regions let you keep names truly local so the problem of name space pollution is much more manageable An explicit use for private name regions in a CORTEX M environment is in building a paged program with duplication of the most used library functions in each page in order to avoid extra page commutation To avoid complaints when multiple copies of the same file redefine sym bols each such contribution is placed in a private name region accessi ble only to other files in the same page The basic sequence of commands for each island
166. ge offset 127 if offset too large addptr offset call a macro elsec otherwise add r1 offset add offset endc Note The elsec and else directives are equivalent and may used without dis tinction They are provided for compatibility with previous assemblers See Also if endc clist else 208 Using The Assembler 2012 COSMIC Software Assembler Directives end end Description Stop the assembly Syntax end Function The end directive stops the assembly process Any statements follow ing it are ignored If the end directive is encountered in an included file it will stop the assembly process for the included file only 2012 COSMIC Software Using The Assembler 209 Assembler Directives endc endc Description End conditional assembly Syntax if lt cc gt lt expression gt instructions endc Function The ende directive closes an if lt cc gt or elsee conditional directive The conditional status reverts to the one existing before entering the if lt cce gt directives The ende directive applies to the closest previous if lt ce gt or elsec directive Example ifge offset 127 if offset too large addptr offset call a macro elsec otherwise add r1 offset add offset endc Note The endc and endif directives are equivalent and may used without dis tinction They are provided for compatibility with previous assemblers See Also if elsec clist end 210
167. gt ifgt Description Conditional assembly Syntax ifgt lt expression gt or ifgt lt expression gt instructions instructions endc elsec instructions endc Function The ifgt elsec and endc directives allow conditional assembly The ifgt directive is followed by a constant expression If the result of the expression is greater than zero the following instructions are assem bled up to the next matching endc or elsec directive otherwise the fol lowing instructions up to the next matching endc or elsec directive are skipped If the ifgt statement ends with an elsec directive the expression result is inverted and the same process applies to the following instructions up to the next matching ende So if the ifgt expression was greater than zero the instructions between elsec and ende are skipped otherwise the instructions between elsec and ende are assembled An elsec direc tive applies to the closest previous if directive The if directives may be nested The skipped lines may or may not in the listing depending on the clist directive status Example ifgt offset 127 if offset too large addptr offset call a macro elsec otherwise add rl offset add to register endc See Also elsec endc clist 222 Using The Assembler 2012 COSMIC Software Assembler Directives ifle ifle Description Conditional assembly Syntax ifle lt expression gt or ifle lt expression gt instructions in
168. h are now obsolete The following features are added to the standard behav iour e acomment line may begin with a character e a label starting in the first column does not need to be ended with a character 198 Using The Assembler 2012 COSMIC Software C Style Directives e no error message is issued if an operand of the de b directive is too large e the section directive handles numbered sections The comment separator at the end of an instruction is still the charac ter because the character is interpreted as the multiply operator C Style Directives The assembler also supports C style directives matching the preproces sor directives of a C compiler The following directives list shows the equivalence with the standard directives C Style Assembler Style include file include file define label expression label equ expression define label label equ 1 if expression if expression ifdef label ifdef label ifndef label ifndef label else else endif endif error message fail message NOTE The define directive does not implement all the text replacement fea tures provided by a C compiler It can be used only to define a symbol equal to a numerical value Assembler Directives This section consists of quick reference descriptions for each of the cacorm assembler directives 2012 COSMIC Software Using
169. h the same ap You need not expand va_arg within the function that contains the variable length argument list You must write an expansion of va_end as an expression statement con taining a function call The call must be followed by a semicolon Return Value Nothing va_end expands to a statement not an expression Example To write multiple strings to a file include lt stdio h gt include lt stdarg h gt main void strput strput pf This is one string n and this is another n char 0 174 Using The Compiler 2012 COSMIC Software C Library va_end void strput FILE pf void strput char ptr void strput ptr char ptr char ptr va_list va if ptr return else puts ptr va_start va ptr while ptr va_arg va char puts ptr va_end va See Also va_arg va_start Notes va_end is a macro declared in the lt stdarg h gt header file You can use it with any function that accepts a variable number of arguments by including lt stdarg h gt with your program 2012 COSMIC Software Using The Compiler 175 a C Library va_start va Start Description Start accessing values in an argument list Syntax include lt stdarg h gt void va_start va_list ap parmN Function va_start is a macro which you must expand before you expand the macro va_arg It initializes the information stored in th
170. han its type size invalid bitfield type a type other than int unsigned int char unsigned char has been used in a bitfield invalid break a break may be used only in while for do or switch statements invalid case a case label has been specified outside of a switch state ment invalid case operand a case label has to be followed by a constant expression invalid cast operand the operand of a cast operator in not an expres sion invalid cast type a cast has been applied to an object that cannot be coerced to a specific type invalid conditional operand the operands of a conditional operator are not compatible invalid constant expression a constant expression is missing or is not reduced to a constant value 334 Compiler Error Messages 2012 COSMIC Software Parser cpcorm Error Messages invalid continue a continue statement may be used only in while for or do statements invalid default a default label has been specified outside of a switch statement invalid do test type the expression of a do while instruction is not a testable expression invalid expression an incomplete or ill formed expression has been detected invalid external initialization an external object has been initialized invalid floating point operation an invalid operator has been applied to floating point operands invalid for test type the second expression of a for instruction is not a testable expr
171. har fmt Function scanf reads formatted input from the output stream using the format string at fmt and the arguments specified by as described below scanf uses getchar to read each character The behavior is unpredictable if there are insufficient argument pointers for the format If the format string is exhausted while arguments remain the excess arguments are evaluated but otherwise ignored Format Specifiers The format string may contain e any number of spaces horizontal tabs and newline characters which cause input to be read up to the next non whitespace char acter and e ordinary characters other than which must match the next character of the input stream Each lt conversion specification gt the definition of which follows con sists of the character an optional assignment suppressing character an optional maximum field width an optional h l or L indicating the size of the receiving object and a lt conversion character gt described below A conversion specification directs the conversion of the next input field The result is placed in the object pointed to by the subsequent argument unless assignment suppression was indicated by a An 140 Using The Compiler 2012 COSMIC Software C Library scanf input field is a string of non space characters it extends to the next con flicting character or until the field width if specified is exhausted The convers
172. haracters as for a 64 character terminal while string strpbrk string string See Also memchr strchr strcspn strrchr strspn Notes strpbrk is packaged in the integer library 2012 COSMIC Software Using The Compiler 161 4 C Library strrchr strrchr Description Scan string for last occurrence of character Syntax include lt string h gt char strrchr char s int c Function strrehr looks for the last occurrence of a specific character c in a NUL terminated string starting at s Return Value strrchr returns a pointer to the last character that matches c or NULL if none does Example To find a filename within a directory pathname if s strrchr usr lib libc user S See Also memchr strchr strpbrk strcspn strspn Notes strrchr is packaged in the integer library 162 Using The Compiler 2012 COSMIC Software C Library strspn strspn Description Find the end of a span of characters not in set Syntax include lt string h gt unsigned int strspn char sl1 char s2 Function strspn scans the string starting at s for the first occurrence of a charac ter not in the string starting at s2 It computes a subscript 7 such that e s1 i is a character in the string starting at s1 e sl i compares equal to no character in the string starting at s2 except possibly its terminating null character Return Value
173. he executable file is complete and contains everything that it needs to run There are a variety of utilities which will take the executable file and convert it to a form required for execution in specific microcontroller environments The linker itself can perform some conversions if all that is required is for certain portions of the executable file to be stripped off and for segments to be relocated in a particular way You can therefore create executable programs using the linker that can be passed directly to a PROM programmer 262 Using The Linker 2012 COSMIC Software Overview The linker works as follows e Options applying to the linker configuration These options are referred to in this chapter as Global Command Line Options on page 267 e Command file options apply only to specific sections of the object being built These options are referred to in this chapter as Seg ment Control Options on page 269 e Sections can be relocated to execute at arbitrary places in physical memory or stacked on suitable storage boundaries one after the other The final output of the linker is a header followed by all the seg ments and the symbol table There may also be an additional debug symbol table which contains information used for debug ging purposes 2012 COSMIC Software Using The Linker 263 6 Linker Command File Processing Linker Command File Processing The command file of the
174. he code section to the default section text Referencing Absolute Addresses This C compiler allows you to read from and write to absolute addresses and to assign an absolute address to a function entry point or to a data object You can give a memory location a symbolic name and associated type and use it as you would do with any C identifier This feature is useful for accessing memory mapped I O ports or for calling functions at known addresses in ROM References to absolute addresses have the general form lt address gt where lt address gt is a valid memory location in your environment For example to associate an I O port at address 0x40 with the identifier name ttystat write a definition of the form char ttystat 0x40 2012 COSMIC Software Programming Environments 41 Referencing Absolute Addresses where 0x40 indicates an absolute address specification and not a data initializer Since input output on the PowerPC architecture is memory mapped performing I O in this way is equivalent to writing in any given location in memory To use the I O port in your application write char c c ttystat to read from input port ttystat c to write to output port Another solutions is to use a define directive with a cast to the type of the object being accessed such as define ttystat char 0x40 which is both inelegant and confusing The COSMIC implementation i
175. he latest data segment Note that there is no default placement for the constants segment const Based Segment Configuration When using a memory model accessing 4K of data using a base regis ter the corresponding segment must be declared using both bias and offset with the bias matching the physical start address and the offset matching the equivalent offset applied to the base register As the Cor tex M uses a 12 bit unsigned offset the full 4K block will be accessed from offset 0 up to the largest possible one using a base register set at the start of the selected area The segment definition must be then seg sdata b 0x20000000 o O m 0x1000 In such a case the base register must be set at address 0x20000000 usually from the linker command file 2012 COSMIC Software Using The Linker 279 6 Linking Objects Linking Objects A new segment is built by concatenating the corresponding sections of the input object modules in the order the linker encounters them As each input section is added to the output segment it is adjusted to be relocated relative to the end portion of the output segment so far con structed The first input object module encountered is relocated relative to a value that can be specified to the linker The size of the output bss segment is the sum of the sizes of the input bss sections Unless the v option has been specified on a segment definition the linker checks that the segment p
176. he name of the compiler The option list is optional You must include the name of at least one input file lt file gt lt file gt can be a C source file with the suffix c or an assembly language source file with the suffix s You may specify multiple input files with any com bination of these suffixes in any order If you do not specify any command line options excorm will compile your lt files gt with the default options It will also write the name of each file as it is processed It writes any error messages to STDERR The following command line cxcorm acia c compiles and assembles the acia c C program creating the relocatable program acia o If the compiler finds an error in your program it halts compilation When an error occurs the compiler sends an error message to your ter minal screen unless the option e has been specified on the command line In this case all error messages are written to a file whose name is obtained by replacing the suffix c of the source file by the suffix err An error message is still output on the terminal screen to indicate that errors have been found Appendix A Compiler Error Messages lists the error messages the compiler generates If one or more command line arguments are invalid excorm processes the next file name on the command line and begins the compilation process again The example command above does not specify any compiler options In this
177. he offset directive has been entered All the labels defined is this section become absolute symbols lt expression gt must be a valid absolute expression It must not contain any forward or external references Example offset 0 next ds b 2 buffer ds b 80 size ldr rO r12 ends the offset section 2012 COSMIC Software Using The Assembler 239 Assembler Directives org org Description Sets the location counter to an offset from the beginning of a section Syntax org lt expresion gt Function lt expression gt must be a valid absolute expression It must not contain any forward or external references For an absolute section the first org before any code or data defines the starting address An org directive cannot define an address smaller than the location counter of the current section Any gap created by an org directive is filled with the byte defined by the f option 240 Using The Assembler 2012 COSMIC Software Assembler Directives page page Description Start a new page in the listing file Syntax page Function The page directive causes a formfeed to be inserted in the listing output if pagination is enabled by either a title directive or the ft option Example xref mult div page ds b charin charout ds w a b sum See Also plen title 2012 COSMIC Software Using The Assembler 241 Assembler Directives plen plen Descri
178. he string is taken as the text representation of a decimal number Leading whitespace is skipped and an optional sign is permitted conversion stops on the first unrecog nizable character Acceptable characters are the decimal digits If the stop character is l or L it is skipped over No checks are made against overflow or invalid character strings Return Value atoi returns the converted integer value If the string has no recogniza ble characters zero is returned Example To read a string from STDIN and convert it to an int at i gets buf i atoi buf See Also atof atol strtol strtod Notes atoi is packaged in the integer library Using The Compiler 2012 COSMIC Software C Library atol atol Description Convert buffer to long Syntax include lt stdlib h gt long atol char nptr Function atol converts the string at nptr into a long integer The string is taken as the text representation of a decimal number Leading whitespace is skipped and an optional sign is permitted conversion stops on the first unrecognizable character Acceptable characters are the decimal digits If the stop character is Lor L it is skipped over No checks are made against overflow or invalid character strings Return Value atol returns the converted long integer If the string has no recognizable characters zero is returned Example To read a string from STDIN and convert it to a long I gets bu
179. heir own local block A local label block is the area between two standard labels or local directives or a combination of the two Example var ds b 1 var2 ds b 1 functionl 10 ldr beq lwz local 10 lwz beq lwz blr 2012 COSMIC Software r2 r9 var 10 r1l var2 r13 r2 var2 r13 10 r1l var r13 Using The Assembler 231 Assembler Directives macro macro Description Define a macro Syntax label macro lt macro_body gt endm Function The macro directive is used to define a macro The name may be any previously unused name a name already used as a macro or an instruc tion mnemonic for the microprocessor Macros are expanded when the name of a previously defined macro is encountered Operands where given follow the name and are separated from each other by commas The lt argument_list gt is optional and if specified is declaring each argument by name Each argument name is prefixed by a character and separated from any other name by a comma An argument name is an identifier which may contain and _ characters The lt macro_body gt consists of a sequence of instructions not including the directives macro or endm It may contain macro variables which will be replaced when the macro is expanded by the corresponding operands following the macro invocation These macro variables take the form 1 to 9 to denote the first to ninth operand respectively and A to Z to
180. hes the space modifier specified in the object declaration stack attribute conflict on cast a cast is attempting to change the stack nostack attribute of an object strict string too long a string is used to initialize an array of characters shorter than the string length struct union size unknown an attempt to compute a structure or union size has occurred on an undefined structure or union syntax error an unexpected identifier has been read token overflow an expression is too complex to be parsed too many argument the number of actual arguments in a function declaration does not match that of the previous prototype declaration too many arguments for macro lt name gt a macro invocation has more arguments than its corresponding macro declaration too many initializers initialization is completed for a given object before initializer list is exhausted too many spaces modifiers too many different names for modifi ers are used 2012 COSMIC Software Compiler Error Messages 341 Parser cpcorm Error Messages truncating assignment the right operand of an assignment is larger than the left operand strict truncating constant cast a cast is attempting to narrow down the value of a constant strict unbalanced a character constant does not end with a simple quote unbalanced a string constant does not end with a double quote lt name gt undefined an undeclared identifier appea
181. horter sequences with the same meaning Directive Description asm start assembler block endasm end assembler block Such an assembler block may be located anywhere inside or outside a function Outside a function it behaves syntactically as a declaration This means that such an assembler block cannot split a C declaration somewhere in the middle Inside a function it behaves syntactically as one C instruction This means that there is no trailing semicolon at the end and no need for enclosing braces It also means that such an assem bler block cannot split a C instruction or expression somewhere in the middle The following example shows a correct syntax 2012 COSMIC Software Programming Environments 43 Inserting Inline Assembly Instructions pragma asm xref asmvar pragma endasm extern int test void func void if test asm no need for ldr r0 r9 asmvar access asm var clz r0 r0 count leading zeroes str r0 r9 asmvar endasm else test 1 Inlining with asm The _asm function inserts inline assembly code in your C program The syntax is _asm string constant arguments The string constant argument is the assembly code you want embed ded in your C program arguments follow the standard C rules for passing arguments NOTE The argument string must be shorter than 255 characters If you wish to insert longer assemb
182. hysical address range does not overlap any other segment of the application Logical addresses are not checked as bank switching creates several segments starting at the same logical address Linking Library Objects The linker will selectively include modules from a library when out standing references to member functions are encountered The library file must be place after all objects that may call it s modules to avoid unresolved references The standard ANSI libraries are provided in three versions to provide the level of support that your application needs This can save a significant amount of code space and execution time when full ANSI double precision floating point support is not needed The first letter after lib in each library file denotes the library type d for double f for single precision and i for integer and the final letters specify the memory model See below libdM cxm Double Precision Library provides ANSI double precision floating point support Link this library before the other libraries when needed 280 Using The Linker 2012 COSMIC Software Linking Library Objects libfM cxm Single Precision Library Used in conjunction with the sprec option to force all floats even variables declared as doubles to single precision This library is used for applications where only single precision floating point sup port is needed This library is significantly smaller and faster than the doub
183. ibrary 2012 COSMIC Software Using The Compiler 115 Ei C Library log log Description Natural logarithm Syntax include lt math h gt double log double x Function log computes the natural logarithm of x to full double precision Return Value log returns the closest internal representation to log x expressed as a double floating value If the input argument is less than zero or is too large to be represented log returns zero Example To compute the hyperbolic arccosine of x arccosh log x sqrt x x 1 See Also exp Notes log is packaged in the floating point library 116 Using The Compiler 2012 COSMIC Software C Library log10 log10 Description Common logarithm Syntax include lt math h gt double 1log10 double x Function log10 computes the common log of x to full double precision by com puting the natural log of x divided by the natural log of 10 If the input argument is less than zero a domain error will occur If the input argu ment is zero a range error will occur Return Value log10 returns the nearest internal representation to Jog 0 x expressed as a double floating value If the input argument is less than or equal to zero og 0 returns zero Example To determine the number of digits in x where x is a positive integer expressed as a double ndig logl0 x 1 See Also log Notes log10 is packaged in the floating
184. ile after all the object files NOTE Whitespaces are not allowed aside the equal sign 2012 COSMIC Software Using The Linker 277 6 Section Relocation Section Relocation The linker relocates the sections of the input files into the segments of the output file An absolute section by definition cannot and should not be relocated The linker will detect any conflicts between the placement of this file and its absolute address given at compile assemble time In the case of a bank switched system it is still possible for an absolute section to specify a physical address different from the one and at com pile assembly time the logical address MUST match the one specified at compile assemble time Address Specification The two most important parameters describing a segment are its bias and its offset respectively its physical and logical start addresses In nonsegmented architectures there is no distinction between bias and off set The bias is the address of the location in memory where the seg ment is relocated to run The offset of a segment will be equal to the bias In this case you must set only the bias The linker sets the offset automatically Overlapping Control The linker is verifying that a segment does not overlap any other one by checking the physical addresses bias This control can be locally disabled for one segment by using the v option For targets implement ing separated address
185. ility sieccasts aectaistiastittecestenthsanetecactemsatasteasion 310 Command Line Options cceecescesecseeseeteeeeeeeeeeeeeeeeeee 310 Return Status FEXAIMP IES oirre sas s5s casavess cgs ugs cdesscadoniencstesuesedeszeseeseniecazeaacas The clabs Utility Command Line Options Return Status Examples sarees vss The clib Utility i ccccscceecassncsassessstececanesescssctonsconsotscenesancnsoncs Command Line Options ceseeeeeeeeeeseeteeeeeeeeeeeeeeeeees 317 Return Status eee Examples denne The cobj Utility ee s Command Line Options ccescsecsecsecseereeeeeeeeeeeeeeeeeee 320 Ret rm Status siscseccseieceedselevededessoscse nesta cet ti ste eag oaeiai 321 Examples 321 The cvdwarf Utility 322 Command Line Options s 322 REMS US ces tetadeesteareadeeeted secs tcteessatacs fatecetetivteatyatcectans 325 EXAMPLES svissisccas caycds cus cus cdusenedeesvedecstsGecsstvededs duvidids aesepeaes 325 Chapter A Parser cpcorm Error Messages cccccsccesceeeseeteeeseeseeteenes 328 Code Generator cgcorm Error Messages 344 Assembler cacorm Error Messages 345 Linker clnk Error Messages c cccssesssesseseeeeeeeceeceeceseeaeenes 348 The Configuration File cccceseesessecsecseeseeneeeeeeeeeeeeeceeeeeees Changing the Default Options Creating Your Own Options Chapter D The cpcorm Parser
186. in that region or by a public definition A previous definition of that symbol will satisfy the reference if that definition is public or if the definition is private and the reference is made in the same region as the definition e Ifa new reference to a symbol occurs and that symbol still has an outstanding unsatisfied reference made in another region then that symbol is marked as requiring a public definition to satisfy it e Any definition of a symbol must satisfy all outstanding references to that symbol therefore a private definition of a symbol which requires a public definition causes a blocked symbol reference error 2012 COSMIC Software Using The Linker 293 6 Special Topics e No symbol reference can reach any definition made earlier than the most recent definition Absolute Symbol Tables Absolute Symbol tables are used to export symbols from one application to another to share common functions for instance or to use functions already built in a ROM from an application downloaded into RAM The linker option s will modify the output file in order to contain only a symbol table without any code but still with an object file format by using the same command file used to build the application itself All symbols are flagged as absolute symbols This file can be used in another link and will then transmit its symbol table allowing another application to use those symbols as externals Note that the linker
187. ine number is obtained by specifying dl2 All information is coded in symbols that are in the debug symbol table e log errors in the text file instead of displaying the mes sages on the terminal screen f merge all C source lines of functions producing code into the C and Assembly listing By default only C lines actually producing assembly code are shown in the listing fp Not yet implemented ge produce error messages directly compatible with the Eclipse environment l merge C source listing with assembly language code listing output defaults to lt file gt ls m0 generate code for MO instruction set By default code is produced for M3 M4 instruction set na do not produce an xdef directive for the equate names cre ated for each C object declared with an absolute address NO do not produce special directives for the post optimizer 0 write the output to the file and write error messages to STDOUT The default is STDOUT for output and STDERR for error messages sf produce each function in a different section thus allowing the linker to suppress a function if it is not used by the appli cation By default all the functions are packed in a single section V When this option is set each function name is send to STDERR when cgcorm starts processing it 370 Compiler Passes 2012 COSMIC Software The cgcorm Code Generator Return Status cgcorm returns suc
188. inst overflow or invalid character strings Return Value strtoul returns the converted long integer If the string has no recogniza ble characters zero is returned Example To read a string from STDIN and convert it to a long gets buf 1 strtoul buf NULL 0 See Also atof atoi strtol strtod Notes strtoul is a macro redefined to strtol 2012 COSMIC Software Using The Compiler 167 Ei C Library tan tan Description Tangent Syntax include lt math h gt double tan double x Function tan computes the tangent of x expressed in radians to full double pre cision Return Value tan returns the nearest internal representation to tan x in the range pi 2 pi 2 expressed as a double floating value If the number in x is too large to be represented tan returns zero An argument with a large size may return a meaningless value i e when x 2 pi has no frac tion bits Example To compute the tangent of theta y tan theta See Also cos sin Notes tan is packaged in the floating point library 168 Using The Compiler 2012 COSMIC Software C Library tanh tanh Description Hyperbolic tangent Syntax include lt math h gt double tanh double x Function tanh computes the value of the hyperbolic tangent of x to double preci sion Return Value tanh returns the nearest internal representation to tanh x expressed as a doubl
189. ion Linking Your Application You can create as many fext sdata and sbss segments as your applica tion requires For example assume we have one sbss one sdata and one text segments Our link command file will look like seg sconst b 0x1000 m Oxf000 n sconst seg text a sconst n text seg sdata b0x20000000 m0x1000 n sdata seg sbss a sdata n sbss tdef _ sdata sdata tdef _ sbss sbss Gresu acia o modulel o c cosmic cxcorm lib libis cxm c cosmic cxcorm lib libm cxm def memory sbss tdef stack 0x20010000 In this example the linker will locate and merge crts o acia o and modulel o in a text segment at 0x1000 a sdata segment at 0x20000000 The libraries will be also merged For more information about the linker see Chapter 6 Using The Linker 2012 COSMIC Software Tutorial Introduction 23 Generating Automatic Data Initialization Generating Automatic Data Initialization Usually in embedded applications your program must reside in ROM This is not an issue when your application contains code and read only data such as string or const variables All you have to do is bum a PROM with the correct values and plug it into your application board The problem comes up when your application uses initial data values that you have defined with initialized static data These static data val ues must reside in RAM There are two types of static data initializations 1
190. ion Usage cont Option Description sprec force all floating point arithmetic to single precision If this option is enabled all floats doubles and long doubles are treated as float and calculation are made in single preci sion In such a case the application must be linked with the libf cxm libf cx0 library instead of libd cxm libd cx0 strict enforce a stronger type checking For more information see Extra verifications in Appendix D warn enable warnings For more information see Warning Lev els in Appendix D 2012 COSMIC Software Using The Compiler 65 Eg File Naming Conventions File Naming Conventions The programs making up the C cross compiler generate the following output file names by default See the documentation on a specific pro gram for information about how to change the default file names accepted as input or generated as output Program Input File Name Output File Name cpcorm lt file gt c lt file gt 1 cgcorm lt file gt 1 lt file gt 2 cocorm lt file gt 2 lt file gt s error listing lt file gt c lt file gt err assembler listing lt file gt c s lt file gt Is C header files lt file gt h cacorm lt file gt s lt file gt o source listing lt file gt s lt file gt Is clnk lt file gt o name required chex lt file gt STDOUT clabs lt file cxm gt lt files gt la clib
191. ion specification indicates the interpretation of the input field the corresponding pointer argument must be a restricted type The lt conversion character gt is one of the following a single is expected in the input at this point no assignment occurs If the character after is not a valid conversion character the behav ior is undefined c a character is expected the subsequent argument must be of type pointer to char The normal behavior skip over space characters is suppressed in this case to read the next non space character use Yols Ifa field width is specified the corresponding argument must refer to a character array the indicated number of characters is read d a decimal integer is expected the subsequent argument must be a pointer to integer e f g a float is expected the subsequent argument must be a pointer to float The input format for floating point numbers is an optionally signed sequence of digits possibly containing a decimal point followed by an optional exponent field consisting of an E or e followed by an optionally signed integer i an integer is expected the subsequent argument must be a pointer to integer If the input field begins with the characters 0x or OX the field is taken as a hexadecimal integer If the input field begins with the charac ter 0 the field is taken as an octal integer Otherwise the input field is taken as a decimal integer n no input is consum
192. irective status Example ifdef offsetl if offsetl is defined addptr offsetl 7 call a macro elsec otherwise addptr offset2 call a macro endif See Also 2012 COSMIC Software ifndef elsec endc clist Using The Assembler 219 Assembler Directives ifeq ifeq Description Conditional assembly Syntax ifeq lt expression gt or ifeq lt expression gt instructions instructions endc elsec instructions endc Function The ifeq elsec and endec directives allow conditional assembly The ifeq directive is followed by a constant expression If the result of the expression is equal to zero the following instructions are assembled up to the next matching endc or elsec directive otherwise the following instructions up to the next matching endc or elsec directive are skipped If the ifeq statement ends with an elsec directive the expression result is inverted and the same process applies to the following instructions up to the next matching endc So if the ifeq expression is equal to zero the instructions between elsec and endec are skipped otherwise the instructions between elsec and endec are assembled An elsec directive applies to the closest previous if directive The if directives may be nested The skipped lines may or may not in the listing depending on the clist directive status Example ifeq offset if offset nul cmp r1 0 just test it elsec otherwise add rl offset add to regist
193. is permitted conversion stops on the first unrecognizable character Acceptable inputs match the pattern d d e dd where d is any decimal digit and e is the character e or E If endptr is not a null pointer endptr is set to the address of the first unconverted character remaining in the string nptr No checks are made against over flow underflow or invalid character strings Return Value strtod returns the converted double value If the string has no recogniz able characters it returns zero Example To read a string from STDIN and convert it to a double at d gets buf d strtod buf NULL See Also atoi atol strtol strtoul Notes strtod is packaged in the floating point library 2012 COSMIC Software Using The Compiler 165 Ei C Library strtol strtol Description Convert buffer to long Syntax include lt stdlib h gt long strtol char nptr char endptr int base Function strtol converts the string at nptr into a long integer Leading whitespace is skipped and an optional sign is permitted conversion stops on the first unrecognizable character If base is not zero characters a z or A Z represents digits in range 10 36 If base is zero a leading 0x or 0X in the string indicates hexadecimal a leading 0 indicates octal other wise the string is take as a decimal representation If base is 16 and a leading Ox or OX is pr
194. is an assumed 0 5 assertion of the weighted bit added to all fractions to put them in the interval 0 5 1 0 The value of the 56 Programming Environments 2012 COSMIC Software Data Representation number is the fraction multiplied by 1 if the sign bit is set multiplied by 2 raised to the exponent 31 30 23 22 0 Sign Characteristic L Mantissa Float representation 63 62 52 51 0 Sign Characteristic L Mantissa 2012 COSMIC Software Double representation Programming Environments S7 CHAPTER 4 Using The Compiler This chapter explains how to use the C cross compiler to compile pro grams on your host system It explains how to invoke the compiler and describes its options It also describes the functions which constitute the C library This chapter includes the following sections Invoking the Compiler File Naming Conventions Generating Listings Generating an Error File C Library Support Descriptions of C Library Functions 2012 COSMIC Software Using The Compiler 59 Eg Invoking the Compiler Invoking the Compiler To invoke the cross compiler type the command cxcorm followed by the compiler options and the name s of the file s you want to compile All the valid compiler options are described in this chapter Commands to compile source files have the form cxcorm options lt files gt c s cxcorm is t
195. is incorrect bad undef syntax undef is not followed by an identifier bad _asm argument type the first argument passed to _asm is miss ing or is not a character string bad alias expression alias definition is not a valid expression bad alias value alias definition is not a constant expression bad bit number a bit number is not a constant between 0 and 7 bad character lt character gt lt character gt is not part of a legal token bad defined syntax the defined operator must be followed by an iden tifier or by an identifier enclosed in parenthesis bad function declaration function declaration has not been termi nated by a right parenthesis 2012 COSMIC Software Compiler Error Messages 329 Parser cpcorm Error Messages bad integer constant an invalid integer constant has been specified bad invocation of macro lt name gt a define macro defined without arguments has been invoked with arguments bad macro argument a parameter in a define macro is not an identi fier bad macro argument syntax parameters in a define macro are not separated by commas bad proto argument type function prototype argument is declared without an explicit type bad real constant an invalid real constant has been specified bad space modifier a modifier beginning with a character is not followed by an identifier bad structure for return the structure for return is not compatible with that of the fun
196. ition double compare double divide double multiply negate a double double substract convert double to float convert double to long float addition float compare float divide float multiply negate a float float substract 2012 COSMIC Software CORTEX M Machine Library 357 c_ftod c_jtab c_ltod c ltoft c_ultod c_ultof convert float to double switch from table MO only convert long to double convert long to float convert unsigned long to double convert unsigned long to float 358 CORTEX M Machine Library 2012 COSMIC Software APPENDIX D Compiler Passes The information contained in this appendix is of interest to those users who want to modify the default operation of the cross compiler by changing the configuration file that the excorm compiler uses to control the compilation process This appendix describes each of the passes of the compiler cpcorm the parser cgcorm the code generator cocorm the assembly language optimizer 2012 COSMIC Software Compiler Passes 359 D The cpcorm Parser The cpcorm Parser cpcorm is the parser used by the C compiler to expand defines includes and other directives signalled by a parse the resulting text and outputs a sequential file of flow graphs and parse trees suitable for input to the code generator cgcorm Command Line Options cpcorm accepts the following options each of which is described in de
197. ker 269 6 Linker Options Segment Control Options Usage cont Option Description i define the initialization option Valid options are it use this segment to host the descriptor and images copies of initialized data used for automatic data initialization id initialize this segment ib do not initialize this segment ik mark this segment as checksum segment ic mark this segment as moveable segment k mark the segment as a root segment for the unused section suppression This flags is usually applied on the reset and interrupt vectors section and as soon as it is specified at least once in the linker command file enables the section suppression mechanism This option can be used on any other segment to force the linker to keep it even if it is not used m set the maximum size of the segment to bytes If not spec ified there is no checking on any segment size If a seg ment is declared with the a option as following a segment which is marked with the m option then set the maximum available space for all the possible consecutive segments If a m is specified on a a segment the actual maximum size checked is equal to the given value minus the size of all the segments already allocated from the first segment of the a list So the new maximum size is computed from the start address of the list and not from the start address of that segment 270 Using The Linker
198. le precision Link this library before the other libraries when only single precision floats are used NOTE The sprec compiler option MUST be used if you want to use the Single Precision library in order to suppress normal ANSI float to double promotions libiM cxm Integer only Library This library is designed for applica tions where no floating point is used Floats can still be used for arithmetic but not with the standard library Link this library before the other libraries when only integer libraries are needed Memory Machine Integer Single Dounie Models Library Only Precision Precision Library Floats Floats Standard libm cxm libi cxm libf cxm libd cxm mods libm cxm libis cxm libsf cxm libds cxm modsc libm cxm libisc cxm libfc cxm libdc cxm modl libm cxm libil cxm libfl cxm libdl cxm modic libm cxm libilc cxm libflc cxm libdic cxm mod0 libm cxO libi cxO libf cxO libd cxO Library Order You should link your application with the libraries in the following orders 2012 COSMIC Software Using The Linker 281 6 Linking Library Objects Integer Only Single Precision Double Precision Application Float Application Float Application libi cxm libf cxm libd cxm libm cxm libi cxm libi cxm libm cxm libm cxm NOTE The library description and loading order also apply to the MO libraries libm cx0 libi cx0 libf cx0 and libd cx0
199. ler is a relocatable object in a format suitable for the linker clnk This will normally consist of machine code initialized data and relocation information The object file also contains information about the sections used a symbol table and a debug symbol table Listings The listing stream contains the source code used as input to the assem bler together with the hexadecimal representation of the corresponding object code and the address for which it was generated The contents of the listing stream depends on the occurrence of the list nolist clist dlist and mlist directives in the source The format of the output is as follows lt address gt lt generated_code gt lt source_line gt where lt address gt is the hexadecimal relocatable address where the lt source_line gt has been assembled lt generated_code gt is the hexadec imal representation of the object code generated by the assembler and lt source_line gt is the original source line input to the assembler If expansion of data macros and included files is not enabled the lt generated_code gt print will not contain a complete listing of all gen erated code Addresses in the listing output are the offsets from the start of the cur rent section After the linker has been executed the listing files may be updated to contain absolute information by the clabs utility Addresses and code will be updated to reflect the actual values as built by the linker Sev
200. limited to 4K and con stants limited to 64K modsc select standard model with variables limited to 4K and unlimited constants modl select the unlimited data and 64K constants modic select the unlimited data and unlimited constants nobss do not use the bss section By default uninitialized varia bles are defined into the bss section This option is useful to force all variables to be grouped into a single section proto enforce prototype declaration for functions An error mes sage is issued if a function is used and no prototype decla ration is found for it By default the compiler accepts both syntaxes without any error rev reverse the bitfield filling order By default bitfields are filled from the Less Significant Bit LSB towards the Most Signifi cant Bit MSB of a memory cell If the rev option is speci fied bitfields are filled from the msb to the sb split create a separate sub section per function up to a maxi mum number of 256 sections thus allowing the linker to suppress unused functions if the k option has been speci fied on at least one segment in the linker command file For objects with more than 256 functions the functions will be grouped together to a minimum number of functions per sub section to not exceed the maximum of 256 sub sec tions See Segment Control Options in Chapter 6 64 Using The Compiler 2012 COSMIC Software Invoking the Compiler Cxcorm Opt
201. linker is a small control language designed to give the user a great deal of power in directing the actions of the linker The basic structure of the command file is a series of command items A command item is either an explicit linker option or the name of an input file which serves as an implicit directive to link in that file or if it is a library scan it and link in any required modules of the library An explicit linker option consists of an option keyword followed by any parameters that the option may require The options fall into five gg z g a Group 1 seg lt section gt controls the creation of new segments and has parameters which are selected from the set of local flags grp lt section gt controls the section grouping inc is used to include files new pub and pri controls name regions and takes no parame ters def lt symbo gt is used to define symbols and aliases and takes one required parameter a string of the form ident1 identz2 a string of the form ident1 constant or a string of the form ident1 segment spc lt segment gt is used to reserve space in a particular lt segment gt and has a required parameter A description of each of these command line options appears below 264 Using The Linker 2012 COSMIC Software Linker Command File Processing The manner in which the linker relocates the various sections is control led by the seg option and its paramete
202. lists the C library functions in the integer library _asm isdigit memmove strcpy abs isgraph memset strcspn atoi islower printf strlen atol isprint putchar strncat calloc ispunct puts strncmp checksum isqrt rand strncpy checksum16 isspace realloc strpbrk checksum16x isupper sbreak strrchr checksumx isxdigit scanf strspn fctcpy labs setjmp strstr Using The Compiler 2012 COSMIC Software C Library Support 2012 COSMIC Software free long jmp sprintf strtol getchar isqrt srand tolower gets malloc sscanf toupper isalnum memchr streat vprintf isalpha memcmp strchr vsprintf isentrl memcpy strcmp Floating Point Library Functions The following table lists the C library functions in the floating point library acos cosh log sinh asin exp log10 sprintf atan fabs modf sqrt atan2 floor pow sscanf atof fmod printf strtod ceil frexp scanf tan cos ldexp sin tanh Common Input Output Functions Six of the functions that perform stream input output are included in both the integer and floating point libraries The functionalities of the versions in the integer library are a subset of the functionalities of their floating point counterparts The versions in the Integer library cannot print or manipulate floating point numbers These functions are printf scanf sprintf sscanf vprintf and vsprintf Functions Implemented as Macros Five of the functions in the C library are actually implemented as mac ros Unlike other
203. lling byte instead of the one specified by the f option Example vowtab dc b aeiou even ensure aligned at even address tentab dc w 1 10 100 1000 2012 COSMIC Software Using The Assembler 215 Assembler Directives fail e fail Description Generate error message Syntax fail string Function The fail directive outputs string as an error message No output file is produced as this directive creates an assembly error fail is generally used with conditional directives Example Max equ 512 ifge value Max fail Value too large 216 Using The Assembler 2012 COSMIC Software Assembler Directives if if Description Conditional assembly Syntax if lt expression gt or if lt expression gt instructions instructions endif else instructions endif Function The if else and endif directives allow conditional assembly The if directive is followed by a constant expression If the result of the expression is not zero the following instructions are assembled up to the next matching endif or else directive otherwise the following instructions up to the next matching endif or else directive are skipped If the if statement ends with an else directive the expression result is inverted and the same process applies to the following instructions up to the next matching endif So if the if expression was not zero the instructions between else and endif are skipped
204. long the process is suspended and the line ends with a sequence indicating that this function is listed later Functions called by pointer are listed between parenthesis or between square brackets if called from an array of pointers Symbols List all the symbols defined in the application specifying for each its name its value the section where it is defined and the modules where it is used If the target processor supports bank switching addresses are displayed as logical addresses by default Physical addresses can be displayed by specifying the p option on the linker command line Special Segments debug and info The map file also displays two informational segments that are not defined in the link command file and users should not create or attempt to relocate them Both segments should always show a starting address of at 0x0 These segments are produced by the compiler and are part of the linked executable but they do NOT generate any code or use any target resources All information is processed and used on the host debug segment The information in the debug segment is used to provide function information such as local variables and source line information for use with a source level debug ger This segment is created when the debug option is used when compiling or xx option on the assembler The information is read directly by Cosmic s ZAP debuggers or converted to other formats such as ELF DWARF or IEEE 695 usin
205. lowing instructions are assembled up to the next matching ende or elsec directive otherwise the following instructions up to the next matching endc or elsec directive are skipped If the ifne statement ends with an elsec directive the expression result is inverted and the same process applies to the following instructions up to the next matching ende So if the ifne expression was not zero the instructions between elsec and endc are skipped otherwise the instruc tions between elsec and ende are assembled An elsec directive applies to the closest previous if directive The if directives may be nested The skipped lines may or may not in the listing depending on the clist directive status Example ifne hello 2 addptr offset 7 call a macro else otherwise add vl offset add to register endif See Also elsec endc clist 2012 COSMIC Software Using The Assembler 225 Assembler Directives ifndef ifndef Description Conditional assembly Syntax ifndef lt label gt or ifndef lt label gt instructions instructions endc elsec instructions endc Function The ifndef else and ende directives allow conditional assembly The ifndef directive is followed by a label lt abel gt If lt label gt is not defined the following instructions are assembled up to the next match ing endc or elsec directive otherwise the following instructions up to the next matching endc or elsec directive are skipped
206. lt abe gt must be first defined It cannot be a forward reference If the ifndef statement ends with an elsec directive the expression result is inverted and the same process applies to the following instruc tions up to the next matching endif So if the ifndef expression was not zero the instructions between elsec and ende are skipped otherwise the instructions between elsec and ende are assembled An elsec direc tive applies to the closest previous if directive The if directives may be nested The skipped lines may or may not be in the listing depending on the clist directive status Example ifndef offsetl if offsetl is not defined addptr offset2 call a macro elsec otherwise addptr offsetl gt call a macro endif See Also ifdef elsec endc clist 226 Using The Assembler 2012 COSMIC Software Assembler Directives ifne ifne Description Conditional assembly Syntax ifne lt expression gt or ifne lt expression gt instructions instructions endc elsec instructions endc Function The ifme elsec and endec directives allow conditional assembly The ifne directive is followed by a constant expression If the result of the expression is not equal to zero the following instructions are assem bled up to the next matching endc or elsec directive otherwise the fol lowing instructions up to the next matching endc or elsec directive are skipped If the ifne statement ends with an elsec direc
207. lt file gt name required cobj lt file gt STDOUT cvdwarf lt file cxm gt lt file gt elf 66 Using The Compiler 2012 COSMIC Software Generating Listings Generating Listings You can generate listings of the output of any or all the compiler passes by specifying the l option to cxcorm You can locate the listing file in a different directory by using the cl option The example program provided in the package shows the listing pro duced by compiling the C source file acia c with the l option excorm 1l acia c Generating an Error File You can generate a file containing all the error messages output by the parser by specifying the e option to the excorm compiler You can locate the listing file in a different directory by using the ce option For example you would type cxcorm e prog c The error file name is obtained from the source filename by replacing the c suffix by the err suffix Return Status cxcorm returns success if it can process all files successfully It prints a message to STDERR and returns failure if there are errors in at least one processed file Examples To echo the names of each program that the compiler runs cxcorm v file c To save the intermediate files created by the code generator and halt before the assembler cxcorm s file c 2012 COSMIC Software Using The Compiler 67 68 Eg C Library Support
208. ly code strings you will have to split your input among consecutive calls to _asm The string you specify follows standard C rules For example carriage returns can be denoted by the n character To produce the following assembly sequence 44 Programming Environments 2012 COSMIC Software Inserting Inline Assembly Instructions ldr r1 r3 12 ldr r2 r3 bl _main you would write _asm ldr r1 r3 12 nldr r2 r3 nbl _main n The n character is used to separate the instructions when writing mul tiple instructions in the same line _asm does not perform any checks on its argument string Only the assembler can detect errors in code passed as argument to an _asm call _asm can be used in expressions if the code produced by _asm com plies with the rules for function returns For example n _asm mrs r0 IPSR will set n to the current interrupt level That way you can use _asm to write equivalents of C functions directly in assembly language NOTE With both methods the assembler source is added as is to the code dur ing the compilation The optimizer does not modify the specified instruc tions unless the a option is specified on the code generator The assembler input can use lowercase or uppercase mnemonics and may include assembler comments By default asm is returning an int as any undeclared function To avoid
209. m command type cat more For example under MS DOS you would type type acia s If you wish to get an interspersed C and assembly language file you should type cxcorm l mods acia c The l option directs the compiler to produce an assembly language file with C source line interspersed in it Please note that the C source lines are commented in the assembly language file they start with As you use the C compiler you may find it useful to see the various actions taken by the compiler and to verify the options you selected 2012 COSMIC Software Tutorial Introduction Compiling and Linking The v option known as verbose mode instructs the C compiler to dis play all of its actions For example if you type cxcorm v s mods acia c the display will look like something similar to the following acia c cpcorm o 2 cx1l i cx hcorm hmods ub m0x3030 acia c egeorm o 2 cx2 2 cx1 cocorm o acia s 2Z cx2 The compiler runs each pass cpcorm the C parser cgcorm the assembly code generator cocorm the optimizer For more information see Appendix D Compiler Passes Step 2 Assembler The second step of the compilation is to assemble the code previously produced The relocatable object file produced is acia o cxcorm mods acia s or cacorm i cx hcorm acia s if you want to use directly the macro cross asse
210. m optimization specified pne Linking clnk combines all the object modules that make up your program with the appropriate modules from the C library You can also build your own libraries and have the linker select files from them as well The linker generates an executable file which after further processing with the chex utility can be downloaded and run on your target system If you specify debugging options when you invoke cxcorm the compiler will generate a file that contains debugging information You can then use the COSMIC s debugger to debug your code Programming Support Utilities Once object files are produced you run clnk the linker to produce an executable image for your target system you can use the programming support utilities to inspect the executable chex absolute hex file generator chex translates executable images produced by the linker into hexadecimal interchange formats for use 2012 COSMIC Software Introduction Listings with in circuit emulators and PROM programmers chex produces the following formats Motorola S record format standard Intel hex format clabs absolute listing utility clabs translates relocatable listings pro duced by the assembler by replacing all relocatable information by absolute information This utility must to be used only after the linker clib build and maintain object module libraries clib allows you to collect related files into a single named libra
211. m0x100000 r12 n vector int tables cxcorm lib crtsi cxm startup with auto init acia o main program modulel o module program cxcorm lib libfs cxm single prec cexcorm lib libis cxm integer lib cxcorm lib libm cxm machine lib vector o reset amp interrupt vectors def _ memory bss end of bss segment tdef stack 0x20000 stack pointer initial value 2012 COSMIC Software Using The Linker 299 CHAPTER 7 Debugging Support This chapter describes the debugging support available with the cross compiler targeting the CORTEX M There are two levels of debugging support available so you can use either the COSMIC s Zap C source level cross debugger or your own debugger or in circuit emulator to debug your application This chapter includes the following sections e Generating Debugging Information e Generating Line Number Information e Generating Data Object Information The cprd Utility The clst utility 2012 COSMIC Software Debugging Support 301 Generating Debugging Information Generating Debugging Information The compiler generates debugging information in response to command line options you pass to the compiler as described below The compiler can generate the following debugging information 1 line number information that allows COSMIC s C source level debugger or another debugger or emulator to locate the address of the code that a particular C source line or set of lines generate
212. m0xf000 r2 n const cre ates a const segment located after the previous vector sgement which is named const line 6 seg text a sconst r2 it n text creates a text code segment located after the sconst segment named fext line 7 seg sdata b0x20000000 o 0x0000 m0x1000 r2 id n sdata creates a word data segment located at 0x2000000 named sdata line 8 seg sbss a sdata n sbss creates an uninitialized data segment located after the sdata segment named sbss line 9 vector o vector file line 10 crts cxm runtime startup code It will be located at 0x 000 line 11 acia o the file that constitutes your application It follows the startup routine for code and data line 12 libis cxm the integer library to resolve references line 13 1ibm cxm the machine library to resolve references 20 Tutorial Introduction 2012 COSMIC Software Compiling and Linking line 14 def __sram pstart sbss defines a symbol _ sram equal to the of the start of sbss segment line 15 def __eram pend sbss defines a symbol __eram equal to the of the end of sbss segment line 16 def __stack 0x20010000 defines a symbol stack equal to the absolute value 20010000 hex value The symbol _ stack is used by the startup routine to initialize the stack pointer line 17 def sdata pstart sdata defines a symbol _ sdata equal to the of the start of sdata segment line 18 def memory end sbss defines a symbol __ mem
213. main 0000003e section text defined public _outch 0000001b section text defined public _buffer 00000000 section bss defined public _ptecr 00000000 section bsct defined public zpage _getch 00000000 section text defined public _ptlec 00000002 section bsct defined public zpage _recept 00000028 section text defined public The information for each symbol is name address section to which it belongs and attribute 2012 COSMIC Software Programming Support 321 8 The cvdwarf Utility The cvdwarf Utility cvdwarf is the utility used to convert a file produced by the linker into an ELF DWARF format file Command Line Options cvdwarf accepts the following options each of which is described in detail below cvdwarf options file bp bank start address bs bank shift dup accept duplicate headers e entry symbol or address loc complex location description zO output file name page define pagination HC12 HCS08 only rb reverse bitfield L to R so add stack offset v be verbose lt file gt specifies a file which must be in executable format Cvdwarf Option usage Option Description bp start address of the banking page bs set the window shift to which implies that the number of bytes in a window is 2 THESE FLAGS ARE CURRENTLY ONLY MEANINGFULL FOR THE HC11K4 dup handle duplicate header files individually By default the converter assumes that all header fil
214. mbler The cross assembler can provide when necessary listings symbol table cross reference and more The following command will generate a listing file named acia s that will also contain a cross reference cacorm c 1 acia s For more information see Chapter 5 Using The Assembler 18 Tutorial Introduction 2012 COSMIC Software Compiling and Linking Step 3 Linking This step consists in linking relocatable files also referred to as object modules produced by the compiler or by the assembler lt files gt o into an absolute executable file acia exm in our example Code and data sections will be located at absolute memory addresses The linker is used with a command file acia Ikf in this example An application that uses one or more object module s may require sev eral sections code data interrupt vectors etc located at different addresses Each object module contains several sections The compiler creates the following sections Type Description text code or program section e g ROM const constant and literal data e g ROM sconst constant and literal data in short range e g ROM data all static initialized data e g RAM bss all non initialized static data e g RAM sdata initialized variables in short range R9 based sbss uninitialized variables in short range R9 based In our example and in the test file provided with th
215. me in place of a standard instruction 2012 COSMIC Software Using The Assembler 193 Assembly Language Syntax ldr rl r9 lword 4 load LSW signex expand macro str r2 r9 lword 7 store result The resulting code will be the same as if the following code had been written ldr rl r9 lword 4 load LSW mov r2 0 prepare MSW cmp r1 0 test sign bpl pos if not positive mvn r2 x2 invert MSW pos str r2 r9 lword store result A macro may have up to 35 parameters A parameter is written 1 2 9 A Z inside the macro body and refers explicitly to the first second ninth argument and A to Z to denote the tenth to 35th oper and on the invocation line which are placed after the macro name and separated by commas Each argument replaces each occurrence of its corresponding parameter An argument may be expressed as a string constant if it contains a comma character A macro can also handle named arguments instead of numbered argu ments In such a case the macro directive is followed by a list of argu ment named each prefixed by a character and separated by commas Inside the macro body arguments will be specified using the same syn tax or a sequence starting by a character followed by the argument named placed between parenthesis This alternate syntax is useful to catenate the argument with a text string immediately starting with alphanumeric characters The special parameter is r
216. mpiler option as described in the next paragraph The contents of the configuration file cxcorm cxf as provided by the default installation appears below CONFIGURATION FILE FOR CORTEX M COMPILER Copyright c 2011 by COSMIC Software pu unsigned char i cosmic hcorm include path pm0x3030 model configuration m debug x debug produce debug info m fast dF2 optimize for speed m mods hmods h 4K data 64K constants m modsc hmods h cm 4K data unlimited constants m modl hmodl h unlimited data 64K constants m modlc hmodlc h cm unlimited data unlimited constants m modO rr m0 n0 MO target m nobss bss nobss do not use bss m proto p proto enable prototype checking m rev rb rev reverse bit field order m strictick strict enforce type checking m split sf functions in different sections m sprec f use float only m warn wl warn enable warnings The following command line cxcorm hello c 352 Modifying Compiler Operation 2012 COSMIC Software The Configuration File in combination with the above configuration file directs the excorm compiler to execute the following commands cpcorm o 2 cxl u m0x3030 i cosmic hcorm hello c cgcorm o 2 cx2 2 cx1 cocorm o 2 cx1 2 cx2 cacorm o hello o i cosmic hcorm 2 cx1 2012 COSMIC Software Modifying Compiler Operation 353 B Changing the Default Options Changing the Default Options To change the combin
217. ms many important functions to establish a runtime environment for C The runtime startup file included with the standard distribution provides the following e Initialization of the bss section if any e ROM into RAM copy if required e Initialization of the stack pointer and base registers if required _ main or other program entry point call and e An exit sequence to return from the C environment Most users must modify the exit sequence provided to meet the needs of their specific execution environment The following is a listing of the standard runtime startup file erts cxm included on your distribution media It does not perform automatic data initialization A special startup program is provided ertsi cxm which is used instead of crts cxm when you need automatic data initialization The runtime startup file can be placed anywhere in memory Usually the startup will be linked with the RESET interrupt and the startup file may be at any convenient location The compiler provides startup files erts cx0 and crtsi cx0 to be used when building an applicaiton for a M0 device Description of Runtime Startup Code 1 gt C STARTUP CODE 2 Copyright c 2011 by COSMIC Software g F 4 xdef exit _ stext 5 xref l main _ sdata sram eram stack 6 3 7 _ stext 8 rdr rl atab 4 get start of ram 9 ldr r2 atab 8 get end of ram 10 subs 1r2 r1 byte size et beq init empty skip 12 lsrs r2 2 word size 13 movs
218. n times asin macro repeat 1 1sl rl 1 endr endm 7 use of above macro asin 10 shift 10 times See Also repeat 2012 COSMIC Software Using The Assembler 213 Assembler Directives equ equ Description Give a permanent value to a symbol Syntax label equ lt expression gt Function The equ directive is used to associate a permanent value to a symbol label Symbols declared with the equ directive may not subsequently have their value altered otherwise the set directive should be used lt expression gt must be either a constant expression or a relocatable expression involving a symbol declared in the same section as the cur rent one Example false true tablen nul ters soh stx etx eot enq See Also lit set 214 Using The Assembler equ equ equ equ equ equ equ equ equ 0 initialize these values 1 tabfin tabsta compute table length 0 define strings for ascii charac 1 2 3 4 5 2012 COSMIC Software Assembler Directives even even Description Assemble next byte at the next even address relative to the start of a section Syntax even lt fill_value gt Function The even directive forces the next assembled byte to the next even address If a byte is added to the section it is set to the value of the fill ing byte defined by the f option If lt fill_value gt is specified it will be used locally as the fi
219. nce ld s n labs bal bal lt 0 CR W See Also abs fabs Notes labs is packaged in the integer library 2012 COSMIC Software Using The Compiler 113 a C Library Idexp Idexp Description Scale double exponent Syntax include lt math h gt double ldexp double x int exp Function Idexp multiplies the double x by two raised to the integer power exp Return Value Idexp returns the double result x J lt lt exp expressed as a double floating value If a range error occurs dexp returns HUGE_VAL Example x exp ldexp x exp 1 0 1 2 0 1 0 0 1 0 1 0 0 5 0 0 0 0 See Also frexp modf Notes Idexp is packaged in the floating point library 114 Using The Compiler 2012 COSMIC Software C Library ldiv Idiv Description Long divide with quotient and remainder Syntax include lt stdlib h gt ldiv_t ldiv long numer long denom Function Idiv divides the long integer numer by the long integer denom and returns the quotient and the remainder in a structure of type div_t The field quot contains the quotient and the field rem contains the remain der Return Value ldiv returns a structure of type div_t containing both quotient and remainder Example To get minutes and seconds from a delay in seconds ldiv_t result result ldiv time 60L min result quot sec result rem See Also div Notes ldiv is packaged in the integer l
220. nction has been called through a pointer with more than one char or int argument or is returning a structure redefined space the version of cpcorm you used to compile your pro gram is incompatible with cgcorm unknown space you have specified an invalid space modifier xxx unknown space modifier you have specified an invalid space modi fier xxx PANIC bad input file cannot read input file PANIC bad output file cannot create output file PANIC can t write cannot write output file All other PANIC messages should never happen If you get such a message please report it with the corresponding source program to COSMIC 344 Compiler Error Messages 2012 COSMIC Software Assembler cacorm Error Messages Assembler cacorm Error Messages The following error messages may be generated by the assembler Note that the assembler s input is machine generated code from the compiler Hence it is usually impossible to fix things on the fly The problem must be corrected in the source and the offending program s recom piled bad source directive a source directive is not followed by a string giving a file name and line numbers bad addressing mode an invalid addressing mode have been con structed bad argument number a parameter sequence n uses a value negative or greater than 9 bad character constant a character constant is too long for an expres sion bad comment delimiter an unexpec
221. ndard startup sequence 52 Programming Environments 2012 COSMIC Software Heap Management Control with the C Compiler Modifying The Heap Location It is easy to modify the _sbreak function in order to handle the heap in a separated memory area The first example shown below handles the heap area in a standard C array which will be part of the application variables The heap area is declared as an array of char simply named heap The algorithm is mainly the same and once the new top is computed it is compared with the array limits Note that the array is declared as a static local variable It is possible to have it declared as a static global varia ble If you want it to be global be careful on the selected name You should start it with a _ character to avoid any conflict with the applica tion variables The modified _sbreak function using an array is as follows f SET SYSTEM BREAK IN AN ARRAY define HSIZE 800 heap size void sbreak int size static char brk NULL memory break static char heap HSIZE heap area char obrk if _brk initialize on first call _brk heap obrk _brk old top _brk size new top if amp heap HSIZE lt _brk _brk lt heap check boundaries _brk obrk restore old top return NULL return NULL pointer return obrk return new area start If you need to place the heap array at a specific l
222. ne 7 starts a new name region which is in the public name space by default Now no reference to the symbol _func can reach the definition created on Line 6 That definition can only be reached now by using the symbol _oldfunc which is publicly defined as an alias for it 292 Using The Linker 2012 COSMIC Software Special Topics Line 8 links the user program and the module newfunc o which pro vides a new and public definition of _ func In this module the old ver sion is accessed by its alias This new version will satisfy all references to _func made in prog o and the libraries Line 9 links in the required libraries The rules governing which name space a symbol belongs to are as fol lows e Any symbol definition in the public space is public and satisfies all outstanding and future references to that symbol e Any symbol definition in the private space of the current region is private and will satisfy any private reference in the current region All private definitions of a symbol must occur before a public def inition of that symbol After a public definition of a symbol any other definition of that symbol will cause a multiply defined sym bol error e Any number of private definitions are allowed but each must be in a separate region to prevent a multiply defined symbol error e Any new reference is associated with the region in which the ref erence is made It can be satisfied by a private definition
223. ng The Linker 2012 COSMIC Software Moveable Code The function contained in the object flash o is now linked at the RAM address 0x100 but stored somewhere in the code space along with any other initialized data It is not necessary to link the application with the startup routine crtsi s if the application does not contain initialized data but the descriptor will be built as soon as a moveable function is used by the application but if the crtsi s startup is used moveable code seg ments are not copied in RAM at the application start up In order to use such a function it is necessary to first copy it from ROM to RAM This is done by calling the library function _fetepy with one character argument equal to the first significant letter of the moveable segment name This argument allows an application to implement sev eral different moveable segments for different kind of situations In such a case all the moveable segment names should have names with different first character This function returns a boolean status equal to 0 if no moveable segment has been copied or a value different of zero otherwise Once the segment has been successfully copied the RAM function can be called directly if _fctcpy b flash There is no possible name conflict between data segment names and moveable code segment names because the linker internally marks the flag byte differently 2012 COSMIC Software Using The Linker 285 6 Ma
224. ng words Example ptlec ds b 2 ptecr ds b 2 chrbuf ds w 128 Note For compatibility with previous assemblers the directive rmb is alias to ds b 206 Using The Assembler 2012 COSMIC Software Assembler Directives else else Description Conditional assembly Syntax if lt expression gt iISisauiclEnoms else instructions endif Function The else directive follows an if directive to define an alternative condi tional sequence It reverts the condition status for the following instruc tions up to the next matching endif directive An else directive applies to the closest previous if directive Example if offset gt 8 if offset too large add rl1 offset add offset else otherwise sub rl1 offset substract offset endif Note The else and elsec directives are equivalent and may used without dis tinction They are provided for compatibility with previous assemblers See Also if endif clist 2012 COSMIC Software Using The Assembler 207 Assembler Directives elsec elsec Description Conditional assembly Syntax if lt expression gt instructions elsec instructions endc Function The elsec directive follows an if directive to define an alternative condi tional sequence It reverts the condition status for the following instruc tions up to the next matching endec directive An elsec directive applies to the closest previous if directive Example if
225. ning that if a segment is declared with a option as following a segment which is marked with the ck option it will automatically inherit the ck marker and will be also checked Note also that if you are using the automatic initialization mechanism and if the code segment hosting the init descriptor it is also marked with ck the init segment and ALL the initialization copy segments will also be checked 2 Create an empty segment which will contain the checksum descrip tor This has to be an empty segment located wherever you want with a b or a option This segment will NOT be checked even if marked or hooked to a marked segment The linker will fill this seg ment with a data descriptor allowing the checking function to scan all the requested segments and compute the final ere This segment 2012 COSMIC Software Using The Linker 287 6 Checksum Computation has to be specially marked with the option ik to allow the linker to recognize it as the checksum segment Here is an example of link command file showing how to use ck and ik LINKER EXAMPLE FOR CHECKSUM IMPLEMENTATION mark the first segment of an attached list with ck seg text b 0x8000 n code ck this segment is marked seg const a code n const this one is implicitly marked create an empty segment for checksum table marked with ik seg cksum a const n cksum ik checksum segment remaining part should contain the verification code seg dat
226. nual Segment Initialization Manual Segment Initialization The linker allows a segment to be manually initialized at runtime by calling a copy routine such as memcpy For such a segment the linker builds a data image linked at the initial segment address but stored at a different location The target address is usually in RAM while the source address is usually in flash In order to enable this mechanism an empty named segment n must be created somewhere in the flash space and the initialized segment must be created with a q option specifying the name of the flash segment containing the image The start addresses of both segments and their length will be obtained with the usage of appropriate def directives Assuming we have a function created in a section named ramcode the following linker command file abstract shows how to define the appropriate segments seg text b 0x8000 n code seg image a code n image seg ramcode b 0x3000 n ramcode q image The code built and expected to run at 0x3000 will be stored in the image segment wherever it is located and will not be loaded at its execution location in the resulting application code It is then possible to use memcpy when the code must be copied to its execution location 0x3000 in this case You can define the following linker symbols in your linker command file for the execution start address copy to the image location address copy from and the image size
227. oat or long constants and switch tables are normally generated into the const section The compiler generates initialized data into the data section External data names are published via xref declarations Data you declare to be of const type by adding the type qualifier const to its base type is nor mally generated into the const section or the sconst for dir con stants Initialized data declared with the dir space modifier will be generated into the sdata section Uninitialized data are normally gener ated into the bss section or the sbss section for dir variables unless forced to the data section by the compiler option nobss Uninitialized data are normally generated into the bss section Section Declaration Reference sdata dir int i 2 xdef Sbss dir int i xdef sconst dir const int i 2 xdef data int init 1 xdef bss int uninit xdef const const int cinit 1 xdef text char putchar c xdef 48 Programming Environments 2012 COSMIC Software Interfacing C to Assembly Language Function calls are performed according to the following 1 Arguments are moved onto the stack or in registers from right to left Character and short data are widened to int 2 The function is called via a b _func instruction 3 The arguments to the function are popped off the stack The first arguments of a function are passed in registers according to the following rules
228. ocation you need to locate this module at a specific address using the linker options In the above example the heap array will be located in the bss segment thus complicating the startup code which would need to zero two bss sec tions instead of one Compiling this function with the nobss option 2012 COSMIC Software Programming Environments 53 Heap Management Control with the C Compiler will force allocation of the heap in the data segment and you can locate it easily with linker directives as seg data b 0x8000 heap start sbreak o sbreak function It is also possible to handle the heap area outside of any C object just by defining the heap start and end values using the linker def direc tives Assuming these symbols are named _heap_start and _heap_end in C it is possible to define them at link time with such directives tdef heap _start 0x8000 heap start tdef _ heap _end 0xA000 heap end NOTE Since the initial content of the area can be undefined the ib option can be specified to not include the segment in the automatic RAM initializa tion G character when defining a C symbol at link You need to add an extra time to match the C compiler naming conventions The modified _sbreak function is as follows SET SYSTEM BREAK IN MEMORY void sbreak int size extern char heap start heap end heap limits static char brk NULL memory break char obrk if
229. oftware Assembler Directives nolist nolist Description Turn off listing Syntax nolist Function The nolist directive controls the parts of the program which will be not written to the listing file until an end or a list directive is encountered It is effective if and only if listings are requested it is ignored otherwise See Also list Note For compatibility with previous assemblers the directive nol is alias to nolist 2012 COSMIC Software Using The Assembler 237 Assembler Directives nopage nopage Description Disable pagination in the listing file Syntax nopage Function The nopage directive stops the pagination mechanism in the listing out put It is ignored if no listing has been required Example xref mult div nopage ds b charin charout ds w a b sum See Also plen title 238 Using The Assembler 2012 COSMIC Software Assembler Directives offset offset Description Creates absolute symbols Syntax offset lt expresion gt Function The offset directive starts an absolute section which will only be used to define symbols and not to produce any code or data This section starts at the address specified by lt expression gt and remains active while no directive or instructions producing code or data is entered This abso lute section is then destroyed and the current section is restored to the one which was active when t
230. oftware The clst utility Cist Option Usage cont Option Description i gt read string to locate the source file in a specific directory Source files will first be searched for in the current directory then in the specified directories in the order they were given to clst You can specify up to 10 different paths Each path is a directory name not terminated by any directory separator character l when paginating output make the listings lines long By default listings are paginated at 66 lines per page 0 redirect output from clst to file You can achieve a similar effect by redirecting output in the command line clst o acia lst acia cxm is equivalent to clst acia cxm gt acia lst p suppress pagination No page breaks will be output r where is a range specification It must be of the form lt number gt lt number gt When this flag is specified only those source files occupying memory in the specified range will be listed If part of a file occupies memory in the speci fied range that file will be listed in its entirety The following is a valid use of r r 0xe000 0xe200 2012 COSMIC Software Debugging Support 307 CHAPTER 8 Programming Support This chapter describes each of the programming support utilities pack aged with the C cross compiler targeting the CORTEX M The follow ing utilities are availabl
231. ointer char volatile ptecr write pointer Character reception Loops until a character is received a int getch void int c character to be returned while ptlec ptecr equal pointers gt loop c ptlectt get the received char if ptlec gt amp buffer SIZE put in in buffer ptlec buffer return c Send a char to the SCI A ui void outch int c 14 Tutorial Introduction 2012 COSMIC Software Acia c Example file while ESCI_A SR amp TDRE wait for READY ESCI_A SR TDRE clear TDRE ESCI_A DR c send it es Character reception routine k This routine is called on interrupt a t puts the received char in the buffer W interrupt void recept void ESCI_A SR RDRF clear interrupt ptecr ESCI_A DR get the char if ptecr gt amp buffer SIZE put it in buffer ptecr buffer Main program Sets up the SCI and starts an infinite a loop of receive transmit void main void ptecr ptlec buffer initialize pointers ESCI_A CR1 0x209L lt lt 16 speed 9600 80MHz 0x002c parameters for interrupt ESCI_A CR2 0 disable LIN cli 3 authorize interrupts for 77 loop outch getch get and put a char 2012 COSMIC Software Tutorial Introduction 15 Acia c Example file Default Compiler Operation By default the compiler compile
232. ompiler looks for a default configuration file named cxcorm cxf in the compiler directory as specified in the installation process See The Configuration File in Appendix B g gt specify code generation options Up to 128 options can be specified See The cgcorm Code Generator in Appendix D for the list of all accepted options 62 Using The Compiler 2012 COSMIC Software Invoking the Compiler Cxcorm Option Usage cont Option Description i gt define include path You can define up to 128 different paths Each path is a directory name not terminated by any directory separator character or a file containing an unlim ited list of directory names l merge C source listing with assembly language code listing output defaults to lt file gt s NO do not use the optimizer 0 gt specify optimizer options Up to 128 options can be speci fied See The cocorm Assembly Language Optimizer in Appendix D for the list of all accepted options p gt specify parser options Up to 128 options can be specified See The cpcorm Parser in Appendix D to get the list of all accepted options S create only assembler files and stop Do not assemble the files produced sm create only a list of make compatible dependencies con sisting for each source file in the object name followed by a list of header files needed to compile that file Sp create
233. on and lt section list gt a list of section names separated by commas When loading an object file each section listed in the right part of the declaration will be loaded as if it was named as defined in the left part of the declaration The target section may be a new section name or the name of an existing section including the pre defined ones When using a new name this directive has to be preceded by a matching seg definition NOTE Whitespaces are not allowed aside the equal sign and the commas Linking Files on the Command line The linker supports linking objects from the command line The link command file has to be modified to indicate where the objects are to be loaded using the following syntax 2012 COSMIC Software Using The Linker 273 6 Linker Options 1 2 include each individual object file at its positional location on the command line and insert them at the respective locations in the link file 1 is the first object file and so on include all of the objects on the command line and insert them at this location in the link file Example Linking objects from the command line clnk o test cxm test 1lkf filel o file2 o Test 1k seg text b0x5000 seg data b0x100 1 seg text b0x7000 2 Is equivalent to clnk o test cxm test 1kf test 1kf seg text b0x5000 seg data b0x100 filel o seg text b0x7000 file2 o Include
234. only preprocessed files and stop Do not compile files produced Preprocessed output defaults to lt file gt p The produced files can be compiled as C source files t specify path for temporary files The path is a directory name not terminated by any directory separator character V be verbose Before executing a command print the com mand along with its arguments to STDOUT The default is to output only the names of each file processed Each name is followed by a colon and newline X do not execute the passes instead write to STDOUT the commands which otherwise would have been performed gt select a predefined compiler option These options are pre defined in the configuration file You can specify up to 128 compiler options on the command line The following docu ments the available options as provided by the default con figuration file 2012 COSMIC Software Using The Compiler 63 Eg Invoking the Compiler Cxcorm Option Usage cont Option Description debug produce debug information to be used by the debug utilities provided with the compiler and by any external debugger fast use movw and movt instructions to load constants instead of using access from table This option cannot be used when targetting the MO instruction set mod0 select the MO instruction set with the unlimited data and unlimited constants mods select standard model with variables
235. ons 000 Generating Listings s Generating an Error File cceccesseeseeseesceseeseeeeeeeeeeceeeeeeeeeeaes Return Stats esia aesa a daieeat alas EXIMPlE S assnret EENE EAE EIET teense C Library Support cccececcesesessenseesecseeeeseeeseeeeeseseeceeseeeeees How C Library Functions are Packaged Inserting Assembler Code Directly Linking Libraries with Your Program a Integer Library Functions ccccceeeeesceeceeceseetecseeeeneenee Common Input Output Functions cccceeeeseseseeereeee Functions Implemented as MacroS sccscesseeseeseereeeees Functions Implemented as Builtins 0 0 0 cceceeeeeeeeeeees Including Header Files 0 Descriptions of C Library Functions Generate inline assembly code m Abort program execution sseeeeeeeseesressssrrsr ress srseesrerer se Find absolute val ecncecninen niriana Arctangent Arctangent Of y X eee Convert buffer to double i Convert buffer to integer sessssessenseseessrseesserrrrersreresreret Convert buffer to long ssesssssessessensesseessrserrsesrrserrsererseess Allocate and clear space on the heap cccccceceeeeeeeees Round to next higher integer eceeceeseeseeeeseeseeeeeeeeees Verify the recorded checksum ccsccssescesceeseeseeeeeeseees Verify the recorded checksum ccceccssessesseeeeeseeeeseeeeees Verify the recorde
236. option must precede any group of options so that the linker can determine which segment the options that follow apply to The linker allows up to 255 different segments seg lt section gt lt options gt start a new segment loading assembler section type lt section gt and build it as directed by the lt options gt that follow Segment Control Options Usage Option Description a make the current segment follow the segment where refers to a segment name given explicitly by a n option Options b and e cannot be specified if a has been speci fied Option o can be specified only with value 0 to reset the logical address to the same value than the physical address b set the physical start address of the segment to Option e or a cannot be specified if b has been specified C do not output any code data for the segment ck mark the segment you want to check For more information see Checksum Computation on page 287 ds set the bank size for paged addresses calculation This option overwrites the global bs option for that segment e set the physical end address of the segment to Option b or a cannot be specified if e has been specified f fill the segment up to the value specified by the m option with single bytes or two byte words whose value is This option has no effect if no m option is specified for that seg ment 2012 COSMIC Software Using The Lin
237. or messages 1 gt library path m map file name o output file name p phys addr in map s symbol table only sa sort symbol by address si suppress info segment sl output local symbols u display unused symbols v verbose The output file name and the link command file must be present on the command line The options are described in terms of the two groups listed above the global options that apply to the linker and the segment control options that apply only to specific segments 266 Using The Linker 2012 COSMIC Software Linker Options Global Command Line Options The global command line options that the linker accepts are Global linker Options Option Description bs set the window shift to which implies that the number of bytes in a window is 2 The default value is For more information see the section Address Specification on page 278 e log errors in the text file instead of displaying the messages on the terminal screen ge produce error messages directly compatible with the Eclipse environment l gt specify library path You can specify up to 128 different paths Each path is a directory name not terminated by any directory separator character m produce map information for the program being built to file 0 write output to the file This option is required and has no default value p display symbols with physical address inst
238. ory equal to the value of the end of the sbss segment This is used to get the address of the end of the bss The symbol _ memory is used by the star tup routine to reset the sbss By default and in our example the sbss segment follows the sdata seg ment The crtsv o file contains the runtime startup that performs the following operations e initialize the bss if any e initialize the stack pointer e call main or any other chosen entry point For more information see Modifving the Runtime Startup in Chapter 3 Programming Environments After you have modified the linker command file you can link by typ ing clnk o acia cxm acia 1kf For more information see Chapter 6 Using The Linker 2012 COSMIC Software Tutorial Introduction 21 Compiling and Linking Step 4 Generating S Records file Although acia cxm is an executable image it may not be in the correct format to be loaded on your target Use the chex utility to translate the format produced by the linker into standard formats To translate acia cxm to Motorola standard S record format chex acia cxm gt acia hex or chex o acia hex acia cxm acia hex is now an executable image in Motorola S record format and is ready to be loaded in your target system For more information see Zhe chex Utility in Chapter 8 22 Tutorial Introduction 2012 COSMIC Software Linking Your Applicat
239. otherwise the instruc tions between else and endif are assembled An else directive applies to the closest previous if directive The if directives may be nested The skipped lines may or may not in the listing depending on the clist directive status Example if offset gt 8 if offset too large add rl offset add offset else otherwise sub rl offset substract offset endif See Also else endif clist 2012 COSMIC Software Using The Assembler 217 Assembler Directives ifc ifc Description Conditional assembly Syntax ifc lt stringl gt lt string2 gt orifc lt stringl gt lt string2 gt instructions instructions endc elsec instructions endc Function The ifc else and ende directives allow conditional assembly The ifc directive is followed by a constant expression If lt string gt and lt string2 gt are equals the following instructions are assembled up to the next matching endc or elsec directive otherwise the following instruc tions up to the next matching endc or elsec directive are skipped If the ife statement ends with an elsec directive the expression result is inverted and the same process applies to the following instructions up to the next matching endec So if the ife expression was not zero the instructions between elsec and endec are skipped otherwise the instruc tions between elsec and endc are assembled An elsec directive applies to the closest previous if directiv
240. our particular application It explains how to create a runtime startup for your applica tion and how to write C routines that perform special tasks such as serial I O direct references to hardware addresses interrupt handling and assembly language calls 2012 COSMIC Software Preface 2 Preface Organization of this Manual Chapter 4 Using The Compiler describes the compiler options This chapter also describes the functions in the C runtime library Chapter 5 Using The Assembler describes the CORTEX M assem bler and its options It explains the rules that your assembly language source must follow and it documents all the directives supported by the assembler Chapter 6 Using The Linker describes the linker and its options This chapter describes in detail all the features of the linker and their use Chapter 7 Debugging Support describes the support available for COSMIC s C source level cross debugger and for other debuggers or in circuit emulators Chapter 8 Programming Support describes the programming sup port utilities Examples of how to use these utilities are also included Appendix A Compiler Error Messages is a list of compile time error messages that the C compiler may generate Appendix B Modifying Compiler Operation describes the configu ration file that serves as default behaviour to the C compiler Appendix C
241. p Function frexp partitions the double at val which should be non zero into a frac tion in the interval 1 2 1 times two raised to an integer power It then delivers the integer power to exp and returns the fractional portion as the value of the function The exponent is generally meaningless if val is zero Return Value frexp returns the power of two fraction of the double at val as the return value of the function and writes the exponent at exp Example To implement the sgrt x function double sqrt double x extern double newton double int n x frexp x amp n x newton x if n amp 1 x SQRT2 return ldexp x n 2 See Also Idexp Notes frexp is packaged in the floating point library Using The Compiler 2012 COSMIC Software C Library getchar getchar Description Get character from input stream Syntax include lt stdio h gt int getchar void Function getchar obtains the next input character if any from the user supplied input stream This user must rewrite this function in C or in assembly language to provide an interface to the input mechanism of the C library Return Value getchar returns the next character from the input stream If end of file break is encountered or a read error occurs getchar returns EOF Example To copy characters from the input stream to the output stream while c getchar EOF putchar
242. pe structure type is not followed by a tag or definition incomplete type for debug information a structure or union is not completely defined in a file compiled with the debug option set integer constant too large a decimal constant is too large to be repre sented on an integer invalid pragma attribute syntax a syntax error has been detected in a pragma attribute directive invalid test expression the first expression of a ternary operator is not a testable expression invalid address expression the address of operator has been applied to a rvalue expression invalid address operand the address of operator has been applied to a register variable invalid address type the address of operator has been applied to a bitfield invalid alias an alias has been applied to an extern object 2012 COSMIC Software Compiler Error Messages 333 Parser cpcorm Error Messages invalid arithmetic operand the operands of an arithmetic operator are not of the same or coercible types invalid array dimension an array has been declared with a dimension which is not a constant expression invalid binary number the syntax for a binary constant is not valid invalid bit assignment the expression assigned to a bit variable must be scalar invalid bit initializer the expression initializing a bit variable must be scalar invalid bitfield size a bitfield has been declared with a size larger t
243. pends a newline character to the output stream puts uses putchar to output each character The terminating NUL is not copied Return Value puts returns zero if successful or else nonzero if a write error occurs Example To copy input to output line by line while puts gets buf F See Also gets Notes puts is packaged in the integer library 136 Using The Compiler 2012 COSMIC Software C Library rand rand Description Generate pseudo random number Syntax include lt stdlib h gt int rand void Function rand computes successive pseudo random integers in the range 0 32767 using a linear multiplicative algorithm which has a period of 2 raised to the power of 32 Example int dice return rand 6 1 Return Value rand returns a pseudo random integer See Also srand Notes rand is packaged in the integer library 2012 COSMIC Software Using The Compiler 137 Ei C Library realloc realloc Description Reallocate space on the heap Syntax include lt stdlib h gt void realloc void ptr unsigned int nbytes Function realloc grows or shrinks the size of the cell pointed to by ptr to the size specified by nbytes The contents of the cell will be unchanged up to the lesser of the new and old sizes The cell pointer ptr must have been obtained by an earlier calloc malloc or realloc call otherwise the heap will become corrupted
244. ple switch bss var ds b var2 ds b save switch functionl 10S adds beq str function2 10 add subs bne bx restore var3 ds b var4 ds b switch add str end See Also restore section 248 Using The Assembler text a E a 10 rl r9 var2 r1 r2 rl 2 10 ee text tL Fs rl r9 var4 2012 COSMIC Software Assembler Directives section section Description Define a new section Syntax lt section_ name gt section lt attributes gt Function The section directive defines a new section and indicates that the fol lowing program is to be assembled into a section named lt section_name gt The section directive cannot be used to redefine an already existing section If no name and no attributes are specified to the section the default is to defined the section as a text section with its same attributes It is possible to associate lt attributes gt to the new sec tion An attribute is either the name of an existing section or an attribute keyword Attributes may be added if prefixed by a character or not prefixed or deleted if prefixed by a character Several attributes may be specified separated by commas Attribute keywords are abs absolute section bss bss style section no data hilo values are stored in descending order of significance even enforce even starting address and size Example 2012 COSMIC Sof
245. pn char s1 char s2 Function strespn scans the string starting at s for the first occurrence of a char acter in the string starting at s2 It computes a subscript i such that e s1 i is a character in the string starting at s1 e s1 i compares equal to some character in the string starting at s2 which may be its terminating null character Return Value strcspn returns the lowest possible value of i s1 i designates the termi nating null character if none of the characters in s1 are in s2 Example To find the start of a decimal constant in a text string if str i strcespn str 0123456789 printf can t find number n See Also memchr strchr strpbrk strrchr strspn Notes strcspn is packaged in the integer library 156 Using The Compiler 2012 COSMIC Software C Library strlen strlen Description Find length of a string Syntax include lt string h gt unsigned int strlen char s Function strlen scans the text string starting at s to determine the number of char acters before the terminating NUL Return Value The value returned is the number of characters in the string before the NUL Notes strlen is packaged in the integer library 2012 COSMIC Software Using The Compiler 157 Description Concatenate strings of length n Syntax include lt string h gt char strncat char sl char s2 unsigned int n Function strnc
246. point library 2012 COSMIC Software Using The Compiler 117 Ei C Library longjmp longjmp Description Restore calling environment Syntax include lt setjmp h gt void longjmp jmp_buf env int val Function longjmp restores the environment saved in env by etjmp If env has not been set by a call to setjmp or if the caller has returned in the mean time the resulting behavior is unpredictable All accessible objects have their values restored when longjmp is called except for objects of storage class register the values of which have been changed between the setjmp and longjmp calls Return Value When Jongjmp returns program execution continues as if the corre sponding call to setjmp had returned the value val Jongjmp cannot force setjmp to return the value zero If val is zero setjmp returns the value one Example You can write a generic error handler as void handle int err extern jmp_buf env longjmp env err return from setjmp See Also setjmp Notes longjmp is packaged in the integer library 118 Using The Compiler 2012 COSMIC Software C Library lsqrt Isqrt Description Long integer square root Syntax include lt stdlib h gt unsigned int lsqrt unsigned long 1 Function Isqrt obtains the integral square root of the unsigned long Return Value Isqrt returns the closest integer smaller or equal to the square root of J expressed a
247. pressed as a double floating value in the range pi 2 pi 2 If x is outside the range 1 1 asin returns zero Example To compute the arcsine of y theta asin y See Also acos atan atan2 Notes asin is packaged in the floating point library Using The Compiler 2012 COSMIC Software C Library atan atan Description Arctangent Syntax include lt math h gt double atan double x Function atan computes the angle in radians the tangent of which is x atan com putes the angle in radians the tangent of which is x to full double preci sion Return Value atan returns the nearest internal representation to atan x expressed as a double floating value in the range pi 2 pi 2 Example To find the phase angle of a vector in degrees theta atan y x 180 0 pi See Also acos asin atan2 Notes atan is packaged in the floating point library 2012 COSMIC Software Using The Compiler 77 78 Description Arctangent of y x Syntax include lt math h gt double atan2 double y double x Function atan2 computes the angle in radians the tangent of which is y to full double precision If y is negative the result is negative If x is negative the magnitude of the result is greater than pi 2 Return Value atan2 returns the closest internal representation to atan y x expressed as a double floating value in the range pi pi If both input
248. private region is used to forget the _malloc reference once it has been aliased to _sbreak 2012 COSMIC Software Programming Environments 55 Data Representation Data Representation Data objects of type char are stored as one byte 7 0 Char representation Data objects of type short int are stored as two bytes less significant byte first 15 87 0 Less Significant Byte Most Significant Byte Short representation Data objects of type long integer and pointer are stored as four bytes in ascending order of significance 31 24 23 16 15 8 7 0 Less Significant Byte E Most Significant Byte Long Pointer representation Data objects of type float and double are represented as for the pro posed IEEE Floating Point Standard four bytes for float or eight bytes for double stored in ascending order of significance The IEEE repre sentation is most significant bit is one for negative numbers and zero otherwise the next eight bits for float or eleven bits for double are the characteristic biased such that the binary exponent of the number is the characteristic minus 126 for float or 1022 for double the remain ing bits are the fraction starting with the weighted bit If the character istic is zero the entire number is taken as zero and should be all zeros to avoid confusing some routines that do not process the entire number Otherwise there
249. produces all user diagnostics This pass deals with control lines and lexical analysis and then with everything else having to do with semantics Only machine dependent extensions are diagnosed in the code generator pass If a pass produces diagnostics later passes will not be run Any compiler message containing an exclamation mark or the word PANIC indicates that the compiler has detected an inconsistent inter nal state Such occurrences are uncommon and should be reported to the maintainers e Parser cpcorm Error Messages e Code Generator cgcorm Error Messages e Assembler cacorm Error Messages Linker clnk Error Messages 2012 COSMIC Software Compiler Error Messages 327 Parser cpcorm Error Messages Parser cpcorm Error Messages lt name gt not a member field name not recognized for this struct union lt name gt not an argument a declaration has been specified for an argument not specified as a function parameter lt name gt undefined a function or a variable is never defined FlexLM lt message gt an error is detected by the license manager _asm string too long the string constant passed to _asm is larger than 255 characters ambiguous space modifier a space modifier attempts to redefine an already specified modifier array size unknown the sizeof operator has been applied to an array of unknown size bad argument in macro lt name gt the argument of a operator in a
250. ption Specify the number of lines per pages in the listing file Syntax plen lt page _length gt Function The plen directive causes lt page_length gt lines to be output per page in the listing output if pagination is enabled by either a title directive or the ft option If the number of lines already output on the current page is less than lt page _length gt then the new page length becomes effec tive with lt page length gt If the number of lines already output on the current page is greater than or equal to lt page_length gt a new page will be started and the new page length is set to lt page_length gt Example plen 58 See Also page title 242 Using The Assembler 2012 COSMIC Software Assembler Directives repeat repeat Description Repeat a list of lines a number of times Syntax repeat lt expression gt repeat _body endr Function The repeat directive is used to cause the assembler to repeat the follow ing list of source line up to the next endr directive The number of times the source lines will be repeated is specified by the expression operand The repeat directive is equivalent to a macro definition fol lowed by the same number of calls on that macro Example shift a value n times asln macro repeat 1 swli PS pd endr endm use of above macro asln 10 shift 10 times See Also endr repeati rexit 2012 COSMIC Software Using The Assembler 243 As
251. quence of random numbers srand 103 See Also rand Notes srand is packaged in the integer library 150 Using The Compiler 2012 COSMIC Software C Library sscanf sscanf Description Read formatted input from a string Syntax include lt stdio h gt int sscanf schar char fmt Function sscanf reads formatted input from the NUL terminated string pointed at by s using the format string at fmt and the arguments specified by in exactly the same way as scanf See the description of the scanf function for information on the format conversion specifiers Return Value sscanf returns the number of assigned input items which can be zero if there is an early conflict between an input character and the format or EOF if the end of the string is encountered before the first conflict or conversion See Also scanf Notes sscanf is packaged in both the integer library and the floating point library The functionality of the integer only version of sscanf is a sub set of the functionality of the floating point version The integer only version cannot print or manipulate floating point numbers If your pro grams call the integer only version of sscanf the following conversion specifiers are invalid e f g and p The L flag is also invalid 2012 COSMIC Software Using The Compiler 151 Description Concatenate strings Syntax include lt string h gt char strcat char s1 ch
252. r 7 s7 sts if isgraph s putchar s See Also iscntrl isprint ispunct isspace Notes If the argument is outside the range 1 255 the result is undefined isgraph is packaged in the integer library 2012 COSMIC Software Using The Compiler 105 Ei C Library islower islower Description Test for lower case character Syntax include lt ctype h gt int islower int c Function islower tests whether c is a lower case alphabetic character Return Value islower returns nonzero if c is a lower case character otherwise the value returned is zero Example To convert to upper case if islower c c A a also see toupper See Also isalnum isalpha isdigit isupper isxdigit tolower toupper Notes If the argument is outside the range 1 255 the result is undefined islower is packaged in the integer library 106 Using The Compiler 2012 COSMIC Software C Library isprint isprint Description Test for printing character Syntax include lt ctype h gt int isprint int c Function isprint tests whether c is any printing character Printing characters are all characters between a space 040 in ASCII and a tilde character 0176 in ASCII Return Value isprint returns nonzero if c is a printing character otherwise the value returned is zero Example To output only printable characters for s s if
253. r a valid C identifier if isalpha s s _ for s isalnum s s _ s F See Also isalpha isdigit islower isupper isxdigit tolower toupper Notes If the argument is outside the range 1 255 the result is undefined isalnum is packaged in the integer library 2012 COSMIC Software Using The Compiler 101 Ei C Library isalpha isalpha Description Test for alphabetic character Syntax include lt ctype h gt int isalpha int c Function isalpha tests whether c is an alphabetic character either upper or lower case Return Value isalpha returns nonzero if the argument is an alphabetic character Oth erwise the value returned is zero Example To find the end points of an alphabetic string while first amp amp isalpha first first for last first isalpha last last F See Also isalnum isdigit islower isupper isxdigit tolower toupper Notes If the argument is outside the range 1 255 the result is undefined isalpha is packaged in the integer library 102 Using The Compiler 2012 COSMIC Software C Library iscntrl iscntrl Description Test for control character Syntax include lt ctype h gt int iscntrl int c Function iscntrl tests whether c is a delete character 0177 in ASCII or an ordi nary control character less than 040 in ASCII Return Value iscntrl returns nonzero if c is a
254. r initial value Se OH OSH HE SHE In the first case the initialized data will be located after the first code segment In the second case the it option instructs the linker to locate the initialized data after the segment marked with this flag The initial ized data will be located after the second code segment located at address 0x5000000 For more information see Initializing data in RAM in Chapter 3 and Automatic Data Initialization in Chapter 6 26 Tutorial Introduction 2012 COSMIC Software Specifying Command Line Options Specifying Command Line Options You specify command line options to cxcorm to control the compila tion process To compile and produce a relocatable file named acia o type cxcorm mods acia c The v option instructs the compiler driver to echo the name and options of each program it calls The l option instructs the compiler driver to create a mixed listing of C code and assembly language code in the file acia ls To perform the operations described above enter the command cxcorm v l mods acia c When the compiler exits the following files are left in your current directory e the C source file acia c e the C and assembly language listing acia ls e the object module acia o It is possible to locate listings and object files in specified directories if they are different from the current one by using respectively the cl and co options
255. r2 cmp rl 0 beq 10 Idr r2 r9 var bx Le function2 108 ldr r2 r9 var2 subs r2 1 bne 10 bx Ie Label Extensions 32 bit relocatable addresses must be loaded in two parts high word and low word using instructions movw and movt The assembler allows a single prefix the dot character recognizing automatically the high word when used with an movt instruction and the low word when used with an movw instruction 190 Using The Assembler 2012 COSMIC Software Assembly Language Syntax movw r0 address movt r0 address The dot syntax cannot be used with other instructions Constants The assembler accepts numeric constants and string constants Numeric constants are expressed in different bases depending ona pre fix character as follows 10 decimal no prefix 1010 binary 12 octal 1F or Ox1F or OX1F hexadecimal The assembler also accepts numerics constants in different bases depending on a suffix character as follow D d or none decimal no prefix Borb binary Qorg octal OAH or 0Ah hexadecimal 2012 COSMIC Software The suffix letter can be entered upper case or lower case Hexadecimal numbers still need to start with a digit String constants are a series of printable characters between single or double quote characters This is a string This is also a string Using The Assembler 191 Assembly Language Syntax
256. r3 0 to clear the bss 2012 COSMIC Software Programming Environments 33 Modifying the Runtime Startup 14 zbcl 15 str r3 r1 4 clear memory 16 subs r2 1 count down 17 bne zbcl and loop back 18 init 19 ldr sp atab 12 initialize SP 20 ldr r9 atab initialize DP 21 bl _main execute main 22 exit 23 b exit stay here 24 25 align 4 26 atab 27 dc l __sdata init value of data pointer 28 dc l __sram start of ram to clear 29 dc l __eram end of ram to clear 30 dc l __stack init value of stack pointer 31 3 32 end _main is the entry point into the user C program __eram is an external symbol defined by the linker as the end of the ram area The start of the ram area is marked by the local symbol __sram The PowerPC needs the full ram to be zeroed to properly ini tialize the ECC mechanism __ stack is an external symbol defined by the linker as an absolute value Lines 8 to 17 reset the bss section Line 19 sets the stack pointer You may have to modify them to meet the needs of your application Line 20 sets the data pointer You may have to modify them to meet the needs of your application Line 21 calls main in the user s C program Lines 22 to 23 trap a return from main If your application must return to a monitor for example you must modify this line 34 Programming Environments 2012 COSMIC Software Initializing data in RAM Initializing data in RAM If
257. rammer The name which is used in the linker for purposes of alias ing is the name as seen at the object module level For more information on this transformation see the section Interfacing C to Assembly Lan guage in Chapter 3 The main thing to note here is that func o and new_func o both define a different function named func The second function func defined in newfunc o calls the old func function by its alias oldfunc Name regions provide limited scope control for symbol names The new command starts a new name region which will be in effect until the next new command Within a region there are public and private name spaces These are entered by the pub and pri commands by default new starts in the public name space Lines 1 2 are the basic linker commands for setting up a separate I D program Note that there may be other options required here either by the system itself or by the user Line 3 starts a new region initially in the public name space Line 4 specifies the startup code for the system being used Line 5 establishes the symbol _o dfunc as an alias for the symbol _ func The symbol _o dfunc is entered in the symbol table as a public defini tion The symbol _func is entered as a private reference in the current region Line 6 switches to the private name space in the current region Then func o is linked and provides a definition private of course which sat isfies the reference to _func Li
258. re are two basic type of symbols that the linker puts into its internal symbol table REFs and DEFs DEFs are symbols that are defined in the object module in which they occur REFs are symbols that are referenced by the object module in which they occur but are not defined there The linker also builds a debug symbol table based on the debug symbol tables in any of the input object modules It builds the debug symbol table by concatenating the debug symbol tables of each input object module in the order it encounters them If debugging is not enabled for any of input object module the debug symbol table will be of zero length An incoming REF is added to the symbol table as a REF if that symbol is not already entered in the symbol table otherwise it is ignored that reference has already been satisfied by a DEF or the reference has already been noted An incoming DEF is added to the symbol table as a DEF if that symbol is not already entered in the symbol table its value is adjusted to reflect how the linker is relocating the input object module in which it occurred If it is present as a REF the entry is changed to a DEF and the symbol s adjusted value is entered in the symbol table entry If it is present as a DEF an error occurs multiply defined symbol When the linker is processing a library an object module in the library becomes an input object module to the linker only if it has at least one DEF which satisfies some outstandin
259. re once s display object size u display unused object where lt file gt is an object file compiled from C source with the com piler command line option debug set Cprd Option Usage Option Description fc print debugging information only about the function By default cprd prints debugging information on all functions in lt file gt Note that information about global data objects is always displayed when available fl print debugging information only about the file By default cprd prints debugging information on all C source files 0 print debugging information to file Debugging information is written to your terminal screen by default 304 Debugging Support 2012 COSMIC Software The cprd Utility Cprd Option Usage cont Option Description ra display any occurence of structure fields with their offset r display the first occurence of structure fields with their offset S display object size in bytes U display only unused global variables By default cprd prints debugging information about all functions and global data objects in lt file gt Examples The following example show sample output generated by running the cprd utility on an object file created by compiling the program acia c with the compiler option debug set cprd cxm Information extracted from acia cxm 2012 COSMIC Software Debugging Support 305 The clst utility
260. relocatable object files The C cross compiler calls cacorm to assemble your code automatically unless specified otherwise cacorm generates also listings if requested This chapter includes the following sections e Invoking cacorm e Object File e Listings e Assembly Language Syntax e Branch Optimization e Old Syntax e C Style Directives e Assembler Directives 2012 COSMIC Software Using The Assembler 181 Invoking cacorm Invoking cacorm cacorm accepts the following command line options each of which is described in detail below cacorm options lt files gt a absolute assembler b do not optimizes branches E output cross reference d gt define symbol value e error file name ff use formfeed in listing ft force title in listing f fill byte value ge eclipse error messages h include header i gt include path al output a listing 1 listing file name m accept old syntax md make dependencies mi accept label syntax n processor name o output file name pe all equates public pl keep local symbol p all symbols public si suppress info section u undefined in listing v be verbose xX include line debug info xp no path in debug info xx include full debug info Cacorm Option Usage Option Description a map all sections to absolute including the predefined ones 182 Using The Assembler 2012 COSMIC Software Invoking cacorm Cacorm Option Usage cont
261. rger than the maximum value allowed by the m option shared segment not empty the host segment for shared data is not empty and cannot be used for allocation symbol lt symbol gt multiply defined an object file attempts to rede fine a symbol symbol lt symbol gt not defined a symbol has been referenced but never defined unknown directive a directive name has not been recognized as a linker directive 350 Compiler Error Messages 2012 COSMIC Software APPENDIX B Modifying Compiler Operation This chapter tells you how to modify compiler operation by making changes to the standard configuration file It also explains how to create your own programmable options which you can use to modify com piler operation from the excorm cxf 2012 COSMIC Software Modifying Compiler Operation 351 B The Configuration File The Configuration File The configuration file is designed to define the default options and behaviour of the compiler passes It will also allow the definition of programmable options thus simplifying the compiler configuration A configuration file contains a list of options similar to the ones accepted for the compiler driver utility cxcorm These options are described in Chapter 4 Using The Compiler There are two differences the option f cannot be specified in a config uration file and the extra m option has been added to allow the defini tion of a programmable co
262. riables heap growing upward and data segment bss segment stack growing downward heap starts here T stack starts here t The heap start is the bss end and is equal to the _ memory symbol defined by the linker with an appropriate def directive The stack pointer is initialized by the application startup crts s to an absolute value generally the end of available memory or a value relative to the end of the bss segment for multi tasking purposes for instance The heap grows upwards and the stack downwards until collision may occur The heap management functions maintain a global pointer named heap pointer or simply HP pointing to the heap top and a linked list of memory blocks free or allocated in the area between the heap start and the heap top In order to be able to easily modify the heap implementa tion the heap management functions use a dedicated function to move the heap pointer whenever necessary The heap pointer is initialized to the heap start the heap is initially empty When malloc needs some memory and no space is available in the free list it calls this dedicated function named _sbreak to move the heap pointer upwards if possible 2012 COSMIC Software Programming Environments 51 Heap Management Control with the C Compiler _sbreak will return a NULL pointer if this move is not possible usually this is because the heap would overlap the stack Therefore it is possi ble to change the heap default location b
263. rs If the size of a current seg ment is zero when a command to start a new segment of the same name is encountered it is discarded Several different sections can be redi rected directly to the same segment by using the grp option clnk links the lt files gt you specify in order If a file is a library it is scanned as long as there are modules to load Only those library mod ules that define public symbols for which there are currently outstand ing unsatisfied references are included Inserting comments in Linker commands Each input line may be ended by a comment which must be prefixed by a character If you have to use the as a significant character you can escape it using the syntax Here is an example for an indirect link file Link for EPROM seg const b0x4000000 n const start eprom address seg vtext a const constants follow program seg sdata b 0x10000 zero page start address seg vector a const m0x100000 r12 n vector int tables cexcorm lib crts cxm startup object file modl o mod2 o input object files cexcorm lib libis cxm C library cexcorm lib libm cxm machine library vector o reset and interrupt vectors 2012 COSMIC Software Using The Linker 265 6 Linker Options Linker Options The linker accepts the following options each of which is described in detail below clnk options lt file 1lkf gt lt files gt bs bank size e error file name ge eclipse err
264. rs in an expression undefined label lt name gt a label is never defined undefined struct union a structure or union is used and is never defined unexpected end of file last declaration is incomplete unexpected return expression a return with an expression has been used within a void function unknown enum definition an enumeration has been declared with no member unknown structure an attempt to initialize an undefined structure has been done unknown union an attempt to initialize an undefined union has been done unreachable code a code sequence cannot be accessed strict lt name gt used before set a local variable has been used before beeing initialized by any previous code strict value out of range a constant is assigned to a variable too small to represent its value strict variable arguments in nostack mode a function has been declared with the syntax and the nostack modifier strict 342 Compiler Error Messages 2012 COSMIC Software Parser cpcorm Error Messages zero divide a divide by zero was detected zero modulus a modulus by zero was detected 2012 COSMIC Software Compiler Error Messages 343 Code Generator cgcorm Error Messages Code Generator cgcorm Error Messages bad builtin the builtin type modifier can be used only on functions bad interrupt usage the interrupt type modifier can only be used on functions invalid indirect call a fu
265. ry file for convenient stor age You use it to build and maintain object module libraries in standard library format cobj object module inspector cobj allows you to examine standard format executable and relocatable object files for symbol table informa tion and to determine their size and configuration cvdwarf ELF DWARF format converter cvdwarf allows you to con vert a file produced by the linker into an ELF DWARF format file Listings Several options for listings are available If you request no listings then error messages from the compiler are directed to your terminal but no additional information is provided Each error is labelled with the C source file name and line number where the error was detected If you request an assembly language and object code listing with inter spersed C source the compiler merges the C source as comments among the assembly language statements and lines of object code that it generates Unless you specify otherwise the error messages are still written to your terminal Your listing is the listing output from the assembler Optimizations The C cross compiler performs a number of compile time and optimiza tions that help make your application smaller and faster 10 Introduction 2012 COSMIC Software Optimizations e The compiler will perform arithmetic operations in 8 bit precision if the operands are 8 bit The compiler eliminates unreachable code e Branch shortening
266. s output format suppress header specify header string maximum data bytes per line output only named segments output file name use paged address format use paged address for data page number for linear mapping use paged address in bank only use paged address with mapping output increasing addresses output word addresses exclude named segments Chex Option Usage Option Description a the argument file is a considered as a pure binary file and is the output address of the first byte b substract to any address before output 310 Programming Support 2012 COSMIC Software The chex Utility Chex Option Usage cont Option Description e define as the entry point address encoded in the dedi cated record of the output format if available f define output file format Valid options are i Intel Hex Format Motorola S19 format m 2 Motorola S2 format 3 Motorola S3 format Default is to produced Motorola S Records fm Any other letter will select the default format h do not output the header sequence if such a sequence exists for the selected format h insert in the header sequence if such a sequence exists for the selected format m output maximum data bytes per line Default is to output 32 bytes per line n gt output only segments whose name is equal to the string Up to twenty different names may
267. s You may put line number information into the object module in either of the two formats or you can generate both line number information and information about program data and function arguments as described below 2 information about the name type storage class and address abso lute or relative to a stack offset of program static data objects func tion arguments and automatic data objects that functions declare Information about what source files produced which relocatable or executable files This information may be localized by address where the output file resides in memory It may be written to a file sorted by address or alphabetical order or it may be output to a printer in paginated or unpaginated format Generating Line Number Information The compiler puts line number information into a special debug symbol table The debug symbol table is part of the relocatable object file pro duced by a compilation It is also part of the output of the c nk linker You can therefore obtain line number information about a single file or about all the files making up an executable program However the compiler can produce line number information only for files that are fewer than 65 535 lines in length Generating Data Object Information The debug option directs the compiler to generate information about data objects and function arguments and return types The debugging information the compiler generates is the information used
268. s more efficient and easier to use at the cost of a slight loss in portability Note that COSMIC C does support the pointer and define methods of implementing I O access It is also possible to define structures at absolute addresses For exam ple one can write struct acia char status char data acia 0x6000 Using this declaration references to acia status will refer to mem ory location 0x6000 and acia data will refer to memory location 0x6001 This is very useful if you are building your own custom I O hardware that must reside at some location in the PowerPC memory map 42 Programming Environments 2012 COSMIC Software Inserting Inline Assembly Instructions Inserting Inline Assembly Instructions The compiler features two ways to insert assembly instructions in a C file The first method uses pragma directives to enclose assembly instructions The second method uses a special function call to insert assembly instructions The first one is more convenient for large sequences but does not provide any connection with C object The sec ond one is more convenient to interface with C objects but is more lim ited regarding the code length Inlining with pragmas The compiler accepts the following pragma sequences to start and fin ish assembly instruction blocks Directive Description pragma asm start assembler block pragma endasm end assembler block The compiler also accepts s
269. s an unsigned int Example To use sgrt to check whether n gt 2 is a prime number if n amp 01 return NOTPRIME sq lsqrt n for div 3 div lt sq div 2 if n div return NOTPRIME return PRIME See Also isqrt sqrt Notes Isqrt is packaged in the integer library 2012 COSMIC Software Using The Compiler 119 Description Allocate space on the heap Syntax include lt stdlib h gt void malloc unsigned int nbytes Function malloc allocates space on the heap for an item of size nbytes The space allocated is guaranteed to be at least nbytes long starting from the pointer returned which is guaranteed to be on a proper storage bound ary for an object of any type The heap is grown as necessary If space is exhausted malloc returns a null pointer Return Value malloc returns a pointer to the start of the allocated cell if successful otherwise it returns NULL The pointer returned may be assigned to an object of any type without casting Example To allocate an array of ten doubles double pd pd malloc 10 sizeof pd See Also calloc free realloc Notes malloc is packaged in the integer library 120 Using The Compiler 2012 COSMIC Software C Library max max Description Test for maximum Syntax include lt stdlib h gt max a b Function max obtains the maximum of its two arguments a and b Since max is implemente
270. s and assembles your program You may then link object files using clnk to create an executable program As it processes the command line cxcorm echoes the name of each input file to the standard output file your terminal screen by default You can change the amount of information the compiler sends to your terminal screen using command line options as described later According to the options you will use the following files recognized by the COSMIC naming conventions will be generated file s Assembler source module file o Relocatable object module file cxm input e g libraries or output e g absolute executable file for the linker 16 Tutorial Introduction 2012 COSMIC Software Compiling and Linking Compiling and Linking To compile and assemble acia c using default options type cxcorm mods acia c The compiler writes the name of the input file it processes acia c The result of the compilation process is an object module named acia o produced by the assembler We will now show you how to use the dif ferent components Step 1 Compiling The first step consists in compiling the C source file and producing an assembly language file named acia s cxcorm s mods acia c The s option directs cxcorm to stop after having produced the assem bly file acia s You can then edit this file with your favourite editor You can also visualize it with the appropriate syste
271. s as unsigned values 362 Compiler Passes 2012 COSMIC Software The cpcorm Parser Parser Option Usage cont Option Description d specify as the name of a user defined preprocessor sym bol define The form of the definition is dsymbol value the symbol is set to 1 if value is omitted You can specify up to 128 such definitions run preprocessor only cpcorm only outputs lines of text e log errors in the text file instead of displaying the mes sages on the terminal screen treat all floating point numbers as float and not double even if they are declared as double All calculations will be made on 32 bits instead of 64 bits Space reservations will be made on a 32 bit basis as well as argument passing enable float registers produce error messages directly compatible with the Eclipse environment h gt include files before to start the compiler process You can specify up to 128 files i gt specify include path You can specify up to 128 different paths Each path is a directory name not terminated by any directory separator character or a file containing an unlim ited list of directory names keep unused statics By default unused statics are removed output line number information for listing or debug create only a list of make compatible dependencies con sisting for each source file in the object name followed by a list of he
272. sembler Directives repeatl repeatl Description Repeat a list of lines a number of times Syntax repeatl lt arguments gt repeat body endr Function The repeatl directive is used to cause the assembler to repeat the fol lowing list of source line up to the next endr directive The number of times the source lines will be repeated is specified by the number of arguments separated with commas with a maximum of 36 arguments and executed each time with the value of an argument The repeatl directive is equivalent to a macro definition followed by the same number of calls on that macro with each time a different argument The repeat argument is denoted 1 unless the argument list is starting by a name prefixed by a character In such a case the repeat argument is specified by its name prefixed by a character A repeatl directive may be terminated early by using the rexit directive which when encountered acts as if the end of the repeatl has been reached Example test a value using the numbered syntax repeatl 1 253 add r1 1 add to register endr end or test a value using the named syntax repeatl count 1 2 3 add r1 count add to accu endr end 244 Using The Assembler 2012 COSMIC Software Assembler Directives repeatl will both produce 2 5 0000 2010101 5 0004 2010102 5 0008 2010103 6 See Also endr repeat rexit 2012 COSMIC Software test a value add add
273. shsax shsub16 shsub8 smc smlabb smlawt smlsd smlsdx smlsld smlsldx smmla smmlar smmls smmlsr smmul smmulr smuad smuadx smulbb smulbt smull smultb smultt smulwb smulwt smusd smusdx srs srsdb srsia ssat ssatl6 ssax ssubl6 ssub8 ste stc2 stc21 stel stmdb stmea stmfd stmia Str strb strbt strd strex sxtb sxtb1l6 sxth tbb tbh teq tst uadd16 uadd8 uasx ubfx udiv uhadd16 uhadd8 uhasx uhsax uhsub16 uhsub8 umaal umlal umull ugqadd16 ugadd8 uqasx uqsax uqsub16 uqsub8 usad8 usada8 usat usatl6 usax usub16 usub8 uxtab uxtab16 uxtah uxtb uxtb16 uxth wfe wfi yield 2012 COSMIC Software Assembly Language Syntax The operand field of an instruction uses addressing modes to describe the instruction argument The following example demonstrates the accepted syntax nop gt implicit mov ri 72 register add r0 1 immediate ldr r3 r5 4 indexed bne loop relative The assembler chooses the smallest addressing mode where several solutions are possible For an exact description of the above instructions refer to the COR TEX M Reference Manual Labels A source line may begin with a label Some directives require a label on the same line otherwise this field is optional A label must begin with an alphabetic character the underscore character _ or the period char acter It is continued by alphabetic A Z or a z or numeric 0 9 characters
274. spaces such as bank switching the linker allows several segments to be isolated from the other ones by giving them a space name with the s option In such a case a segment in a named space is checked only against the other segments of the same space The unnamed segments are checked together Setting Bias and Offset The bias and offset of a segment are controlled by the b option and o option The rules for dealing with these options are described below 278 Using The Linker 2012 COSMIC Software Setting Bias and Offset Setting the Bias If the b option is specified the bias is set to the value specified by Otherwise the bias is set to the end of the last segment of the same name If the e option is specified the bias is set to value obtain by subtracting the segment size to the value specified by Setting the Offset If the o option is specified the offset is set to the value specified by Otherwise the offset is set equal to the bias Using Default Placement If none of b e or o options is specified the segment may be placed after another one by using the a option where is the name of another segment Otherwise the linker will try to use a default place ment based on the segment name The compiler produces specific sec tions for code text and data data bss By default text and bsct segments start at zero data segment follows the latest text segment and bss segment follows t
275. structions endc elsec instructions endc Function The ifle elsec and ende directives allow conditional assembly The ifle directive is followed by a constant expression If the result of the expression is less or equal to zero the following instructions are assembled up to the next matching endc or elsec directive otherwise the following instructions up to the next matching endc or elsec direc tive are skipped If the ifle statement ends with an elsec directive the expression result is inverted and the same process applies to the following instructions up to the next matching endce So if the ifle expression was less or equal to zero the instructions between elsee and endec are skipped otherwise the instructions between elsec and endec are assembled An elsec direc tive applies to the closest previous if directive The if directives may be nested The skipped lines may or may not in the listing depending on the clist directive status Example ifle offset 127 if offset small enough add vl offset add to register elsec otherwise addptr offset 7 call a macro endc See Also elsec endc clist 2012 COSMIC Software Using The Assembler 223 Assembler Directives iflt e iflt Description Conditional assembly Syntax iflt lt expression gt or iflt lt expression gt instructions instructions endc elsec instructions endc Function The iflt else and ende directives allow conditional assembly The i
276. t file 318 file 280 floating point 68 integer 68 281 list file 318 load all files 318 load modules 265 machine 68 path specification 267 replace file 318 scanned 265 single precision 281 Standard ANSI 280 version 280 line number information 370 link command file 20 266 linker character prefix comment 265 build freestanding program 262 clnk 9 command file 264 command file example 298 command item 264 comment 265 global command line options 267 output file 263 physical memory 263 list directive 229 listing cross reference 18 file location 27 file path specification 314 interspersed C and assembly file 17 lit directive 230 local directive 190 231 local variable reorder 365 locate source file 307 log function 116 log10 function 117 longjmp function 118 lowercase menmonics 45 M MO mod0 option 64 accessible register set 365 instruction set 31 50 64 instruction set generation 370 libraries 281 282 startup files 33 macro argument 194 Index 7 assembler directive 232 internal label 189 named argument 194 named syntax 195 numbered argument 194 numbered syntax 194 main function 295 main routine 34 malloc function 120 map file description 295 modules section 295 produce information 267 segment section 295 stack usage section 295 symbols section 295 max function 121 maximum 121 memchr function 122 memcmp function 123 memcpy function 124 memmove function 125 memory location 41 mapped I O
277. t two lines are assembled Oth erwise they are skipped i offset gt 8 if offset too large add rl1 offset add offset else otherwise sub rl offset use quick instruction endif 196 Using The Assembler 2012 COSMIC Software Assembly Language Syntax Conditional directives may be nested An else directive refers to the closest previous if directive and an endif directive refers to the closest previous if or else directive If a listing is produced the skipped lines are printed only if enabled by the clist directive Otherwise only the assembled lines are printed Sections The assembler allows code and data to be splitted in sections A section is a set of code or data referenced by a section name and providing a contiguous block of relocatable information A section is defined with a section directive which creates a new section and redirects the follow ing code and data thereto The directive switch can be used to redirect the following code and data to another section data section defines data section text section defines text section Starts ldr rl r9 value fills text section b print switch data use now data section value d b E fills data section The assembler allows up to 255 different sections A section name is limited to 15 characters If a section name is too long it is simply trun cated without any error message The assembler predefines the following sections meaning that
278. tail below 360 Compiler Passes 2012 COSMIC Software The cpcorm Parser cpcorm options file a register allocation mode ad expand defines in assembly c99 c99 type behaviour cc do not cast const expressions ck extra type checkings cp no constant propagation csb check signed bitfields d gt define symbol value e run preprocessor only e error file name E single precision floats ame enable float registers ge eclipse error messages h gt include header alee include path ku keep unused static al output line information md make dependencies m model configuration nc no const replacement ne no enum optimization np allow pointer narrowing ns do not share locals o output file name p need prototypes rb reverse bitfield order SEE reduce register set s do not reorder locals sa strict ANSI conformance sr no strength reduction u plain char is unsigned w enable warnings xd debug info for data xf full path in debug info xp no path in debug info xu no debug info if unused XX extended debug info R output debug info 2012 COSMIC Software Compiler Passes 361 D The cpcorm Parser Parser Option Usage Option Description a define the register variables allocation features The three first bits of enable the following behaviours bit 0 keep register variables as declared bit 1 do not map autos to registers bit 2 do not map static addresses to registers The defa
279. ted field is not a comment bad constant a constant uses illegal characters bad else an e se directive has been found without a previous if direc tive bad endif an endif directive has been found without a previous if or else directive bad file name the include directive operand is not a character string bad index register an invalid register has been used in an indexed addressing mode bad register an invalid register has been specified as operand of an instruction bad relocatable expression an external label has been used in either a constant expression or with illegal operators 2012 COSMIC Software Compiler Error Messages 345 Assembler cacorm Error Messages bad string constant a character constant does not end with a single or double quote bad symbol name lt name gt an expected symbol is not an identifier can t create lt name gt the file lt name gt cannot be opened for writing can t open lt name gt the file lt name gt cannot be opened for reading can t open source lt name gt the file lt name gt cannot be included cannot include from a macro the directive include cannot be speci fied within a macro definition cannot move back current pc an org directive has a negative offset illegal size the size of a ds directive is negative or zero missing label a label must be specified for this directive missing operand operand is expected for this instruction missing register
280. ted size 32 convert ELF DWARF format 322 hex format 310 CORTEX M addressing mode 189 instruction set 187 Cortex M0O processor 184 Cortex M3 M4 processors 184 cos function 88 cosh function 89 cprd utility 304 cross reference 4 Index information 183 table in listing 187 cvdwarf utility 322 D data 64K size 31 automatic initialization 35 char representation 56 const type 37 const volatile 38 double representation 56 float representation 56 long integer representation 56 pointer representation 56 short int representation 56 unlimited size 32 volatile type 37 data object automatic 304 scope 302 type 302 de directive 203 deb directive 204 debug information adding 365 366 debug symbol build table 289 table 302 debugging data 302 support tools 301 debugging information data object 302 extract 304 generate 302 365 line number 302 print file 304 print function 304 default output file 184 default placement bsct segment 279 bss segment 279 data segment 279 text segment 279 definition 289 DEFs 289 descriptor host to 270 div function 90 divide 90 dlist directive 205 double library 280 ds directive 206 E Eclipse error messages 62 183 267 363 370 ELF DWARF format converter 10 else directive 207 208 211 217 219 226 end directive 209 end5 directive 213 endc directive 219 226 endif directive 207 210 211 217 endm directive 212 232 235 247 endr 243 244 enum size optimization 364
281. tf is packaged in both the integer library and the floating point library The functionality of the integer only version of printf is a subset of the functionality of the floating point version The integer only ver sion cannot print or manipulate floating point numbers If your pro grams call the integer only version of printf the following conversion specifiers are invalid e E f g and G The L modifier is also invalid If printf encounters an invalid conversion specifier the invalid specifier is ignored and no special message is generated 134 Using The Compiler 2012 COSMIC Software C Library putchar putchar Description Put a character to output stream Syntax include lt stdio h gt int putchar c Function putchar copies c to the user specified output stream You must rewrite putchar in either C or assembly language to provide an interface to the output mechanism to the C library Return Value putchar returns c If a write error occurs putchar returns EOF Example To copy input to output while c getchar EOF putchar c See Also getchar Notes putchar is packaged in the integer library 2012 COSMIC Software Using The Compiler 135 Ei C Library puts puts Description Put a text line to output stream Syntax include lt stdio h gt int puts char s Function puts copies characters from the buffer starting at s to the output stream and ap
282. the file and write error messages to STDOUT The default is STDOUT for output and STDERR for error messages V write a log of modifications to STDERR This displays the number of removed instructions followed by the number of modified instructions 372 Compiler Passes 2012 COSMIC Software The cocorm Assembly Language Optimizer Optimizer Option Usage cont Option Description X Disable register optimizations for instructions producing a value in a register variable when the debug option has been selected The code may be larger to allow a correct variable display in debuggers If lt file gt is present it is used as the input file instead of the default STDIN Return Status cocorm returns success if it produces no diagnostics Example cocorm is usually invoked after cgcorm as follows cpcorm o 2 cx1 u i cosmic hcorm file c cgcorm o 2 cx2 2 cx1 cocorm o file s 2 cx2 2012 COSMIC Software Compiler Passes 373 Symbols asm directive 43 362 endasm directive 43 362 pragma asm directive 43 pragma endasm directive 43 grp directive 273 seg option 269 bss section 40 section generated 24 const section 40 segment 279 data section 40 section generated 24 Sbss section 19 40 sconst section 19 40 sdata section 19 40 text section 40 dir modifier 31 space modifier 48 variables 48 ext modifier 31 interrupt functions 46 qualifier 46
283. the need of several definitions usually conflictuous when _asm is used with different return types the compiler implements a special behaviour when a cast is applied to _asm In such a case the cast is considered to define the return type of _asm instead of asking for a type conversion There is no need for any prototype for the _asm function as the parser verifies that the first argument is a string constant 2012 COSMIC Software Programming Environments Writing Interrupt Handlers Writing Interrupt Handlers A function declared with the type qualifier interrupt is suitable for direct connection to an interrupt hardware or software interrupt functions may not return any value interrupt functions are allowed to have arguments although hardware generated interrupts are not likely to supply anything meaningful When you define an interrupt function the compiler saves if neces sary the registers used by the compiler for its internal usage You define an interrupt function by using the type qualifier inter rupt to qualify the type returned by the function you declare An exam ple of such a definition is interrupt void it handler void NOTE The interrupt function is an extension to the ANSI standard 46 Programming Environments 2012 COSMIC Software Placing Addresses in Interrupt Vectors Placing Addresses in Interrupt Vectors The compiler allows the interrupt table
284. timization ne Sr suppress the strength reduction optimization for indexed arrays or pointers inside loops u take a plain char to be of type unsigned char not signed char This also affects in the same way strings constants w enable warnings from level By default warnings are disa bled For more information see Warning Levels below X generate debugging information for use by the cross debug ger or some other debugger or in circuit emulator The default is to generate no debugging information xd add debug information in the object file only for data objects hiding any function 2012 COSMIC Software Compiler Passes 365 D The cpcorm Parser Parser Option Usage cont Option Description xf prefix filenames in the debug information with absolute full path name Xp do not prefix filenames in the debug information with any absolute path name Debuggers will have to be informed about the actual files location Xu do not produce debug information for localized variables if they are not used By default the compiler produces a com plete debug information regardless the variable is accessed or not XX add debug information in the object file for any label defin ing code or data Warning Levels The option enabling warnings also allows to define a minimum level which reduces the amount of warning produced They are grouped on 7 levels depending on their effe
285. tive the expression result is inverted and the same process applies to the following instructions up to the next matching endce So if the ifne expression was not equal to zero the instructions between elsee and endec are skipped otherwise the instructions between elsec and endec are assembled An elsec direc tive applies to the closest previous if directive The if directives may be nested The skipped lines may or may not in the listing depending on the clist directive status Example ifne offset if offset not nul add rl offset add to register elsec otherwise cmp v1 0 just test it endc See Also elsec endc clist 2012 COSMIC Software Using The Assembler 227 Assembler Directives include include Description Include text from another text file Syntax include filename Function The include directive causes the assembler to switch its input to the specified filename until end of file is reached at which point the assem bler resumes input from the line following the include directive in the current file The directive is followed by a string which gives the name of the file to be included This string must match exactly the name and extension of the file to be included the host system convention for uppercase lower case characters should be respected Example include include include include 228 Using The Assembler datstr bldstd matmac ports 2 z us
286. tl static jmp_buf ev 2 switch setjmp ev 0 case 0 registered break default event 0 occurred event0 next switch setjmp ev 1 case 0 registered break default event 1 occurred eventl next 144 Using The Compiler 2012 COSMIC Software C Library setimp next next int i for i anyevent Lf a Ha longjmp ev i See Also longjmp Notes setjmp is packaged in the integer library 2012 COSMIC Software Using The Compiler 145 Ei C Library sin sin Description Sin Syntax include lt math h gt double sin double x Function sin computes the sine of x expressed in radians to full double preci sion If the magnitude of x is too large to contain a fractional quadrant part the value of sin is 0 Return Value sin returns the closest internal representation to sin x in the range pi 2 pi 2 expressed as a double floating value A large argument may return a meaningless result Example To rotate a vector through the angle theta xnew xold cos theta yold sin theta ynew xold sin theta yold cos theta See Also cos tan Notes sin is packaged in the floating point library 146 Using The Compiler 2012 COSMIC Software C Library sinh sinh Description Hyperbolic sine Syntax include lt math h gt double sinh double x Fun
287. tment flag has been given to the field width The padding is with spaces unless the field width digit string starts with zero in which case the padding is with zeros 130 Using The Compiler 2012 COSMIC Software C Library printf lt precision gt a decimal number which specifies the minimum number of digits to appear for d i 0 u x and X conversions the number of digits to appear after the decimal point for e E f and r con versions the maximum number of significant digits for the g and G conversions or the maximum number of characters to be printed from a string in an s conversion The precision takes the form of a period fol lowed by a decimal digit string A null digit string is treated as zero h optionally specifies that the following d i 0 u x or X conversion character applies to a short int or unsigned short int argument the argu ment will have been widened according to the integral widening con versions and its value must be cast to short or unsigned short before printing It specifies a short pointer argument if associated with the p conversion character If an h appears with any other conversion charac ter it is ignored l optionally specifies that the d i o u x and X conversion character applies to a long int or unsigned long int argument It specifies a long or far pointer argument if used with the p conversion character It specifies a long _Fract if used with the r conversion character I
288. to decimal notation in the style 0 ddd where the number of digits following the decimal point is equal to the precision specification If the precision is missing it is taken as 6 S the argument is taken to be a char pointer to a string Characters from the string are written up to but not including the terminating NUL or until the number of characters indicated by the precision are written If the precision is missing it is taken to be arbitrarily large so all characters before the first NUL are printed If the character after is not a valid conversion character the behav ior is undefined If any argument is or points to an aggregate except for an array of char acters using s conversion or any pointer using p conversion unpredictable results will occur A nonexistent or small field width does not cause truncation of a field if the result is wider than the field width the field is expanded to con tain the conversion result 2012 COSMIC Software Using The Compiler 133 Ej C Library printf Return Value printf returns the number of characters transmitted or a negative number if a write error occurs Notes A call with more conversion specifiers than argument variables will cause unpredictable results Example To print arg which is a double with the value 5100 53 printft 38 2f n arg printf S f n 8 2 arg both forms will output 05100 53 See Also sprintf Notes prin
289. tware long enforce 32 bit relocation CODE section text 7 section of text labi ds b S DATA section data section of data lab2 ds b 6 switch CODE lab3 ds b i switch DATA lab4 ds b 8 Using The Assembler 249 Assembler Directives section This will place lab1 and then lab3 into consecutive locations in sec tion CODE and lab2 and lab4 in consecutive locations in section DATA frame section data even The frame section is declared with same attributes than the data sec tion and with the even attribute ram section long teven hilo The ram section is declared using 32 bit relocation with an even align ment and storing data with an ascending order of significance When the m option is used the section directive also accepts a number as operand In that case a labelled directive is considered as a section definition and an unlabelled directive is considered as a section open ing switch rom section 1 define section 1 nop ram section 2 define section 2 dc b dl section 1 Switch back to section 1 nop It is still possible to add attributes after the section number of a section definition line separated by a comma See Also switch 250 Using The Assembler 2012 COSMIC Software Assembler Directives set set Description Give a resetable value to a symbol Syntax label set lt expression gt Function The set directive allows a value to be associate
290. ult value is 0 meaning that the compiler tries to allocate as many as locals in registers regardless of any register declarations and tries to fill remaining registers with the address of the most used global variables ad enable define expansion inside inline assembly code between asm and endasm directives By default define symbols are expanded only in the C code c99 authorize the repetition of the const and volatile modifiers in the declaration either directly or indirectly in the typedef CC do not apply standard type casting to the result of a con stant expression This option allows compatibility with pars ers previous to version V4 5p These previous parsers were behaving as if all constants were considered of type long instead of the default type int Such expressions were allow ing intermediate results to become larger that an int without any truncation ck enable extra type checking For more information see Extra verifications below Cp disable the constant propagation optimization By default when a variable is assigned with a constant any subse quent access to that variable is replaced by the constant itself until the variable is modified or a flow break is encoun tered function call loop label csb produce an error message if a bitfield is declared explicitly with the signed keyword By default the compiler silently ignores the signed feature and handles all bitfield
291. underscores dollar signs or periods Labels are case sen sitive The processor register names a d and sp are reserved and cannot be used as labels datal dc b 56 c_reg ds b al When a label is used within a macro it may be expanded more than once and in that case the assembler will fail with a multiply defined symbol error In order to avoid that problem the special sequence may be used as a label prefix This sequence will be replaced by a unique sequence for each macro expansion This prefix is only allowed inside a macro definition wait macro loop tst r2 4 bne loop endm 2012 COSMIC Software Using The Assembler 189 Assembly Language Syntax Temporary Labels The assembler allows temporary labels to be defined when there is no need to give them an explicit name Such a label is composed by a dec imal number immediately followed by a character Such a label is valid until the next standard label or the ocal directive Then the same temporary label may be redefined without getting a multiply defined error message 1 subs ri 1 bne 1 2 subs r2 1 bne 2 Temporary labels do not appear in the symbol table or the cross refer ence list For example to define 3 different local blocks and create and use 3 dif ferent local labels named 10 function 10 idr ri r9 var cmp r1 0 beq 10 ldr r2 r9 var2 local 108 idr ri r9 va
292. ure union definition contains a reference to itself enum size unknown the range of an enumeration is not available to choose the smallest integer type exponent overflow in real the exponent specified in a real constant is too large for the target encoding file too large for label information the source file is producing too many labels in the code and debug parts for the coding restrictions float value too large for integer cast a float constant is too large to be casted in an integer strict hexadecimal constant too large an hexadecimal constant is too large to be represented on an integer illegal storage class storage class is not legal in this context illegal type specification type specification is not recognizable 2012 COSMIC Software Compiler Error Messages 331 Parser cpcorm Error Messages illegal void operation an object of type void is used as operand of an arithmetic operator illegal void usage an object of type void is used as operand of an assignment operator implicit int type in argument declaration an argument has been declared without any type strict implicit int type in global declaration a global variable has been declared without any type strict implicit int type in local declaration a local variable has been declared without any type strict implicit int type in struct union declaration a structure or union field has been declared without any type strict
293. x6000 NOTE Due to the page width limitations of this manual a single invocation line may be represented as two or more lines You should however type the invocation as one line unless otherwise directed Italics Used for value substitution talic type indicates categories of items for which you must substitute appropriate values such as arguments or hypothetical filenames For example if the text was demonstrating a hypothetical command line to compile and generate debugging infor mation for any file it might appear as cxcorm debug file c In this example cxcorm debug file c is shown in typewriter font because it must be typed exactly as shown Because the filename must be specified by the user however file is shown in italics Brackets Items enclosed in brackets are optional For example the line options means that zero or more options may be specified because options appears in brackets Conversely the line options means that one or more options must be specified because options is not enclosed by brackets 2012 COSMIC Software Introduction 6 Document Conventions As another example the line filel o cxm means that one file with the extension o or cxm may be specified and the line filel file2 means that additional files may be specified Conventions All the compiler utilities share the same optional arguments syntax They are invok
294. xpected For more information see Checksum Computation in Chapter 6 Return Value _ checksum 16x returns 0 if the checksum is correct or a value different of 0 otherwise Example if _checksum16x abort Notes The descriptor is built by the linker only if the _checksum16x function is called by the application even if there are segments marked with the ck option _ checksum 16x is packaged in the integer library See Also _checksum _checksumx _checksum16 2012 COSMIC Software Using The Compiler 87 88 Ei C Library cos Cos Description Cosine Syntax include lt math h gt double cos double x Function cos computes the cosine of x expressed in radians to full double preci sion If the magnitude of x is too large to contain a fractional quadrant part the value of cos is 1 Return Value cos returns the nearest internal representation to cos x in the range 0 pi expressed as a double floating value A large argument may return a meaningless value Example To rotate a vector through the angle theta xnew xold cos theta yold sin theta ynew xold sin theta yold cos theta See Also sin tan Notes cos is packaged in the floating point library Using The Compiler 2012 COSMIC Software C Library cosh cosh Description Hyperbolic cosine Syntax include lt math h gt double cosh double x Function cosh computes
295. xt bSTART 0x100 mMAXSIZE 0x100 The first line defines the symbol START equals to the absolute value 1000 hex value the second line defines the symbol MAXSIZE equals to the absolute value 2000 hex value The last line opens a text seg ment located at 1100 hex value with a maximum size of 1f00 hex value For more information see the section Symbol Definition Option on page 276 272 Using The Linker 2012 COSMIC Software Linker Options Unless b is given to set the bss segment start address the bss segment will be made to follow the last data segment in the output file Unless b is given to set the data segment start address the data segment will be made to follow the last bsct segment in the output file The bsct and text segments are set to start at zero unless you specify otherwise by using b option It is permissible for all segments to overlap as far as clnk is concerned the target machine may or may not make sense of this situation as with separate instruction and data spaces NOTE A new segment of the specified type will not actually be created if the last segment of the same name has a size of zero However the new options will be processed and will override the previous values Segment Grouping Different sections can be redirected directly to the same segment with the grp directive grp lt section gt lt section list gt where lt section gt is the name of the target secti
296. y of the floating point version The integer only version cannot print or manipulate floating point numbers If your pro grams call the integer only version of sprintf the following conversion specifiers are invalid e E f g and G The L flag is also invalid 148 Using The Compiler 2012 COSMIC Software C Library sqrt sqrt Description Real square root Syntax include lt math h gt double sqrt double x Function sqrt computes the square root of x to full double precision Return Value sqrt returns the nearest internal representation to sqrt x expressed as a double floating value If x is negative sqrt returns zero Example To use sqrt to check whether n gt 2 is a prime number if n amp 01 return NOTPRIME sq sqrt double n for div 3 div lt sq div 2 if n div return NOTPRIME return PRIME Notes sqrt is packaged in the floating point library 2012 COSMIC Software Using The Compiler 149 Description Seed pseudo random number generator Syntax include lt stdlib h gt void srand unsigned char nseed Function srand uses nseed as a seed for a new sequence of pseudo random num bers to be returned by subsequent calls to rand If srand is called with the same seed value the sequence of pseudo random numbers will be repeated The initial seed value used by rand and srand is 0 Return Value Nothing Example To set up a new se
297. y rewriting the _sbreak func tion The default _sbreak function provided by the library is as follows i SET SYSTEM BREAK EJ void sbreak int size extern char _memory static char _brk NULL memory break char obrk yellow 40 if _brk initialize on first call _brk amp memory obrk _brk old top _brk size new top if yellow brk brk lt amp memory check boundaries _brk obrk restore old top return NULL return NULL pointer return obrk return new area start The yellow array is used to calculate the stack pointer value to check the heap limits This array is declared as the last local variable so its address is almost equal to the stack pointer once the function has been entered It is declared to be 40 bytes wide to allow for some security margin If the new top is outside the authorized limits the function returns a NULL pointer otherwise it returns the start of the new allo cated area Note that the top variable _brk is a static variable initialized to zero NULL pointer It is set to the heap start on the first call It is also possible to initialize it directly within the declaration but in this case we create an initialized variable in the data segment which needs to be initialized by the startup The current code avoids such a require ment by initializing the variable to zero in the bss segment which is simply done by the sta

Download Pdf Manuals

image

Related Search

Related Contents

  importante - Metalúrgica Siemsen  memorial descritivo para instalações de rede lógica  SoftBank 108SH かんたんガイドブック  

Copyright © All rights reserved.
Failed to retrieve file