NiosIIEmbeddedToolsReference

TR0130Dec01,2009 Software,hardware,documentationandrelatedmaterials:

CopyrightE2008AltiumLimited.AllRightsReserved.

Thematerialprovidedwiththisnoticeissubjecttovariousformsofnationalandinternationalintellectualpropertyprotection,includingbutnot limitedtocopyrightprotection.Youhavebeengrantedanon−exclusivelicensetousesuchmaterialforthepurposesstatedintheend−user licenseagreementgoverningitsuse.Innoeventshallyoureverseengineer,decompile,duplicate,distribute,createderivativeworksfromorin anywayexploitthemateriallicensedtoyouexceptasexpresslypermittedbythegoverningagreement.Failuretoabidebysuchrestrictionsmay resultinseverecivilandcriminalpenalties,includingbutnotlimitedtofinesandimprisonment.Provided,however,thatyouarepermittedto makeonearchivalcopyofsaidmaterialsforbackuppurposesonly,whicharchivalcopymaybeaccessedandusedonlyintheeventthatthe originalcopyofthematerialsisinoperable.Altium,AltiumDesigner,BoardInsight,DXP,InnovationStation,LiveDesign,NanoBoard,NanoTalk, OpenBus,P−CAD,SimCode,Situs,TASKING,andTopologicalAutoroutingandtheirrespectivelogosaretrademarksorregisteredtrademarks ofAltiumLimitedoritssubsidiaries.Allotherregisteredorunregisteredtrademarksreferencedhereinarethepropertyoftheirrespectiveowners andnotrademarkrightstothesameareclaimed.v8.031/3/08 TableofContents

TableofContents

CLanguage 1−1 1.1 Introduction ...................................................................... 1−1 1.2 DataTypes ...................................................................... 1−2 1.2.1 ChangingtheAlignment:__unaligned,__packed__and__align()....................... 1−2 1.3 MemoryQualifiers ................................................................ 1−3 1.3.1 PlacinganObjectatanAbsoluteAddress:__at()..................................... 1−4 1.4 UsingAssemblyintheCSource:__asm()........................................... 1−4 1.5 PragmastoControltheCompiler................................................... 1−7 1.6 PredefinedPreprocessorMacros................................................... 1−11 1.7 Functions ........................................................................ 1−12 1.7.1 ParameterPassing ...............................................................1−12 1.7.2 FunctionReturnTypes............................................................ 1−12 1.7.3 InliningFunctions:inline/__noinline................................................ 1−13 1.7.4 IntrinsicFunctions ................................................................ 1−14 1.7.5 InterruptFunctions ................................................................ 1−15 1.7.5.1 DefininganInterruptServiceRoutine:__interruptkeyword............................. 1−15 1.8 Libraries ......................................................................... 1−15 1.8.1 PrintfandScanfRoutines.......................................................... 1−15

C++Language 2−1 2.1 Introduction ...................................................................... 2−1 2.2 C++LanguageExtensionKeywords................................................. 2−1 2.3 C++DialectAccepted .............................................................2−1 2.3.1 StandardLanguageFeaturesAccepted.............................................. 2−1 2.3.2 C++0xLanguageFeaturesAccepted................................................ 2−3 2.3.3 AnachronismsAccepted........................................................... 2−4 2.3.4 ExtensionsAcceptedinNormalC++Mode........................................... 2−4 2.4 GNUExtensions .................................................................. 2−5 2.5 NamespaceSupport ..............................................................2−13 2.6 TemplateInstantiation .............................................................2−14 2.6.1 AutomaticInstantiation............................................................ 2−14 2.6.2 InstantiationModes ...............................................................2−15 2.6.3 Instantiation#pragmaDirectives.................................................... 2−16 2.6.4 ImplicitInclusion .................................................................. 2−17 2.6.5 ExportedTemplates ...............................................................2−18 2.6.5.1 FindingtheExportedTemplateDefinition............................................. 2−18 2.6.5.2 SecondaryTranslationUnits....................................................... 2−19 2.6.5.3 LibrarieswithExportedTemplates.................................................. 2−19 2.7 InliningFunctions ................................................................. 2−20 2.8 ExternInlineFunctions............................................................ 2−20 2.9 PragmastoControltheC++Compiler............................................... 2−21 2.10 PredefinedMacros ................................................................ 2−22 2.11 PrecompiledHeaders .............................................................2−24 2.11.1 AutomaticPrecompiledHeaderProcessing.......................................... 2−24 2.11.2 ManualPrecompiledHeaderProcessing............................................. 2−26 2.11.3 OtherWaystoControlPrecompiledHeaders......................................... 2−26 2.11.4 PerformanceIssues ...............................................................2−26

iii NiosIIEmbeddedToolsReference

Libraries 3−1 3.1 Introduction ...................................................................... 3−1 3.2 LibraryFunctions ................................................................. 3−3 3.2.1 assert.h ......................................................................... 3−3 3.2.2 complex.h ....................................................................... 3−3 3.2.3 ctype.handwctype.h ..............................................................3−3 3.2.4 errno.h .......................................................................... 3−4 3.2.5 fcntl.h ........................................................................... 3−4 3.2.6 fenv.h ........................................................................... 3−5 3.2.7 float.h ........................................................................... 3−5 3.2.8 fss.h ............................................................................ 3−5 3.2.9 inttypes.handstdint.h .............................................................3−6 3.2.10 io.h ............................................................................. 3−6 3.2.11 iso646.h ......................................................................... 3−6 3.2.12 limits.h .......................................................................... 3−7 3.2.13 locale.h ......................................................................... 3−7 3.2.14 malloc.h ......................................................................... 3−7 3.2.15 math.handtgmath.h ..............................................................3−7 3.2.16 setjmp.h ......................................................................... 3−11 3.2.17 signal.h ......................................................................... 3−11 3.2.18 stdarg.h ......................................................................... 3−11 3.2.19 stdbool.h ........................................................................ 3−11 3.2.20 stddef.h ......................................................................... 3−12 3.2.21 stdint.h .......................................................................... 3−12 3.2.22 stdio.handwchar.h ...............................................................3−12 3.2.23 stdlib.handwchar.h ...............................................................3−17 3.2.24 string.handwchar.h ..............................................................3−19 3.2.25 time.handwchar.h ................................................................ 3−21 3.2.26 unistd.h ......................................................................... 3−22 3.2.27 wchar.h ......................................................................... 3−23 3.2.28 wctype.h ........................................................................ 3−24

AssemblyLanguage 4−1 4.1 AssemblySyntax ................................................................. 4−1 4.2 AssemblerSignificantCharacters................................................... 4−2 4.3 OperandsofanAssemblyInstruction................................................ 4−2 4.4 SymbolNames ................................................................... 4−2 4.4.1 PredefinedPreprocessorSymbols.................................................. 4−3 4.5 Registers ........................................................................ 4−3 4.6 AssemblyExpressions ............................................................4−3 4.6.1 NumericConstants ...............................................................4−4 4.6.2 Strings .......................................................................... 4−4 4.6.3 ExpressionOperators .............................................................4−5 4.7 Built−inAssemblyFunctions....................................................... 4−5 4.7.1 OverviewofBuilt−inAssemblyFunctions............................................ 4−6 4.7.2 DetailedDescriptionofBuilt−inAssemblyFunctions................................... 4−6 4.8 AssemblerDirectives ..............................................................4−9 4.8.1 OverviewofAssemblerDirectives................................................... 4−9 4.8.2 DetailedDescriptionofAssemblerDirectives......................................... 4−11 4.9 MacroOperations ................................................................ 4−44 4.9.1 DefiningaMacro ................................................................. 4−44 4.9.2 CallingaMacro .................................................................. 4−44 4.9.3 UsingOperatorsforMacroArguments............................................... 4−45 4.9.4 Usingthe.FORand.REPEATDirectivesasMacros................................... 4−47 4.9.5 ConditionalAssembly .............................................................4−47 4.10 GenericInstructions ...............................................................4−49

iv TableofContents

ToolOptions 5−1 5.1 CCompilerOptions ...............................................................5−1 5.2 C++CompilerOptions .............................................................5−59 5.3 AssemblerOptions ...............................................................5−162 5.4 LinkerOptions ................................................................... 5−195 5.5 ControlProgramOptions.......................................................... 5−236 5.6 MakeUtilityOptions ...............................................................5−285 5.7 LibrarianOptions ................................................................. 5−311

ListFileFormats 6−1 6.1 AssemblerListFileFormat......................................................... 6−1 6.2 LinkerMapFileFormat ............................................................6−3

ObjectFileFormats 7−1 7.1 ELF/DWARFObjectFormat........................................................ 7−1 7.2 MotorolaS−RecordFormat........................................................ 7−2 7.3 HexRecordFormat........................................................... 7−5

LinkerScriptLanguage 8−1 8.1 Introduction ...................................................................... 8−1 8.2 StructureofaLinkerScriptFile..................................................... 8−1 8.3 SyntaxoftheLinkerScriptLanguage................................................ 8−3 8.3.1 Preprocessing .................................................................... 8−3 8.3.2 LexicalSyntax ................................................................... 8−3 8.3.3 Identifiers ........................................................................ 8−4 8.3.4 Expressions ..................................................................... 8−4 8.3.5 Built−inFunctions ................................................................. 8−5 8.3.6 LSLDefinitionsintheLinkerScriptFile.............................................. 8−6 8.3.7 MemoryandBusDefinitions....................................................... 8−6 8.3.8 ArchitectureDefinition .............................................................8−7 8.3.9 DerivativeDefinition ...............................................................8−9 8.3.10 ProcessorDefinitionandBoardSpecification......................................... 8−10 8.3.11 SectionLayoutDefinitionandSectionSetup.......................................... 8−10 8.4 ExpressionEvaluation .............................................................8−13 8.5 SemanticsoftheArchitectureDefinition.............................................. 8−14 8.5.1 DefininganArchitecture........................................................... 8−15 8.5.2 DefiningInternalBuses............................................................ 8−15 8.5.3 DefiningAddressSpaces.......................................................... 8−15 8.5.4 Mappings ........................................................................ 8−18 8.6 SemanticsoftheDerivativeDefinition............................................... 8−20 8.6.1 DefiningaDerivative ..............................................................8−20 8.6.2 InstantiatingCoreArchitectures..................................................... 8−20 8.6.3 DefiningInternalMemoryandBuses................................................ 8−21 8.7 SemanticsoftheBoardSpecification................................................ 8−22 8.7.1 DefiningaProcessor ..............................................................8−22 8.7.2 InstantiatingDerivatives........................................................... 8−22 8.7.3 DefiningExternalMemoryandBuses................................................ 8−23 8.8 SemanticsoftheSectionSetupDefinition............................................ 8−24 8.8.1 SettingupaSection ...............................................................8−24 8.9 SemanticsoftheSectionLayoutDefinition........................................... 8−25 8.9.1 DefiningaSectionLayout.......................................................... 8−25 8.9.2 CreatingandLocatingGroupsofSections........................................... 8−26 8.9.3 CreatingorModifyingSpecialSections.............................................. 8−30 8.9.4 CreatingSymbols ................................................................. 8−32 8.9.5 ConditionalGroupStatements...................................................... 8−33

v NiosIIEmbeddedToolsReference

CERTCSecureCodingStandard 9−1 9.1 Preprocessor(PRE) ..............................................................9−1 9.2 DeclarationsandInitialization(DCL)................................................. 9−2 9.3 Expressions(EXP) ................................................................ 9−2 9.4 Integers(INT) .................................................................... 9−3 9.5 FloatingPoint(FLP) ...............................................................9−3 9.6 Arrays(ARR) .................................................................... 9−3 9.7 CharactersandStrings(STR)...................................................... 9−4 9.8 MemoryManagement(MEM)...................................................... 9−4 9.9 Environment(ENV) ...............................................................9−4 9.10 Signals(SIG) .................................................................... 9−5 9.11 Miscellaneous(MSC) .............................................................9−5

MISRA−CRules 10−1 10.1 MISRA−C:1998 .................................................................. 10−1 10.2 MISRA−C:2004 .................................................................. 10−5

Index

vi ManualPurposeandStructure

ManualPurposeandStructure

WindowsUsers ThedocumentationexplainsanddescribeshowtousetheTASKINGNiosIItoolsettoprogramaNiosIIprocessor. YoucanusethetoolseitherwiththegraphicalAltiumDesignerorfromthecommandlineinacommandpromptwindow.

Structure Thetoolsetdocumentationconsistsofauser’smanual(UsingtheNiosIIEmbeddedTools),whichincludesaGettingStarted section,andaseparatereferencemanual(thismanual). StartbyreadingtheGettingStartedinChapter1oftheuser’smanual. Theotherchaptersintheuser’smanualexplainhowtousethecompiler,assembler,linkerandthevariousutilities. Onceyouarefamiliarwiththesetools,youcanusethisreferencemanualtolookupspecificoptionsanddetailstomakefulluse oftheTASKINGtoolset. ThereferencemanualdescribestheC++languageimplementation,theClanguageimplementationandtheassembly language.

vii NiosIIEmbeddedToolsReference

ShortTableofContents

Chapter1:CLanguage TheTASKINGCcompilersarefullycompatiblewithISO−C.ThischapterdescribesthespecifictargetfeaturesoftheC language,includinglanguageextensionsthatarenotstandardinISO−C.Forexample,pragmasareawaytocontrolthe compilerfromwithintheCsource.Thefollowinglanguageextensionsaredescribed: • Datatypes • Keywords • Functionqualifiers • Intrinsicfunctions • Pragmas • Predefinedmacros Chapter2:C++Language DescribestheC++languageimplementation.TheC++languageitselfisnotdescribed.

Chapter3:Libraries ContainsoverviewsofalllibraryfunctionsyoucanuseinyourCsource.Firstlibrariesarelistedperheaderfilethatcontainsthe prototypes.Thesetablesalsoshowthelevelofimplementationperfunction.Second,alllibraryfunctionsarelistedand discussedintodetail.

Chapter4:AssemblyLanguage Describesthespecificfeaturesoftheassemblylanguageaswellas’directives’,whicharepseudoinstructionsthatare interpretedbytheassembler.

Chapter5:ToolOptions Containsadescriptionofalltooloptions: • Ccompileroptions • C++compileroptions • Assembleroptions • Linkeroptions • Controlprogramoptions • Makeutilityoptions • Librarianoptions Chapter6:ListFileFormats Containsadescriptionofthefollowinglistfileformats: • AssemblerListFileFormat • LinkerMapFileFormat Chapter7:ObjectFileFormats Containsadescriptionofthefollowingobjectfileformats: • ELF/DWARF2ObjectFormat • MotorolaS−RecordFormat • IntelHexRecordFormat Chapter8:LinkerScriptLanguage

Containsadescriptionofthelinkerscriptlanguage(LSL).

Chapter9:CERTCSecureCodingStandard ContainsanoverviewofthesupportedCERTCSecureCodingStandardrecommendationsandrules. viii ManualPurposeandStructure

Chapter10:MISRA−CRules ContainsadescriptionthesupportedandunsupportedMISRA−Ccodecheckingrules.

ConventionsUsedinthisManual

Notationforsyntax Thefollowingnotationisusedtodescribethesyntaxofcommandlineinput: bold Typethispartofthesyntaxliterally. italics Substitutetheitalicwordbyaninstance.Forexample: filename Typethenameofafileinplaceofthewordfilename. {} Enclosesalistfromwhichyoumustchooseanitem. [] Enclosesitemsthatareoptional.Forexample cnios[−?] Bothcniosandcnios−?arevalidcommands. | Separatesitemsinalist.ReaditasOR. ... Youcanrepeattheprecedingitemzeroormoretimes.

Example cnios[option]...filename Youcanreadthislineasfollows:enterthecommandcnioswithorwithoutanoption,followthisbyzeroormoreoptionsand specifyafilename.Thefollowinginputlinesareallvalid: cniostest.c cnios−gtest.c cnios−g−stest.c

Notvalidis: cnios−g

Accordingtothesyntaxdescription,youhavetospecifyafilename.

Icons Thefollowingillustrationsareusedinthismanual:

Note:notesgiveyouextrainformation.

Warning:readtheinformationcarefully.Itpreventsyoufrommakingseriousmistakesorfromloosinginformation.

Thisillustrationindicatesactionsyoucanperformwiththemouse.SuchasAltiumDesignermenuentriesanddialogs.

Commandline:typeyourinputonthecommandline.

Reference:followthisreferencetofindrelatedtopics.

ix NiosIIEmbeddedToolsReference

RelatedPublications

CStandards • ISO/IEC9899:1999(E),Programminglanguages−C[ISO/IEC] Moreinformationonthestandardscanbefoundathttp://www.ansi.org • DSP−C,AnExtensiontoISO/IEC9899:1999(E), Programminglanguages−C[TASKING,TK0071−14] C++Standards • TheC++ProgrammingLanguage(secondedition) byBjarneStraustrup(1991,AddisonWesley) • ISO/IEC14882:1998C++standard[ANSI] Moreinformationonthestandardscanbefoundathttp://www.ansi.org • TheAnnotatedC++ReferenceManual byMargaretA.EllisandBjarneStraustrup(1990,AddisonWesley) CERTCSecureCodingStandard • TheCERTCSecureCodingStandard byRobertC.Seacord(October2008,AddisonWesley) • TheCERTCSecureCodingStandardwebsitehttp://www.securecoding.cert.org/ ForgeneralinformationaboutCERTsecurecoding,seehttp://www.cert.org/secure−coding MISRA−C • GuidelinesfortheUseoftheCLanguageinVehicleBasedSoftware[MIRAlimited,1998] Seealsohttp://www.misra.org.uk • MISRA−C:2004:GuidelinesfortheuseoftheCLanguageincriticalsystems[MIRAlimited,2004] Seealsohttp://www.misra−c.com TASKINGTools • UsingtheNiosIIEmbeddedTools [Altium,GU0115] NiosII • NiosIIProcessorReferenceHandbook [2008,Corporation,NII5V1−8.0] • NiosIISoftwareDeveloper’sHandbook [2008,AlteraCorporation,NII5V2−8.0]

x 1 CLanguage

Summary ThischapterdescribesthetargetspecificfeaturesoftheClanguage,including languageextensionsthatarenotstandardinISO−C.Forexample,pragmasarea waytocontrolthecompilerfromwithintheCsource.

1.1 Introduction

TheTASKINGCcompilerfullysupportstheISOCstandardbutaddspossibilitiestoprogramthespecialfunctionsoftheNiosII . InadditiontothestandardClanguage,thecompilersupportsthefollowing: • intrinsic(built−in)functionsthatresultintargetspecificassemblyinstructions • pragmastocontrolthecompilerfromwithintheCsource • predefinedmacros • thepossibilitytouseassemblyinstructionsintheCsource • keywordstospecifymemorytypesfordataandfunctions • attributetospecifyabsoluteaddresses • keywordsforinliningfunctionsandprogramminginterruptroutines • libraries Allnon−standardkeywordshavetwoleadingunderscores( __). InthischapterthetargetspecificcharacteristicsoftheClanguagearedescribed,includingtheabovementionedextensions.

1−1 NiosIIEmbeddedToolsReference

1.2 DataTypes

TheTASKINGCcompilerfortheNiosIIarchitecture(cnios)supportsthefollowingdatatypes:

Size Align Type CType Limits (bit) (bit) Boolean _Bool 8 8 0or1 Character char 8 8 −27..27−1 signedchar unsignedchar 8 8 0..28−1 Integral short 16 16 −215..215−1 signedshort unsignedshort 16 16 0..216−1 enum 32 32 −231..231−1 int signedint 32 32 −231..231−1 long signedlong unsignedint 32 32 0..232−1 unsignedlong longlong 64 32 −263..263−1 signedlonglong unsignedlonglong 64 32 0..264−1 Pointer pointertofunctionordata 32 32 0..232−1 Floating−Point −3.402E+38..−1.175E−38 float(23−bitmantissa) 32 32 1.175E−38..3.402E+38 double −1.798E+308..−2.225E−308 64 32 longdouble(52−bitmantissa) 2.225E−308..1.798E+308

Table1−1:DataTypesfortheNiosII

1.2.1 ChangingtheAlignment:__unaligned,__packed__and__align()

Normallydata,pointersandstructuremembersarealignedaccordingtothetableintheprevioussection.

Suppressalignment

Withthetypequalifier__unalignedyoucanspecifytosuppressthealignmentofobjectsorstructuremembers.Thiscanbe usefultocreatecompactdatastructures.Inthiscasethealignmentwillbeonebitforbit−fieldsoronebyteforotherobjec tsor structuremembers. Attheleftsideofapointerdeclarationyoucanusethetypequalifier __unalignedtomarkthepointervalueaspotentially unaligned.Thiscanbeusefultoaccessexternallydefineddata.Howeverthecompilercangeneratelessefficientinstructions to dereferencesuchapointer,toavoidunalignedmemoryaccess. Example: struct { charc; __unalignedinti;/*alignedatoffset1!*/ }s;

__unalignedint*up=&s.i;

1−2 CLanguage

Packedstructures

Topreventalignmentgapsinstructures,youcanusetheattribute __packed__.Whenyouusetheattribute__packed__ directlyafterthekeywordstruct,allstructuremembersaremarked__unaligned.Forexamplethefollowingtwo declarationsarethesame: struct__packed__ { charc; int*i; }s1;

struct { char__unalignedc; int*__unalignedi;/*__unalignedatrightsideof’*’topackpointermember*/ }s2;

Theattribute__packed__hasthesameeffectasaddingthetypequalifier __unalignedtothedeclarationtosuppressthe standardalignment. Youcanalsouse__packed__inapointerdeclaration.Inthatcaseitaffectsthealignmentofthepointeritself,notthevalueof thepointer.Thefollowingtwodeclarationsarethesame: int*__unalignedp; int*p__packed__;

Changealignment Withtheattribute__align(n)youcanoverrulethedefaultalignmentofobjectsorstructuremembersto nbytes.

1.3 MemoryQualifiers

Youcanusestaticmemoryqualifierstoallocatestaticobjectsinaparticularpartoftheaddressingspaceoftheprocessoro rto useaspecificaddressingmode. Youcanspecifythefollowingmemorytypes:

Qualifier Description __no_sdata DirectaddressableRAM __sdata DirectshortaddressableRAM (Smalldata,+/−32kBoffsetfromglobalpointerregister$gp)

Table1−2:MemoryTypeQualifiersfortheNiosII Bydefault,allglobalandstaticdataobjectssmallerthan4bytesareplacedinsmalldatasections.Withthe __no_sdataand __sdatakeywords,youoverrulethisdefault.

SeeCcompileroption−−sdata=sizeinsection5.1,CCompilerOptionsinChapterToolOptionstochangethesize beneathwhichdataobjectsareplacedinsmallmemory. Examplesusingexplicitmemorytypes: longlongl=1234; longlongreservedindata(bydefault) __sdatalonglongk=1234; longlongreservedinsdata Thememorytypequalifiersaretreatedlikeanyotherdatatypespecifier(suchas unsigned).Thismeanstheexamplesabove canalsobedeclaredas: longlong__sdatak=1234;

1−3 NiosIIEmbeddedToolsReference

1.3.1 PlacinganObjectatanAbsoluteAddress:__at() Justlikeyoucandeclareavariableinaspecific partofmemory(usingmemorytypequalifiers),youcanalsoplaceanobjectat anabsoluteaddressinmemory. Withtheattribute__at()youcanspecifyanabsoluteaddress.

Examples unsignedcharDisplay[80*24]__at(0x2000);

ThearrayDisplayisplacedataddress0x2000.Inthegeneratedassembly,anabsolutesectioniscreated.Onthisposition spaceisreservedforthevariable Display. inti__at(0x1000)=1;

Thevariableiisplacedataddress0x1000andisinitializedat1. voidf(void)__at(0xf0ff+1){}

Thefunctionfisplacedataddress0xf100.

Restrictions Takenoteofthefollowingrestrictionsifyouplaceavariableatanabsoluteaddress: • Theargumentofthe__at()attributemustbeaconstantaddressexpression. • Youcanplaceonlyglobalvariablesatabsoluteaddresses.Parametersoffunctions,orautomaticvariableswithinfunctions cannotbeplacedatabsoluteaddresses. • Avariablethatisdeclaredextern,isnotallocatedbythecompilerinthecurrentmodule.Henceitisnotpossibletousethe keyword__at()onanexternalvariable.Use__at()atthedefinitionofthevariable. • Youcannotplacestructuremembersatanabsoluteaddress. • Absolutevariablescannotoverlapeachother.Ifyoudeclaretwoabsolutevariablesatthesameaddress,theassemblerand /orlinkerissuesanerror.Thecompilerdoesnotcheckthis. • Ifyouuse0asanaddress,thisvalueisignored.Azerovalueindicatesarelocatablesection.

1.4 UsingAssemblyintheCSource:__asm()

Withthe__asmkeywordyoucanuseassemblyinstructionsintheCsource.BeawarethatCmodulesthatcontainassembly arenotportableandhardertocompileinotherenvironments. Furthermore,assemblyblocksarenotinterpretedbythecompiler:theyareregardedasablackbox.So,itisyourresponsibili ty tomakesurethattheassemblyblockissyntacticallycorrect.

Generalsyntaxofthe__asmkeyword __asm("instruction_template" [:output_param_list [:input_param_list [:register_save_list]]]);

instruction_template Assemblyinstructionsthatmaycontainparametersfromtheinputlistor outputlistintheform:%parm_nr %parm_nr[.regnum] Parameternumberintherange0..9.Withtheoptional.regnumyoucan accessanindividualregisterfromaregisterpair. output_param_list [["=[&]constraint_char"(C_expression)],...] input_param_list [["constraint_char"(C_expression)],...] & Saysthatanoutputoperandiswrittentobeforetheinputsareread,so thisoutputmustnotbethesameregisterasanyinput. constraint_char Constraintcharacter:thetypeofregistertobeusedforthe C_expression.

1−4 CLanguage

C_expression AnyCexpression.Foroutputparametersitmustbean lvalue,thatis, somethingthatislegaltohaveontheleftsideofanassignment. register_save_list [["register_name"],...] register_name:q Nameoftheregisteryouwanttoreserve.

Typicalexample:addingtwoCvariablesusingassembly chara,b; intresult;

voidmain(void) { a=3; b=4; __asm("ADD%0,%1,%2":"=r"(result):"r"(a),"r"(b)); }

%0correspondswiththefirstCvariable, %1withthesecondandsoon. Generatedassemblycode: main:.typefunc movuir2,0x3 stbr2,@gprel(a)(gp) movuir3,0x4 stbr3,@gprel(b)(gp) ADDr2,r2,r3 stwr2,@gprel(result)(gp) ret

SpecifyingregistersforCvariables

Withaconstraintcharacteryouspecifytheregistertypeforaparameter.Intheexampleabove,the risusedtoforcetheuseof registers(Rn)fortheparametersaandb. Youcanreservetheregistersthatarealreadyusedintheassemblyinstructions,eitherintheparameterlistsorinthereser ved registerlist(register_save_list,alsocalled"clobberlist").Thecompilertakesaccountoftheselists,sonounnecessaryregister savingandrestoringinstructionsareplacedaroundtheinlineassemblyinstructions.

Constraint Type Operand Remark character R generalpurpose r0..r31 Basedonthespecifiedregister,aregisterpairisformed(64−bit). register(64bits) Forexampler0:r1. r generalpurpose r0..r31 register(32bits) i immediatevalue #value l label label m memorylabel variable stackormemoryoperand,afixedaddress number otheroperand sameas%number Inputconstraintonly.Thenumbermustrefertoanoutput parameter.Indicatesthat%numberandnumberarethesame register. Use%number.0and%number.1toindicatethefirstandsecond halfofaregisterpairwhenusedincombinationwithR.

Table1−3:Availableinput/outputoperandconstraintsfortheNiosII

Loopsandconditionaljumps Thecompilerdoesnotdetectloopsthatarecodedwithmultiple __asmstatementsor(conditional)jumpsacross __asm statementsandwillgenerateincorrectcodefortheregistersinvolved.

1−5 NiosIIEmbeddedToolsReference

Ifyouwanttocreatealoopwith__asm,thewholeloopmustbecontainedinasingle __asmstatement.Thesamecountsfor (conditional)jumps.Asaruleofthumb,allreferencestoalabelinan __asmstatementmustbecontainedinthesame statement.

Example1:noinputoroutput Asimpleexamplewithoutinputoroutputparameters.Youcanuseanyinstructionorlabel.NotethatyoucanusestandardC escapesequences. __asm("nop\n\t" "nop");

Generatedcode: nop nop

Example2:usingoutputparameters

Assigntheresultofinlineassemblytoavariable.Aregisterischosenfortheparameterbecauseoftheconstraint r;the compilerdecideswhichregisterisbesttouse.The %0intheinstructiontemplateisreplacedwiththenameofthisregister. Finally,thecompilergeneratescodetoassigntheresulttotheoutputvariable. charout;

voidmain(void) { __asm("movui%0,0xff":"=r"(out)); }

Generatedassemblycode: movuir2,0xff stbr2,@gprel(_out)(gp)

Example3:usinginputandoutputparameters AddtwoCvariablesandassigntheresulttoathirdCvariable.Registersareusedfortheinputparameters(constraint r,%1for aand%2forbintheinstructiontemplate)andfortheoutputparameter(constraintr,%0forresultintheinstructiontemplate). Thecompilergeneratescodetomovetheinputexpressionsintotheinputregistersandtoassigntheresulttotheoutput variable. chara,b; intresult;

voidmain(void) { a=3; b=4; __asm("ADD%0,%1,%2":"=r"(result):"r"(a),"r"(b)); }

Generatedassemblycode: main:.typefunc movuir2,0x3 stbr2,@gprel(a)(gp) movuir3,0x4 stbr3,@gprel(b)(gp) ADDr2,r2,r3 stwr2,@gprel(result)(gp) ret

1−6 CLanguage

Example4:reserveregisters

Sometimesaninstructionknocksoutcertainspecificregisters.Themostcommonexampleofthisisafunctioncall,wherethe calledfunctionisallowedtodowhateveritlikeswithsomeregisters.Ifthisisthecase,youcanlistspecificregistersth atget clobberedbyanoperationaftertheinputs. SameasExample3,butnowregisterR3isareservedregister.Youcandothisbyaddingareservedregisterlist( :"R3").As youcanseeinthegeneratedassemblycode,register R3isnotused. chara,b; intresult;

voidmain(void) { a=3; b=4; __asm("ADD%0,%1,%2":"=r"(result):"r"(a),"r"(b):"R3"); }

Generatedassemblycode: main:.typefunc movuir2,0x3 stbr2,@gprel(a)(gp) movuir4,0x4 stbr4,@gprel(b)(gp) ADDr2,r2,r4 stwr2,@gprel(result)(gp) ret

1.5 PragmastoControltheCompiler

PragmasarekeywordsintheCsourcethatcontrolthebehaviorofthecompiler.Pragmasoverrulecompileroptions.Put pragmasinyourCsourcewhereyouwantthemtotakeeffect.Unlessstatedotherwise,apragmaisineffectfromthepoint whereitisincludedtotheendofthecompilationunitoruntilanotherpragmachangesitsstatus. Forexample,youcansetacompileroptiontospecifywhichoptimizationsthecompilershouldperform.Withthe #pragma optimizeflagsyoucansetanoptimizationlevelforaspecificpartoftheCsource.Thisoverrulesthegeneraloptimization levelthatissetintheCcompilerOptimizationpageintheProjectOptionsdialog(commandlineoption −−optimize(−O)). Thegeneralsyntaxforpragmasis:

#pragmapragma−spec[ON|OFF|DEFAULT|RESTORE] or: _Pragma("pragma−spec[ON|OFF|DEFAULT|RESTORE]")

Pragmasmarkedwith(*)acceptthefollowingspecialarguments: default setthepragmatotheinitialvalue restore restorethepreviousvalueofthepragma Pragmasmarkedwith(+)arebooleanflags,andacceptthefollowingarguments: on switchtheflagon(sameaswithoutargument) off switchtheflagoff Thecompilerrecognizesthefollowingpragmas,otherpragmasareignored. aliassymbol=defined_symbol

Definesymbolasanaliasfordefinined_symbol.Itcorrespondstoanequatedirective( .equ)atassemblylevel.Thesymbol shouldnotbedefinedelsewhere,and defined_symbolshouldbedefinedwithstaticstorageduration(notexternor automatic).

1−7 NiosIIEmbeddedToolsReference

Seeassemblerdirective.EQUinsection4.8.2,AssemblerDirectives,inChapterAssemblyLanguage. call{near|far}(*)

Bydefault,functionsarecalledwith28−bitPC−regioncalls.This nearcallisdirectlycodedintotheinstruction,resultingin higherexecutionspeedandsmallercodesize. Theothercallmodeisa32−bitindirectcall.With farcallsyoucanaddressthefullrangeofmemory.Theaddressisfirst loadedintoaregisterafterwhichthecallisexecuted.

Nearcallsareonlypossibleifthedestinationaddressofthecallislocatedwithinthesame256MBregionastheaddress ofthecallitself(hardwarerestriction).Ifyouneedtocallafunction(just)outsidethe256MBregionfromwhereitis called,youmustuseafarcall.

SeeCcompileroption−−call(−m)insection5.1,CCompilerOptions,inChapterToolOptions. externsymbol

Forceanexternalreference(.externassemblerdirective),evenwhenthesymbolisnotusedinthemodule.

Seeassemberdirective.EXTERNinsection4.8.2,AssemblerDirectives,inChapterAssemblyLanguage. extern_sdata(*)(+) endextern_sdata Withthispragmayoutellthecompilertousesmalldataaddressingforexternaldataaswellasforsymbolsdefinedinthe currentmodule.endextern_sdatarestoresthedefaultsettingforthe−−extern−sdataoption.

SeeCcompileroption−−extern−sdatainsection5.1,CCompilerOptions,inChapterToolOptions. inline noinline smartinline

Insteadofthequalifierinline,youcanalsousepragmainlineandpragmanoinlinetoinlineafunctionbody: intw,x,y,z; #pragmainline intadd(inta,intb) { inti=4; return(a+b); } #pragmanoinline voidmain(void) { w=add(1,2); z=add(x,y); }

Ifafunctionhasaninlineor__noinlinefunctionqualifier,thenthisqualifierwilloverrulethecurrentpragmasetting.

Seesection1.7.3,InliningFunctions:inline/__noinline .

Bydefault,smallfuctionsthatarenottoooftencalled(fromdifferentlocations),areinlined.Thisreducesexecutionspeed at thecostofcodesize(Ccompileroption −Oi).Withthepragmanoinline/pragmasmartinlineyoucantemporarily disablethisoptimization.

1−8 CLanguage

WiththeCcompileroptions−−inline−max−incrand−−inline−max−sizeyouhavemorecontrolovertheautomaticfunction inliningprocessofthecompiler.

SeeformoreinformationtheCcompileroptions−−inline−max−incrand−−inline−max−sizeinsection5.1,CCompiler OptionsinChapterToolOptions. macro nomacro(*)(+) Turnsmacroexpansiononoroff.Bydefault,macroexpansionisenabled. message"message"...

Printthemessagestring(s)onstandardoutput. optimizeflags(*) endoptimize

Youcanoverrulethecompileroption−Oforthecodebetweenthepragmasoptimizeandendoptimize.Thepragma worksthesameascompileroption−O.

Seesection2.6,CompilerOptimizationsinChapterUsingtheCompilerintheuser’smanual. SeeCcompileroption−−optimize(−O)insection5.1,CCompilerOptions,inChapterToolOptions. profile[flag,...](*) endprofile Controltheprofilesettings.Thepragmaworksthesameascompileroption−−profile(−p).Notethatthispragmawillonlybe checkedatthestartofafunction.endprofileswitchesbacktothepreviousprofilingsettings.

SeeCcompileroption−−profile(−p)insection5.1,CCompilerOptions,inChapterToolOptions. profiling(*)(+) Ifprofilingisenabledonthecommandline, Ccompileroption−−profile(−p),youcandisablepartofyoursourcecodefor profilingwiththepragmasprofilingoffandprofiling. protect(*)(+) endprotect

Withthesepragmasyoucanprotectsectionsagainstlinkeroptimizations.Thisexcludesasectionfromunreferencedsection removalandduplicatesectionremovalbythelinker. endprotextrestoresthedefaultsectionprotection. runtime[flag,...](*) Checkforrun−timeerrors.Thepragmaworksthesameascompileroption −−runtime(−r).

SeeCcompileroption−−runtime(−r)insection5.1,CCompilerOptions,inChapterToolOptions. sdatasize(*) Withthispragmayoutellthecompilertoplacealldataobjectssmallerthanthespecified size(bytes)insdataorsbss sections.Youcanstilloverrulethisoptionwiththekeywords __no_sdataand__sdataforindividiualdataobjectsinyour source.

SeeCcompileroption−−sdatainsection5.1,CCompilerOptions,inChapterToolOptions. section[name=]{suffix|−f|−m|−fm}(*) endsection

Renamesectionsbyaddingasuffixtoallsectionnamesspecifiedwith name,orrestoredefaultsectionnaming.Ifyou specifyonlyasuffix(withoutaname),thesuffixisaddedtoallsectionnames.

1−9 NiosIIEmbeddedToolsReference

SeeCcompileroption−−rename−sectionsinsection5.1,CCompilerOptionsinChapterToolOptions. Seeassemblerdirective.SECTION(Startorcontinuesection),insection4.8.2, AssemblerDirectives,inChapter AssemblyLanguage. section_code_init(*)(+) section_no_code_init CopyordonotcopycodesectionsfromROMtoRAMatapplicationstartup. section_const_init(*)(+) section_no_const_init Copyordonotcopyread−onlydatasectionsfromROMtoRAMatapplicationstartup. source(*)(+) nosource WiththesepragmasyoucanchoosewhichCsourcelinesmustbelistedascommentsinassemblyoutput.

SeealsoCcompileroption−−source(−s) stdinc(*)(+) Thispragmachangesthebehaviorofthe#includedirective.Whenset,theCcompileroptions −−include−directoryand −−no−stdincareignored. tradeofflevel(*) Specifytradeoffbetweenspeed(0)andsize(4).

SeealsoCcompileroption−−tradeoff(−t) unroll_max_sizevalue(*)(+) end_unroll_max_size

Specifythemaximumsizeforanunrolledloop.end_unroll_max_sizerestoresthedefaultloopunrollingbehavior.

SeeCcompileroption−−unroll−max−sizeinsection5.1,CCompilerOptionsinChapterToolOptions. warning[number,...](*) Withthispragmayoucandisablewarningmessages.Ifyoudonotspecifyawarningnumber,allwarningswillbesuppressed.

SeealsoCcompileroption−−no−warnings(−w) weaksymbol Markasymbolas"weak"(.weakassemblerdirective).Thesymbolmusthaveexternallinkage,whichmeansaglobalor externalobjectorfunction.Astaticsymbolcannotbedeclaredweak. Aweakexternalreferenceisresolvedbythelinkerwhenaglobal(orweak)definitionisfoundinoneoftheobjectfiles. However,aweakreferencewillnotcausetheextractionofamodulefromalibrarytoresolvethereference.Whenaweak externalreferencecannotberesolved,thenullpointerissubstituted. Aweakdefinitioncanbeoverruledbyanormalglobaldefinition.Thelinkerwillnotcomplainabouttheduplicatedefinition, andignoretheweakdefinition.

Seeassemblerdirective.WEAKinSection4.8.2,AssemblerDirectives,inChapterAssemblyLanguage.

1−10 CLanguage

1.6 PredefinedPreprocessorMacros

InadditiontothepredefinedmacrosrequiredbytheISOCstandard,suchas __DATE__and__FILE__,theTASKINGC compilersupportsthepredefinedmacrosasdefinedinthetablebelow.ThemacrosareusefultocreateconditionalCcode.

Macro Description __BIG_ENDIAN__ Expandsto1ifbig−endianmodeisselected( −−endianness=big),otherwiseunrecognizedas macro. __BUILD__ Identifiesthebuildnumberofthecompiler,composedofdecimaldigitsforthebuildnumber,three digitsforthemajorbranchnumberandthreedigitsfortheminorbranchnumber.Forexample,if youusebuild1.22.1ofthecompiler,__BUILD__expandsto1022001.Ifthereisnobranch number,thebranchdigitsexpandtozero.Forexample,build127resultsin127000000. __CHAR_UNSIGNED__ Expandsto1ifyouusedoption−−uchar(chardefaultstounsigned),otherwiseunrecognizedas macro. __CNIOS__ Expandsto1fortheNiosIItoolset,otherwiseunrecognizedasmacro. __CPU__ ExpandstotheCPUcorename(option−−cpu=cpu). __DOUBLE_FP__ Expandsto1ifyoudidnotuseoption−−no−double(Treat’double’as’float’),otherwise unrecognizedasmacro. __HW_DIVIDE__ Expandsto1ifyouusedoption−−use−hardware=d,otherwiseunrecognizedasmacro. __HW_MULTIPLY__ Expandsto1ifyouusedoption−−use−hardware=m,otherwiseunrecognizedasmacro. __HW_MULX__ Expandsto1ifyouusedoption−−use−hardware=x,otherwiseunrecognizedasmacro. __LITTLE_ENDIAN__ Expandsto1iflittle−endianmodeisselected( −−endianness=little),otherwiseunrecognizedas macro.Thisisthedefault. __NIOS2__ Expandsto1fortheNiosIItoolset,otherwiseunrecognizedasmacro. __REVISION__ Identifiestherevisionnumberofthecompiler.Forexample,ifyouuseversion1.0r2ofthe compiler,__REVISION__expandsto2. __SINGLE_FP__ Expandsto1ifyouusedoption−−no−double(Treat’double’as’float’),otherwiseunrecognized asmacro. __TASKING__ IdentifiesthecompilerasaTASKINGcompiler.Expandsto1ifaTASKINGcompilerisused. __VERSION__ Identifiestheversionnumberofthecompiler.Forexample,ifyouuseversion1.0r2ofthe compiler,__VERSION__expandsto1000(dotandrevisionnumberareomitted,minorversion numberin3digits).

Table1−4:Predefinedpreprocessormacros

Example #ifdef__CNIOS__ /*thispartisonlycompiledfortheNiosII*/ ...

#endif

1−11 NiosIIEmbeddedToolsReference

1.7 Functions

1.7.1 ParameterPassing

Alotofexecutiontimeofanapplicationisspenttransferringparametersbetweenfunctions.Thefastestparametertransporti s viaregisters.Therefore,functionparametersarefirstpassedviaregisters.Ifnomoreregistersareavailableforaparamete r,the compilerpushesparametersonthestack.Seethetablebelow.

ParameterType ParameterNumber 1 2 3 4 _Bool r4 r5 r6 r7 char r4 r5 r6 r7 short r4 r5 r6 r7 int/long r4 r5 r6 r7 float r4 r5 r6 r7 32−bitpointer r4 r5 r6 r7 32−bitstruct r4 r5 r6 r7 longlong r4r5 r5r6 r6r7 double r4r5 r5r6 r6r7 64−bitstruct r4r5 r5r6 r6r7

Table1−5:Registerusageforparameterpassing

Ifaregistercorrespondingtoaparameternumberisalreadyinusethenextregisterisused.

Examplewiththreearguments func1(inta,intb,int*c) • a(firstparameter)ispassedinregisterr4. • b(secondparameter)ispassedinregisterr5. • c(thirdparameter)ispassedinregisterr6. Examplewithonelonglong/doubleargumentsandoneotherargument func2(longlongd,chare) • d(firstparameter)ispassedinregisterr4andr5 • e(secondparameter)ispassedinregisterr6. Examplewithtwolonglong/doubleargumentsandoneotherargument func3(doublef,longlongg,charh) • f(firstparameter)ispassedinregisterr4andr5 • g(secondparameter)ispassedinregisterr6andr7. • h(thirdparameter)cannotbepassedthroughregistersanymore,andispassedviathestack.

1.7.2 FunctionReturnTypes TheCcompilerusesregisterstostoreCfunctionreturnvalues,dependingonthefunctionreturntypes.

ReturnType Register _Bool r2 char r2 short r2 int/long r2

1−12 CLanguage

ReturnType Register float r2 32−bitpointer r2 32−bitstruct r2 longlong r2r3 double r2r3 64−bitstruct r2r3

Table1−6:Registerusageforfunctionreturntypes Objectslargerthan64bitsarereturnedviathestack.

1.7.3 InliningFunctions:inline/__noinline

WiththeCcompileroption−−optimize=+inline,theCcompilerautomaticallyinlinessmallfunctionsinordertoreduce executiontime(smartinlining).Thecompilerinsertsthefunctionbodyattheplacethefunctioniscalled.TheCcompilerdecides whichfunctionswillbeinlined.Youcanoverrulethisbehaviorwiththetwokeywords inline(ISO−C)and__noinline. Withtheinlinekeywordyouforcethecompilertoinlinethespecifiedfunction,regardlessoftheoptimizationstrategyofthe compileritself: inlineunsignedintabs(intval) { unsignedintabs_val=val; if(val<0)abs_val=−val; returnabs_val; }

Ifafunctionwiththekeywordinlineisnotcalledatall,thecompilerdoesnotgeneratecodeforit. Youmustdefineinlinefunctionsinthesamesourcemoduleasinwhichyoucallthefunction,becausethecompileronlyinlinesa functioninthemodulethatcontainsthefunctiondefinition.Whenyouneedtocalltheinlinefunctionfromseveralsource modules,youmustincludethedefinitionoftheinlinefunctionineachmodule(forexampleusingaheaderfile). Withthe__noinlinekeyword,youpreventafunctionfrombeinginlined: __noinlineunsignedintabs(intval) { unsignedintabs_val=val; if(val<0)abs_val=−val; returnabs_val; }

Usingpragmas:inline,noinline,smartinline Insteadoftheinlinequalifier,youcanalsouse#pragmainlineand#pragmanoinlinetoinlineafunctionbody: #pragmainline unsignedintabs(intval) { unsignedintabs_val=val; if(val<0)abs_val=−val; returnabs_val; } #pragmanoinline voidmain(void) { inti; i=abs(−1); }

Ifafunctionhasaninline/__noinlinefunctionqualifier,thenthisqualifierwilloverrulethecurrentpragmasetting.

1−13 NiosIIEmbeddedToolsReference

Withthe#pragmanoinline/#pragmasmartinlineyoucantemporarilydisablethedefaultbehaviorthattheCcompiler automaticallyinlinessmallfunctionswhenyouturnontheCcompileroption −−optimize=+inline.

1.7.4 IntrinsicFunctions SomespecificassemblyinstructionshavenoequivalenceinC. Intrinsicfunctionsgivethepossibilitytousetheseinstructions. Intrinsicfunctionsarepredefinedfunctionsthatarerecognizedbythecompiler.Thecompilergeneratesthemostefficient assemblycodeforthesefunctions. Thecompileralwaysinlinesthecorrespondingassemblyinstructionsintheassemblysource(ratherthancallingitasa function).Thisavoidsparameterpassingandregistersavinginstructionswhicharenormallynecessaryduringfunctioncalls. Intrinsicfunctionsproduceveryefficientassemblycode.Thoughitispossibletoinlineassemblycodebyhand,intrinsic functionsuseregistersevenmoreefficiently.AtthesametimeyourCsourceremainsveryreadable. YoucanuseintrinsicfunctionsinCasiftheywereordinaryC(library)functions.Allintrinsicsbeginwithadoubleundersc ore character. TheTASKINGNiosIICcompilerrecognizesthefollowingintrinsicfunctions:

__alloc void*volatile__alloc(__size_tsize);

Allocatememory. Returns:apointertospaceinexternalmemoryof sizebyteslength.NULLifthereisnotenoughspaceleft.

__dotdotdot__ void*__dotdotdot__(void);

Variableargument’...’operator.Usedinlibraryfunctionva_start(). Returns:thestackoffsettothevariableargumentlist.

__free voidvolatile__free(void*p);

Deallocatesthememorypointedtobyp.pmustpointtomemoryearlierallocatedbyacallto __alloc(). Returns:nothing.

__nop void__nop(void);

GenerateNOPinstructions. Returns:nothing. Example: __nop();/*generateNOPinstruction*/

__get_return_address __codeptrvolatile__get_return_address(void);

Usedbythecompilerforprofilingwhenyoucompilewiththe −−profile(−p)option. Returns:returnaddressofafunction.

1−14 CLanguage

1.7.5 InterruptFunctions TheTASKINGCcompilersupportsanumberoffunctionqualifiersandkeywordstoprograminterruptserviceroutines(ISR).An interruptserviceroutine(or:interruptfunction,interrupthandler,exceptionhandler)iscalledwhenaninterruptevent(or: service request)occurs.

1.7.5.1 DefininganInterruptServiceRoutine:__interruptkeyword Withthefunctiontypequalifier__interruptyoucandeclareafunctionasaninterruptserviceroutine.Youcanspecifythe interruptjumplocation(exceptionaddress)withtheattribute __at().Notethatthisaddressisdeterminedbyyourhardware. Interruptfunctionscannotreturnanythingandmusthavea voidargumenttypelist: void__interrupt isr(void)__at(exception_address) { ... }

FormoreinformationaboutexceptionhandlingrefertosectionIII.6 ExceptionHandlingintheNiosIISoftware Developer’sHandbook[Altera].

Example void__interruptmy_handler(void)__at(0x20) { ... }

1.8 Libraries

TheTASKINGcompilerscomewithstandardClibraries(ISO/IEC9899:1999)andheaderfileswiththeappropriateprototypes forthelibraryfunctions.AllstandardClibrariesareavailableinobjectformatandinCorassemblysourcecode. AnumberofstandardoperationswithinCaretoocomplextogenerateinlinecodefor(toomuchcode).Theseoperationsare implementedasrun−timelibraryfunctionstosavecode.

Seesection3.2,LibraryFunctions,inChapterLibraries,foranextensivedescriptionofallstandardClibraryfunctions.

1.8.1 PrintfandScanfRoutines TheClibraryfunctionsprintf(),fprintf(),vfprintf(),vsprintf(),...callonesinglefunction,_doprint(),that dealswiththeformatstringandarguments.Thesameappliestoall scanftypefunctions,whichcallthefunction _doscan(), andalsoforthewprintfandwscanftypefunctionswhichcall_dowprint()and_dowscan()respectively.TheClibrary containsthreeversionsoftheseroutines: int,longandlonglongversions.Ifyouusefloating−pointtheformatterfunction forfloating−point_doflt()or_dowflt()iscalled.Dependingontheformattingargumentsyouuse,thecorrectroutineis usedfromthelibrary.Ofcoursethelargertheversionoftheroutinethelargeryourproducedcodewillbe. Notethatwhenyoucallanyoftheprintf/scanfroutinesindirect,theargumentsarenotknownandalwaysthe longlong versionwithfloating−pointsupportisusedfromthelibrary.

Example #include

longL;

voidmain(void) { printf("Thisisalong:%ld\n",L); }

Thelinkerextractsthelongversionwithoutfloating−pointsupportfromthelibrary.

1−15 NiosIIEmbeddedToolsReference

Seealsothedescriptionof#pragmaweakinsection1.5,PragmastoControltheCompilerintheuser’smanual.

1−16 2 C++Language

Summary ThischapterdescribestheC++languageimplementationandsomespecific features.

2.1 Introduction

TheTASKINGC++compileroffersanewapproachtohigh−levellanguageprogrammingforyourtargetprocessor.TheC++ compileracceptstheC++languageasdefinedbytheISO/IEC14882:1998standardandmodifiedbyTC1forthatstandard.It alsoacceptsthelanguageextensionsoftheCcompiler(seeChapter1,CLanguage). NotethattheC++languageitselfisnotdescribedinthisdocument.FormoreinformationontheC++language,seethe followingpublications. • TheC++ProgrammingLanguage(secondedition)byBjarneStraustrup(1991,AddisonWesley) • ISO/IEC14882:1998C++standard[ANSI]Moreinformationonthestandardscanbefoundathttp://www.ansi.org/.

2.2 C++LanguageExtensionKeywords

TheC++compilersupportsthesamelanguageextensionkeywordsastheCcompiler.Whenoption−−strictisused,the extensionswillbedisabled. Additionallythefollowinglanguageextensionsaresupported: attributes Attributes,introducedbythekeyword__attribute__,canbeusedondeclarationsofvariables,functions,types,andfields. Thealias,aligned,cdecl,const,constructor,deprecated,destructor,format,format_arg,init_priority, malloc,mode,naked,no_check_memory_usage,no_instrument_function,nocommon,noreturn,packed,pure, section,sentinel,stdcall,transparent_union,unused,used,visibility,volatile,andweakattributesare supported. pragmas TheC++compilersupportsthesamepragmasastheCcompilerandsomeextrapragmasasexplainedinsection2.9,Pragmas toControltheC++Compiler.Pragmasgivedirectionstothecodegeneratorofthecompiler.

2.3 C++DialectAccepted

TheC++compileracceptstheC++languageasdefinedbytheISO/IEC14882:1998standardandmodifiedbyTC1forthat standard. Commandlineoptionsarealsoavailabletoenableanddisableanachronismsandstrictstandard−conformancechecking.

2.3.1 StandardLanguageFeaturesAccepted

ThefollowingfeaturesnotintraditionalC++(theC++languageof"TheAnnotatedC++ReferenceManual"byEllisand Stroustrup(ARM))butinthestandardareimplemented: • Thedependentstatementofanif,while,do−while,orforisconsideredtobeascope,andtherestrictiononhaving suchadependentstatementbeadeclarationisremoved. • Theexpressiontestedinanif,while,do−while,orfor,asthefirstoperandofa"?"operator,orasanoperandofthe "&&",":",or"!"operatorsmayhaveapointer−to−membertypeoraclasstypethatcanbeconvertedtoapointer−to−member typeinadditiontothescalarcasespermittedbytheARM.

2−1 NiosIIEmbeddedToolsReference

• Qualifiednamesareallowedinelaboratedtypespecifiers. • Aglobal−scopequalifierisallowedinmemberreferencesoftheformx.::A::Bandp−>::A::B. • Theprecedenceofthethirdoperandofthe"?"operatorischanged. • Ifcontrolreachestheendofthemain()routine,andmain()hasanintegralreturntype,itistreatedasifareturn0; statementwereexecuted. • Pointerstoarrayswithunknownboundsasparametertypesarediagnosedaserrors. • Afunctional−notationcastoftheformA()canbeusedevenifAisaclasswithouta(nontrivial)constructor.Thetemporary createdgetsthesamedefaultinitializationtozeroasastaticobjectoftheclasstype. • Acastcanbeusedtoselectoneoutofasetofoverloadedfunctionswhentakingtheaddressofafunction. • Templatefrienddeclarationsanddefinitionsarepermittedinclassdefinitionsandclasstemplatedefinitions. • Typetemplateparametersarepermittedtohavedefaultarguments. • Functiontemplatesmayhavenontypetemplateparameters. • Areferencetoconstvolatilecannotbeboundtoanrvalue. • Qualificationconversions,suchasconversionfromT** toTconst*const*areallowed. • Digraphsarerecognized. • Operatorkeywords(e.g.,not,and,bitand,etc.)arerecognized. • Staticdatamemberdeclarationscanbeusedtodeclarememberconstants. • Whenoption−−wchar_t−keywordisset,wchar_tisrecognizedasakeywordandadistincttype. • boolisrecognized. • RTTI(run−timetypeidentification),includingdynamic_castandthetypeidoperator,isimplemented. • Declarationsintestedconditions(inif,switch,for,andwhilestatements)aresupported. • Arraynewanddeleteareimplemented. • New−stylecasts(static_cast,reinterpret_cast,andconst_cast)areimplemented. • Definitionofanestedclassoutsideitsenclosingclassisallowed. • mutableisacceptedonnon−staticdatamemberdeclarations. • Namespacesareimplemented,includingusingdeclarationsanddirectives.Accessdeclarationsarebroadenedtomatch thecorrespondingusingdeclarations. • Explicitinstantiationoftemplatesisimplemented. • Thetypenamekeywordisrecognized. • explicitisacceptedtodeclarenon−convertingconstructors. • Thescopeofavariabledeclaredinthefor−init−statementofaforloopisthescopeoftheloop(notthesurrounding scope). • Membertemplatesareimplemented. • Thenewspecializationsyntax(using"template<>")isimplemented. • Cv−qualifiersareretainedonrvalues(inparticular,onfunctionreturnvalues). • Thedistinctionbetweentrivialandnontrivialconstructorshasbeenimplemented,ashasthedistinctionbetweenPODsand non−PODswithtrivialconstructors. • Thelinkagespecificationistreatedaspartofthefunctiontype(affectingfunctionoverloadingandimplicitconversions). • externinlinefunctionsaresupported,andthedefaultlinkageforinlinefunctionsisexternal. • Atypedefnamemaybeusedinanexplicitdestructorcall. • Placementdeleteisimplemented. • Anarrayallocatedviaaplacementnewcanbedeallocatedviadelete. • Covariantreturntypesonoverridingvirtualfunctionsaresupported. • enumtypesareconsideredtobenon−integraltypes. • Partialspecializationofclasstemplatesisimplemented. • Partialorderingoffunctiontemplatesisimplemented. • Functiondeclarationsthatmatchafunctiontemplateareregardedasindependentfunctions,notas"guidingdeclarations" thatareinstancesofthetemplate. • Itispossibletooverloadoperatorsusingfunctionsthattakeenumtypesandnoclasstypes. • Explicitspecificationoffunctiontemplateargumentsissupported.

2−2 C++Language

• Unnamedtemplateparametersaresupported. • Thenewlookuprulesformemberreferencesoftheformx.A::Bandp−>A::Baresupported. • Thenotation::template(and−>template,etc.)issupported. • Inareferenceoftheformf()−>g(),withgastaticmemberfunction,f()isevaluated.TheARMspecifiesthattheleft operandisnotevaluatedinsuchcases. • enumtypescancontainvalueslargerthancanbecontainedinanint. • Defaultargumentsoffunctiontemplatesandmemberfunctionsofclasstemplatesareinstantiatedonlywhenthedefault argumentisusedinacall. • Stringliteralsandwidestringliteralshaveconsttype. • Classnameinjectionisimplemented. • Argument−dependent(Koenig)lookupoffunctionnamesisimplemented. • Classandfunctionnamesdeclaredonlyinunqualifiedfrienddeclarationsarenotvisibleexceptforfunctionsfoundby argument−dependentlookup. • Avoidexpressioncanbespecifiedonareturnstatementinavoidfunction. • Function−try−blocks,i.e.,try−blocksthatarethetop−levelstatementsoffunctions,constructors,ordestructors,are implemented. • Universalcharactersetescapes(e.g.,\uabcd)areimplemented. • Onacallinwhichtheexpressiontotheleftoftheopeningparenthesishasclasstype,overloadresolutionlooksfor conversionfunctionsthatcanconverttheclassobjecttopointer−to−functiontypes,andeachsuchpointed−to"surrogate function"typeisevaluatedalongsideanyothercandidatefunctions. • Dependentnamelookupintemplatesisimplemented.Nondependentnamesarelookeduponlyinthecontextofthe templatedefinition.Dependentnamesarealsolookedupintheinstantiationcontext,viaargument−dependentlookup. • Value−initializationisimplemented.Thisformofinitializationisindicatedbyaninitializerof"()"andcauseszeroingofcertain POD−typedmembers,wheretheusualdefault−initializationwouldleavethemuninitialized. • Apartialspecializationofaclassmembertemplatecannotbeaddedoutsideoftheclassdefinition. • Qualificationconversionsmaybeperformedaspartofthetemplateargumentdeductionprocess. • Theexportkeywordfortemplatesisimplemented.

2.3.2 C++0xLanguageFeaturesAccepted

ThefollowingfeaturesaddedintheworkingpaperforthenextC++standard(expectedtobecompletedin2009orlater)are enabledinC++0xmode(withoption−−c++0x).Severalofthesefeaturesarealsoenabledindefault(nonstrict)C++mode. • A"rightshifttoken"(>>)canbetreatedastwoclosinganglebrackets.Forexample: templatestructS{}; S>s;//OK.Nowhitespaceneeded //betweenclosinganglebrackets. • Thefriendclasssyntaxisextendedtoallownonclasstypesaswellasclasstypesexpressedthroughatypedeforwithoutan elaboratedtypename.Forexample: typedefstructSST; classC{ friendS;//OK(requiresStobeinscope). friendST;//OK(sameas"friendS;"). friendint;//OK(noeffect). friendSconst;//Error:cv−qualifierscannot //appeardirectly. }; • Mixedstringliteralconcatenationsareaccepted(afeaturecarriedoverfromC99): wchar_t*str="a"L"b";//OK,sameasL"ab". • Variadicmacrosandemptymacroargumentsareaccepted,asinC99. • Atrailingcommainthedefinitionofanenumerationtypeissilentlyaccepted(afeaturecarriedoverfromC99): enumE{e,};

2−3 NiosIIEmbeddedToolsReference

• Ifthecommandlineoption−−long−longisspecified,thetypelonglongisaccepted.Unsuffixedintegerliteralsthat cannotberepresentedbytypelong,butcouldpotentiallyberepresentedbytypeunsignedlong,havetypelonglong instead(thismatchesC99,butnotthetreatmentofthelonglongextensioninC89ordefaultC++mode). • Thekeywordtypenamefollowedbyaqualified−idcanappearoutsideatemplatedeclaration. structS{structN{};}; typenameS::N*p;//SilentlyacceptedinC++0xmode

2.3.3 AnachronismsAccepted

Thefollowinganachronismsareacceptedwhenanachronismsareenabled(with−−anachronisms): • overloadisallowedinfunctiondeclarations.Itisacceptedandignored. • Definitionsarenotrequiredforstaticdatamembersthatcanbeinitializedusingdefaultinitialization.Theanachronismdoes notapplytostaticdatamembersoftemplateclasses;theymustalwaysbedefined. • Thenumberofelementsinanarraymaybespecifiedinanarraydeleteoperation.Thevalueisignored. • Asingleoperator++()andoperator−−()functioncanbeusedtooverloadbothprefixandpostfixoperations. • Thebaseclassnamemaybeomittedinabaseclassinitializerifthereisonlyoneimmediatebaseclass. • Assignmenttothisinconstructorsanddestructorsisallowed.Thisisallowedonlyifanachronismsareenabledandthe "assignmenttothis"configurationparameterisenabled. • Aboundfunctionpointer(apointertoamemberfunctionforagivenobject)canbecasttoapointertoafunction. • Anestedclassnamemaybeusedasanon−nestedclassnameprovidednootherclassofthatnamehasbeendeclared. Theanachronismisnotappliedtotemplateclasses. • Areferencetoanon−consttypemaybeinitializedfromavalueofadifferenttype.Atemporaryiscreated,itisinitialized fromthe(converted)initialvalue,andthereferenceissettothetemporary. • Areferencetoanon−constclasstypemaybeinitializedfromanrvalueoftheclasstypeoraderivedclassthereof.No (additional)temporaryisused. • Afunctionwithold−styleparameterdeclarationsisallowedandmayparticipateinfunctionoverloadingasthoughitwere prototyped.Defaultargumentpromotionisnotappliedtoparametertypesofsuchfunctionswhenthecheckforcompatibility isdone,sothatthefollowingdeclarestheoverloadingoftwofunctionsnamedf: intf(int); intf(x)charx;{returnx;}

NotethatinCthiscodeislegalbuthasadifferentmeaning:atentativedeclarationoffisfollowedbyitsdefinition. • Whenoption−−nonconst−ref−anachronismisset,areferencetoanon−constclasscanbeboundtoaclassrvalueofthe sametypeoraderivedtypethereof. structA{ A(int); Aoperator=(A&); Aoperator+(constA&); }; main(){ Ab(1); b=A(1)+A(2);//Allowedasanachronism }

2.3.4 ExtensionsAcceptedinNormalC++Mode

Thefollowingextensionsareacceptedinallmodes(exceptwhenstrictANSI/ISOviolationsarediagnosedaserrorsorwere explicitlynoted): • Afrienddeclarationforaclassmayomittheclasskeyword: classA{ friendB;//Shouldbe"friendclassB" };

2−4 C++Language

• Constantsofscalartypemaybedefinedwithinclasses: classA{ constintsize=10; inta[size]; }; • Inthedeclarationofaclassmember,aqualifiednamemaybeused: structA{ intA::f();//Shouldbeintf(); }; • Therestrictkeywordisallowed. • Implicittypeconversionbetweenapointertoanextern"C"functionandapointertoanextern"C++"functionis permitted.Here’sanexample: extern"C"voidf();//f’stypehasextern"C"linkage void(*pf)()//pfpointstoanextern"C++"function =&f;//errorunlessimplicitconversionis //allowed

ThisextensionisallowedinenvironmentswhereCandC++functionssharethesamecallingconventions.Itisenabledby default. • A"?"operatorwhosesecondandthirdoperandsarestringliteralsorwidestringliteralscanbeimplicitlyconvertedto"char *"or"wchar_t*".(RecallthatinC++stringliteralsareconst.Thereisadeprecatedimplicitconversionthatallows conversionofastringliteralto"char*",droppingtheconst.Thatconversion,however,appliesonlytosimplestring literals.Allowingitfortheresultofa"?"operationisanextension.) char*p=x?"abc":"def"; • Defaultargumentsmaybespecifiedforfunctionparametersotherthanthoseofatop−levelfunctiondeclaration(e.g.,they areacceptedontypedefdeclarationsandonpointer−to−functionandpointer−to−member−functiondeclarations). • Non−staticlocalvariablesofanenclosingfunctioncanbereferencedinanon−evaluatedexpression(e.g.,asizeof expression)insidealocalclass.Awarningisissued. • IndefaultC++mode,thefriendclasssyntaxisextendedtoallownonclasstypesaswellasclasstypesexpressedthrougha typedeforwithoutanelaboratedtypename.Forexample: typedefstructSST; classC{ friendS;//OK(requiresStobeinscope). friendST;//OK(sameas"friendS;"). friendint;//OK(noeffect). friendSconst;//Error:cv−qualifierscannot //appeardirectly. }; • IndefaultC++mode,mixedstringliteralconcatenationsareaccepted.(ThisisafeaturecarriedoverfromC99andalso availableinGNUmodes). wchar_t*str="a"L"b";//OK,sameasL"ab". • IndefaultC++mode,variadicmacrosareaccepted.(ThisisafeaturecarriedoverfromC99andalsoavailableinGNU modes.) • IndefaultC++mode,emptymacroargumentsareaccepted(afeaturecarriedoverfromC99). • Atrailingcommainthedefinitionofanenumerationtypeissilentlyaccepted(afeaturecarriedoverfromC99): enumE{e,};

2.4 GNUExtensions

TheC++compilercanbeconfiguredtosupporttheGNUC++mode(commandlineoption−−g++).Inthismode,many extensionsprovidedbytheGNUC++compilerareaccepted.ThefollowingextensionsareprovidedinGNUC++mode. • Extendeddesignatorsareaccepted • Compoundliteralsareaccepted.

2−5 NiosIIEmbeddedToolsReference

• Non−standardanonymousunionsareaccepted • Thetypeofoperatorissupported.Thisoperatorcantakeanexpressionoratype(likethesizeofoperator,but parenthesesarealwaysrequired)andexpandstothetypeofthegivenentity.Itcanbeusedwhereveratypedefnameis allowed typeof(2*2.3)d;//Declaresa"double" typeof(int)i;//Declaresan"int"

Thiscanbeusefulinmacroandtemplatedefinitions. • The__extension__keywordisacceptedprecedingdeclarationsandcertainexpressions.Ithasnoeffectonthemeaning ofaprogram. __extension____inline__intf(inta){ returna>0?a/2:f(__extension__1−a); } • InallGNUCmodesandinGNUC++modeswithgnu_version<30400,thetypemodifierssigned,unsigned,longandshort canbeusedwithtypedeftypesifthespecifierisvalidwiththeunderlyingtypeofthetypedefinANSIC.E.g.: typedefintI; unsignedI*pui;//OKinGNUC++mode; //sameas"unsignedint*pui" • Ifthecommandlineoption−−long−longisspecified,theextensionsforthelonglongandunsignedlonglongtypes areenabled. • Zero−lengtharraytypes(specifiedby[0])aresupported.Thesearecompletetypesofsizezero. • C99−styleflexiblearraymembersareaccepted.Inaddition,thelastfieldofaclasstypehaveaclasstypewhoselastfieldis aflexiblearraymember.InGNUC++mode,flexiblearraymembersaretreatedexactlylikezero−lengtharrays,andcan thereforeappearanywhereintheclasstype. • TheC99_Pragmaoperatorissupported. • Thegccbuilt−inandfacilities(__builtin_va_list,__builtin_va_arg,...)areaccepted. • Thesizeofoperatorisapplicabletovoidandtofunctiontypesandevaluatestothevalueone. • Variablescanberedeclaredwithdifferenttop−levelcv−qualifiers(thenewqualificationismergedintoexistingqualifiers).For example: externintvolatilex; intconstx=32;//xisnowconstvolatile • The"assemblername"ofvariablesandroutinescanbespecified.Forexample: intcounter__asm__("counter_v1")=0; • Registervariablescanbemappedonspecificregistersusingtheasmkeyword. registerintiasm("eax"); //Map"i"ontoregistereax. • Thekeywordinlineisignored(withawarning)onvariabledeclarationsandonblock−externfunctiondeclarations. • Excessaggregateinitializersareignoredwithawarning. structS{inta,b;}; structSa1={1,2,3}; //"3"ignoredwithawarning;noerror inta2[2]={7,8,9}; //"9"ignoredwithawarning;noerror • Expressionsoftypesvoid*,voidconst*,voidvolatile*andvoidconstvolatile*canbedereferenced;the resultisanlvalue. • The__restrict__keywordisaccepted.ItisidenticaltotheC99restrictkeyword,exceptforitsspelling. • Out−of−rangefloating−pointvaluesareacceptedwithoutadiagnostic.WhenIEEEfloating−pointisbeingused,the"infinity" valueisused. • Extendedvariadicmacrosaresupported. • Dollarsigns($)areallowedinidentifiers. • Hexadecimalfloatingpointconstantsarerecognized.

2−6 C++Language

• The__asm__keywordisrecognizedandequivalenttotheasmtoken.Extendedsyntaxissupportedtoindicatehow assemblyoperandsmaptoC/C++variables. asm("fsinx%1,%0":"=f"(x):"f"(a)); //Maptheoutputoperandon"x", //andtheinputoperandon"a". • The\eescapesequenceisrecognizedandstandsfortheASCII"ESC"character. • Theaddressofastatementlabelcanbetakenbyuseoftheprefix"&&"operator,e.g.,void*a=&&L.Atransfertothe addressofalabelcanbedonebythe"goto*"statement,e.g.,goto*a. • Multi−linestringsaresupported,e.g., char*p="abc def"; • ASCII"NULL"charactersareacceptedinsourcefiles. • Asourcefilecanendwithabackslash("\")character. • Caseranges(e.g.,"case’a’...’z’:")aresupported. • AnumberofmacrosarepredefinedinGNUmode.Seesection2.10,PredefinedMacros. • Apredefinedmacrocanbeundefined. • Alargenumberofspecialfunctionsoftheform__builtin_xyz(e.g.,__builtin_alloca)arepredeclared. • Someexpressionsareconsideredtobeconstant−expressionseventhoughtheyarenotsoconsideredinstandardCand C++.Examplesinclude"((char*)&((structS*)0)−>c[0])−(char*)0"and"(int)"Hello"&0". • Themacro__GNUC__ispredefinedtothemajorversionnumberoftheemulatedGNUcompiler.Similarly,themacros __GNUC_MINOR__and__GNUC_PATCHLEVEL__arepredefinedtothecorrespondingminorversionnumberandpatch level.Finally,__VERSION__ispredefinedtoastringdescribingthecompilerversion. • The__threadspecifiercanbeusedtoindicatethatavariableshouldbeplacedinthread−localstorage(requires gnu_version>=30400). • Anexterninlinefunctionthatisreferencedbutnotdefinedispermitted(withawarning). • Trigraphsareignored(withawarning). • Non−standardcastsareallowedinnullpointerconstants,e.g.,(int)(int*)0isconsideredanullpointerconstantin spiteofthepointercastinthemiddle. • Statementexpressions,e.g.,({intj;j=f();j;)}areaccepted.Branchesintoastatementexpressionarenot allowed.InC++mode,branchesoutarealsonotallowed.Variable−lengtharrays,destructibleentities,try,catch,local non−PODclassdefinitions,anddynamically−initializedlocalstaticvariablesarenotallowedinsideastatementexpression. • Labelscanbedeclaredtobelocalinstatementexpressionsbyintroducingthemwitha__label__declaration. ({__label__lab;inti=4;lab:i=2*i−1;if(!(i%17))gotolab;i;}) • Not−evaluatedpartsofconstantexpressionscancontainnon−constantterms: inti; inta[1||i];//Acceptedingcc/g++mode • Castsonanlvaluethatdon’tfallundertheusual"lvaluecast"interpretation(e.g.,becausetheycasttoatypehavinga differentsize)areignored,andtheoperandremainsanlvalue.Awarningisissued. inti; (short)i=0;//Accepted,castisignored;entireintisset • Variablelengtharrays(VLAs)aresupported.GNUCalsoallowsVLAtypesforfieldsoflocalstructures,whichcanleadto run−timedependentsizesandoffsets.TheC++compilerdoesnotimplementthis,butinsteadtreatssucharraysashaving lengthzero(withawarning);thisenablessomepopularprogrammingidiomsinvolvingfieldswithVLAtypes. voidf(intn){ struct{ inta[n];//Warning:nignoredand //replacedbyzero }; } • Complextypeextensionsaresupported(thesearethesameastheC99complextypefeatures,withtheeliminationof _Imaginaryandtheadditionof__complex,__real,__imag,theuseof"~"todenotecomplexconjugation,andcomplex literalssuchas"1.2i").

2−7 NiosIIEmbeddedToolsReference

• Ifanexplicitinstantiationdirectiveisprecededbythekeywordextern,no(explicitorimplicit)instantiationisforthe indicatedspecialization. • Anexplicitinstantiationdirectivethatnamesaclassmayomittheclasskeyword,andmayrefertoatypedef. • Anexplicitinstantiationorexterntemplatedirectivethatnamesaclassisacceptedinaninvalidnamespace. • std::type_infodoesnotneedtobeintroducedwithaspecialpragma. • Aspecialkeyword__nullexpandstothesameconstantastheliteral"0",butisexpectedtobeusedasanullpointer constant. • Whengnu_version<30400,namesfromdependentbaseclassesareignoredonlyifanothernamewouldbefoundbythe lookup. constintn=0; templatestructB{ staticconstintm=1;staticconstintn=2; }; templatestructD:B{ intf(){returnm+n;} //B::m+::ning++mode }; • Anon−staticdatamemberfromadependentbaseclass,whichwouldusuallybeignoredasdescribedabove,isfoundifthe lookupwouldhaveotherwisefoundanonstaticdatamemberofanenclosingclass(whengnu_versionis<30400). templatestructC{ structA{inti;}; structB:publicA{ voidf(){ i=0;//g++usesA::inotC::i } }; inti; }; • Anewoperationinatemplateisalwaystreatedasdependent(whengnu_version>=30400). templatestructA{ voidf(){ void*p=0; new(&p)int(0);//callsoperatornew //declaredbelow } }; void*operatornew(size_t,void*p); • Whendoingnamelookupinabaseclass,theinjectedclassnameofatemplateclassisignored. namespaceN{ templatestructA{}; } structA{ inti; }; structB:N::A{ B(){Ax;x.i=1;}//g++uses::A,notN::A }; • Theinjectedclassnameisfoundincertaincontextsinwhichtheconstructorshouldbefoundinstead. structA{ A(int){}; }; A::Aa(1);

2−8 C++Language

• Inaconstructordefinition,whatshouldbetreatedasatemplateargumentlistoftheconstructorisinsteadtreatedasthe templateargumentlistoftheenclosingclass. templatestructA{}; template<>structA<1>{ templateA(Ti,intj); };

template<>A<1>::A<1>(inti,intj){} //accepteding++mode • Adifferenceincallingconventionisignoredwhenredeclaringatypedef. typedefvoidF();

extern"C"{ typedefvoidF();//AcceptedinGNUC++mode //(errorotherwise) } • Themacro__GNUG__isdefinedidenticallyto__GNUC__(i.e.,themajorversionnumberoftheGNUcompilerversionthat isbeingemulated). • Themacro_GNU_SOURCEisdefinedas"1". • Guidingdeclarations(afeaturepresentinearlydraftsofthestandard,butnotinthefinalstandard)aredisabled. • Namespacestdispredeclared. • Noconnectionismadebetweendeclarationsofidenticalnamesindifferentscopesevenwhenthesenamesaredeclared extern"C".E.g., extern"C"{voidf(int);} namespaceN{ extern"C"{ voidf(){}//Warning(noterror)ing++mode } } intmain(){f(1);}

ThisexampleisacceptedbytheC++compiler,butitwillemittwoconflictingdeclarationsforthefunctionf. • Whenausing−directivelookupencountersmorethanoneextern"C"declaration(createdwhenmorethanone namespacedeclaresanextern"C"functionofagivenname,asdescribedabove),onlythefirstdeclarationencountered isconsideredforthelookup. extern"C"intf(void); extern"C"intg(void); namespaceN{ extern"C"intf(void);//sametype extern"C"voidg(void);//differenttype }; usingnamespaceN; inti=f();//calls::f intj=g();//calls::f • Thedefinitionofamemberofaclasstemplatethatappearsoutsideoftheclassdefinitionmaydeclareanontypetemplate parameterwithatypethatisdifferentthanthetypeusedinthedefinitionoftheclasstemplate.Awarningisissued(GNU version30300andbelow). templatestructA{voidf();}; templatevoidA::f(){} • Aclasstemplatemayberedeclaredwithanontypetemplateparameterthathasatypethatisdifferentthanthetypeusedin theearlierdeclaration.Awarningisissued. templateclassA; templateclassA{};

2−9 NiosIIEmbeddedToolsReference

• Afrienddeclarationmayrefertoamembertypedef. classA{ classB{}; typedefBmy_b; friendclassmy_b; }; • Whenafriendclassisdeclaredwithanunqualifiedname,thelookupofthatnameisnotrestrictedtothenearestenclosing namespacescope. structS; namespaceN{ classC{ friendstructS;//::Sing++mode, //N::Sindefaultmode }; } • Afriendclassdeclarationcanrefertonamesmadevisiblebyusing−directives. namespaceN{structA{};} usingnamespaceN; structB{ voidf(){Aa;} friendstructA;//ing++modeN::A, };//notanewdeclarationof::A • Aninheritedtypenamecanbeusedinaclassdefinitionandlaterredeclaredasatypedef. structA{typedefintI;}; structB:A{ typedefIJ;//ReferstoA::I typedefdoubleI;//Accepteding++mode };//(introducesB::I) • Inacatchclause,anentitymaybedeclaredwiththesamenameasthehandlerparameter. try{} catch(inte){ chare; } • Thediagnosticissuedforanexceptionspecificationmismatchisreducedtoawarningifthepreviousdeclarationwasfound inasystemheader. • Theexceptionspecificationforanexplicittemplatespecialization(forafunctionormemberfunction)doesnothavetomatch theexceptionspecificationofthecorrespondingprimarytemplate. • Atemplateargumentlistmayappearfollowingaconstructornameinconstructordefinitionthatappearsoutsideoftheclass definition: templatestructA{ A(); }; templateA::A(){} • Whengnu_version<30400,anincompletetypecanbeusedasthetypeofanonstaticdatamemberofaclasstemplate. classB; templatestructA{ Bb; };

2−10 C++Language

• Aconstructorneednotprovideaninitializerforeverynonstaticconstdatamember(butawarningisstillissuedifsuchan initializerismissing). structS{ intconstic; S(){}//WarningonlyinGNUC++mode //(errorotherwise). }; • Exceptionspecificationsareignoredonfunctiondefinitionswhensupportforexceptionhandlingisdisabled(normally,they areonlyignoredonfunctiondeclarationsthataren’tdefinitions). • Afrienddeclarationinaclasstemplatemayrefertoanundeclaredtemplate. templatestructA{ friendvoidf<>(A); }; • Whengnu_versionis<30400,thesemanticanalysisofafriendfunctiondefinedinaclasstemplateisperformedonlyifthe functionisactuallyusedandisdoneattheendofthetranslationunit(insteadofatthepointoffirstuse). • Afunctiontemplatedefaultargumentmayberedeclared.Awarningisissuedandthedefaultfromtheinitialdeclarationis used. templatevoidf(inti=1); templatevoidf(inti=2){} intmain(){ f(); } • Adefinitionofamemberfunctionofaclasstemplatethatappearsoutsideoftheclassmayspecifyadefaultargument. templatestructA{voidf(T);}; templatevoidA::f(Tvalue=T()){} • Functiondeclarations(thatarenotdefinitions)canhaveduplicateparameternames. voidf(inti,inti);//AcceptedinGNUC++mode • Defaultargumentsareretainedaspartofdeducedfunctiontypes. • Anamespacemembermayberedeclaredoutsideofitsnamespace. • Atemplatemayberedeclaredoutsideofitsclassornamespace. namespaceN{ template<typenameT>structS{}; } template<typenameT>structN::S; • Theinjectedclassnameofaclasstemplatecanbeusedasatemplatetemplateargument. templateclassT>structA{}; templatestructB{ Aa; }; • Apartialspecializationmaybedeclaredafteraninstantiationhasbeendonethatwouldhaveusedthepartialspecialization ifithadbeendeclaredearlier.Awarningisissued. templateclassX{}; Xxi; templateclassX{}; • The"."or"−>"operatormaybeusedinanintegralconstantexpressioniftheresultisanintegralorenumerationconstant: structA{enum{e1=1};}; intmain(){ Aa; intx[a.e1];//AcceptedinGNUC++mode return0; }

2−11 NiosIIEmbeddedToolsReference

• Strongusing−directivesaresupported. usingnamespacedebug__attribute__((strong)); • Partialspecializationsthatareunusablebecauseofnondeductibletemplateparametersareacceptedandignored. templatestructA{classC{};}; templatestructB{enum{e=1};}; templatestructB::C>{enum{e=2};}; intmain(intargc,char**argv){ printf("%d\n",B::e); printf("%d\n",B::C>::e); } • Templateparametersthatarenotusedinthesignatureofafunctiontemplatearenotignoredforpartialorderingpurposes (i.e.,theresolutionofcorelanguageissue214isnotimplemented)whengnu_versionis<40100. templatevoidf(Tt); templatevoidf(Tt); intmain(){ f(3);//notambiguouswhengnu_version //is<40100 } • Prototypeinstantiationsoffunctionsaredeferreduntilthefirstactualinstantiationofthefunctiontoallowthecompilationof programsthatcontaindefinitionsofunusablefunctiontemplates(gnu_version30400andabove).Theexamplebelowis acceptedwhenprototypeinstantiationsaredeferred. classA{}; templatestructB{ B(){};//error:noinitializerfor //referencemember"B::a" A&a; }; • Whendoingnonclassprototypeinstantiations(e.g.,gnu_version30400andabove),theseverityofthediagnosticissuedifa consttemplatestaticdatamemberisdefinedwithoutaninitializerisreducedtoawarning. templatestructA{ staticconstinti; }; templateconstintA::i; • Whendoingnonclassprototypeinstantiations(e.g.,gnu_version30400andabove),atemplatestaticdatamemberwithan invalidaggregateinitializerisaccepted(theerrorisdiagnosedifthestaticdatamemberisinstantiated). structA{ A(doubleval); }; templatestructB{ staticconstAI[1]; }; templateconstAB::I[1]={ {1.,0.,0.,0.} };

ThefollowingGNUextensionsarenotcurrentlysupported: • Theforwarddeclarationoffunctionparameters(sotheycanparticipateinvariable−lengtharrayparameters). • GNU−stylecomplexintegraltypes(complexfloating−pointtypesaresupported) • Nestedfunctions

2−12 C++Language

2.5 NamespaceSupport

Namespacesareenabledbydefault.Youcanusethecommandlineoption−−no−namespacestodisablethefeatures. Whendoingnamelookupinatemplateinstantiation,somenamesmustbefoundinthecontextofthetemplatedefinitionwhile othersmayalsobefoundinthecontextofthetemplateinstantiation.TheC++compilerimplementstwodifferentinstantiation lookupalgorithms:theonemandatedbythestandard(referredtoas"dependentnamelookup"),andtheonethatexistedbefore dependentnamelookupwasimplemented. Dependentnamelookupisdoneinstrictmode(unlessexplicitlydisabledbyanothercommandlineoption)orwhendependent nameprocessingisenabledbyeitheraconfigurationflagorcommandlineoption.

DependentNameProcessing Whendoingdependentnamelookup,theC++compilerimplementstheinstantiationnamelookuprulesspecifiedinthe standard.Thisprocessingrequiresthatnon−classprototypeinstantiationsbedone.Thisinturnrequiresthatthecodebewritten usingthetypenameandtemplatekeywordsasrequiredbythestandard.

LookupUsingtheReferencingContext Whennotusingdependentnamelookup,theC++compilerusesanamelookupalgorithmthatapproximatesthetwo−phaselookup ruleofthestandard,butdoessoinsuchawaythatismorecompatiblewithexistingcodeandexistingcompilers. Whenanameislookedupaspartofatemplateinstantiationbutisnotfoundinthelocalcontextoftheinstantiation,itislooked upinasynthesizedinstantiationcontextthatincludesbothnamesfromthecontextofthetemplatedefinitionandnamesfrom thecontextoftheinstantiation.Here’sanexample: namespaceN{ intg(int); intx=0; templatestructA{ Tf(Tt){returng(t);} Tf(){returnx;} }; } namespaceM{ intx=99; doubleg(double); N::Aai; inti=ai.f(0);//N::A::f(int)calls //N::g(int) inti2=ai.f();//N::A::f()returns //0(=N::x) N::Aad; doubled=ad.f(0);//N::A::f(double) //callsM::g(double) doubled2=ad.f();//N::A::f()also //returns0(=N::x) }

Thelookupofnamesintemplateinstantiationsdoesnotconformtotherulesinthestandardinthefollowingrespects: • Althoughonlynamesfromthetemplatedefinitioncontextareconsideredfornamesthatarenotfunctions,thelookupisnot limitedtothosenamesvisibleatthepointatwhichthetemplatewasdefined. • Functionsfromthecontextinwhichthetemplatewasreferencedareconsideredforallfunctioncallsinthetemplate. Functionsfromthereferencingcontextshouldonlybevisiblefor"dependent"functioncalls. ArgumentDependentLookup Whenargument−dependentlookupisenabled(thisisthedefault),functionsmadevisibleusingargument−dependentlookup overloadwiththosemadevisiblebynormallookup.Thestandardrequiresthatthisoverloadingoccursevenwhenthename foundbynormallookupisablockexterndeclaration.TheC++compilerdoesthisoverloading,butindefaultmode, argument−dependentlookupissuppressedwhenthenormallookupfindsablockextern.

2−13 NiosIIEmbeddedToolsReference

Thismeansaprogramcanhavedifferentbehavior,dependingonwhetheritiscompiledwithorwithoutargument−dependent lookup−−no−arg−dep−lookup,eveniftheprogrammakesnouseofnamespaces.Forexample: structA{}; Aoperator+(A,double); voidf(){ Aa1; Aoperator+(A,int); a1+1.0;//callsoperator+(A,double) //witharg−dependentlookupenabledbut //otherwisecallsoperator+(A,int); }

2.6 TemplateInstantiation

TheC++languageincludestheconceptoftemplates.Atemplateisadescriptionofaclassorfunctionthatisamodelfora familyofrelatedclassesorfunctions.1Forexample,onecanwriteatemplateforaStackclass,andthenuseastackof integers,astackoffloats,andastackofsomeuser−definedtype.Inthesource,thesemightbewrittenStack, Stack,andStack.Fromasinglesourcedescriptionofthetemplateforastack,thecompilercancreate instantiationsofthetemplateforeachofthetypesrequired. Theinstantiationofaclasstemplateisalwaysdoneassoonasitisneededinacompilation.However,theinstantiationsof templatefunctions,memberfunctionsoftemplateclasses,andstaticdatamembersoftemplateclasses(hereafterreferredtoas templateentities)arenotnecessarilydoneimmediately,forseveralreasons: • Onewouldliketoendupwithonlyonecopyofeachinstantiatedentityacrossalltheobjectfilesthatmakeupaprogram. (Thisofcourseappliestoentitieswithexternallinkage.) • Thelanguageallowsonetowriteaspecializationofatemplateentity,i.e.,aspecificversiontobeusedinplaceofaversion generatedfromthetemplateforaspecificdatatype.(Onecould,forexample,writeaversionofStack,orofjust Stack::push,thatreplacesthetemplate−generatedversion;often,suchaspecializationprovidesamoreefficient representationforaparticulardatatype.)Sincethecompilercannotknow,whencompilingareferencetoatemplateentity,if aspecializationforthatentitywillbeprovidedinanothercompilation,itcannotdotheinstantiationautomaticallyinany sourcefilethatreferencesit. • C++templatescanbeexported(i.e.,declaredwiththekeywordexport).Suchtemplatescanbeusedinatranslationunit thatdoesnotcontainthedefinitionofthetemplatetoinstantiate.Theinstantiationofsuchatemplatemustbedelayeduntil thetemplatedefinitionhasbeenfound. • Thelanguagealsodictatesthattemplatefunctionsthatarenotreferencedshouldnotbecompiled,that,infact,such functionsmightcontainsemanticerrorsthatwouldpreventthemfrombeingcompiled.Therefore,areferencetoatemplate classshouldnotautomaticallyinstantiateallthememberfunctionsofthatclass. (Itshouldbenotedthatcertaintemplateentitiesarealwaysinstantiatedwhenused,e.g.,inlinefunctions.) Fromtheserequirements,onecanseethatifthecompilerisresponsiblefordoingalltheinstantiationsautomatically,itcanonly dosoonaprogram−widebasis.Thatis,thecompilercannotmakedecisionsaboutinstantiationoftemplateentitiesuntilithas seenallthesourcefilesthatmakeupacompleteprogram. ThisC++compilerprovidesaninstantiationmechanismthatdoesautomaticinstantiationatlinktime.Forcaseswhereyouwant moreexplicitcontroloverinstantiation,theC++compileralsoprovidesinstantiationmodesandinstantiationpragmas,whichcan beusedtoexertfine−grainedcontrolovertheinstantiationprocess.

2.6.1 AutomaticInstantiation

Thegoalofanautomaticinstantiationmodeistoprovidepainlessinstantiation.Youshouldbeabletocompilesourcefilesto objectcode,thenlinkthemandruntheresultingprogram,andneverhavetoworryabouthowthenecessaryinstantiationsget done. Inpractice,thisishardforacompilertodo,anddifferentcompilersusedifferentautomaticinstantiationschemeswithdifferent strengthsandweaknesses:

1Sincetemplatesaredescriptionsofentities(typically,classes)thatareparameterizableaccordingtothe typestheyoperateupon,theyaresometimescalledparameterizedtypes.

2−14 C++Language

• AT&T/USL/Novell’scfrontproductsavesinformationabouteachfileitcompilesinaspecialdirectorycalledptrepository. Itinstantiatesnothingduringnormalcompilations.Atlinktime,itlooksforentitiesthatarereferencedbutnotdefined,and whosemanglednamesindicatethattheyaretemplateentities.Foreachsuchentity,itconsultstheptrepository informationtofindthefilecontainingthesourcefortheentity,anditdoesacompilationofthesourcetogenerateanobject filecontainingobjectcodeforthatentity.Thisobjectcodeforinstantiatedobjectsisthencombinedwiththe"normal"object codeinthelinkstep. Ifyouareusingcfrontyoumustfollowaparticularcodingconvention:alltemplatesmustbedeclaredin.hfiles,andforeach suchfiletheremustbeacorresponding.ccfilecontainingtheassociateddefinitions.Thecompilerisnevertoldaboutthe .ccfilesexplicitly;onedoesnot,forexample,compiletheminthenormalway.Thelinksteplooksforthemwhenandifit needsthem,anddoessobytakingthe.hfilenameandreplacingitssuffix.2 Thisschemehasthedisadvantagethatitdoesaseparatecompilationforeachinstantiatedfunction(or,atbest,one compilationforallthememberfunctionsofoneclass).Eventhoughthefunctionitselfisoftenquitesmall,itmustbe compiledalongwiththedeclarationsforthetypesonwhichtheinstantiationisbased,andthosedeclarationscaneasilyrun intomanythousandsoflines.Forlargesystems,thesecompilationscantakeaverylongtime.Thelinksteptriestobesmart aboutrecompilinginstantiationsonlywhennecessary,butbecauseitkeepsnofine−graineddependencyinformation,itis oftenforcedto"recompiletheworld"foraminorchangeina.hfile.Inaddition,cfronthasnowayofensuringthat preprocessingsymbolsaresetcorrectlywhenitdoestheseinstantiationcompilations,ifpreprocessingsymbolsaresetother thanonthecommandline. • Borland’sC++compilerinstantiateseverythingreferencedinacompilation,thenusesaspeciallinkertoremoveduplicate definitionsofinstantiatedfunctions. IfyouareusingBorland’scompileryoumustmakesurethateverycompilationseesallthesourcecodeitneedsto instantiateallthetemplateentitiesreferencedinthatcompilation.Thatis,onecannotrefertoatemplateentityinasource fileifadefinitionforthatentityisnotincludedbythatsourcefile.Inpractice,thismeansthateitherallthedefinitioncodeis putdirectlyinthe.hfiles,orthateach.hfileincludesanassociated.cc(actually,.cpp)file. Ourapproachisalittledifferent.Itrequiresthat,foreachinstantiationofanon−exportedtemplate,thereissome(normal, top−level,explicitly−compiled)sourcefilethatcontainsthedefinitionofthetemplateentity,areferencethatcausesthe instantiation,andthedeclarationsofanytypesrequiredfortheinstantiation.3Thisrequirementcanbemetinvariousways: • TheBorlandconvention:each.hfilethatdeclaresatemplateentityalsocontainseitherthedefinitionoftheentityor includesanotherfilecontainingthedefinition. • Implicitinclusion:whenthecompilerseesatemplatedeclarationina.hfileanddiscoversaneedtoinstantiatethatentity,it isgivenpermissiontogoofflookingforanassociateddefinitionfilehavingthesamebasenameandadifferentsuffix,andit implicitlyincludesthatfileattheendofthecompilation.Thismethodallowsmostprogramswrittenusingthecfront conventiontobecompiledwithourapproach.Seesection2.6.4,ImplicitInclusion. • Theadhocapproach:youmakesurethatthefilesthatdefinetemplateentitiesalsohavethedefinitionsofalltheavailable types,andaddcodeorpragmasinthosefilestorequestinstantiationoftheentitiesthere. Exportedtemplatesarealsosupportedbyourautomaticinstantiationmethod,buttheyrequireadditionalmechanismsexplained furtheron. Theautomaticinstantiationmodeisenabledbydefault.Itcanbeturnedoffbythecommandlineoption −−no−auto−instantiation.Ifautomaticinstantiationisturnedoff,theextrainformationabouttemplateentitiesthatcouldbe instantiatedinafileisnotputintotheobjectfile.

2.6.2 InstantiationModes

Normally,whenafileiscompiled,templateentitiesareinstantiatedeverywherewheretheyareused.Theoverallinstantiation modecan,however,bechangedbyacommandlineoption: −−instantiate=used Instantiatethosetemplateentitiesthatwereusedinthecompilation.Thiswillincludeallstaticdatamembersforwhichthere aretemplatedefinitions.Thisisthedefault.

2Theactualimplementationallowsforseveraldifferentsuffixesandprovidesacommandlineoptionto changethesuffixessought. 3Isn’tthisalwaysthecase?No.SupposethatfileAcontainsadefinitionofclassXandareferenceto Stack::push,andthatfileBcontainsthedefinitionforthememberfunctionpush.Therewouldbeno filecontainingboththedefinitionofpushandthedefinitionofX. 2−15 NiosIIEmbeddedToolsReference

−−instantiate=all Instantiatealltemplateentitiesdeclaredorreferencedinthecompilationunit.Foreachfullyinstantiatedtemplateclass,allof itsmemberfunctionsandstaticdatamemberswillbeinstantiatedwhetherornottheywereused.Non−membertemplate functionswillbeinstantiatedeveniftheonlyreferencewasadeclaration. −−instantiate=local Similarto−−instantiate=usedexceptthatthefunctionsaregiveninternallinkage.Thisisintendedtoprovideaverysimple mechanismforthosegettingstartedwithtemplates.Thecompilerwillinstantiatethefunctionsthatareusedineach compilationunitaslocalfunctions,andtheprogramwilllinkandruncorrectly(barringproblemsduetomultiplecopiesof localstaticvariables.)However,onemayendupwithmanycopiesoftheinstantiatedfunctions,sothisisnotsuitablefor productionuse.−−instantiate=localcannotbeusedinconjunctionwithautomatictemplateinstantiation.Ifautomatic instantiationisenabledbydefault,itwillbedisabledbythe−−instantiate=localoption. Inthecasewherethecontrolprogramiscalledwithasinglefiletocompileandlink,e.g., ccniostest.cc thecompilerknowsthatallinstantiationswillhavetobedoneinthesinglesourcefile.Therefore,itusesthe −−instantiate=usedmodeandsuppressesautomaticinstantiation.

2.6.3 Instantiation#pragmaDirectives

Instantiationpragmascanbeusedtocontroltheinstantiationofspecifictemplateentitiesorsetsoftemplateentities.Thereare threeinstantiationpragmas: • Theinstantiatepragmacausesaspecifiedentitytobeinstantiated. • Thedo_not_instantiatepragmasuppressestheinstantiationofaspecifiedentity.Itistypicallyusedtosuppressthe instantiationofanentityforwhichaspecificdefinitionwillbesupplied. • Thecan_instantiatepragmaindicatesthataspecifiedentitycanbeinstantiatedinthecurrentcompilation,butneednotbe; itisusedinconjunctionwithautomaticinstantiation,toindicatepotentialsitesforinstantiationifthetemplateentityturnsout toberequired. Theargumenttotheinstantiationpragmamaybe: • atemplateclassname A • atemplateclassdeclaration classA • amemberfunctionname A::f • astaticdatamembername A::i • astaticdatadeclaration intA::i • amemberfunctiondeclaration voidA::f(int,char) • atemplatefunctiondeclaration char*f(int,float) Apragmainwhichtheargumentisatemplateclassname(e.g.,AorclassA)isequivalenttorepeatingthe pragmaforeachmemberfunctionandstaticdatamemberdeclaredintheclass.Wheninstantiatinganentireclassagiven memberfunctionorstaticdatamembermaybeexcludedusingthedo_not_instantiatepragma.Forexample, #pragmainstantiateA #pragmado_not_instantiateA::f

Thetemplatedefinitionofatemplateentitymustbepresentinthecompilationforaninstantiationtooccur.Ifaninstantiationis explicitlyrequestedbyuseoftheinstantiatepragmaandnotemplatedefinitionisavailableoraspecificdefinitionisprovided, anerrorisissued. templatevoidf1(T);//Nobodyprovided templatevoidg1(T);//Nobodyprovided

2−16 C++Language

voidf1(int){}//Specificdefinition voidmain() { inti; doubled; f1(i); f1(d); g1(i); g1(d); } #pragmainstantiatevoidf1(int)//error−specific //definition #pragmainstantiatevoidg1(int)//error−nobody //provided f1(double)andg1(double)willnotbeinstantiated(becausenobodiesweresupplied)butnoerrorswillbeproducedduring thecompilation(ifnobodiesaresuppliedatlinktime,alinkererrorwillbeproduced). Amemberfunctionname(e.g.,A::f)canonlybeusedasapragmaargumentifitreferstoasingleuserdefined memberfunction(i.e.,notanoverloadedfunction).Compiler−generatedfunctionsarenotconsidered,soanamemayrefertoa userdefinedconstructorevenifacompiler−generatedcopyconstructorofthesamenameexists.Overloadedmemberfunctions canbeinstantiatedbyprovidingthecompletememberfunctiondeclaration,asin #pragmainstantiatechar*A::f(int,char*)

Theargumenttoaninstantiationpragmamaynotbeacompiler−generatedfunction,aninlinefunction,orapurevirtualfunction.

2.6.4 ImplicitInclusion

Whenimplicitinclusionisenabled,theC++compilerisgivenpermissiontoassumethatifitneedsadefinitiontoinstantiatea templateentitydeclaredina.hfileitcanimplicitlyincludethecorresponding.ccfiletogetthesourcecodeforthedefinition. Forexample,ifatemplateentityABC::fisdeclaredinfilexyz.h,andaninstantiationofABC::fisrequiredinacompilation butnodefinitionofABC::fappearsinthesourcecodeprocessedbythecompilation,thecompilerwilllooktoseeifafile xyz.ccexists,andifsoitwillprocessitasifitwereincludedattheendofthemainsourcefile. TofindthetemplatedefinitionfileforagiventemplateentitytheC++compilerneedstoknowthepathnamespecifiedinthe originalincludeofthefileinwhichthetemplatewasdeclaredandwhetherthefilewasincludedusingthesystemincludesyntax (e.g.,#include).Thisinformationisnotavailableforpreprocessedsourcecontaining#linedirectives. Consequently,theC++compilerwillnotattemptimplicitinclusionforsourcecodecontaining#linedirectives. Thefiletobeimplicitlyincludedisfoundbyreplacingthefilesuffixwitheachofthesuffixesspecifiedintheinstantiationfilesuffix list.Thenormalincludesearchpathmechanismisthenusedtolookforthefiletobeimplicitlyincluded. Bydefault,thelistofdefinition−filesuffixestriedis.c,.cc,.cpp,and.cxx. Implicitinclusionworkswellalongsideautomaticinstantiation,butthetwoareindependent.Theycanbeenabledordisabled independently,andimplicitinclusionisstillusefulwhenautomaticinstantiationisnotdone. Theimplicitinclusionmodecanbeturnedonbythecommandlineoption−−implicit−include.Ifthisoptionisturnedon,you cannotuseexportedtemplates. Implicitinclusionsareonlyperformedduringthenormalcompilationofafile,(i.e.,notwhendoingonlypreprocessing).A commonmeansofinvestigatingcertainkindsofproblemsistoproduceapreprocessedsourcefilethatcanbeinspected.When usingimplicitinclusionitissometimesdesirableforthepreprocessedsourcefiletoincludeanyimplicitlyincludedfiles.Thismay bedoneusingthecommandlineoption−−no−preprocessing−only.Thiscausesthepreprocessedoutputtobegeneratedas partofanormalcompilation.Whenimplicitinclusionisbeingused,theimplicitlyincludedfileswillappearaspartofthe preprocessedoutputinthepreciselocationatwhichtheywereincludedinthecompilation.

2−17 NiosIIEmbeddedToolsReference

2.6.5 ExportedTemplates

Exportedtemplatesaretemplatesdeclaredwiththekeywordexport.Exportingaclasstemplateisequivalenttoexportingeach ofitsstaticdatamembersandeachofitsnon−inlinememberfunctions.Anexportedtemplateisspecialbecauseitsdefinition doesnotneedtobepresentinatranslationunitthatusesthattemplate.Inotherwords,thedefinitionofanexported(non−class) templatedoesnotneedtobeexplicitlyorimplicitlyincludedinatranslationunitthatinstantiatesthattemplate.Forexample,the followingisavalidC++programconsistingoftwoseparatetranslationunits: //File1: #include staticvoidtrace(){printf("File1\n");}

exporttemplateTconst&min(Tconst&,Tconst&); intmain() { trace(); returnmin(2,3); } //File2: #include staticvoidtrace(){printf("File2\n");}

exporttemplateTconst&min(Tconst&a,Tconst&b) { trace(); returna

Notethatthesetwofilesareseparatetranslationunits:oneisnotincludedintheother.Thatallowsthetwofunctionstrace() tocoexist(withinternallinkage). Supportforexportedtemplatesisenabledbydefault,butyoucanturnitoffwithcommandlineoption−−no−export. Youcannotuseexportedtemplatestogetherwiththecommandlineoption−−implicit−include.

2.6.5.1 FindingtheExportedTemplateDefinition

Theautomaticinstantiationofexportedtemplatesissomewhatsimilar(fromauser’sperspective)tothatofregular(included) templates.However,aninstantiationofanexportedtemplateinvolvesatleasttwotranslationunits:onewhichrequiresthe instantiation,andonewhichcontainsthetemplatedefinition. Whenafilecontainingdefinitionsofexportedtemplatesiscompiled,afilewitha.etsuffixiscreatedandsomeextra informationisincludedintheassociated.tifile.The.etfilesareusedlaterbytheC++compilertofindthetranslationunitthat definesagivenexportedtemplate. Whenafilethatpotentiallymakesuseofexportedtemplatesiscompiled,thecompilermustbetoldwheretolookfor.etfiles forexportedtemplatesusedbyagiventranslationunit.Bydefault,thecompilerlooksinthecurrentdirectory.Otherdirectories maybespecifiedwiththecommandlineoption−−template−directory.Strictlyspeaking,the.etfilesareonlyreallyneeded whenitcomestimetogenerateaninstantiation.Thismeansthatcodeusingexportedtemplatescanbecompiledwithouthaving thedefinitionsofthosetemplatesavailable.Thosedefinitionsmustbeavailablewhenexplicitinstantiationisdone. The.etfilesonlyinformtheC++compileraboutthelocationofexportedtemplatedefinitions;theydonotactuallycontainthose definitions.Thesourcescontainingtheexportedtemplatedefinitionsmustthereforebemadeavailableatthetimeof instantiation.Inparticular,theexportfacilityisnotamechanismforavoidingthepublicationoftemplatedefinitionsinsource form.

2−18 C++Language

2.6.5.2 SecondaryTranslationUnits Aninstantiationofanexportedtemplatecanbetriggeredbyanexplicitinstantiationdirective,orbythecommandlineoption −−instantiate=used.Ineachcase,thetranslationunitthatcontainstheinitialpointofinstantiationwillbeprocessedasthe primarytranslationunit.Basedoninformationitfindsinthe.etfiles,theC++compilerwillthenloadandparsethetranslation unitcontainingthedefinitionofthetemplatetoinstantiate.Thisisasecondarytranslationunit.Thesimultaneousprocessingof theprimaryandsecondarytranslationunitsenablestheC++compilertocreateinstantiationsoftheexportedtemplates(which canincludeentitiesfrombothtranslationunits).Thisprocessmayrevealtheneedforadditionalinstantiationsofexported templates,whichinturncancauseadditionalsecondarytranslationunitstobeloaded4. Whensecondarytranslationunitsareprocessed,thedeclarationstheycontainarecheckedforconsistency.Thisprocessmay reporterrorsthatwouldotherwisenotbecaught.Manytheseerrorsareso−called"ODRviolations"(ODRstandsfor "one−definitionrule").Forexample: //File1: structX{ intx; };

intmain(){ returnmin(2,3); } //File2: structX{ unsignedx;//Error:X::xdeclareddifferently //inFile1 };

exporttemplateTconst&min(Tconst&a,Tconst&b) { returna

Iftherearenoerrors,theinstantiationsaregeneratedintheoutputassociatedwiththeprimarytranslationunit.Thismayalso requirethatentitieswithinternallinkageinsecondarytranslationunitsbe"externalized"sotheycanbeaccessedfromthe instantiationsintheprimarytranslationunit.

2.6.5.3 LibrarieswithExportedTemplates

Typicallya(non−export)libraryconsistsofanincludedirectoryandalibdirectory.Theincludedirectorycontainsthe headerfilesrequiredbyusersofthelibraryandthelibdirectorycontainstheobjectcodelibrariesthatclientprogramsmust usewhenlinkingprograms. Withexportedtemplates,usersofthelibrarymustalsohaveaccesstothesourcecodeoftheexportedtemplatesandthe informationcontainedintheassociated.etfiles.Thisinformationshouldbeplacedinadirectorythatisdistributedalongwith theincludeandlibdirectories:Thisistheexportdirectory.Itmustbespecifiedusingthecommandlineoption −−template−directorywhencompilingclientprograms. Therecommendedproceduretobuildtheexportdirectoryisasfollows: 1. Foreach.etfileintheoriginalsourcedirectory,copytheassociatedsourcefiletotheexportdirectory. 2. Concatenateallofthe.etfilesintoasingle.etfile(e.g.,mylib.et)intheexportdirectory.Theindividual.etfiles couldbecopiedtotheexportdirectory,buthavingallofthe.etinformationinonefilewillmakeuseofthelibrarymore efficient. 3. Createanexport_infofileintheexportdirectory.Theexport_infofilespecifiestheincludesearchpathstobeused whenrecompilingfilesintheexportdirectory.Ifnoexport_infofileisprovided,theincludesearchpathusedwhen compilingtheclientprogramthatusesthelibrarywillalsobeusedtorecompilethelibraryexportedtemplatefiles.

4Asaconsequence,usingexportedtemplatesmayrequireconsiderablymorememorythatsimilarusesof regular(included)templates.

2−19 NiosIIEmbeddedToolsReference

Theexport_infofileconsistsofaseriesoflinesoftheform include=x or sys_include=x wherexisapathnametobeplacedontheincludesearchpath.Thedirectoriesaresearchedintheorderinwhichtheyare encounteredintheexport_infofile.Thefilecanalsocontaincomments,whichbeginwitha"#",andblanklines.Spacesare ignoredbuttabsarenotcurrentlypermitted.Forexample: #Theincludedirectoriestobeusedforthexyzlibrary

include=/disk1/xyz/include sys_include=/disk2/abc/include include=/disk3/jkl/include

TheincludesearchpathspecifiedforaclientprogramisignoredbytheC++compilerwhenitprocessesthesourceintheexport library,exceptwhennoexport_infofileisprovided.commandlinemacrodefinitionsspecifiedforaclientprogramarealso ignoredbytheC++compilerwhenprocessingasourcefilefromtheexportlibary;thecommandlinemacrosspecifiedwhenthe corresponding.etfilewasproduceddoapply.Allothercompilationoptions(otherthantheincludesearchpathandcommand linemacrodefinitions)usedwhenrecompilingtheexportedtemplateswillbeusedtocompiletheclientprogram. Whenalibraryisinstalledonanewsystem,itislikelythattheexport_infofilewillneedtobeadaptedtoreflectthelocation oftherequiredheadersonthatsystem.

2.7 InliningFunctions

TheC++compilersupportsaminimalformoffunctioninlining.WhentheC++compilerencountersacallofafunctiondeclared inlineitcanreplacethecallwiththebodyofthefunctionwiththeparametersreplacedbythecorrespondingarguments. Whenafunctioncalloccursasastatement,thestatementsofthefunctionbodyareinsertedinplaceofthecall.Whenthe functioncalloccurswithinanexpression,thebodyofthefunctionisrewrittenasonelargeexpressionandthatexpressionis insertedintheproperplaceinthecontainingexpression.Itisnotalwayspossibletodothissortofinlining:therearecertain constructs(e.g.loopsandinlineassembly)thatcannotberenderedinexpressionform.Evenwheninliningisdoneatthe statementlevel,therearecertainconstructsthatarenotpracticaltoinline.Callsthatcannotbeinlinedareleftintheiroriginal callform,andanout−of−linecopyofthefunctionisused.Whenenabled,aremarkisissued. Afunctionisdisqualifiedforinliningimmediatelyifanyofthefollowingaretrue: • Thefunctionhaslocalstaticvariables. • Thefunctionhaslocalconstants. • Thefunctionhaslocaltypes. • Thefunctionhasblockscopes. • Thefunctionincludespragmas. • Thefunctionhasavariableargumentlist.

2.8 ExternInlineFunctions

DependingonthewayinwhichtheC++compilerisconfigured,out−of−linecopiesofexterninlinefunctionsareeither implementedusingstaticfunctions,orareinstantiatedusingamechanismlikethetemplateinstantiationmechanism.Notethat out−of−linecopiesofinlinefunctionsareonlyrequiredincaseswherethefunctioncannotbeinlined,orwhentheaddressofthe functionistaken(whetherexplicitlybytheuser,byimplicitlygeneratedfunctions,orbycompiler−generateddatastructuressuch asvirtualfunctiontablesorexceptionhandlingtables). Whenstaticfunctionsareused,localstaticvariablesofthefunctionsarepromotedtoglobalvariableswithspeciallyencoded names,sothateventhoughtheremaybemultiplecopiesofthecode,thereisonlyonecopyofsuchglobalvariables.This mechanismdoesnotstrictlyconformtothestandardbecausetheaddressofanexterninlinefunctionisnotconstantacross translationunits.

2−20 C++Language

Whentheinstantiationmechanismisused,theaddressofanexterninlinefunctionisconstantacrosstranslationunits,butatthe costofrequiringtheuseofoneofthetemplateinstantiationmechanisms,evenforprogramsthatdon’tusetemplates. Definitionsofexterninlinefunctionscanbeprovidedeitherthroughuseoftheautomaticinstantiationmechanismorbyuseof the−−instantiate=usedor−−instantiate=allinstantiationmodes.Thereisnomechanismtomanuallycontrolthedefinitionof externinlinefunctionbodies.

2.9 PragmastoControltheC++Compiler

PragmasarekeywordsintheC++sourcethatcontrolthebehaviorofthecompiler.Pragmasoverrulecompileroptions. Thesyntaxis: #pragmapragma−spec

TheC++compilersupportsthefollowingpragmasandallCcompilerpragmasthataredescribedinsection1.5,Pragmasto ControltheCompiler. instantiate/do_not_instantiate/can_instantiate Thesearetemplateinstantiationpragmas.Theyaredescribedindetailinsection2.6.3,Instantiation#pragmaDirectives. hdrstop/no_pch Theseareprecompiledheaderpragmas.Theyaredescribedindetailinsection2.11,PrecompiledHeaders. once Whenplacedatthebeginningofaheaderfile,indicatesthatthefileiswritteninsuchawaythatincludingitseveraltimeshas thesameeffectasincludingitonce.Thus,iftheC++compilersees#pragmaonceatthestartofaheaderfile,itwillskipover itifthefileis#includedagain. Atypicalidiomistoplacean#ifndefguardaroundthebodyofthefile,witha#defineoftheguardvariableafterthe#ifndef: #pragmaonce//optional #ifndefFILE_H #defineFILE_H ...bodyoftheheaderfile... #endif

The#pragmaonceismarkedasoptionalinthisexample,becausetheC++compilerrecognizesthe#ifndefidiomanddoes theoptimizationeveninitsabsence.#pragmaonceisacceptedforcompatibilitywithothercompilersandtoallowthe programmertouseotherguard−codeidioms. ident Thispragmaisgivenintheform: #pragmaident"string" or #ident"string"

2−21 NiosIIEmbeddedToolsReference

2.10 PredefinedMacros

TheC++compilerdefinesanumberofpreprocessingmacros.Manyofthemareonlydefinedundercertaincircumstances.This sectiondescribesthemacrosthatareprovidedandthecircumstancesunderwhichtheyaredefined.

Macro Description __ABI_COMPATIBILITY_VERSION DefinestheABIcompatibilityversionbeingused.Thismacroissetto 9999,whichmeansthelatestversion.Thismacroisusedwhen buildingtheC++library. __ABI_CHANGES_FOR_RTTI ThismacroissettoTRUE,meaningthattheABIchangesforRTTI areimplemented.ThismacroisusedwhenbuildingtheC++library. __ABI_CHANGES_FOR_ARRAY_NEW_AND_DELETE ThismacroissettoTRUE,meaningthattheABIchangesforarray newanddeleteareimplemented.Thismacroisusedwhenbuilding theC++library. __ABI_CHANGES_FOR_PLACEMENT_DELETE ThismacroissettoTRUE,meaningthattheABIchangesfor placementdeleteareimplemented.Thismacroisusedwhen buildingtheC++library. __ARRAY_OPERATORS Definedwhenarraynewanddeleteareenabled.Thisisthe default. __BASE_FILE__ Similarto__FILE__butindicatestheprimarysourcefileratherthan thecurrentone(i.e.,whenthecurrentfileisanincludedfile). __BIG_ENDIAN__ Expandsto1ifbig−endianmodeisselected(−−endianness=big), otherwiseunrecognizedasmacro. _BOOL Definedwhenboolisakeyword.Thisisthedefault. __BUILD__ IdentifiesthebuildnumberoftheC++compiler,composedof decimaldigitsforthebuildnumber,threedigitsforthemajorbranch numberandthreedigitsfortheminorbranchnumber.Forexample,if youusebuild1.22.1ofthecompiler,__BUILD__expandsto 1022001.Ifthereisnobranchnumber,thebranchdigitsexpandto zero.Forexample,build127resultsin127000000. __CHAR_MIN/__CHAR_MAX Usedinlimits.htodefinetheminimum/maximumvalueofaplain charrespectively. __CPNIOS__ IdentifiestheC++compiler.Youcanusethissymboltoflagpartsof thesourcewhichmustberecognizedbytheC++compileronly.It expandsto1. __cplusplus Alwaysdefined. __CPU__ ExpandstoastringwiththeCPUsuppliedwiththeoption−−cpu. Whenno−−cpuissupplied,thissymbolisnotdefined. __DATE__ Definedtothedateofthecompilationintheform"Mmmddyyyy". __DELTA_TYPE Definesthetypeoftheoffsetfieldinthevirtualfunctiontable.This macroisusedwhenbuildingtheC++library. __DOUBLE_FP__ Expandsto1ifyoudidnotuseoption−−no−double(Treat’double’ as’float’),otherwiseunrecognizedasmacro. __embedded_cplusplus Definedas1inEmbeddedC++mode. __EXCEPTIONS Definedwhenexceptionhandlingisenabled(−−exceptions). __FILE__ Expandstothecurrentsourcefilename. __func__ Sameas__FUNCTION__inGNUmode. __IMPLICIT_USING_STD Definedwhenthestandardheaderfilesshouldimplicitlydoa using−directiveonthestdnamespace(−−using−std). __JMP_BUF_ELEMENT_TYPE Specifiesthetypeofanelementofthesetjmpbuffer.Thismacrois usedwhenbuildingtheC++library. __JMP_BUF_NUM_ELEMENTS Definesthenumberofelementsinthesetjmpbuffer.Thismacrois usedwhenbuildingtheC++library. __LINE__ Expandstothelinenumberofthelinewherethismacroiscalled.

2−22 C++Language

Macro Description __LITTLE_ENDIAN__ Expandsto1iflittle−endianmodeisselected(−−endianness=little), otherwiseunrecognizedasmacro.Thisisthedefault. __NAMESPACES Definedwhennamespacesaresupported(thisisthedefault,you candisablesupportfornamespaceswith−−no−namespaces). __NO_LONG_LONG Definedwhenthelonglongtypeisnotsupported.Thisisthe default. __NULL_EH_REGION_NUMBER Definesthevalueusedasthenullregionnumbervalueinthe exceptionhandlingtables.ThismacroisusedwhenbuildingtheC++ library. __PLACEMENT_DELETE Definedwhenplacementdeleteisenabled. __PRETTY_FUNCTION__ Definedtothenameofthecurrentfunction.Thisincludesthereturn typeandparametertypesofthefunction.Anerrorisissuedifitis usedoutsideofafunction. __PTRDIFF_MIN/__PTRDIFF_MAX Usedinstdint.htodefinetheminimum/maximumvalueofa ptrdiff_ttyperespectively. __REGION_NUMBER_TYPE Definesthetypeofaregionnumberfieldintheexceptionhandling tables.ThismacroisusedwhenbuildingtheC++library. __REVISION__ ExpandstotherevisionnumberoftheC++compiler.Digitsare representedastheyare;characters(forprototypes,alphas,betas) arerepresentedby−1.Examples:v1.0r1−>1,v1.0rb−>−1 __RTTI DefinedwhenRTTIisenabled(−−rtti). __RUNTIME_USES_NAMESPACES Definedwhentherun−timeusesnamespaces. __SIGNED_CHARS__ Definedwhenplaincharissigned. __SINGLE_FP__ Expandsto1ifyouusedoption−−no−double(Treat’double’as ’float’),otherwiseunrecognizedasmacro. __SIZE_MIN/__SIZE_MAX Usedinstdint.htodefinetheminimum/maximumvalueofa size_ttyperespectively. __STDC__ Alwaysdefined,butthevaluemayberedefined. __STDC_VERSION__ IdentifiestheISO−Cversionnumber.Expandsto199901LforISO C99,butthevaluemayberedefined. _STLP_NO_IOSTREAMS Definedwhenoption−−io−streamsisnotused.ThisdisablesI/O streamfunctionsintheSTLportC++library. __TASKING__ AlwaysdefinedfortheTASKINGC++compiler. __TIME__ Expandstothecompilationtime:"hh:mm:ss" __TYPE_TRAITS_ENABLED Definedwhentypetraitspseudo−functions(toeasethe implementationofISO/IECTR19768;e.g.,__is_union)are enabled.ThisisthedefaultinC++mode. __VAR_HANDLE_TYPE Definesthetypeofthevariable−handlefieldintheexception handlingtables.ThismacroisusedwhenbuildingtheC++library. __VERSION__ IdentifiestheversionnumberoftheC++compiler.Forexample,if youuseversion2.1r1ofthecompiler,__VERSION__expandsto 2001(dotandrevisionnumberareomitted,minorversionnumberin 3digits). __VIRTUAL_FUNCTION_INDEX_TYPE Definesthetypeofthevirtualfunctionindexfieldofthevirtual functiontable.ThismacroisusedwhenbuildingtheC++library. __VIRTUAL_FUNCTION_TYPE Definesthetypeofthevirtualfunctionfieldofthevirtualfunction table.ThismacroisusedwhenbuildingtheC++library. __WCHAR_MIN/__WCHAR_MAX Usedinstdint.htodefinetheminimum/maximumvalueofa wchar_ttyperespectively. _WCHAR_T Definedwhenwchar_tisakeyword.

Table2−1:Predefinedmacros

2−23 NiosIIEmbeddedToolsReference

2.11 PrecompiledHeaders

Itisoftendesirabletoavoidrecompilingasetofheaderfiles,especiallywhentheyintroducemanylinesofcodeandtheprimary sourcefilesthat#includethemarerelativelysmall.TheC++compilerprovidesamechanismfor,ineffect,takingasnapshot ofthestateofthecompilationataparticularpointandwritingittoadiskfilebeforecompletingthecompilation;then,when recompilingthesamesourcefileorcompilinganotherfilewiththesamesetofheaderfiles,itcanrecognizethe"snapshot point",verifythatthecorrespondingprecompiledheader(PCH)fileisreusable,andreaditbackin.Undertheright circumstances,thiscanproduceadramaticimprovementincompilationtime;thetrade−offisthatPCHfilescantakealotof diskspace.

2.11.1 AutomaticPrecompiledHeaderProcessing

When−−pchappearsonthecommandline,automaticprecompiledheaderprocessingisenabled.ThismeanstheC++ compilerwillautomaticallylookforaqualifyingprecompiledheaderfiletoreadinand/orwillcreateoneforuseonasubsequent compilation. ThePCHfilewillcontainasnapshotofallthecodeprecedingthe"headerstop"point.Theheaderstoppointistypicallythefirst tokenintheprimarysourcefilethatdoesnotbelongtoapreprocessingdirective,butitcanalsobespecifieddirectlyby #pragmahdrstop(seebelow)ifthatcomesfirst.Forexample: #include"xxx.h" #include"yyy.h" inti;

Theheaderstoppointisint(thefirstnon−preprocessortoken)andthePCHfilewillcontainasnapshotreflectingtheinclusion ofxxx.handyyy.h.Ifthefirstnon−preprocessortokenorthe#pragmahdrstopappearswithina#ifblock,theheader stoppointistheoutermostenclosing#if.Toillustrate,heresamorecomplicatedexample: #include"xxx.h" #ifndefYYY_H #defineYYY_H1 #include"yyy.h" #endif #ifTEST inti; #endif

Here,thefirsttokenthatdoesnotbelongtoapreprocessingdirectiveisagainint,buttheheaderstoppointisthestartofthe #ifblockcontainingit.ThePCHfilewillreflecttheinclusionofxxx.handconditionallythedefinitionofYYY_Handinclusionof yyy.h;itwillnotcontainthestateproducedby#ifTEST. APCHfilewillbeproducedonlyiftheheaderstoppointandthecodeprecedingit(mainly,theheaderfilesthemselves)meet certainrequirements: • Theheaderstoppointmustappearatfilescope−−itmaynotbewithinanunclosedscopeestablishedbyaheaderfile.For example,aPCHfilewillnotbecreatedinthiscase: //xxx.h classA{ //xxx.C #include"xxx.h" inti;}; • Theheaderstoppointmaynotbeinsideadeclarationstartedwithinaheaderfile,nor(inC++)mayitbepartofadeclaration listofalinkagespecification.Forexample,inthefollowingcasetheheaderstoppointisint,butsinceitisnotthestartofa newdeclaration,noPCHfilewillbecreated: //yyy.h static //yyy.C #include"yyy.h" inti; • Similarly,theheaderstoppointmaynotbeinsidea#ifblockora#definestartedwithinaheaderfile.

2−24 C++Language

• Theprocessingprecedingtheheaderstopmustnothaveproducedanyerrors.(Note:warningsandotherdiagnosticswill notbereproducedwhenthePCHfileisreused.) • Noreferencestopredefinedmacros__DATE__or__TIME__mayhaveappeared. • Nouseofthe#linepreprocessingdirectivemayhaveappeared. • #pragmano_pch(seebelow)mustnothaveappeared. • Thecodeprecedingtheheaderstoppointmusthaveintroducedasufficientnumberofdeclarationstojustifytheoverhead associatedwithprecompiledheaders.Theminimumnumberofdeclarationsrequiredis1. Whenthehostsystemdoesnotsupportmemorymapping,sothateverythingtobesavedintheprecompiledheaderfileis assignedtopreallocatedmemory(MS−Windows),twoadditionalrestrictionsapply: • Thetotalmemoryneededattheheaderstoppointcannotexceedthesizeoftheblockofpreallocatedmemory. • Nosingleprogramentitysavedcanexceed16384,thepreallocationunit. Whenaprecompiledheaderfileisproduced,itcontains,inadditiontothesnapshotofthecompilerstate,someinformationthat canbecheckedtodetermineunderwhatcircumstancesitcanbereused.Thisincludes: • Thecompilerversion,includingthedateandtimethecompilerwasbuilt. • Thecurrentdirectory(i.e.,thedirectoryinwhichthecompilationisoccurring). • Thecommandlineoptions. • Theinitialsequenceofpreprocessingdirectivesfromtheprimarysourcefile,including#includedirectives. • Thedateandtimeoftheheaderfilesspecifiedin#includedirectives. ThisinformationcomprisesthePCHprefix.Theprefixinformationofagivensourcefilecanbecomparedtotheprefix informationofaPCHfiletodeterminewhetherthelatterisapplicabletothecurrentcompilation. Asanillustration,considertwosourcefiles: //a.cc #include"xxx.h" ...//Startofcode //b.cc #include"xxx.h" ...//Startofcode

Whena.cciscompiledwith−−pch,aprecompiledheaderfilenameda.pchiscreated.Then,whenb.cciscompiled(or whena.ccisrecompiled),theprefixsectionofa.pchisreadinforcomparisonwiththecurrentsourcefile.Ifthecommandline optionsareidentical,ifxxx.hhasnotbeenmodified,andsoforth,then,insteadofopeningxxx.handprocessingitlinebyline, theC++compilerreadsintherestofa.pchandtherebyestablishesthestatefortherestofthecompilation. ItmaybethatmorethanonePCHfileisapplicabletoagivencompilation.Ifso,thelargest(i.e.,theonerepresentingthemost preprocessingdirectivesfromtheprimarysourcefile)isused.Forinstance,consideraprimarysourcefilethatbeginswith #include"xxx.h" #include"yyy.h" #include"zzz.h"

IfthereisonePCHfileforxxx.handasecondforxxx.handyyy.h,thelatterwillbeselected(assumingbothareapplicable tothecurrentcompilation).Moreover,afterthePCHfileforthefirsttwoheadersisreadinandthethirdiscompiled,anewPCH fileforallthreeheadersmaybecreated. Whenaprecompiledheaderfileiscreated,ittakesthenameoftheprimarysourcefile,withthesuffixreplacedbyan implementation−specifiedsuffix(pchbydefault).Unless−−pch−dirisspecified(seebelow),itiscreatedinthedirectoryofthe primarysourcefile. Whenaprecompiledheaderfileiscreatedorused,amessagesuchas "test.cc":creatingprecompiledheaderfile"test.pch" isissued.Theusermaysuppressthemessagebyusingthecommandlineoption−−no−pch−messages. Whentheoption−−pch−verboseisused,theC++compilerwilldisplayamessageforeachprecompiledheaderfilethatis consideredthatcannotbeusedgivingthereasonthatitcannotbeused.

2−25 NiosIIEmbeddedToolsReference

Inautomaticmode(i.e.,when−−pchisused)theC++compilerwilldeemaprecompiledheaderfileobsoleteanddeleteitunder thefollowingcircumstances: • iftheprecompiledheaderfileisbasedonatleastoneout−of−dateheaderfilebutisotherwiseapplicableforthecurrent compilation;or • iftheprecompiledheaderfilehasthesamebasenameasthesourcefilebeingcompiled(e.g.,xxx.pchandxxx.cc)butis notapplicableforthecurrentcompilation(e.g.,becauseofdifferentcommandlineoptions). Thishandlessomecommoncases;otherPCHfileclean−upmustbedealtwithbyothermeans(e.g.,bytheuser). Supportforprecompiledheaderprocessingisnotavailablewhenmultiplesourcefilesarespecifiedinasinglecompilation:an errorwillbeissuedandthecompilationabortedifthecommandlineincludesarequestforprecompiledheaderprocessingand specifiesmorethanoneprimarysourcefile.

2.11.2 ManualPrecompiledHeaderProcessing

Commandlineoption−−create−pch=filenamespecifiesthataprecompiledheaderfileofthespecifiednameshouldbecreated. Commandlineoption−−use−pch=filenamespecifiesthattheindicatedprecompiledheaderfileshouldbeusedforthis compilation;ifitisinvalid(i.e.,ifitsprefixdoesnotmatchtheprefixforthecurrentprimarysourcefile),awarningwillbeissued andthePCHfilewillnotbeused. Wheneitheroftheseoptionsisusedinconjunctionwith−−pch−dir,theindicatedfilename(whichmaybeapathname)is tackedontothedirectoryname,unlessthefilenameisanabsolutepathname. Theoptions−−create−pch,−−use−pch,and−−pchmaynotbeusedtogether.Ifmorethanoneoftheseoptionsisspecified, onlythelastonewillapply.Nevertheless,mostofthedescriptionofautomaticPCHprocessingappliestooneortheotherof thesemodes−−headerstoppointsaredeterminedthesameway,PCHfileapplicabilityisdeterminedthesameway,andso forth.

2.11.3 OtherWaystoControlPrecompiledHeaders

Thereareseveralwaysinwhichtheusercancontroland/ortunehowprecompiledheadersarecreatedandused. • #pragmahdrstopmaybeinsertedintheprimarysourcefileatapointpriortothefirsttokenthatdoesnotbelongtoa preprocessingdirective.Itenablesyoutospecifywherethesetofheaderfilessubjecttoprecompilationends.Forexample, #include"xxx.h" #include"yyy.h" #pragmahdrstop #include"zzz.h"

Here,theprecompiledheaderfilewillincludeprocessingstateforxxx.handyyy.hbutnotzzz.h.(Thisisusefulifthe userdecidesthattheinformationaddedbywhatfollowsthe#pragmahdrstopdoesnotjustifythecreationofanotherPCH file.) • #pragmano_pchmaybeusedtosuppressprecompiledheaderprocessingforagivensourcefile. • Commandlineoption−−pch−dir=directory−nameisusedtospecifythedirectoryinwhichtosearchforand/orcreateaPCH file. Moreover,whenthehostsystemdoesnotsupportmemorymappingandpreallocatedmemoryisusedinstead,thenoneofthe commandlineoptions−−pch,−−create−pch,or−−use−pch,ifitappearsatall,mustbethefirstoptiononthecommandline.

2.11.4 PerformanceIssues

Therelativeoverheadincurredinwritingoutandreadingbackinaprecompiledheaderfileisquitesmallforreasonablylarge headerfiles. Ingeneral,itdoesnotcostmuchtowriteaprecompiledheaderfileoutevenifitdoesnotendupbeingused,andifitisusedit almostalwaysproducesasignificantspeedupincompilation.Theproblemisthattheprecompiledheaderfilescanbequite large(fromaminimumofabout250Kbytestoseveralmegabytesormore),andsooneprobablydoesnotwantmanyofthem sittingaround.

2−26 C++Language

Thus,despitethefasterrecompilations,precompiledheaderprocessingisnotlikelytobejustifiedforanarbitrarysetoffileswith nonuniforminitialsequencesofpreprocessingdirectives.Rather,thegreatestbenefitoccurswhenanumberofsourcefilescan sharethesamePCHfile.Themoresharing,thelessdiskspaceisconsumed.Withsharing,thedisadvantageoflarge precompiledheaderfilescanbeminimized,withoutgivinguptheadvantageofasignificantspeedupincompilationtimes. Consequently,totakefulladvantageofheaderfileprecompilation,usersshouldexpecttoreorderthe#includesectionsof theirsourcefilesand/ortogroup#includedirectiveswithinacommonlyusedheaderfile. Belowisanexampleofhowthiscanbedone.Acommonidiomisthis: #include"comnfile.h" #pragmahdrstop #include... wherecomnfile.hpullsin,directlyandindirectly,afewdozenheaderfiles;the#pragmahdrstopisinsertedtogetbetter sharingwithfewerPCHfiles.ThePCHfileproducedforcomnfile.hcanbeabitoveramegabyteinsize.Anotheridiom,used bythesourcefilesinvolvedindeclarationprocessing,isthis: #include"comnfile.h" #include"decl_hdrs.h" #pragmahdrstop #include... decl_hdrs.hpullsinanotherdozenheaderfiles,andasecond,somewhatlarger,PCHfileiscreated.Inall,thesourcefilesof aparticularprogramcansharejustafewprecompiledheaderfiles.Ifdiskspacewereatapremium,youcoulddecidetomake comnfile.hpullinalltheheaderfilesused−−then,asinglePCHfilecouldbeusedinbuildingtheprogram. Differentenvironmentsanddifferentprojectswillhavedifferentneeds,butingeneral,usersshouldbeawarethatmakingthe bestuseoftheprecompiledheadersupportwillrequiresomeexperimentationandprobablysomeminorchangestosource code.

2−27 NiosIIEmbeddedToolsReference

2−28 3 Libraries

Summary ThischapterlistsalllibraryfunctionsthatyoucancallinyourCsource.

3.1 Introduction

ThischaptercontainsanoverviewofalllibraryfunctionsthatyoucancallinyourCsource.Thisincludesallfunctionsofthe standardClibrary(ISOC99)andsomefunctionsofthefloating−pointlibrary. AnumberofstandardoperationswithinCaretoocomplextogenerateinlinecodefor(toomuchcode).Theseoperationsare implementedasrun−timelibraryfunctionstosavecode. Section3.2,LibraryFunctions,givesanoverviewofalllibraryfunctionsyoucanuse,groupedperheaderfile.Anumberof functionsdeclaredinwchar.hareparalleltofunctionsinotherheaderfiles.Thesearediscussedtogether.

CLibrary

Libraries Description cnios.lib Clibrary(somefunctionsalsoneedthefloating−pointlibrary) cniosm.lib d=supportforDIVinstructions cniosmdx.lib m=supportforMULinstructions cniosmx.lib x=supportforMULXinstructions cnioss.lib SingleprecisionClibrary cniosms.lib (somefunctionsalsoneedthefloating−pointlibrary) cniosmdxs.lib cniosmxs.lib fpnios.lib Floating−pointlibrary fpniosm.lib fpniosmdx.lib fpniosmx.lib rtnios.lib Run−timelibrary rtniosm.lib rtniosmdx.lib rtniosmx.lib pbnios*.lib Profilinglibraries:pb=block/functioncounter pcnios*.lib pc=callgraph pctnios*.lib pct=callgraphandtiming pdnios*.lib pd=dummy ptnios*.lib pt=functiontiming

Table3−1:Overviewoflibraries

C++Library TheTASKINGC++compilersupportstheSTLportC++libraries.STLportisamultiplatformISOC++StandardLibrary implementation.Itisafree,open−sourceproduct,whichisdeliveredwiththeTASKINGC++compiler.Thelibrarysupports standardtemplatesandI/Ostreams. TheincludefilesfortheSTLportC++librariesarepresentindirectoryinclude.stlrelativetotheproductinstallationdirectory. YoucanfindmoreinformationontheSTLportlibraryonthefollowingsite:http://stlport.sourgeforge.net/ Alsoreadthelicenseagreementonhttp://stlport.sourgeforge.net/License.shtml.Thislicenseagreementisapplicabletothe STLportC++libraryonly.AllotherproductcomponentsfallundertheTASKINGlicenseagreement.

3−1 NiosIIEmbeddedToolsReference

ForanSTLProgrammer’sGuideyoucanseehttp://www.sgi.com/tech/stl/index.html. ThefollowingC++librariesaredeliveredwiththeproduct:

Libraries Description cpnios*[s][e].lib C++libraries s=singleprecisionfloating−point e=exceptionhandling stlnios*[s][e].lib STLportC++libraries

3−2 Libraries

3.2 LibraryFunctions

Thefollowingsectionslistalllibraryfunctions,groupedperheaderfileinwhichtheyaredeclared.Somefunctionsarenot completelyimplementedbecausetheirimplementationdependsonthecontextwhereyourapplicationwillrun.Thesefunctions areforexampleallI/Orelatedfunctions.Wherepossible,thesefunctionsareimplementedusingfilesystemsimulation(FSS). ThissystemcanbeusedbythedebuggertosimulateanI/Oenvironmentwhichenablesyoutodebugyourapplication. Anumberofwide−characterfunctionsareavailableasCsourcecode,buthavenotbeencompiledwiththeClibrary.Touse completewide−characterfunctionality,youmustrecompilethelibrarieswiththemacroWCHAR_SUPPORT_ENABLEDand keepthismacroalsodefinedwhencompilingyourownsources.(SeeCcompileroption−−define(−D)insection5.1,C CompilerOptions,inChapter5,Tooloptions.)

3.2.1 assert.h

assert(expr) PrintsadiagnosticmessageifNDEBUGisnotdefined. (Implementedasmacro)

3.2.2 complex.h

TheNiosIIdoesnotsupportcomplexnumbers.

3.2.3 ctype.handwctype.h

Theheaderfilectype.hdeclaresthefollowingfunctionswhichtakeacharactercasanintegertypeargument.Theheaderfile wctype.hdeclaresparallelwide−characterfunctionswhichtakeacharactercofthewchar_ttypeasargument.

ctype.h wctype.h Description isalnum iswalnum Returnsanon−zerovaluewhencisanalphabeticcharacteroranumber([A−Z][a−z][0−9]). isalpha iswalpha Returnsanon−zerovaluewhencisanalphabeticcharacter([A−Z][a−z]). isblank iswblank Returnsanon−zerovaluewhencisablankcharacter(tab,space...) iscntrl iswcntrl Returnsanon−zerovaluewhencisacontrolcharacter. isdigit iswditit Returnsanon−zerovaluewhencisanumericcharacter([0−9]). isgraph iswgraph Returnsanon−zerovaluewhencisprintable,butnotaspace. islower iswlower Returnsanon−zerovaluewhencisalowercasecharacter([a−z]). isprint iswprint Returnsanon−zerovaluewhencisprintable,includingspaces. ispunct iswpunct Returnsanon−zerovaluewhencisapunctuationcharacter (suchas’.’,’,’,’!’). isspace iswspace Returnsanon−zerovaluewhencisaspacetypecharacter(space,tab,verticaltab, formfeed,linefeed,carriagereturn). isupper iswupper Returnsanon−zerovaluewhencisanuppercasecharacter([A−Z]). isxdigit iswxdigit Returnsanon−zerovaluewhencisahexadecimaldigit([0−9][A−F][a−f]). tolower towlower Returnscconvertedtoalowercasecharacterifitisanuppercasecharacter,otherwisecis returned. toupper towupper Returnscconvertedtoanuppercasecharacterifitisalowercasecharacter,otherwisecis returned. _tolower − Convertsctoalowercasecharacter,doesnotcheckifcreallyisanuppercasecharacter. Implementedasmacro.ThismacrofunctionisnotdefinedinISOC99. _toupper − Convertsctoanuppercasecharacter,doesnotcheckifcreallyisalowercasecharacter. Implementedasmacro.ThismacrofunctionisnotdefinedinISOC99. isascii Returnsanon−zerovaluewhencisintherangeof0and127. ThisfunctionisnotdefinedinISOC99. toascii ConvertsctoanASCIIvalue(striphighestbit). ThisfunctionisnotdefinedinISOC99.

3−3 NiosIIEmbeddedToolsReference

3.2.4 errno.h

interrno Externalvariablethatholdsimplementationdefinederrorcodes.

Thefollowingerrorcodesaredefinedasmacrosinerrno.h:

EPERM1Notowner ENOENT2Nosuchfileordirectory EINTR3Interruptedsystemcall EIO4I/Oerror EBADF5Badfilenumber EAGAIN6Nomoreprocesses ENOMEM7Notenoughcore EACCES8Permissiondenied EFAULT9Badaddress EEXIST10Fileexists ENOTDIR11Notadirectory EISDIR12Isadirectory EINVAL13Invalidargument ENFILE14Filetableoverflow EMFILE15Toomanyopenfiles ETXTBSY16Textfilebusy ENOSPC17Nospaceleftondevice ESPIPE18Illegalseek EROFS19Read−onlyfilesystem EPIPE20Brokenpipe ELOOP21Toomanylevelsofsymboliclinks ENAMETOOLONG22Filenametoolong Floating−pointerrors

EDOM23Argumenttoolarge ERANGE24Resulttoolarge Errorsreturnedbyprinff/scanf

ERR_FORMAT25Illegalformatstringforprintf/scanf ERR_NOFLOAT26Floating−pointnotsupported ERR_NOLONG27Longnotsupported ERR_NOPOINT28Pointersnotsupported Encodingerrorstoredinerrnobyfunctionslikefgetwc,getwc,mbrtowc,etc...

EILSEQ29Invalidorincompletemultibyteorwidecharacter ErrorssetbyRTOS

EILSEQ30Operationcanceled ENODEV31Nosuchdevice

3.2.5 fcntl.h

Thefilefcntl.hcontainsthefunctionopen(),whichcallsthelowlevelfunction_open(),anddefinitionsofflagsusedbythe lowlevelfunction_open().ThisheaderfileisnotdefinedinISOC99.

open Opensafileforreadingorwriting.Calls_open. (FSSimplementation)

3−4 Libraries

3.2.6 fenv.h

Containsmechanismstocontrolthefloating−pointenvironment.Thefunctionsinthisheaderfilearenotimplemented.

fegetenv Storesthecurrentfloating−pointenvironment.(Notimplemented) feholdexept Savesthecurrentfloating−pointenvironmentandinstallsanenvironmentthatignoresallfloating−point exceptions.(Notimplemented) fesetenv Restoresapreviouslysaved(fegetenvorfeholdexcept)floating−pointenvironment.(Notimplemented) feupdateenv Savesthecurrentlyraisedfloating−pointexceptions,restoresapreviouselysavedfloating−pointenvironĆ mentandfinallyraisesthesavedexceptions.(Notimplemented)

feclearexcept Clearsthecurrentexceptionstatusflagscorrespondingtotheflagsspecifiedintheargument.(NotimĆ plemented) fegetexceptflag Storesthecurrentsettingofthefloating−pointstatusflags.(Notimplemented) feraiseexcept Raisestheexceptionsrepresentedintheargument.Asaresult,otherexceptionsmayberaisedaswell. (Notimplemented) fesetexceptflag Setsthecurrentfloating−pointstatusflags.(Notimplemented) fetestexcept Returnsthebitwise−ORoftheexceptionmacroscorrespondingtotheexceptionflagswhicharecurrentĆ lysetandarespecifiedintheargument.(Notimplemented)

Foreachsupportedexception,amacroisdefined.Thefollowingexceptionsaredefined:

FE_DIVBYZERO FE_INEXACT FE_INVALID FE_OVERFLOW FE_UNDERFLOWFE_ALL_EXCEPT

fegetround Returnsthecurrentroundingdirection,representedasoneofthevaluesoftheroundingdirectionmacĆ ros.(Notimplemented) fesetround Setsthecurrentroundingdirections.(Notimplemented)

Currentlynoroundingmodemacrosareimplemented.

3.2.7 float.h

Theheaderfilefloat.hdefinesthecharacteristicsoftherealfloating−pointtypesfloat,doubleandlongdouble.

Float.husedtocontainprototypesforthefunctionscopysign(f),isinf(f),isfinite(f),isnan(f)andscalb(f). ThesefunctionshaveaccordinglytotheISOC99standardbeenmovedtotheheaderfilemath.h.Seealsosection 3.2.15,math.handtgmath.h.

3.2.8 fss.h

Theheaderfilefss.hcontainsdefinitionsforthedebugger’sfilesystemsimulation(FSS).ThisheaderfileisnotdefinedinISO C99.

fss.h Description _fss_break(void) Bufferandbreakpointfunctionsforthedebugger.

_fss_init(fd,is_close) Opensfiledescriptors0(stdin),1(stdout)and2(stderr)andassociatesthemwithterminal windowFSS0ofthedebugger.

3−5 NiosIIEmbeddedToolsReference

3.2.9 inttypes.handstdint.h

Theheaderfilesstdint.handinttypes.hprovideadditionaldeclarationsforintegertypesandhavevariouscharacteristics. Thestdint.hheaderfilecontainsbasicdefinitionsofintegertypesofcertainsizes,andcorrespondingsetsofmacros.This headerfileclearlyreferstothecorrespondingsectionsintheISOC99standard. Theinttypes.hheaderfileincludesstdint.handaddsportableformattingandconversionfunctions.Belowtheconversion functionsfrominttypes.harelisted.

intmax_timaxabs(intmax_tj); Returnstheabsolutevalueofj imaxdiv_timaxdiv(intmax_tnumer, Computesnumer/denomandnumer%denom.Theresultisstoredinthequot intmax_tdenom); andremcomponentsoftheimaxdiv_tstructuretype. intmax_tstrtoimax(constchar* Convertstringtomaximumsizedinteger.(Comparestrtol) restrictnptr,char**restrict endptr,intbase); uintmax_tstrtoumax(constchar* Convertstringtomaximumsizedunsignedinteger.(Comparestrtoul) restrictnptr,char**restrict endptr,intbase); intmax_twcstoimax(constwchar_t Convertwidestringtomaximumsizedinteger.(Comparewctol) *restrictnptr,wchar_t**reĆ strictendptr,intbase); uintmax_twcstoumax(constwchar_t Convertwidestringtomaximemsizedunsignedinteger.(Comparewctoul) *restrictnptr,wchar_t**reĆ strictendptr,intbase);

3.2.10 io.h

Theheaderfileio.hcontainsdefinitionsandprototypesforlowlevelI/Ofunctions.Thisheaderfileisnotdefinedin ISO/IEC9899.

_close(fd) Usedbythefunctionscloseandfclose. (FSSimplementation) _lseek(fd,offset,whence) Usedbyallfilepositioningfunctions:fgetpos,fseek,fsetpos,ftell,rewind.(FSSimpleĆ mentation) _open(fd,flags) Usedbythefunctionsfopenandfreopen. (FSSimplementation) _read(fd,*buff,cnt) Readsasequenceofcharactersfromafile. (FSSimplementation) _unlink(*name) Usedbythefunctionremove. (FSSimplementation) _write(fd,*buffer,cnt) Writesasequenceofcharacterstoafile. (FSSimplementation)

3.2.11 iso646.h

Theheaderfileiso646.haddstokensthatcanbeusedinsteadofregularoperatortokens. #defineand&& #defineand_eq&= #definebitand& #definebitor| #definecompl~ #definenot! #definenot_eq!= #defineor|| #defineor_eq|= #definexor^ #definexor_eq^=

3−6 Libraries

3.2.12 limits.h

Containsthesizesofintegraltypes,definedasmacros.

3.2.13 locale.h

TokeepCcodereasonableportableaccrossdifferentlanguagesandcultures,anumberoffacilitiesareprovidedintheheader filelocal.h. char*setlocale(intcategory,constchar*locale)

Thefunctionabovechangeslocale−specificfeaturesoftherun−timelibraryasspecifiedbythecategorytochangeandthe nameofthelocale. Thefollowingcategoriesaredefinedandcanbeusedasinputforthisfunction: LC_ALL0 LC_NUMERIC3 LC_COLLATE1 LC_TIME4 LC_CTYPE2 LC_MONETARY5 structlconv*localeconv(void)

Returnsapointertotypestuctlconvwithvaluesappropriatefortheformattingofnumericquantitiesaccordingtothe rulesofthecurrentlocale.ThestructlconvinthisheaderfileisconformingtheISOstandard.

3.2.14 malloc.h

Theheaderfilemalloc.hcontainsprototypesformemoryallocationfunctions.ThisincludefileisnotdefinedinISOC99,itis includedforbackwardscompatibilitywithISOC90.ForISOC99,thememoryallocationfunctionsarepartofstdlib.h.See section3.2.23,stdlib.handwchar.h.

malloc(size) Allocatesspaceforanobjectwithsizesize.Theallocatedspaceisnotinitialized.ReturnsapointĆ ertotheallocatedspace. calloc(nobj,size) Allocatesspacefornobjectswithsizesize.Theallocatedspaceisinitializedwithzeros.Returns apointertotheallocatedspace. free(*ptr) Deallocatesthememoryspacepointedtobyptrwhichshouldbeapointerearlierreturnedbythe mallocorcallocfunction. realloc(*ptr,size) Deallocatestheoldobjectpointedtobyptrandreturnsapointertoanewobjectwithsizesize, whilepreservingitscontents.Ifthenewsizeissmallerthantheoldsize,somecontentsatthe endoftheoldregionwillbediscarded.Ifthenewsizeislargerthantheoldsize,alloftheold contentsarepreservedandanybytesinthenewobjectbeyondthesizeoftheoldobjectwillhave indeterminatevalues.

3.2.15 math.handtgmath.h

Theheaderfilemath.hcontainstheprototypesformanymathematicalfunctions.BeforeISOC99,allfunctionswerecomputed usingthedoubletype(thefloatwasautomaticallyconvertedtodouble,priortocalculation).InthisISOC99version,parallelsets offunctionsaredefinedfordouble,floatandlongdouble.Theyarerespectivelynamedfunction,functionf,functionl.Alllong typefunctions,thoughdeclaredinmath.h,areimplementedasthedoubletypevariantwhichnearlyalwaysmeetsthe requirementinembeddedapplications. Theheaderfiletgmath.hcontainsparalleltypegenericmathmacroswhoseexpansiondependsontheusedtype.tgmath.h includesmath.handtheeffectofexpansionisthatthecorrectmath.hfunctionsarecalled.Thetypegenericmacro,if available,islistedinthesecondcolumnofthetablesbelow.

Trigonometricandhyperbolicfunctions

math.h tgmath.h Description sin sinf sinl sin Returnsthesineofx. cos cosf cosl cos Returnsthecosineofx. tan tanf tanl tan Returnsthetangentofx. asin asinf asinl asin Returnsthearcsinesin−1(x)ofx.

3−7 NiosIIEmbeddedToolsReference

math.htgmath.h Description acos acosf acosl acos Returnsthearccosinecos−1(x)ofx. atan atanf atanl atan Returnsthearctangenttan−1(x)ofx. atan2 atan2f atan2l atan2 Returnstheresultof:tan−1(y/x). sinh sinhf sinhl sinh Returnsthehyperbolicsineofx. cosh coshf coshl cosh Returnsthehyperboliccosineofx. tanh tanhf tanhl tanh Returnsthehyperbolictangentofx. asinh asinhf asinhl asinh Returnsthearchyperbolicsinusofx. acosh acoshf acoshl acosh Returnsthenon−negativearchyperboliccosinusofx. atanh atanhf atanhl atanh Returnsthearchyperbolictangentofx.

Exponentialandlogarithmicfunctions AllofthesefunctionsarenewinISOC99,exceptforexp,logandlog10.

math.h tgmath.h Description exp expf expl exp Returnstheresultoftheexponentialfunctionex. exp2 exp2f exp2l exp2 Returnstheresultoftheexponentialfunction2x. (Notimplemented) expm1 expm1f expm1l expm1 Returnstheresultoftheexponentialfunctionex−1 (Notimplemented) log logf logl log Returns thenaturallogarithmln(x),x>0. log10 log10f log10l log10 Returnsthebase−10logarithmofx,x>0. log1p log1pf log1pl log1p Returnsthebase−elogarithmof(1+x).x<>−1. (Notimplemented) log2 log2f log2l log2 Returnsthebase−2logarithmofx.x>0. (Notimplemented) ilogbilogbf ilogbl ilogb Returnsthesignedexponentofxasaninteger.x>0. (Notimplemented) logb logbf logbl logb Returnstheexponentofxasasignedintegerinvalueinfloating−pointnotation.x >0. (Notimplemented) frexp,ldexp,modf,scalbn,scalbln

math.h tgmath.h Description frexp frexpl frexpf frexp Splitsafloatxintofractionfandexponentn,sothat: f=0.0or0.5≤|f|≤1.0andf*2n=x.Returnsf,storesn. ldexp ldexpl ldexpf ldexp Inverseoffrexp.Returnstheresultofx*2n. (xandnarebotharguments). modf modfl modff − Splitsafloatxintofractionfandintegern,sothat: |f|<1.0andf+n=x.Returnsf,storesn. scalbn scalbnl scalbnf scalbn Computestheresultofx*FLT_RADIXn.efficiently,notnormallybycomputing FLT_RADIXnexplicitly. scalbln scalblnl scalblnf scalbln Sameasscalbnbutwithargumentnaslongint.

3−8 Libraries

Roundingfunctions

math.h tgmath.h Description ceil ceilf ceill ceil Returnsthesmallestintegernotlessthanx,asadouble. floor floorf floorl floor Returnsthelargestintegernotgreaterthanx,asadouble. rint rintl rintf rint Returnstheroundedintegervalueasanintaccordingtothecurrentrounding direction.Seefenv.h.(Notimplemented) lrint lrintf lrintl lrint Returnstheroundedintegervalueasalongintaccordingtothecurrent roundingdirection.Seefenv.h.(Notimplemented) llrint lrintf lrintl llrint Returnstheroundedintegervalueasalonglongintaccordingtothe currentroundingdirection.Seefenv.h.(Notimplemented) nearbyintnearbyintf nearbyint Returnstheroundedintegervalueasafloating−pointaccordingtothecurrent nearbyintl roundingdirection.Seefenv.h.(Notimplemented) round roundl roundf round Returnsthenearestintegervalueofxasint.(Notimplemented) lround lroundl lroundf lround Returnsthenearestintegervalueofxaslongint.(Notimplemented) llround llroundl llroundf llround Returnsthenearestintegervalueofxaslonglongint.(Notimplemented) trunc truncl truncf trunc Returnsthetruncatedintegervaluex.(Notimplemented)

Remainderafterdevision

math.h tgmath.h Description fmod fmodl fmodf fmod Returnstheremainderrofx−ny.nischosenastrunc(x/y).rhasthesame signasx. remainderremainderl remainder Returnstheremainderrofx−ny.nischosenastrunc(x/y).rmaynothave remainderf thesamesignasx.(Notimplemented) remquo remquol remquof remquo Sameasremainder.Inaddition,theargument*quoisgivenaspecificvalue (seeISO).(Notimplemented)

Powerandabsolute−valuefunctions

math.h tgmath.h Description cbrt cbrtl cbrtf cbrt Returnstherealcuberootofx(=x1/3). (Notimplemented) fabs fabsl fabsf fabs Returnstheabsolutevalueofx(|x|).(abs,labs,llabs,div,ldiv,lldiv aredefinedinstdlib.h) fma fmal fmaf fma Floating−pointmultiplyadd.Returnsx*y+z. (Notimplemented) hypot hypotl hypotf hypot Returnsthesquarerootofx2+y2. pow powl powf power Returnsxraisedtothepowery(xy). sqrt sqrtl sqrtf sqrt Returnsthenon−negativesquarerootofx.x00.

Manipulationfunctions:copysign,nan,nextafter,nexttoward

math.h tgmath.h Description copysigncopysignl copysign Returnsthevalueofxwiththesignofy. copysignf nan nanl nanf − ReturnsaquietNaN,ifavailable,withcontentindcatedthroughtagp.(Not implemented) nextafternextafterl nextafter Returnsthenextrepresentablevalueinthespecifiedformatafterxinthe nextafterf directionofy.Returnsyisx=y.(Notimplemented) nexttowardnexttowardl nexttoward Sameasnextafter,exceptthatthesecondargumentinallthreevariantsis nexttowardf oftypelongdouble.Returnsyifx=y.(Notimplemented)

3−9 NiosIIEmbeddedToolsReference

Positivedifference,maximum,minimum

math.h tgmath.h Description fdim fdiml fdimf fdim Returnsthepositivedifferencebetween:|x−y|. (Notimplemented) fmax fmaxl fmaxf fmax Returnsthemaximumvalueoftheirarguments. (Notimplemented) fmin fminl fminf fmin Returnstheminimumvalueoftheirarguments. (Notimplemented)

Errorandgamma(Notimplemented)

math.h tgmath.h Description erf erfl erff erf Computestheerrorfunctionofx. (Notimplemented) erfc erfcl erfcf erc Computesthecomplementaryerrorfunctionofx. (Notimplemented)

lgamma lgammal lgammaf lgamma Computesthe*loge|Γ(x)| (Notimplemented) tgamma tgammal tgammaf tgamma ComputesΓ(x) (Notimplemented)

Comparisonmacros Thenextareimplementedasmacros.Foranyorderedpairofnumericvaluesexactlyoneoftherelationships−less,greater, andequal−istrue.Thesemacrosaretypegenericandtherefordonothaveaparallelfunctionintgmath.h.Allarguments mustbeexpressionsofreal−floatingtype.

math.h tgmath.h Description isgreater − Returnsthevalueof(x)>(y) isgreaterequal − Returnsthevalueof(x)>=(y) isless − Returnsthevalueof(x)<(y) islessequal − Returnsthevalueof(x)<=(y) islessgreater − Returnsthevalueof(x)<(y)||(x)>(y) isunordered − Returns1ifitsargumentsareunordered,0otherwise.

Classificationmacros Thenextareimplementedasmacros.Thesemacrosaretypegenericandtherefordonothaveaparallelfunctionintgmath.h. Allargumentsmustbeexpressionsofreal−floatingtype.

math.h tgmath.h Description fpclassify − Returnstheclassofitsargument: FP_INFINITE,FP_NAN,FP_NORMAL,FP_SUBNORMALorFP_ZERO isfinite − Returnsanonzerovalueifandonlyifitsargumenthasafinitevalue isinf − Returnsanonzerovalueifandonlyifitsargumenthasaninfinitvalue isnan − ReturnsanonzerovalueifandonlyifitsargumenthasNaNvalue. isnormal − Returnsanonzerovalueifanonlyifitsargumenthasanormalvalue. signbit − Returnsanonzerovalueifandonlyifitsargumentvalueisnegative.

3−10 Libraries

3.2.16 setjmp.h

Thesetjmpandlongjmpinthisheaderfileimplementaprimitiveformofnonlocaljumps,whichmaybeusedtohandle exceptionalsituations.Thisfacilityistraditionallyconsideredmoreportablethansignal.h.

intsetjmp(jmp_bufenv) Recordsitscaller’senvironmentinenvandreturns0. voidlongjmp(jmp_bufenv, Restorestheenvironmentpreviouslysavedwithacalltosetjmp(). intstatus)

3.2.17 signal.h

Signalsarepossibleasynchronouseventsthatmayrequirespecialprocessing.Eachsignalisnamedbyanumber.The followingsignalsaredefined: SIGINT1 Receiptofaninteractiveattentionsignal SIGILL2 Detectionofaninvalidfunctionmessage SIGFPE3 Anerrouneousarithmeticoperation(forexample,zerodevide,overflow) SIGSEGV4 Aninvalidaccesstostorage SIGTERM5 Aterminationrequestsenttotheprogram SIGABRT6 Abnormalterminiation,suchasisinitiatedbytheabortfunction. Thenextfunctionsendsthesignalsigtotheprogram:

intraise(intsig)

Thenextfunctiondetermineshowsubsequentsignalswillbehandled:

signalfunction*signal(int,signalfunction*);

Thefirstargumentspecifiesthesignal,thesecondargumentpointstothesignal−handlerfunctionorhasoneofthefollowing values: SIG_DFL Defaultbehaviourisused SIG_IGN Thesignalisignored Thefunctionreturnsthepreviousvalueofsignalfunctionforthespecificsignal,orSIG_ERRifanerroroccurs.

3.2.18 stdarg.h

Thefacilitiesinthisheaderfilegivesyouaportablewaytoaccessvariableargumentslists,suchasneededforasfprintf andvfprintf.va_copyisnewinISOC99.Thisheaderfilecontainsthefollowingmacros:

va_arg(ap,type) Returnsthevalueofthenextargumentinthevariableargumentlist.It’sreturntypehasthetype ofthegivenargumenttype.Anextcalltothismacrowillreturnthevalueofthenextargument. va_copy(va_listdest, Thismacroduplicatesthecurrentstateofsrcindest,creatingasecondpointerintothe va_listsrc) argumentlist.Afterthiscall,va_arg()maybeusedonsrcanddestindependently. va_end(va_listap) Thismacromustbecalledaftertheargumentshavebeenprocessed.Itshouldbecalledbefore thefunctionusingthemacro’va_start’isterminated(ANSIspecification). va_start(va_listap, Thismacroinitializesap.Afterthiscall,eachcalltova_arg()willreturnthevalueofthenext lastarg); argument.Inourimplementation,va_listcannotcontainanybittypevariables.Alsothe givenargumentlastargmustbethelastnon−bittypeargumentinthelist.

3.2.19 stdbool.h

Thisheaderfilecontainsthefollowingmacrodefinitions.ThesenamesforbooleantypeandvaluesareconsistentwithC++.You areallowedto#undefineorredefinethemacrosbelow. #definebool_Bool #definetrue1 #definefalse0 #define__bool_true_false_are_defined1

3−11 NiosIIEmbeddedToolsReference

3.2.20 stddef.h

Thisheaderfiledefinesthetypesforcommonuse:

ptrdiff_t signedintegertypeoftheresultofsubtractingtwopointers. size_t unsignedintegraltypeoftheresultofthesizeofoperator. wchar_t integertypetorepresentcharactercodesinlargecharactersets.

Besidesthesetypes,thefollowingmacrosaredefined:

NULL expandstothenullpointerconstant offsetof(_type,_member) expandstoanintegerconstantexpressionwithtypesize_tthatistheoffsetinbytesof _memberwithinstructuretype_type.

3.2.21 stdint.h

Seesection3.2.9,inttypes.handstdint.h

3.2.22 stdio.handwchar.h

Types Theheaderfilestdio.hcontainsfunctionsforperforminginputandoutput.Anumberoffunctionsalsohaveaparallelwide characterfunctionormacro,definedinwchar.h.Theheaderfilewchar.halsoincludesstdio.h. IntheClanguage,manyI/Ofacilitiesarebasedontheconceptofstreams.Thestdio.hheaderfiledefinesthedatatype FILEwhichholdstheinformationaboutastream.AnFILEobjectiscreatedwiththefunctionfopen.Thepointertothisobject isusedasanargumentinmanyoftheinthisheaderfile.TheFILEobjectcancontainthefollowinginformation: • thecurrentpositionwithinthestream • pointerstoanyassociatedbuffers • indicationsofforread/writeerrors • endoffileindication Theheaderfilealsodefinestypefpos_tasanunsignedlong.

Macros

stdio.h/wchar.h Description NULL expandstothenullpointerconstant BUFSIZ Sizeofthebufferusedbythesetbuf/setvbuffunction:512 EOF Endoffileindicator.Expandsto−1. WEOF Endoffileindicator.ExpandstoUINT_MAX(definedinlimits.h) NOTE:WEOFneednottobeanegativenumberaslongasitsvaluedoesnotcorrespondtoamember ofthewidecharacterset.(Definedinwchar.h). FOPEN_MAX Numberoffilesthatcanbeopenedsimultaneously:10 FILENAME_MAX Maximumlengthofafilename:100 _IOFBF Expandtoanintegerexpression,suitableforuseasargumenttothesetvbuffunction. _IOLBF _IONBF L_tmpnam Sizeofthestringusedtoholdtemporaryfilenames:8(tmpxxxxx) TMP_MAX Maximumnumberofuniquetemporaryfilenamesthatcanbegenerated:0x8000 SEEK_CUR Expandtoanintegerexpression,suitableforuseasthethirdargumenttothefseekfunction. SEEK_END SEEK_SET stderr Expressionsoftype"pointertoFILE"thatpointtotheFILEobjectsassociatedwithstandarderror,input stdin andoutputstreams. stdout

3−12 Libraries

Fileaccess

stdio.h Description fopen(name,mode) Opensafileforagivenmode.Availablemodesare: "r" read;opentextfileforreading "w" write;createtextfileforwriting;ifthefilealreadyexistsitscontentsisdiscarded "a" append;openexistingtextfileorcreatenewtextfileforwritingatendoffile "r+" opentextfileforupdate;readingandwriting "w+" createtextfileforupdate;previouscontentsifanyisdiscarded "a+" append;openorcreatetextfileforupdate,writesatendoffile fclose(name) Flushesthedatastreamandclosesthespecifiedfilethatwaspreviouslyopenedwith fopen. fflush(name) Ifstreamisanoutputstream,anybufferedbutunwrittendateiswritten.Else,theeffectis undefined. freopen(name,mode,stream) Similartofopen,butratherthengeneratinganewvalueoftypeFILE*,theexistingvalue isassociatedwithanewstream. setbuf(stream,buffer) IfbufferisNULL,bufferingisturnedoffforthestream. Otherwise,setbufisequivalentto: (void)setvbuf(stream,buf,_IOFBF,BUFSIZ). setvbuf(stream,buffer, Controlsbufferingforthestream;thisfunctionmustbecalledbeforereadingorwriting. mode,size) Modecanhavethefollowingvalues: _IOFBF causesfullbuffering _IOLBF causeslinebufferingoftextfiles _IONBF causesnobuffering IfbufferisnotNULL,itwillbeusedasabuffer;otherwiseabufferwillbeallocated.size determinesthebuffersize.

Characterinput/output

Theformatstringofprintfrelatedfunctionscancontainplaintextmixedwithconversionspecifiers.Eachconversion specifiershouldbeprecededbya’%’character.Theconversionspecifiershouldbebuildinorder: − Flags(inanyorder): − specifiesleftadjustmentoftheconvertedargument. + anumberisalwaysprecededwithasigncharacter. +hashigherprecedencethanspace. space anegativenumberisprecededwithasign,positivenumberswithaspace. 0 specifiespaddingtothefieldwidthwithzeros(onlyfornumbers). # specifiesanalternateoutputform.Foro,thefirstdigitwillbezero.ForxorX,"0x"and"0X"willbeprefixedtothe number.Fore,E,f,g,G,theoutputalwayscontainsadecimalpoint,trailingzerosarenotremoved. − Anumberspecifyingaminimumfieldwidth.Theconvertedargumentisprintedinafieldwithatleastthelengthspecified here.Iftheconvertedargumenthasfewercharactersthanspecified,itwillbepaddedattheleftside(orattherightwhenthe flag’−’wasspecified)withspaces.Paddingtonumericfieldswillbedonewithzeroswhentheflag’0’isalsospecified(only whenpaddingleft).Insteadofanumericvalue,also’*’maybespecified,thevalueisthentakenfromthenextargument, whichisassumedtobeoftypeint. − Aperiod.Thisseparatestheminimumfieldwidthfromtheprecision. − Anumberspecifyingthemaximumlengthofastringtobeprinted.Orthenumberofdigitsprintedafterthedecimalpoint (onlyforfloating−pointconversions).Ortheminimumnumberofdigitstobeprintedforanintegerconversion.Insteadofa numericvalue,also’*’maybespecified,thevalueisthentakenfromthenextargument,whichisassumedtobeoftype int. − Alengthmodifier’h’,’hh’,’l’,’ll’,’L’,’j’,’z’or’t’.’h’indicatesthattheargumentistobetreatedasashortorunsigned short.’hh’indicatesthattheargumentistobetreatedasacharorunsignedchar.’l’shouldbeusediftheargumentis alonginteger,’ll’foralonglong.’L’indicatesthattheargumentisalongdouble.’j’indicatesapointertointmax_t oruintmax_t,’z’indicatesapointertosize_tand’t’indicatesapointertoptrdiff_t.

3−13 NiosIIEmbeddedToolsReference

Flags,lengthspecifier,period,precisionandlengthmodifierareoptional,theconversioncharacterisnot.Theconversion charactermustbeoneofthefollowing,ifacharacterfollowing’%’isnotinthelist,thebehaviorisundefined.

Character Printedas d,i int,signeddecimal o int,unsignedoctal x,X int,unsignedhexadecimalinlowercaseoruppercaserespectively u int,unsigneddecimal c int,singlecharacter(convertedtounsignedchar) s char*,thecharactersfromthestringareprinteduntilaNULLcharacterisfound.Whenthegivenprecisionis metbefore,printingwillalsostop f double e,E double g,G double a,A double n int*,thenumberofcharacterswrittensofariswrittenintotheargument.ThisshouldbeapointertoaninteĆ gerindefaultmemory.Novalueisprinted. p pointer(hexadecimal24−bitvalue) % Noargumentisconverted,a’%’isprinted.

Table3−2:Printfconversioncharacters Allargumentstothescanfrelatedfunctionsshouldbepointerstovariables(indefaultmemory)ofthetypewhichisspecifiedin theformatstring. Theformatstringcancontain: − Blanksortabs,whichareskipped. − Normalcharacters(not’%’),whichshouldbematchedexactlyintheinputstream. − Conversionspecifications,startingwitha’%’character. Conversionspecificationsshouldbebuiltasfollows(inorder): − A’*’,meaningthatnoassignmentisdoneforthisfield. − Anumberspecifyingthemaximumfieldwidth. − Theconversioncharactersd,i,n,o,uandxmaybeprecededby’h’iftheargumentisapointertoshortratherthanint, orby’hh’iftheargumentisapointertochar,orby’l’(letterell)iftheargumentisapointertolong,orby’ll’forapointerto longlong,’j’forapointertointmax_toruintmax_t,’z’forapointertosize_tor’t’forapointertoptrdiff_t.The conversioncharacterse,f,andgmaybeprecededby’l’iftheargumentisapointertodoubleratherthanfloat,andby ’L’forapointertoalongdouble. − Aconversionspecifier.’*’,maximumfieldwidthandlengthmodifierareoptional,theconversioncharacterisnot.The conversioncharactermustbeoneofthefollowing,ifacharacterfollowing’%’isnotinthelist,thebehaviorisundefined. Lengthspecifierandlengthmodifierareoptional,theconversioncharacterisnot.Theconversioncharactermustbeoneofthe following,ifacharacterfollowing’%’isnotinthelist,thebehaviorisundefined.

Character Scannedas d int,signeddecimal. i int,theintegermaybegivenoctal(i.e.aleading0isentered)orhexadecimal(leading"0x"or"0X"),orjust decimal. o int,unsignedoctal. u int,unsigneddecimal. x int,unsignedhexadecimalinlowercaseoruppercase. c singlecharacter(convertedtounsignedchar). s char*,astringofnonwhitespacecharacters.Theargumentshouldpointtoanarrayofcharacters,large enoughtoholdthestringandaterminatingNULLcharacter.

3−14 Libraries

Character Scannedas f float e,E float g,G float a,A float n int*,thenumberofcharacterswrittensofariswrittenintotheargument.Noscanningisdone. p pointer;hexadecimal24−bitvaluewhichmustbeenteredwithout0x−prefix. [...] Matchesastringofinputcharactersfromthesetbetweenthebrackets.ANULLcharacterisaddedtotermiĆ natethestring.Specifying[]...]includesthe’]’characterinthesetofscanningcharacters. [^...] Matchesastringofinputcharactersnotinthesetbetweenthebrackets.ANULLcharacterisaddedtotermiĆ natethestring.Specifying[^]...]includesthe’]’characterintheset. % Literal’%’,noassignmentisdone.

Table3−3:Scanfconversioncharacters

stdio.h wchar.h Description fscanf(stream, fwscanf(stream, Performsaformattedreadfromthegivenstream.Returnsthenumberof format,...) format,...) itemsconvertedsuccesfully.(FSSimplementation) scanf(format,...) wscanf(format,...) Performsaformattedreadfromthestdinstream.Returnsthenumber ofitemsconvertedsuccesfully.(FSSimplementation) sscanf(*s, swscanf(*s, Performsaformattedreadfromthestrings.Returnsthenumberofitems format,...) format,...) convertedsuccesfully. vfscanf(stream, vfwscanf(stream, Sameasfscanf/fwscanf,butextraargumentsaregivenasvariable format,arg) format,arg) argumentlistarg. (Seesection3.2.18,stdarg.h) vscanf(format,arg) vwscanf(format,arg) Sameasscanf/wscanf,butextraargumentsaregivenasvariablearĆ gumentlistarg. (Seesection3.2.18,stdarg.h) vsscanf(s,format, vswscanf(s,format, Sameasscanf/wscanf,butextraargumentsaregivenasvariablearĆ arg) arg) gumentlistarg. (Seesection3.2.18,stdarg.h) fprintf(stream, fwprintf(stream, Performsaformattedwritetothegivenstream.ReturnsEOF/WEOFon format,...) format,...) error. (FSSimplementation) printf(format,...) wprintf(format,...) Performsaformattedwritetothestreamstdout.ReturnsEOF/WEOF onerror. (FSSimplementation) sprintf(*s, − Performsaformattedwritetostrings.ReturnsEOF/WEOFonerror. format,...) snprintf(*s,n swprintf(*s,n Sameassprintf,butnspecifiesthemaximumnumberofcharacters format,...) format,...) (includingtheterminatingnullcharacter)tobewritten. vfprintf(stream, vfwprintf(stream, Sameasfprintf/fwprintf,butextraargumentsaregivenasvariable format,arg) format,arg) argumentlistarg.(Seesection3.2.18,stdarg.h) (FSSimplementation) vprintf(format, vwprintf(format, Sameasprintf/wprintf,butextraargumentsaregivenasvariable arg) arg) argumentlistarg.(Seesection3.2.18,stdarg.h) (FSSimplementation) vsprintf(*s, vswprintf(*s, Sameassprintf/swprintf,butextraargumentsaregivenasvariable format,arg) format,arg) argumentlistarg.(Seesection3.2.18,stdarg.h) (FSSimplementation)

3−15 NiosIIEmbeddedToolsReference

Characterinput/output

stdio.h wchar.h Description fgetc(stream) fgetwc(stream) Readsonecharacterfromstream.Returnsthereadcharacter,orEOF/ WEOFonerror. (FSSimplementation) getc(stream) getwc(stream) Sameasfgetc/fgetwcexceptthatisimplementedasamacro.(FSS implementation) NOTE:Currently#definedasgetchar()/getwchar()becauseFILE I/Oisnotsupported.Returnsthereadcharacter,orEOF/WEOFonerror. getchar(stdin) getwchar(stdin) Readsonecharacterfromthestdinstream.Returnsthecharacterread orEOF/WEOFonerror.Implementedasmacro. (FSSimplementation) fgets(*s,n, fgetws(*s,n, Readsatmostthenextn−1charactersfromthestreamintoarraysuntil stream) stream) anewlineisfound.ReturnssorNULLorEOF/WEOFonerror. (FSSimplementation) gets(*s,n,stdin) − Readsatmostthenextn−1charactersfromthestdinstreamintoarray s.Anewlineisignored.ReturnssorNULLorEOF/WEOFonerror. (FSSimplementation) ungetc(c,stream) ungetwc(c,stream) Pushescharactercbackontotheinputstream.ReturnsEOF/WEOFon error. fputc(c,stream) fputwc(c,stream) Putcharactercontothegivenstream. ReturnsEOF/WEOFonerror. (FSSimplementation) putc(c,stream) putwc(c,stream) Sameasfpuc/fputwcexceptthatisimplementedasamacro.(FSS implementation) putchar(c,stdout) putwchar(c,stdout) Putcharactercontothestdoutstream. ReturnsEOF/WEOFonerror. Implementedasmacro.(FSSimplementation) fputs(*s,stream) fputws(*s,stream) Writesstringstothegivenstream. ReturnsEOF/WEOFonerror. puts(*s)− Writesstringstothestdoutstream. ReturnsEOF/WEOFonerror. (FSSimplementation)

Directinput/output

stdio.h Description fread(ptr,size,nobj,stream) Readsnobjmembersofsizebytesfromthegivenstreamintothearraypointedtoby ptr.Returnsthenumberofelementssuccesfullyread. (FSSimplementation) fwrite((ptr,size,nobj,stream) Writesnobjmembersofsizebytesfromtothearraypointedtobyptrtothegiven stream.Returnsthenumberofelementssuccesfullywritten. (FSSimplementation)

Randomaccess

stdio.h Description fseek(stream,offset, Setsthepositionindicatorforstream.(FSSimplementation) origin)

Whenrepositioningabinaryfile,thenewpositionoriginisgivenbythefollowingmacros:

SEEK_SET0 offsetcharactersfromthebeginningofthefile SEEK_CUR1 offsetcharactersfromthecurrentpositioninthefile SEEK_END2 offsetcharactersfromtheendofthefile

3−16 Libraries

ftell(stream) Returnsthecurrentfilepositionforstream,or−1Lonerror. (FSSimplementation) rewind(stream) Setsthefilepositionindicatorforthestreamtothebeginningofthefile.Thisfunctionis equivalentto: (void)fseek(stream,0L,SEEK_SET); clearerr(stream); (FSSimplementation) fgetpos(stream,pos) Storesthecurrentvalueofthefilepositionindicatorforstreamintheobjectpointedtoby pos. (FSSimplementation) fsetpos(stream,pos) Positionsstreamatthepositionrecordedbyfgetposin*pos. (FSSimplementation)

Operationsonfiles

stdio.h Description remove(file) Removesthenamedfile,sothatasubsequentattempttoopenitfails.Returnsanon−zero valueifnotsuccesful. rename(old,new) Changesthenameofthefilefromoldnametonewname.Returnsanon−zerovalueifnot succesful. tmpfile() Createsatemporaryfileofthemode"wb+"thatwillbeautomaticallyremovedwhen closedorwhentheprogramterminatesnormally.Returnsafilepointer. tmpnam(buffer) Createsnewfilenamesthatdonotconflictwithotherfilenamescurrentlyinuse.Thenew filenameisstoredinabufferwhichmusthaveroomforL_tmpnamcharacters.Returnsa pointertothetemporaryname.Thefilenamesarecreatedinthecurrentdirectoryandall startwith"tmp".AtmostTMP_MAXuniquefilenamescanbegenerated.

Errorhandling

stdio.h Description clearerr(stream) Clearstheendoffileanderrorindicatorsforstream. ferror(stream) Returnsanon−zerovalueiftheerrorindicatorforstreamisset. feof(stream) Returnsanon−zerovalueiftheendoffileindicatorforstreamisset. perror(*s) Printssandtheerrormessagebelongingtotheintegererrno. (Seesection3.2.4,errno.h)

3.2.23 stdlib.handwchar.h

Theheaderfilestdlib.hcontainsgeneralutilityfunctionswhichfallintothefollowingcategories(Somehaveparallel wide−character,declaredinwchar.h) • Numericconversions • Randomnumbergeneration • Memorymanagement • Envirnomentcommunication • Searchingandsorting • Integerarithmetic • Multibyte/widecharacterandstringconversions. Macros

EXIT_SUCCES0 Predefinedexitcodesthatcanbeusedintheexitfunction. EXIT_FAILURE1 RAND_MAX32767 Highestnumberthatcanbereturnedbytherand/srandfunction. MB_CUR_MAX1 Maximumnumberofbytesinamultibytecharacterfortheextendedcharactersetspecifiedbythe currentlocale(categoryLC_CTYPE,seesection3.2.13,locale.h).

3−17 NiosIIEmbeddedToolsReference

Numericconversions Thefollowingfunctionsconverttheintialportionofastring*stoadouble,int,longintandlonglongintvalue respectively.

doubleatof(*s) intatoi(*s) longatol(*s) longlongatoll(*s)

Thefollowingfunctionsconverttheinitialportionofthestring*stoafloat,doubleandlongdoublevaluerespectively.*endpwill pointtothefirstcharacternotusedbytheconversion.

stdlib.h wchar.h floatstrtof(*s,**endp) floatwcstof(*s,**endp) doublestrtod(*s,**endp) doublewcstod(*s,**endp) longdoublestrtold(*s,**endp) longdoublewcstold(*s,**endp)

Thefollowingfunctionsconverttheinitialportionofthestring*stoalong,longlong,unsignedlongandunsigned longlongrespectively.Basespecifiestheradix.*endpwillpointtothefirstcharacternotusedbytheconversion.

stdlib.h wchar.h longstrtol(*s,**endp,base) longwcstol(*s,**endp,base) longlongstrtoll(*s,**endp,base) longlongwcstoll(*s,**endp,base) unsignedlongstrtoul(*s,**endp,base) unsignedlongwcstoul(*s,**endp,base) unsignedlonglong unsignedlonglong strtoull(*s,**endp,base) wcstoull(*s,**endp,base)

Randomnumbergeneration

rand Returnsapseudorandomintegerintherange0toRAND_MAX. srand(seed) Sameasrandbutusesseedforanewsequenceofpseudorandomnumbers.

Memorymanagement

malloc(size) Allocatesspaceforanobjectwithsizesize.Theallocatedspaceisnotinitialized.Returnsa pointertotheallocatedspace. calloc(nobj,size) Allocatesspacefornobjectswithsizesize.Theallocatedspaceisinitializedwithzeros.Returns apointertotheallocatedspace. free(*ptr) Deallocatesthememoryspacepointedtobyptrwhichshouldbeapointerearlierreturnedbythe mallocorcallocfunction. realloc(*ptr,size) Deallocatestheoldobjectpointedtobyptrandreturnsapointertoanewobjectwithsizesize, whilepreservingitscontents.Ifthenewsizeissmallerthantheoldsize,somecontentsatthe endoftheoldregionwillbediscarded.Ifthenewsizeislargerthantheoldsize,alloftheold contentsarepreservedandanybytesinthenewobjectbeyondthesizeoftheoldobjectwillhave indeterminatevalues.

Environmentcommunication

abort() Causesabnormalprogramtermination.IfthesignalSIGABRTiscaught,thesignalhandlermay takeovercontrol.(Seesection3.2.17,signal.h). atexit(*func) Funcpointstoafunctionthatiscalled(withoutarguments)whentheprogramnormally terminates. exit(status) Causesnormalprogramtermination.Actsasifmain()returnswithstatusasthereturnvalue. StatuscanalsobespecifiedwiththepredefinedmacrosEXIT_SUCCESorEXIT_FAILURE. _Exit(status) Sameasexit,butnoregisteredbytheatexitfunctionorsignalhandlersregisterdbythe signalfunctionarecalled.

3−18 Libraries

getenv(*s) Searchesanenvironmentlistforastrings.Returnsapointertothecontentsofs. NOTE:thisfunctionisnotimplementedbecausethereisnoOS. system(*s) Passesthestringstotheenvironmentforexecution. NOTE:thisfunctionisnotimplementedbecausethereisnoOS.

Searchingandsorting

bsearch(*key,*base, Thisfunctionsearchesinanarrayofnmembers,fortheobjectpointedtobykey.Theinitialbase n,size,*cmp) ofthearrayisgivenbybase.Thesizeofeachmemberisspecifiedbysize.Thegivenarraymust besortedinascendingorder,accordingtotheresultsofthefunctionpointedtobycmp.Returnsa pointertothematchingmemberinthearray,orNULLwhennotfound. qsort(*base,n, Thisfunctionsortsanarrayofnmembersusingthequicksortalgorithm.Theinitialbaseofthe size,*cmp) arrayisgivenbybase.Thesizeofeachmemberisspecifiedbysize.ThearrayissortedinasĆ cendingorder,accordingtotheresultsofthefunctionpointedtobycmp.

Integerarithmetic

intabs(j) Computetheabsolutevalueofanint,longint,andlonglongintjresepectively. longlabs(j) longlongllabs(j) div_tdiv(x,y) Computex/yandx%yinasingleoperation.Xandyhaverespectivelytypeint,longintand ldiv_tldiv(x,y) longlongint.Theresultisstoredinthemembersquotandremofstructdiv_t, lldiv_tlldiv(x,y) ldiv_tandlldiv_twhichhavethesametypes.

Multibyte/widecharacterandstringconversions

mblen(*s,n) Determinesthenumberofbytesinthemulti−bytecharacterpointedtobys.Atmostncharacters willbeexamined.(Seealsombrleninsection3.2.27,wchar.h) mbtowc(*pwc,*s,n) Convertsthemulti−bytecharacterinstoawide−charactercodeandstoresitinpwc.Atmostn characterswillbeexamined. wctomb(*s,wc) Convertsthewide−characterwcintoamulti−byterepresentationandstoresitinthestringpointed tobys.AtmostMB_CUR_MAXcharactersarestored. mbstowcs(*pwcs,*s,n) Convertsasequenceofmulti−bytecharactersinthestringpointedtobysintoasequenceof widecharactersandstoresatmostnwidecharactersintothearraypointedtobypwcs.(Seealso mbsrtowcsinsection3.2.27,wchar.h) wcstombs(*s,*pwcs,n) Convertsasequenceofwidecharactersinthearraypointedtobypwcsintomulti−bytecharacĆ tersandstoresatmostnmulti−bytecharactersintothestringpointedtobys.(Seealso wcsrtowmbinsection3.2.27,wchar.h)

3.2.24 string.handwchar.h

Thisheaderfileprovidesnumerousfunctionsformanipulatingstrings.Byconvention,stringsinCarearraysofcharacterswitha terminatingnullcharacter.Mostfunctionsthereforetakeargumentsoftype*char.However,manyfunctionshavealsoparallel wide−characterfunctionswhichtakeargumentsoftype*wchar_t.Thesefunctionsaredeclaredinwchar.h.

Copyingandconcatenationfunctions

stdio.h wchar.h Description memcpy(*s1,*s2,n) wmemcpy(*s1,*s2,n) Copiesncharactersfrom*s2into*s1andreturns*s1.If*s1and*s2 overlaptheresultisundefined. memmove(*s1,*s2,n) wmemmove(*s1,*s2,n) Sameasmemcpy,butoverlappingstringsarehandledcorrectly.Returns *s1. strcpy(*s1,*s2) wcscpy(*s1,*s2) Copies*s2into*s1andreturns*s1.If*s1and*s2overlaptheresultis undefined. strncpy(*s1,*s2,n) wcsncpy(*s1,*s2,n) Copiesnotmorethanncharactersfrom*s2into*s1andreturns*s1.If *s1and*s2overlaptheresultisundefined.

3−19 NiosIIEmbeddedToolsReference

stdio.h wchar.h Description strcat(*s1,*s2) wcscat(*s1,*s2) Appendsacopyof*s2to*s1andreturns*s1.If*s1and*s2overlapthe resultisundefined. strncat(*s1,*s2,n) wcsncat(*s1,*s2,n) Appendsnotmorethanncharactersfrom*s2to*s1andreturns*s1.If *s1and*s2overlaptheresultisundefined.

Comparisonfunctions

stdio.h wchar.h Description memcmp(*s1,*s2,n) wmemcmp(*s1,*s2,n) Comparesthefirstncharactersof*s1tothefirstncharactersof*s2. Returns<0if*s1<*s2,0if*s1==*s2,or>0if*s1>*s2. strcmp(*s1,*s2) wcscmp(*s1,*s2) Comparesstring*s1tostring*s2.Returns<0if*s1<*s2,0if*s1== *s2,or>0if*s1>*s2. strncmp(*s1,*s2,n) wcsncmp(*s1,*s2,n) Comparesthefirstncharactersof*s1tothefirstncharactersof*s2. Returns<0if*s1<*s2,0if*s1==*s2,or>0if*s1>*s2. strcoll(*s1,*s2) wcscoll(*s1,*s2) Performsalocal−specificcomparisonbetweenstring*s1andstring*s2 accordingtotheLC_COLLATEcategoryofthecurrentlocale.Returns< 0if*s1<*s2,0if*s1==*s2,or>0if*s1>*s2.(Seesection3.2.13, locale.h) strxfrm(*s1,*s2,n) wcsxfrm(*s1,*s2,n) Transforms(alocal)string*s2sothatacomparisonbetween transformedstringswithstrcmpgivesthesameresultasacomparison betweennon−transformedstringswithstrcoll.Returnsthe transformedstring*s1.

Searchfunctions

stdio.h wchar.h Description memchr(*s,c,n) wmemchr(*s,c,n) Checksthefirstncharactersof*sontheoccurenceofcharacterc. Returnsapointertothefoundcharacter. strchr(*s,c) wcschr(*s,c) Returnsapointertothefirstoccurenceofcharactercinstring*sorthe nullpointerifnotfound. strrchr(*s,c) wcsrchr(*s,c) Returnsapointertothelastoccurenceofcharactercinstring*sorthe nullpointerifnotfound. strspn(*s,*set) wcsspn(*s,*set) Searches*sforasequenceofcharactersspecifiedin*set.Returnsthe lengthofthefirstsequencefound. strcspn(*s,*set) wcscspn(*s,*set) Searches*sforasequenceofcharactersnotspecifiedin*set.Returns thelengthofthefirstsequencefound. strpbrk(*s,*set) wcspbrk(*s,*set) Sameasstrspn/wcsspnbutreturnsapointertothefirstcharacterin*s thatalsoisspecifiedin*set. strstr(*s,*sub) wcsstr(*s,*sub) Searchesforasubstring*subin*s.Returnsapointertothefirst occurenceof*subin*s. strtok(*s,*delim) wcstok(*s,*delim) Asequenceofcallstothisfunctionbreaksthestring*sintoasequence oftokensdelimitedbyacharacterspecifiedin*delim.Thetokenfoundin *sisterminatedwithanullcharacter.Thefunctionreturnsapointertothe firstpositionin*softhetoken.

Miscellaneousfunctions

stdio.h wchar.h Description memset(*s,c,n) wmemset(*s,c,n) Fillsthefirstnbytesof*swithcharactercandreturns*s. strerror(errno)− Typically,thevaluesforerrnocomefrominterrno.ThisfunctionreĆ turnsapointertotheassociatederrormessage.(Seealsosection3.2.4, errno.h) strlen(*s) wcslen(*s) Returnsthelengthofstring*s.

3−20 Libraries

3.2.25 time.handwchar.h

Theheaderfiletime.hprovidesfacilitiestoretrieveandusethe(calendar)dateandtime,andtheprocesstime.Timecanbe representedasanintegervalue,orcanbebroken−downincomponents.Twoarithmeticdatatypesaredefinedwhichare capableofholdingtheintegerrepresentationoftimes: clock_t unsignedlonglong time_t unsignedlong

ThetypestructtmbelowisdefinedaccordingtoISO/IEC9899withoneexception:thisimplementationdoesnotsupportleap seconds.Thestructtmtypeisdefinesasfollows: structtm { inttm_sec;/*secondsaftertheminute−[0,59]*/ inttm_min;/*minutesafterthehour−[0,59]*/ inttm_hour;/*hourssincemidnight−[0,23]*/ inttm_mday;/*dayofthemonth−[1,31]*/ inttm_mon;/*monthssinceJanuary−[0,11]*/ inttm_year;/*yearsince1900*/ inttm_wday;/*dayssinceSunday−[0,6]*/ inttm_yday;/*dayssinceJanuary1−[0,365]*/ inttm_isdst;/*DaylightSavingTimeflag*/ };

Timemanipulation

clock Returnstheapplication’sbestapproximationtotheprocessortimeusedbytheprogramsinceitwas started.Thislow−levelroutineisnotimplementedbecauseitstronglydependsonthehardware.To determinethetimeinseconds,theresultofclockshouldbedividedbythevaluedefinedas CLOCKS_PER_SEC12000000 difftime(t1,t0) Returnsthedifferencet1−t0inseconds. mktime(tm*tp) Convertsthebroken−downtimeinthestructurepointedtobytp,toavalueoftypetime_t.The returnvaluehasthesameencodingasthereturnvalueofthetimefunction. time(*timer) Returnsthecurrentcalendartime.Thisvalueisalsoassignedto*timer.

Timeconversion

asctime(tm*tp) Convertsthebroken−downtimeinthestructurepointedtobytpintoastringintheformMonJan 2116:15:142004\n\0.Returnsapointertothisstring. ctime(*timer) Convertsthecalendertimepointedtobytimertolocaltimeintheformofastring.Thisisequivalent to:asctime(localtime(timer)) gmtime(*timer) Convertsthecalendertimepointedtobytimertothebroken−downtime,expressedasUTC. Returnsapointertothebroken−downtime. localtime(*timer) Convertsthecalendartimepointedtobytimertothebroken−downtime,expressedaslocaltime. Returnsapointertothebroken−downtime.

Formattedtime Thenextfunctionhasaparallelfunctiondefinedinwchar.h:

stdio.h wchar.h strftime(*s,smax,*fmt,tm*tp) wstrftime(*s,smax,*fmt,tm*tp)

Formatsdateandtimeinformationfromstructtm*tpinto*saccordingtothespecifiedformat*fmt.Nomorethansmax charactersareplacedinto*s.Theformattingofstrftimeislocale−specificusingtheLC_TIMEcategory(seesection3.2.13, locale.h).Youcanusethenextconversionspecifiers:

3−21 NiosIIEmbeddedToolsReference

%a abbreviatedweekdayname %A fullweekdayname %b abbreviatedmonthname %B fullmonthname %c localdateandtimerepresentation(sameas%a%b%e%T%Y) %C lasttwooftheyear %d dayofthemonth(01−31) %D sameas%m/%d/%y %e dayofthemonth(1−31),withsingledigitsprecededbyaspace %F ISO8601dateformat:%Y−%m−%d %g lasttwodigitsoftheweekbasedyear(00−99) %G weekbasedyear(0000˘9999) %h sameas%b %H hour,24−hourclock(00−23) %I hour,12−hourclock(01−12) %j dayoftheyear(001−366) %m month(01−12) %M minute(00−59) %n replacedbythenewlinecharacter %p localequivalentofAMorPM %r locale’s12−hourclocktime;sameas%I:%M:%S%p %R sameas%H:%M %S second(00−59) %t replacedbyhorizontaltabcharacter %T ISO8601timeformat:%H:%M:%S %u ISO8601weekdaynumber(1−7),Mondayasfirstdayoftheweek %U weeknumberoftheyear,Sundayasfirstdayoftheweek(00−53) %V ISO8601weeknumber(01−53)intheweek−basedyear %w weekday(0−6,Sundayis0) %W weeknumberoftheyear(00−53),week1hasthefirstMonday %x localdaterepresentation %X localtimerepresentation %y yearwithoutcentury(00−99) %Y yearwithcentury %z ISO8601offsetoftimezonefromUTC,ornothing %Z timezonename,ifany %% %

3.2.26 unistd.h

Thefileunistd.hcontainsstandardUNIXI/Ofunctions.Thesefunctionsareallimplementedusingthedebugger’sfilesystem simulation.Exceptforlstatandfstatwhicharenotimplemented.ThisheaderfileisnotdefinedinISOC99.

access(*name,mode) Usethefilesystemsimulationofthedebuggertocheckthepermissionsofafileonthehost.mode specifiesthetypeofaccessandisabitpatternconstructedbyalogicalORofthefollowingvalues: R_OK Checksreadpermission. W_OK Checkswritepermission. X_OK Checksexecute(search)permission. F_OK Checkstoseeifthefileexists. (FSSimplementation) chdir(*path) Usethefilesystemsimulationfeatureofthedebuggertochangethecurrentdirectoryonthehost tothedirectoryindicatedbypath. (FSSimplementation) close(fd) Fileclosefunction.Thegivenfiledescriptorshouldbeproperlyclosed.Thisfunctioncalls _close(). (FSSimplementation) getcwd(*buf,size) Usethefilesystemsimulationfeatureofthedebuggertoretrievethecurrentdirectoryonthehost. Returnsthedirectoryname. (FSSimplementation)

3−22 Libraries

lseek(fd,offset, Movesread−writefileoffset.Calls_lseek(). whence) (FSSimplementation) read(fd,*buff,cnt) Readsasequenceofcharactersfromafile.Thisfunctioncalls_read().(FSSimplementation) stat(*name,*buff) Usethefilesystemsimulationfeatureofthedebuggertostat()afileonthehostplatform. (FSSimplementation) lstat(*name,*buff) Thisfunctionisidenticaltostat(),exceptinthecaseofasymboliclink,wherethelinkitselfis ’stat’−ed,notthefilethatitrefersto. (Notimplemented) fstat(fd,*buff) Thisfunctionisidenticaltostat(),exceptthatitusesafiledescriptorinsteadofaname.(Not implemented)

unlink(*name) Removesthenamedfile,sothatasubsequentattempttoopenitfails.Calls_unlink(). (FSSimplementation) write(fd,*buff,cnt) Writeasequenceofcharacterstoafile.Calls_write(). (FSSimplementation)

3.2.27 wchar.h

Manyinwchar.hrepresentthewide−charactervariantofothersothesearediscussedtogether.(Seesections3.2.22,stdio.h andwchar.h,3.2.23,stdlib.handwchar.h,3.2.24,string.handwchar.hand3.2.25,time.handwchar.h). Theremainingaredescribedbelow.Theyperformconversionsbetweenmulti−bytecharactersandwidecharacters.Inthese,ps pointstostructmbstate_twhichholdstheconversionstateinformationnecessarytoconvertbetweensequencesofmultibyte charactersandwidecharacters: typedefstruct { wchar_twc_value;/*widecharactervaluesolvedsofar*/ unsignedshortn_bytes;/*numberofbytesofsolvedmultibyte*/ unsignedshortencoding;/*encodingruleforwidecharacter<=> multibyteconversion*/ }mbstate_t;

Whenmultibytecharacterslargerthan1byteareused,thisstructwillbeusedtostoretheconversioninformationwhennotall thebytesofaparticularmultibytecharacterhavebeenreadfromthesource.Inthisimplementation,multi−bytecharactersare1 bytelong(MB_CUR_MAXandMB_LEN_MAXaredefinedas1)andthiswillneveroccur.

mbsinit(*ps) Determineswhethertheobjectpointedtobyps,isaninitialconversionstate.Returns anon−zerovalueifso. mbsrtowcs(*pwcs,**src,n,*ps) Restartableversionofmbstowcs.Seesection3.2.23,stdlib.handwchar.h.Theinitial conversionstateisspecifiedbyps.Theinputsequenceofmultibytecharactersis specifiedindirectlybysrc. wcsrtombs(*s,**src,n,*ps) Restartableversionofwcstombs.Seesection3.2.23,stdlib.handwchar.h.Theinitial conversionstateisspecifiedbyps.Theinputwidestringisspecifiedindirectlybysrc. mbrtowc(*pwc,*s,n,*ps) Convertsamultibytecharacter*stoawidecharacter*pwcaccordingtoconversionstate ps.Seealsombtowcinsection3.2.23,stdlib.handwchar.h. wcrtomb(*s,wc,*ps) Convertsawidecharacterwctoamulti−bytecharacteraccordingtoconversionstate psandstoresthemulti−bytecharacterin*s. btowc(c) Returnsthewidecharactercorrespondingtocharacterc.ReturnsWEOFonerror. wctob(c) Returnsthemulti−bytecharactercorrespondingtothewidecharacterc.Thereturned multi−bytecharacterisrepresentedasonebyte.ReturnsEOFonerror. mbrlen(*s,n,*ps) Inspectsuptonbytesfromthestring*stoseeifthosecharactersrepresentvalid multibytecharacters,relativetotheconversionstateheldin*ps.

3−23 NiosIIEmbeddedToolsReference

3.2.28 wctype.h

Mostinwctype.hrepresentthewide−charactervariantofdeclaredinctype.handarediscussedinsection3.2.3,ctype.hand wctype.h.Inaddition,thisheaderfileprovidesextensible,localespecific,widecharacterclassification.

wctype(*property) Constructsavalueoftypewctype_tthatdescribesaclassofwidecharactersidentifiedbythe string*property.IfpropertyidentifiesavalidclassofwidecharactersaccordingtotheLC_TYPE category(seesection3.2.13,locale.h)ofthecurrentlocale,anon−zerovalueisreturnedthatcan beusedasanargumentintheiswctypefunction. iswctype(wc,desc) Testswhetherthewidecharacterwcisamemberoftheclassrepresentedbywctype_tdesc. Returnsanon−zerovalueiftestedtrue.

Function Equivalenttolocalespecifictest iswalnum(wc) iswctype(wc,wctype("alnum")) iswalpha(wc) iswctype(wc,wctype("alpha")) iswcntrl(wc) iswctype(wc,wctype("cntrl")) iswdigit(wc) iswctype(wc,wctype("digit")) iswgraph(wc) iswctype(wc,wctype("graph")) iswlower(wc) iswctype(wc,wctype("lower")) iswprint(wc) iswctype(wc,wctype("print")) iswpunct(wc) iswctype(wc,wctype("punct")) iswspace(wc) iswctype(wc,wctype("space")) iswupper(wc) iswctype(wc,wctype("upper")) iswxditig(wc) iswctype(wc,wctype("xdigit"))

wctrans(*property) Constructsavalueoftypewctype_tthatdescribesamappingbetweenwidecharactersidentiĆ fiedbythestring*property.Ifpropertyidentifiesavalidmappingofwidecharactersaccordingto theLC_TYPEcategory(seesection3.2.13,locale.h)ofthecurrentlocale,anon−zerovalueis returnedthatcanbeusedasanargumentinthetowctransfunction. towctrans(wc,desc) Transformswidecharacterwcintoanotherwide−character,describedbydesc.

Function Equivalenttolocalespecifictransformation towlower(wc) towctrans(wc,wctrans("tolower") towupper(wc) towctrans(wc,wctrans("toupper")

3−24 4 AssemblyLanguage

Summary ThischapterdescribesthemostimportantaspectsoftheTASKINGassembly languageandcontainsadetaileddescriptionofallbuilt−inassemblyfunctionsand assemblerdirectives.Foracompleteoverviewofthearchitectureyouareusingand adescriptionoftheassemblyinstructionset,refertothetarget’sCoreReference Manual.

4.1 AssemblySyntax

Anassemblyprogramconsistsofzeroormorestatements.Astatementmayoptionallybefollowedbyacomment.Anysource statementcanbeextendedtomorelinesbyincludingthelinecontinuationcharacter(\)asthelastcharacterontheline.The lengthofasourcestatement(firstlineandcontinuationlines)isonlylimitedbytheamountofavailablememory. Mnemonicsanddirectivesarecaseinsensitive.Labels,symbols,directivearguments,andliteralstringsarecasesensitive. Thesyntaxofanassemblystatementis: [label[:]][instruction|directive|macro_call][;comment] label Alabelisaspecialsymbolwhichisassignedthevalueandtypeofthecurrentprogramlocationcounter.Alabel canconsistofletters,digitsandunderscorecharacters(_).Thefirstcharactercannotbeadigit.Alabelwhichis prefixedbywhitespace(spacesortabs)hastobefollowedbyacolon(:).Thesizeofanidentifierisonlylimited bytheamountofavailablememory. Examples: LAB1:;Thislabelisfollowedbyacolonand ;canbeprefixedbywhitespace LAB1;Thislabelhastostartatthebeginning ;ofaline instruction Aninstructionconsistsofamnemonicandzero,oneormoreoperands.Itmustnotstartinthefirstcolumn. Operandsaredescribedinsection4.3,OperandsofanAssemblyInstruction.Theinstructionsaredescribedin thetarget’sCoreReferenceManual. Theinstructioncanalsobeaso−called’genericinstruction’.Genericinstructionsarepseudoinstructions(no instructionsfromtheinstructionset).Dependingonthesituationinwhichagenericinstructionisused,the assemblerreplacesthegenericinstructionwithappropriaterealassemblyinstruction(s).Foracompletelist,see section4.10,GenericInstructions. directive Withdirectivesyoucancontroltheassemblerfromwithintheassemblysource.Exceptforpreprocessing directives,thesemustnotstartinthefirstcolumn.Directivesaredescribedinsection4.8,AssemblerDirectives. macro_call Acalltoapreviouslydefinedmacro.Itmustnotstartinthefirstcolumn.Seesection4.9MacroOperations. comment Comment,precededbya;(semicolon). Youcanuseemptylinesorlineswithonlycomments.

4−1 NiosIIEmbeddedToolsReference

4.2 AssemblerSignificantCharacters

YoucanuseallASCIIcharactersintheassemblysourcebothinstringsandincomments.Alsotheextendedcharactersfrom theISO8859−1(Latin−1)setareallowed. Somecharactershaveaspecialmeaningtotheassembler.Specialcharactersassociatedwithexpressionevaluationare describedinsection4.6.3,ExpressionOperators.Otherspecialassemblercharactersare:

Character Description ; Startofacomment \ Linecontinuationcharacteror Macrooperator:argumentconcatenation ? Macrooperator:returndecimalvalueofasymbol % Macrooperator:returnhexvalueofasymbol ^ Macrooperator:overridelocallabel " Macrostringdelimiteror Quotedstring.DEFINEexpansioncharacter ’ Stringconstantsdelimiter @ Startofabuilt−inassemblyfunction $ Locationcountersubstitution [] Substringdelimiter

Notethatmacrooperatorshaveahigherprecedencethanexpressionoperators.

4.3 OperandsofanAssemblyInstruction

Inaninstruction,themnemonicisfollowedbyzero,oneormoreoperands.Anoperandhasoneofthefollowingtypes:

Operand Description symbol Asymbolicnameasdescribedinsection4.4,SymbolNames.Symbolscanalsooccurinexpressions. register Anyvalidregisteraslistedinsection4.5,Registers. expression Anyvalidexpressionasdescribedinsection4.6,AssemblyExpressions. address Acombinationofexpression,registerandsymbol.

4.4 SymbolNames

User−definedsymbols Auser−definedsymbolcanconsistofletters,digitsandunderscorecharacters(_).Thefirstcharactercannotbeadigit.Thesize ofanidentifierisonlylimitedbytheamountofavailablememory.Thecaseofthesecharactersissignificant.Youcandefinea symbolbymeansofalabeldeclarationoranequateorsetdirective.

Predefinedpreprocessorsymbols Thesesymbolsstartandendwithtwounderscorecharacters,__symbol__,andyoucanusetheminyourassemblysourceto createconditionalassembly.Seesection4.4.1,PredefinedPreprocessorSymbols.

Labels Symbolsusedformemorylocationsarereferredtoaslabels. Itisallowedtousereservedsymbolsaslabelsaslongasthelabelisfollowedbyacolonorstartsatthefirstcolumn

4−2 AssemblyLanguage

Reservedsymbols Symbolnamesandotheridentifiersbeginningwithaperiod(.)arereservedforthesystem(forexamplefordirectivesorsection names).Instructionsarealsoreserved.Thecaseofthesebuilt−insymbolsisinsignificant.

Examples Validsymbolnames: loop_1 ENTRY a_B_c _aBC

Invalidsymbolnames: 1_loop(startswithanumber) .DEFINE(reserveddirectivename)

4.4.1 PredefinedPreprocessorSymbols

TheTASKINGassemblerknowsthepredefinedsymbolsasdefinedinthetablebelow.Thesymbolsareusefultocreate conditionalassembly.

Macro Description __ASNIOS__ Expandsto1fortheNiosIItoolset,otherwiseunrecognizedasmacro. __BUILD__ Identifiesthebuildnumberoftheassembler,composedofdecimaldigitsforthebuildnumber, threedigitsforthemajorbranchnumberandthreedigitsfortheminorbranchnumber.For example,ifyouusebuild1.22.1ofthecompiler,__BUILD__expandsto1022001.Ifthereisno branchnumber,thebranchdigitsexpandtozero.Forexample,build127resultsin127000000. __REVISION__ Identifiestherevisionnumberoftheassembler.Forexample,ifyouuseversion1.0r2ofthe compiler,__REVISION__expandsto2. __TASKING__ IdentifiestheassemblerasaTASKINGassembler.Expandsto1ifaTASKINGcompilerisused. __VERSION__ Identifiestheversionnumberoftheassembler.Forexample,ifyouuseversion1.0r2ofthe assembler,__VERSION__expandsto1000(dotandrevisionnumberareomitted,minorversion numberin3digits).

Table4−1:Assemblerpredefinedpreprocessorsymbols

4.5 Registers

Thefollowingregisternames,eitherupperorlowercase,shouldnotbeusedforuser−definedsymbolnamesinanassembly languagesourcefile:

NiosIIregisters r0..r31 ctl0..ctl4 zero(aliasforr0)at(aliasforr1) et(aliasforr24)bt(aliasforr25) gp(aliasforr26)sp(aliasforr27) fp(aliasforr28)ea(aliasforr29) ba(aliasforr30)ra(aliasforr31)

4.6 AssemblyExpressions

Anexpressionisacombinationofsymbols,constants,operators,andparentheseswhichrepresentavaluethatisusedasan operandofanassemblerinstruction(ordirective). Expressionsmaycontainuser−definedlabels(andtheirassociatedintegervalues),andanycombinationofintegersorASCII literalstrings.

4−3 NiosIIEmbeddedToolsReference

Expressionsfollowtheconventionalrulesofalgebraandbooleanarithmetic. Expressionsthatcanbeevaluatedatassemblytimearecalledabsoluteexpressions.Expressionswheretheresultisunknown untilallsectionshavebeencombinedandlocated,arecalledrelocatableorrelativeexpressions. Whenanyoperandofanexpressionisrelocatable,theentireexpressionisrelocatable.Relocatableexpressionsareemittedin theobjectfileandevaluatedbythelinker. Theassemblerevaluatesexpressionswith64−bitprecisionintwo’scomplement. Thesyntaxofanexpressioncanbeanyofthefollowing: − numericcontant − string − symbol − expressionbinary_operatorexpression − unary_operatorexpression − (expression) − functioncall Alltypesofexpressionsareexplainedinseparatesections.

4.6.1 NumericConstants

Numericconstantscanbeusedinexpressions.Ifthereisnoprefix,bydefaulttheassemblerassumesthenumberisadecimal number.

Base Description Example 0b1101 Binary A0bprefixfollowedbybinarydigits(0,1).Oruseabsuffix 11001010b 0x12FF Hexadecimal A0xprefixfollowedbyahexadecimaldigits(0−9,A−F,a−f).Oruseahsuffix 0x45 0fa10h Decimal, 12 Decimaldigits(0−9). integer 1245

Table4−2:Numericconstants

4.6.2 Strings

ASCIIcharacters,enclosedinsingle(’)ordouble(″)quotesconstitueanASCIIstring.Stringsbetweendoublequotesallow symbolsubstitutionbya.DEFINEdirective,whereasstringsbetweensinglequotesarealwaysliteralstrings.Bothtypesof stringscancontainescapecharacters. Stringsconstantsinexpressionsareevaluatedtoanumber(eachcharacterisreplacedbyitsASCIIvalue).Stringsin expressionscanhaveasizeofupto8charactersorlessdependingontheoperandofaninstructionordirective;any subsequentcharactersinthestringareignored.Inthiscasetheassemblerissuesawarning.Anexceptiontothisruleiswhena stringisusedina.DBassemblerdirective;inthatcaseallcharactersresultinaconstantvalueofthespecifiedsize.Nullstrings haveavalueof0. Squarebrackets([])delimitasubstringoperationintheform: [string,offset,length] offsetisthestartpositionwithinstring.lengthisthelengthofthedesiredsubstring.Bothvaluesmaynotexceedthesizeof string.

Examples ’ABCD’;(0x41424344) ’’’79’;toencloseaquotedoubleit "A\"BC";ortoencloseaquoteescapeit ’AB’+1;(0x4143)stringusedinexpression

4−4 AssemblyLanguage

’’;nullstring [’TASKING’,0,4];resultsinthesubstring’TASK’

4.6.3 ExpressionOperators

Thenexttableshowstheassembleroperators.Theyareorderedaccordingtotheirprecedence.Operatorsofthesame precedenceareevaluatedlefttoright.Parentheticalexpressionshavethehighestpriority(innermostfirst). Validoperandsincludenumericconstants,literalASCIIstringsandsymbols.

Type Oper Name Description ator () parenthesis Expressionsenclosedbyparenthesisareevaluatedfirst. Unary + plus Returnsthevalueofitsoperand. − minus Returnsthenegativeofitsoperand. ~ complement Returnscomplement,integeronly ! logicalnegate Returns1iftheoperands’valueis0;otherwise0.Forexample,ifbufis0then !bufis1. Arithmetic * multiplication Yieldstheproductoftwooperands. / division Yieldsthequotientofthedivisionofthefirstoperandbythesecond. Withintegers,thedivideoperationproducesatruncatedinteger. % modulo Integeronly:yieldstheremainderfromadivisionofthefirstoperandbythe second. + addition Yieldsthesumofitsoperands. − subtraction Yieldsthedifferenceofitsoperands. Shift << shiftleft Integeronly:shiftstheleftoperandtotheleft(zero−filled)bythenumberofbits specifiedbytherightoperand. >> shiftright Integeronly:shiftstheleftoperandtotheright(signbitextended)bythenumber ofbitsspecifiedbytherightoperand. Relational < lessthan <= lessorequal Returns: > greaterthan aninteger1iftheindicatedconditionisTRUE. >= greaterorequal aninteger0iftheindicatedconditionisFALSE. == equal != notequal Bitwise & AND Integeronly:yieldsbitwiseAND | OR Integeronly:yieldsbitwiseOR ^ exclusiveOR Integeronly:yieldsbitwiseexlusiveOR Logical && logicalAND Returnsaninteger1ifbothoperandsarenon−zero;otherwise,itreturnsan integer0. || logicalOR Returnsaninteger1ifeitheroftheoperandsisnon−zero;otherwise,itreturnsan integer1

Table4−3:Assemblyexpressionoperators

4.7 Built−inAssemblyFunctions

TheTASKINGassemblershaveseveralbuilt−infunctionstosupportdataconversion,stringcomparison,andmath computations.Youcanusefunctionsastermsinanyexpression.

Syntaxofanassemblyfunction @function_name([argument[,argument]...])

4−5 NiosIIEmbeddedToolsReference

Functionsstartwith’@’characterandhavezeroormorearguments,andarealwaysfollowedbyopeningandclosing parentheses.Whitespace(ablankortab)isnotallowedbetweenthefunctionnameandtheopeningparenthesisandbetween the(comma−separated)arguments.

4.7.1 OverviewofBuilt−inAssemblyFunctions

Thefollowingtableprovidesanoverviewofallbuilt−inassemblyfunctions.Nextallfunctionsaredescribedintomoredetail.expr canbeanyassemblyexpressionresultinginanintegervalue.Expressionsareexplainedinsection4.6,AssemblyExpressions.

Overviewofassemblyfunctions

Function Description @ARG(’symbol’|expr) Testwhethermacroargumentispresent @BIGENDIAN() Testifassemblergeneratescodeforbig−endianmode @CNT() Returnnumberofmacroarguments @CPU(string) TestifcurrentCPUmatchesstring @DEFINED(’symbol’|symbol) Testwhethersymbolexists @GPREL(symbol) Offsetofsymbolfromtheglobalpointer(R26) @HI(expr) Mostsignificanthalfwordoftheexpression @HIADJ(expr) Mostsignificanthalfwordoftheexpression,signadjusted @LO(expr) Leastsignificanthalfwordoftheexpression,signadjusted @LSB(expr) Leastsignificantbyteoftheexpression @LSH(expr) Leastsignificanthalfwordoftheabsoluteexpression @LSW(expr) Leastsignificantwordoftheexpression @MSB(expr) Mostsignificantbyteoftheexpression @MSH(expr) Mostsignificanthalfwordoftheabsoluteexpression @MSW(expr) Mostsignificantwordoftheexpression @STRCAT(str1,str2) Concatenatestr1andstr2 @STRCMP(str1,str2) Comparestr1withstr2 @STRLEN(str) Returnlengthofstring @STRPOS(str1,str2[,start]) Returnpositionofstr1instr2

4.7.2 DetailedDescriptionofBuilt−inAssemblyFunctions

@ARG(’symbol’|expression) Returnsinteger1ifthemacroargumentrepresentedbysymbolorexpressionispresent,0otherwise. Youcanspecifytheargumentwithasymbolname(thenameofamacroargumentenclosedinsinglequotes)orwithexpression (theordinalnumberoftheargumentinthemacroformalargumentlist). Ifyouusethisfunctionwhenmacroexpansionisnotactive,theassemblerissuesawarning. Example: .IF@ARG(’TWIDDLE’);isargumenttwiddlepresent? .IF@ARG(1);isfirstargumentpresent?

@BIGENDIAN() Returns1iftheassemblergeneratescodeforbig−endianmode,returns0iftheassemblergeneratescodeforlittle−endian mode(thisisthedefault).

@CNT() Returnsthenumberofmacroargumentsofthecurrentmacroexpansionasaninteger. Ifyouusethisfunctionwhenmacroexpansionisnotactive,theassemblerissuesawarning. 4−6 AssemblyLanguage

Example: ARGCOUNT.SET@CNT();reserveargumentcount

@CPU(’processor_type’) Withthe@CPUfunctionyoucancheckwhetherthesourcecodeisbeingassembledforacertainprocessortype.Thefunction evaluatestoTRUEwhenthespecifiedprocessor_typematchestheprocessortypethatwasspecifiedwiththeoption −−cpu=cpu. Thisfunctionisusefultocreateconditionalcodeforseveraltargetsasshownintheexample. Example: .IF@CPU(’nios2f’);trueifyouspecifiedoption−−cpu=nios2f ...;codefortheNiosII/f .ELIF@CPU(’nios2e’);trueifyouspecifiedoption−−cpu=nios2e ...;codefortheNiosII/e .ELSE ...;codeforotherprocessortypes .ENDIF

Ccompileroption−−cpu(SelectCPU)insection5.1,CCompilerOptions,ofChapterToolOptions.

@DEFINED(’symbol’|symbol) Returns1ifsymbolhasbeendefined,0otherwise.Ifsymbolisquoted,itislookedupasa.DEFINEsymbol;ifitisnotquoted,it islookedupasanordinarysymbol,macroorlabel. Example: .IF@DEFINED(’ANGLE’);issymbolANGLEdefined? .IF@DEFINED(ANGLE);doeslabelANGLEexist?

@GPREL(symbol) Returnstheoffsetofsymbolfromtheglobalpointer(r26). IfyouwanttheassemblertogenerateGP−relativeoffsetsautomatically(option−−gp−relative)enabletheoptionAutomatically generateGP−relativeoffsetsintheAssemblerMiscellaneouspageoftheProjectOptionsdialog.

@HI(expression) Returnsthemostsignificanthalfwordoftheresultoftheexpression.@HI(expression)isequivalentto ((expression>>16)&0xffff).expressioncanbeanyrelocatableorabsoluteexpression. Example: ;TheinstructionMOVIAR1,labelexpandsto ORHIR1,R0,@hi(label) ORIR1,R1,@lo(label)

@HIADJ(expression) Returnsthemostsignificanthalfwordoftheresultoftheexpression,adjustedforsignedaddition.@HIADJ(expression)is equivalentto((expression>>16)+((expression&0x8000)?1:0))&0xFFFF.expressioncanbeany relocatableorabsoluteexpression.

@LO(expression) Returnstheleastsignificanthalfword(bits0..15)oftheresultoftheexpression,adjustedforsignedaddition.expressioncanbe anyrelocatableorabsoluteexpression.

4−7 NiosIIEmbeddedToolsReference

@LSB(expression) Returnstheleastsignificantbyteoftheresultoftheexpression. Theresultoftheexpressioniscalculatedas16bits.

@LSH(expression) Returnstheleastsignificanthalfword(bits0..15)oftheresultoftheabsoluteexpression. Theresultoftheexpressioniscalculatedasaword(32bits).

@LSW(expression) Returnstheleastsignificantword(bits0..31)oftheresultoftheexpression. Theresultoftheexpressioniscalculatedasadouble−word(64bits).

@MSB(expression) Returnsthemostsignificantbyteoftheresultoftheexpression. Theresultoftheexpressioniscalculatedas16bits.

@MSH(expression) Returnsthemostsignificanthalfword(bits16..31)oftheresultoftheabsoluteexpression. Theresultoftheexpressioniscalculatedasaword(32bits).@MSH(expression)isequivalentto((expression>>16)& 0xffff).

@MSW(expression) Returnsthemostsignificantword(bits32..63)oftheresultoftheexpression. Theresultoftheexpressioniscalculatedasadouble−word(64bits).

@STRCAT(string1,string2) Concatenatesstring1andstring2andreturnsthemasasinglestring. Youmustenclosestring1andstring2eitherwithsinglequotesorwithdoublequotes. Example: .DEFINEID"@STRCAT(’TAS’,’KING’)";ID=’TASKING’

@STRCMP(string1,string2) Comparesstring1withstring2bycomparingthecharactersinthestring.Thefunctionreturnsthedifferencebetweenthe charactersatthefirstpositionwheretheydisagree,orzerowhenthestringsareequal: <0 ifstring1<string2 0 ifstring1==string2 >0 ifstring1>string2 Example: .IF(@STRCMP(STR,’MAIN’))==0;doesSTRequal’MAIN’?

@STRLEN(string) Returnsthelengthofstringasaninteger. Example: SLENSET@STRLEN(’string’);SLEN=6

@STRPOS(string1,string2[,start]) Returnsthepositionofstring2instring1asaninteger.Ifstring2doesnotoccurinstring1,thelaststringpostition+1isreturned. Withstartyoucanspecifythestartingpositionofthesearch.Ifyoudonotspecifystart,thesearchisstartedfromthebeginning ofstring1.

4−8 AssemblyLanguage

Example: ID.set@STRPOS(’TASKING’,’ASK’);ID=1 ID.set@STRPOS(’TASKING’,’BUG’);ID=7

4.8 AssemblerDirectives

Anassemblerdirectiveissimplyamessagetotheassembler.Assemblerdirectivesarenottranslatedintomachineinstructions, butcanproducedata.Therearethreetypesofassemblerdirectives. • Assemblerdirectivesthattelltheassemblerhowtogoabouttranslatinginstructionsintomachinecode.Thisisthemost typicalformofassemblydirectives.Typicallytheytelltheassemblerwheretoputaprograminmemory,whatspaceto allocateforvariables,andallowyoutoinitializememorywithdata.Whentheassemblysourceisassembled,alocation counterintheassemblerkeepstrackofwherethecodeanddataistogoinmemory. Thefollowingdirectivesfallunderthisgroup: − Assemblycontroldirectives − Symboldefinitiondirectives − Datadefinition/Storageallocationdirectives − HLLdirectives • Directivesthatareinterpretedbythemacropreprocessor.Thesedirectivestellthemacropreprocessorhowtomanipulate yourassemblycodebeforeitisactuallybeingassembled.Youcanusethesedirectivestowritemacrosandtowrite conditionalsourcecode.Partsofthecodethatdonotmatchthecondition,willnotbeassembledatall.Unlikeother directives,preprocesssordirectivescanstartinthefirstcolumn. • Somedirectivesactasassembleroptionsandmostofthemindeeddohaveanequivalentassembler(commandline)option. Theadvantageofusingadirectiveisthatwithsuchadirectiveyoucanoverruletheassembleroptionforaparticularpartof thecode.Atypicalexampleistotelltheassemblerwithanoptiontogeneratealistfilewhilewiththedirectives.NOLIST and.LISTyouoverrulethisoptionforapartofthecodethatyoudonotwanttoappearinthelistfile.Directivesofthiskind sometimesarecalledcontrols. Eachassemblerdirectivehasitsownsyntax.Someassemblerdirectivescanbeprecededwithalabel.Ifyoudonotprecedean assemblerdirectivewithalabel,youmustusewhitespaceinstead(spacesortabs).Youcanuseassemblerdirectivesinthe assemblycodeaspseudoinstructions.

4.8.1 OverviewofAssemblerDirectives

Thefollowingtablesprovideanoverviewofallassemblerdirectives.Foradetaileddescriptionofthesedirectives,referto section4.8.2,DetailedDescriptionofAssemblerDirectives.

Overviewofassemblycontroldirectives

Directive Description .END Indicatestheendofanassemblymodule .INCLUDE Includefile .MESSAGE Programmergeneratedmessage

4−9 NiosIIEmbeddedToolsReference

Overviewofsymboldefinitiondirectives

Directive Description .EQU Setpermanentvaluetoasymbol .EXTERN Importglobalsectionsymbol .GLOBAL Declareglobalsectionsymbol .RESUME Resumeapreviouslydefinedsection .SECTION/.ENDSEC Startanewsection .SET Settemporaryvaluetoasymbol .SIZE SetsizeofsymbolintheELFsymboltable .SOURCE SpecifynameoforiginalCsourcefile .TYPE SetsymboltypeintheELFsymboltable .WEAK Markasymbolas’weak’

Overviewofdatadefinition/storageallocationdirectives

Directive Description .ALIGN Alignlocationcounter .BS/.BSB/.BSH/ Defineblockstorage(initialized) .BSW/.BSD .DB Definebyte .DH Definehalfword .DW Defineword .DD Definedouble−word .DS/.DSB/.DSH/ Definestorage .DSW/.DSD .OFFSET Movelocationcounterforwards

Overviewofmacroandconditionalassemblydirectives

Directive Description .DEFINE Definesubstitutionstring .BREAK Breakoutofcurrentmacroexpansion .REPEAT/.ENDREP Repeatsequenceofsourcelines .FOR/.ENDFOR Repeatsequenceofsourcelinesntimes .IF/.ELIF/.ELSE Conditionalassemblydirective .ENDIF Endofconditionalassemblydirective .MACRO/.ENDM Definemacro .UNDEF Undefine.DEFINEsymbolormacro

Overviewoflistingcontrolassemblydirectives

Directive Description .LIST/.NOLIST Print/donotprintsourcelinestolistfile .PAGE Settopofpage/sizeofpage .TITLE Setprogramtitleinheaderofassemblylistfile

4−10 AssemblyLanguage

OverviewofHLLdirectives

Directive Description .CALLS Passcalltreeinformation

4.8.2 DetailedDescriptionofAssemblerDirectives

.ALIGN

Syntax .ALIGNexpression

Description Withthe.ALIGNdirectiveyoutelltheassemblertoalignthelocationcounter. Whentheassemblerencountersthe.ALIGNdirective,itmovesthelocationcounterforwardstoanaddressthatisalignedas specifiedbyexpressionandplacesthenextinstructionordirectiveonthataddress.Thealignmentisinminimaladdressable units(MAUs).Theassemblerfillsthe’gap’withNOPinstructionsforcodesectionsorwithzerosfordatasections.Ifthelocation counterisalreadyalignedonthespecifiedalignment,itremainsunchanged.Thelocationofabsolutesectionswillnotbe changed. Theexpressionmustbeapoweroftwo:2,4,8,16,...Ifyouspecifyanothervalue,theassemblerchangesthealignmenttothe nexthigherpoweroftwoandissuesawarning.

Examples .SECTION.text .ALIGN16;theassembleraligns instruction;thisinstructionat16MAUsand ;fillsthe’gap’withNOPinstructions. .SECTION.text .ALIGN12;WRONG:notapoweroftwo,the instruction;assembleralignsthisinstructionat ;16MAUsandissuesawarning.

4−11 NiosIIEmbeddedToolsReference

.BREAK

Syntax .BREAK

Description The.BREAKdirectivecausesimmediateterminationofamacroexpansion,a.FORloopexansionora.REPEATloop expansion.Incaseofnestedloopsormacros,the.BREAKdirectivereturnstothepreviouslevelofexpansion. The.BREAKdirectiveis,forexample,usefulincombinationwiththe.IFdirectivetoterminateexpansionwhenerrorconditions aredetected.

Example .FORMYVARIN10TO20 ...; ...;assemblysourcelines ...; .IFMYVAR>15 .BREAK .ENDIF .ENDREP

4−12 AssemblyLanguage

.BS/.BSB/.BSH/.BSW/.BSD

Syntax [label].BSexpression1[,expression2] [label].BSBexpression1[,expression2] [label].BSHexpression1[,expression2] [label].BSWexpression1[,expression2] [label].BSDexpression1[,expression2]

Description Withthe.BSdirective(BlockStorage)theassemblerreservesablockofmemory.Thereservedblockofmemoryisinitializedto thevalueofexpression2,orzeroifomitted. Withexpression1youspecifythenumberofminimumaddressableunits(MAUs)youwanttoreserve,andhowmuchthe locationcounterwilladvance.Theexpressionmustbeanintegergreaterthanzeroandcannotcontainanyforwardreferences toaddresslabels(labelsthathavenotyetbeendefined). Withexpression2youcanspecifyavaluetoinitializetheblockwith.OnlytheleastsignificantMAUofexpression2isused.If youomitexpression2,thedefaultiszero. Ifyouspecifylabel,itgetsthevalueofthelocationcounteratthestartofthedirectiveprocessing.

Youcannotinitializeofablockofmemoryinsectionswithprefix.sbssor.bss.Inthosesections,theassemblerissues awarningandonlyreservesspace,justaswith.DS. The.BSB,.BSH,.BSWand.BSDdirectivesarevariantsofthe.BSdirective: .BSB Theexpression1argumentspecifiesthenumberofbytestoreserve. .BSH Theexpression1argumentspecifiesthenumberofhalfwordstoreserve(onehalfwordis16bits). .BSW Theexpression1argumentspecifiesthenumberofwordstoreserve(onewordis32bits). .BSD Theexpression1argumentspecifiesthenumberofdouble−wordstoreserve(onedouble−wordis64bits).

Example The.BSBdirectiveisforexampleusefultodefineandinitializeanarraythatisonlypartiallyfilled: .section.data .DB84,101,115,116;initialize4bytes .BSB96,0xFF;reserveanother96bytes,initializedwith0xFF

Relatedinformation

.DS(DefineStorage)

4−13 NiosIIEmbeddedToolsReference

.CALLS

Syntax .CALLS’caller’,’callee’ or .CALLS’caller’,’’,stack0_usage[,stack1_usage]...

Description Thefirstsyntaxcreatesacallgraphreferencebetweencallerandcallee.Thelinkerneedsthisinformationtobuildacallgraph. Ifapplicablethecallgraphisusedtocreateastaticstackoverlay.callerandcalleearenamesoffunctions. Thesecondsyntaxspecifiesstackinformation.Whencalleeisanemptyname,thismeanswedefinethestackusageofthe functionitself.Thevaluesspecifiedarethestackusageinbytesatthetimeofthecallincludingthereturnaddress.This informationisusedbythelinkertocomputetheusedstackwithintheapplication.Theinformationisfoundinthegenerated linkermapfilewithintheMemoryUsage. Normally.CALLSdirectivesareautomaticallygeneratedbythecompiler.Usethe.CALLSdirectiveinhandcodedassembly whentheassemblycodecallsaCfunction.Ifyoumanuallyadd.CALLSdirectives,makesuretheyconnecttothecompiler generated.CALLSdirectives:thenameofthecallermustalsobenamedasacalleeinanotherdirective.

Example .CALLS’_main’,’_nfunc’

Indicatesthatthefunctionmaincallsthefunctionnfunc .CALLS’main’,’’,8

Thefunctionmainuses8bytesonthestack.

4−14 AssemblyLanguage

.DB

Syntax [label].DBargument[,argument]...

Description Withthe.DBdirective(DefineByte)theassemblerallocatesandinitializesonebyteofmemoryforeachargument. Anargumentcanbe: • asingleormultiplecharacterstringconstant • anintegerexpression • NULL(indicatedbytwoadjacentcommas:,,) Ifyouspecifylabel,itgetsthevalueofthelocationcounteratthestartofthedirectiveprocessing. Multipleargumentsarestoredinsuccessiveaddresslocations.IfanargumentisNULL,itscorrespondingaddresslocationis flledwithzeros. Integerargumentsarestoredasis,butmustbebytevalues(withintherange0−255);floating−pointnumbersarenotallowed.If theevaluatedexpressionisoutoftherange[−256,+255]theassemblerissuesanerror.Fornegativevalueswithinthatrange, theassembleradds256tothespecifiedvalue(forexample,−254isstoredas2). Incaseofsingleandmultiplecharacterstrings,eachcharacterisstoredinconsecutivebyteswhoselowersevenbitsrepresent theASCIIvalueofthecharacter.ThestandardCescapesequencesareallowed: .DB’R’;=0x52 .DB’AB’,,’D’;=0x41420043(secondargumentisempty)

Example TABLE:.DB14,253,0x62,’ABCD’ CHARS:.DB’A’,’B’,,’C’,’D’

Relatedinformation

.BS(BlockStorage) .DS(DefineStorage) .DH(DefineHalfWord) .DW(DefineWord) .DD(DefineDouble−Word)

4−15 NiosIIEmbeddedToolsReference

.DD

Syntax [label].DDargument[,argument]...

Description Withthe.DDdirective(DefineDouble−Word)youallocateandinitializeonedouble−wordofmemoryforeachargument. Onedouble−wordis64bits. Anargumentis: • asingleormultiplecharacterstringconstant • anexpression • NULL(indicatedbytwoadjacentcommas:,,) Ifyouspecifylabel,itgetsthevalueofthelocationcounteratthestartofthedirectiveprocessing. Multipleargumentsarestoredinsetsofeightbytes.IfanargumentisNULL,itscorrespondingaddresslocationsareflledwith zeros. Double−wordargumentsarestoredasis.Floating−pointvaluesarenotallowed.Iftheevaluatedargumentistoolargetobe representedinadouble−word,theassemblerissuesawarningandtruncatesthevalue. Incaseofcharacterstrings,eachASCIIvalueofthecharacterisstoredinsuccessivelocationsstartingatthemostsignificant byteofadouble−word: .DD’AB’,,’D’=>0x4241000000000000 0x0000000000000000(secondargumentisempty) 0x4400000000000000

Example TABLE:.DD14,253,0x62,’ABCD’ CHARS:.DD’A’,’B’,,’C’,’D’

Relatedinformation

4−16 AssemblyLanguage

.DEFINE

Syntax .DEFINEsymbolstring

Description Withthe.DEFINEdirectiveyoudefineasubstitutionstringthatyoucanuseonallfollowingsourcelines.Theassembler searchesallsucceedinglinesforanoccurrenceofsymbol,andreplacesitwithstring.Ifthesymboloccursinadoublequoted stringitisalsoreplaced.Stringsbetweensinglequotesarenotexpanded. Thisdirectiveisusefulforprovidingbetterdocumentationinthesourceprogram.Asymbolcanconsistofletters,digitsand underscorecharacters(_),andthefirstcharactercannotbeadigit. Theassemblerissuesawarningifyouredefineanexistingsymbol.

Example SupposeyoudefinedthesymbolLENwiththesubstitutionstring"32": .DEFINELEN"32"

ThenyoucanusethesymbolLENforexampleasfollows: .DSLEN .MESSAGEI"Thelengthis:LEN"

TheassemblerpreprocessorreplacesLENwith32"andassemblesthefollowinglines: .DS32 .MESSAGEI"Thelengthis:32"

Relatedinformation

.UNDEF(Undefinea.DEFINEsymbolormacro) .MACRO/.ENDM(Defineamacro)

4−17 NiosIIEmbeddedToolsReference

.DH

Syntax [label].DHargument[,argument]...

Description Withthe.DHdirective(DefineHalfWord)youallocateandinitializeahalfwordofmemoryforeachargument. Ahalfwordis16bits. Anargumentis: • asingleormultiplecharacterstringconstant • anexpression • NULL(indicatedbytwoadjacentcommas:,,) Ifyouspecifylabel,itgetsthevalueofthelocationcounteratthestartofthedirectiveprocessing. Multipleargumentsarestoredinsuccessivehalfwordaddresslocations.IfanargumentisNULL,itscorrespondingaddress locationisfilledwithzeros. Halfwordargumentsarestoredasis.Floating−pointvaluesarenotallowed. Iftheevaluatedargumentistoolargetoberepresentedinahalfword,theassemblerissuesawarningandtruncatesthevalue. Incaseofsingleandmultiplecharacterstrings,eachASCIIvalueofthecharacterisstoredinsuccessivelocationsstartingat themostsignificantbyteofahalfword.ThestandardCescapesequencesareallowed: .DH’AB’,,’D’=>0x4241 0x0000(secondargumentisempty) 0x4400

Example TABLE:.DH14,253,0x62,’ABCD’ CHARS:.DH’A’,’B’,,’C’,’D’

Relatedinformation

.BS(BlockStorage) .DS(DefineStorage) .DB(DefineByte) .DW(DefineWord) .DD(DefineDouble−Word)

4−18 AssemblyLanguage

.DS/.DSB/.DSH/.DSW/.DSD

Syntax [label].DSexpression [label].DSBexpression [label].DSHexpression [label].DSWexpression [label].DSDexpression

Description Withthe.DSdirective(DefineStorage)theassemblerreservesablockofmemory.Thereservedblockofmemoryisnot initializedtoanyvalue. Withtheexpressionyouspecifythenumberofminimumaddressableunits(MAUs)thatyouwanttoreserve.Theexpression mustevaluatetoanintegerlargerthanzeroandcannotcontainreferencestosymbolsthatarenotyetdefinedintheassembly source. Ifyouspecifylabel,itgetsthevalueofthelocationcounteratthestartofthedirectiveprocessing.

Youcannotusethe.DSdirectiveinsectionswithattributeinit.Ifyouneedtoreserveinitializedspaceinaninitsection, usethe.BSdirectiveinstead. The.DSB,.DSH,.DSWand.DSDdirectivesarevariantsofthe.DSdirective: .DSB Theexpressionargumentspecifiesthenumberofbytestoreserve. .DSH Theexpressionargumentspecifiesthenumberofhalfwordstoreserve(onehalfwordis16bits). .DSW Theexpressionargumentspecifiesthenumberofwordstoreserve(onewordis32bits). .DSD Theexpressionargumentspecifiesthenumberofdouble−wordstoreserve(onedouble−wordis64bits).

Example RES:.DS5+3;allocate8bytes

Relatedinformation

.BS(BlockStorage) .DB(DefineByte) .DH(DefineHalfWord) .DW(DefineWord) .DD(DefineDouble−Word)

4−19 NiosIIEmbeddedToolsReference

.DW

Syntax [label].DWargument[,argument]...

Description Withthe.DWdirective(DefineWord)youallocateandinitializeonewordofmemoryforeachargument. Onewordis32bits. Anargumentis: • asingleormultiplecharacterstringconstant • anexpression • NULL(indicatedbytwoadjacentcommas:,,) Ifyouspecifylabel,itgetsthevalueofthelocationcounteratthestartofthedirectiveprocessing. Multipleargumentsarestoredinsetsoffourbytes.IfanargumentisNULL,itscorrespondingaddresslocationsareflledwith zeros. Wordargumentsarestoredasis.Floating−pointvaluesarenotallowed.Iftheevaluatedargumentistoolargetoberepresented inaword,theassemblerissuesawarningandtruncatesthevalue. Incaseofsingleandmultiplecharacterstrings,eachASCIIvalueofthecharacterisstoredinsuccessivelocationsstartingat themostsignificantbyteofaword.ThestandardCescapesequencesareallowed: .DW’AB’,,’D’=>0x42410000 0x00000000(secondargumentisempty) 0x44000000

Example TABLE:.DW14,253,0x62,’ABCD’ CHARS:.DW’A’,’B’,,’C’,’D’

Relatedinformation

4−20 AssemblyLanguage

.END

Syntax .END

Description Withthe.ENDdirectiveyoutelltheassemblerthattheendofthemoduleisreached.Iftheassemblerfindsassemblysource linesbeyondthe.ENDdirective,itignoresthoselinesandissuesawarning.

Example .section.text ;sourcelines .END;Endofassemblymodule

4−21 NiosIIEmbeddedToolsReference

.EQU

Syntax symbol.EQUexpression

Description Withthe.EQUdirectiveyouassignthevalueofexpressiontosymbolpermanently.Oncedefined,youcannotredefinethe symbol.Withthe.GLOBALdirectiveyoucandefinethesymbolglobal.

Example Toassignthevalue0x4000permanentlytothesymbolMYSYMBOL: MYSYMBOL.EQU0x4000

Youcannotredefinetheusedsymbols.

Relatedinformation

.SET(Settemporaryvaluetoasymbol)

4−22 AssemblyLanguage

.EXTERN

Syntax .EXTERNsymbol[,symbol]...

Description Withthe.EXTERNdirectiveyoudefineanexternalsymbol.Itmeansthatthesymbolisreferencedinthecurrentmodulewhileit isdefinedoutsidethecurrentmodule. Youmustdefinethesymbolseitheroutsideanymoduleordeclareitasgloballyaccessiblewithinanothermodulewiththe .GLOBALdirective. Ifyoudonotusethe.EXTERNdirectiveandthesymbolisnotdefinedwithinthecurrentmodule,theassemblerissuesa warningandinsertsthe.EXTERNdirective.

Example .EXTERNAA,CC,DD;definedelsewhere

Relatedinformation

.GLOBAL(Declareglobalsectionsymbol)

4−23 NiosIIEmbeddedToolsReference

.FOR/.ENDFOR

Syntax [label].FORvarINexpression[,expression]...... ENDFOR or: [label].FORvarINstartTOend[STEPstep] .... .ENDFOR

Description Withthe.FOR/.ENDFORdirectiveyoucanrepeatasequenceofassemblysourcelineswithaniterator.Asshownbythe syntax,youcanusethe.FOR/.ENDFORintwoways. 1. Inthefirstmehod,theloopisrepeatedasmanytimesasthenumberofargumentsfollowingIN.Ifyouusethesymbolvarin theassemblylinesbetween.FORand.ENDFOR,foreachrepetitionthesymbolvarissubstitutedbyasubsequent expressionfromtheargumentlist.Iftheargumentisanull,thentheloopisrepeatedwitheachoccurrenceofthesymbolvar removed. 2. Inthesecondmethod,theloopisrepeatedusingthesymbolvarasacounter.Thecounterpassesallintegervaluesfrom starttoendwithastep.Ifyoudonotspecifystep,thecounterisincreasedbyoneforeveryrepetition. Ifyouspecifylabel,itgetsthevalueofthelocationcounteratthestartofthedirectiveprocessing.

Example Inthefollowingexampletheloopisrepeated4times(therearefourarguments).Withthe.DBdirectiveyouallocateand initializeabyteofmemoryforeachrepetitionoftheloop(awordforthe.DWdirective).Effectively,thepreprocessorduplicates the.DBand.DWdirectivesfourtimesintheassemblysource. .FORVAR1IN1,2+3,4,12 .DBVAR1 .DW(VAR1*VAR1) .ENDFOR

Inthefollowingexampletheloopisrepeated16times.Withthe.DWdirectiveyouallocateandinitializefourbytesofmemoryfor eachrepetitionoftheloop.Effectively,thepreprocessorduplicatesthe.DWdirective16timesintheassembledfile,and substitutesVAR2withthesubsequentnumbers. .FORVAR2IN1to0x10 .DW(VAR1*VAR1) .ENDFOR

Relatedinformation

.REPEAT/.ENDREP(Repeatsequenceofsourcelines)

4−24 AssemblyLanguage

.GLOBAL

Syntax .GLOBALsymbol[,symbol]...

Description Allsymbolsorlabelsdefinedinthecurrentsectionormodulearelocaltothemodulebydefault.Youcanchangethisdefault behaviorwithassembleroption−ig. Withthe.GLOBALdirectiveyoudeclareoneofmoresymbolsasglobal.Itmeansthatthespecifiedsymbolsaredefinedwithin thecurrentsectionormodule,andthatthosedefinitionsshouldbeaccessiblebyallmodules. Toaccessasymbol,definedwith.GLOBAL,fromanothermodule,usethe.EXTERNdirective. Onlyprogramlabelsandsymbolsdefinedwith.EQUcanbemadeglobal.

Example LOOPA.EQU1;definitionofsymbolLOOPA .GLOBALLOOPA;LOOPAwillbeglobally ;accessiblebyothermodules

Relatedinformation

.EXTERN(Importglobalsectionsymbol)

4−25 NiosIIEmbeddedToolsReference

.IF/.ELIF/.ELSE/.ENDIF

Syntax .IFexpression . . [.ELIFexpression] (the.ELIFdirectiveisoptional) . . [.ELSE] (the .ELSEdirectiveisoptional) . . .ENDIF

Description Withthe.IF/.ENDIFdirectivesyoucancreateapartofconditionalassemblycode.Theassemblerassemblesonlythecode thatmatchesaspecifiedcondition. Theexpressionmustevaluatetoanintegerandcannotcontainforwardreferences.Ifexpressionevaluatestozero,the IF−conditionisconsideredFALSE,anynon−zeroresultofexpressionisconsideredasTRUE. Youcannest.IFdirectivestoanylevel.The.ELSEand.ELIFdirectivealwaysrefertothenearestprevious.IFdirective.

Example Supposeyouhaveanassemblesourcefilewithspecificcodeforatestversion,forademoversionandforthefinalversion. Withintheassemblysourceyoudefinethiscodeconditionallyasfollows: .IFTEST ...;codeforthetestversion .ELIFDEMO ...;codeforthedemoversion .ELSE ...;codeforthefinalversion .ENDIF

BeforeassemblingthefileyoucansetthevaluesofthesymbolsTESTandDEMOintheassemblysourcebeforethe.IF directiveisreached.Forexample,toassemblethedemoversion: TEST.SET0 DEMO.SET1

YoucanalsodefinethesymbolsinAltiumDesigneraspreprocessormacrosindialogProject»ProjectOptions»Assembler »Preprocessing(assembleroption−−define).

Relatedinformation

Assembleroption−−define(Definepreprocessormacro)inSection5.3,AssemblerOptions,ofChapterToolOptions.

4−26 AssemblyLanguage

.INCLUDE

Syntax .INCLUDE"filename"|

Description Withthe.INCLUDEdirectiveyouincludeanotherfileattheexactlocationwherethe.INCLUDEoccurs.Thishappensbefore theresultingfileisassembled.The.INCLUDEdirectiveworkssimilarlytothe#includestatementinC.Thesourcefromthe includefileisassembledasifitfollowedthepointofthe.INCLUDEdirective.Whentheendoftheincludedfileisreached, assemblyoftheoriginalfilecontinues. Thestringspecifiesthefilenameofthefiletobeincluded.Thefilenamemustbecompatiblewiththeoperatingsystem (forward/backwardslashes)andcancontainadirectoryspecification.Ifyouomitafilenameextension,theassemblerassumes theextension.asm. Ifanabsolutepathnameisspecified,theassemblersearchesforthatfile.Ifarelativepathisspecifiedorjustafilename,the orderinwhichtheassemblersearchesforincludefilesis: 1. Thecurrentdirectoryifyouusethe"filename"construction. Thecurrentdirectoryisnotsearchedifyouusethesyntax. 2. Thepaththatisspecifiedwiththeassembleroption−−include−directory(−I). 3. ThepaththatisspecifiedintheenvironmentvariableAStargetINCwhentheproductwasinstalled. 4. Thedefaultdirectory...\ctarget\include.

Example Supposethatyourassemblysourcefiletest.srccontainsthefollowingline: .INCLUDE"c:\myincludes\myinc.inc"

Theassemblerissuesanerrorifitcannotfindthefileatthespecifiedlocation. .INCLUDE"myinc.inc"

Theassemblersearchesthefilemyinc.incaccordingtotherulesdescribedabove.

Relatedinformation

Assembleroption−−include−directory(Adddirectorytoincludefilesearchpath)inSection5.3,AssemblerOptions,of ChapterToolOptions.

4−27 NiosIIEmbeddedToolsReference

.LIST/.NOLIST

Syntax .NOLIST . .;assemblysourcelines . .LIST

Description Ifyougeneratealistfile(seeassembleroption−−list−file),youcanusethe.LISTand.NOLISTdirectivestospecifywhich sourcelinestheassemblermustwritetothelistfile. Theassemblerprintsallsourcelinestothelistfile,untillitencountersa.NOLISTdirective.Theassemblerdoesnotprintthe .NOLISTdirectiveandsubsequentsourcelines.Whentheassemblerencountersthe.LISTdirective,itresumesprintingtothe listfile,startingwiththe.LISTdirectiveitself. Itispossibletonestthe.LIST/.NOLISTdirectives.

Example Supposeyouassemblethefollowingassemblycodewiththeassembleroption−−list−file: .SECTION.text ...;sourceline1 .NOLIST ...;sourceline2 .LIST ...;sourceline3 .END

Theassemblergeneratesalistfilewiththefollowinglines: .SECTION.text ...;sourceline1 .LIST ...;sourceline3 .END

Relatedinformation

Assembleroption−−list−file(Generatelistfile)inSection5.3,AssemblerOptions,ofChapterToolOptions.

4−28 AssemblyLanguage

.MACRO/.ENDM

Syntax macro_name.MACRO[argument[,argument]...] ... macro_definition_statements ... .ENDM

Description Withthe.MACROdirectiveyoudefineamacro.Macrosprovideashorthandmethodforhandlingarepeatedpatternofcodeor groupofinstructions.Youcandefinethepatternasamacro,andthencallthemacroatthepointsintheprogramwherethe patternwouldrepeat. Thedefinitionofamacroconsistsofthreeparts: • Header,whichassignsanametothemacroanddefinesthearguments. • Body,whichcontainsthecodeorinstructionstobeinsertedwhenthemacroiscalled. • Terminator,whichindicatestheendofthemacrodefinition(.ENDMdirective). Theargumentsaresymbolicnamesthatthemacroprocessorreplaceswiththeliteralargumentswhenthemacroisexpanded (called).Eachformalargumentmustfollowthesamerulesassymbolnames:thenamecanconsistofletters,digitsand underscorecharacters(_).Thefirstcharactercannotbeadigit.Argumentnamescannotstartwithapercentsign(%). Macrodefinitionscanbenestedbutthenestedmacrowillnotbedefineduntiltheprimarymacroisexpanded. Youcanusethefollowingoperatorsinmacrodefinitionstatements:

Operator Name Description \ Macroargument Concatenatesamacroargumentwithadjacentalphanumericcharacters. concatenation ? Returndecimal Substitutesthe?symbolsequencewithacharacterstringthatrepresentsthedecimalvalue valueofsymbol ofthesymbol. % Returnhex Substitutesthe%symbolsequencewithacharacterstringthatrepresentsthehexadecimal valueofsymbol valueofthesymbol. " Macrostring Allowstheuseofmacroargumentsasliteralstrings. delimiter ^ Macrolocallabel Preventsnamemanglingonlabelsinmacros. override

Example Themacrodefinition: macro_a.MACROarg1,arg2;header .dbarg1;body .dw(arg1*arg2) .ENDM;terminator

Themacrocall: .section.data macro_a2,3

Themacroexpandsasfollows: .db2 .dw(2*3)

4−29 NiosIIEmbeddedToolsReference

Relatedinformation

.DEFINE(Defineasubstitutionstring) Section4.9,MacroOperations.

4−30 AssemblyLanguage

.MESSAGE

Syntax .MESSAGEtype[{str|exp|symbol}[,{str|exp|symbol}]...]

Description Withthe.MESSAGEdirectiveyoutelltheassemblertoprintamessagetostdoutduringtheassemblingprocess. Withtypeyoucanspecifythefollowingtypesofmessages: I Informationmessage.Errorandwarningcountsarenotaffectedandtheassemblercontinuestheassemblingprocess. W Warningmessage.Incrementsthewarningcountandtheassemblercontinuestheassemblingprocess. E Errormessage.Incrementstheerrorcountandtheassemblercontinuestheassemblingprocess. F Fatalerrormessage.Theassemblerimmediatelyabortstheassemblingprocessandgeneratesnoobjectfileorlistfile. The.MESSAGEdirectiveisforexampleusefulincombinationwithconditionalassemblytoindicatewhichpartisassembled.

Example .MESSAGEI’Generatingtables’ ID.EQU4 .MESSAGEE’ThevalueofIDis’,ID .DEFINELONG"SHORT" .MESSAGEI’ThisisaLONGstring’ .MESSAGEI"ThisisaLONGstring"

Withinsinglequotes,thedefinedsymbolLONGisnotexpanded.WithindoublequotesthesymbolLONGisexpandedsothe actualmessageisprintedas: ThisisaLONGstring ThisisaSHORTstring

4−31 NiosIIEmbeddedToolsReference

.OFFSET

Syntax .OFFSETexpression

Description Withthe.OFFSETdirectiveyoutelltheassemblertogivethelocationcounteranewoffsetrelativetothestartofthesection. Whentheassemblerencountersthe.OFFSETdirective,itmovesthelocationcounterforwardstothespecifiedaddress,relative tothestartofthesection,andplacesthenextinstructiononthataddress.Ifyouspecifyanaddressequaltoorlowerthanthe currentpositionofthelocationcounter,theassemblerissuesanerror.

Example .SECTION.text nop nop nop .OFFSET0x20;theassemblerplaces nop;thisinstructionataddress0x20 ;relativetothestartofthesection. .SECTION.text nop nop nop .OFFSET0x02;WRONG:thecurrentpositionofthe nop;locationcounteris0x0C.

4−32 AssemblyLanguage

.PAGE

Syntax .PAGE[width,length,blanktop,blankbtm,blankleft]

Description Ifyougeneratealistfile(seeassembleroption−−list−file),youcanusethe.PAGEdirectivetoformatthegeneratedlistfile. width Numberofcharactersonaline(1−255).Defaultis132. length Numberoflinesperpage(10−255).Defaultis66. blanktop Numberofblanklinesatthetopofthepage.Default=0. Specifyavaluesothatblanktop+blankbtm≤length−10. blankbtm Numberofblanklinesatthebottomofthepage.Default=0. Specifyavaluesothatblanktop+blankbtm≤length−10. blankleft Numberofblankcolumnsattheleftofthepage.Default=0.Specifyavaluesmallerthanwidth. Ifyouusethe.PAGEdirectivewithoutarguments,itcausesa’formfeed’:thenextsourcelineisprintedonthenextpageinthe listfile. Youcanomitanargumentbyusingtwoadjacentcommas.Iftheremainingargumentsafteranargumentareallempty,youcan omitthem. Alabelisnotallowedwiththisdirective.

Example .PAGE;formfeed,thenextsourcelineisprinted ;onthenextpageinthelistfile. .PAGE96;setpagewidthto96.Notethatyoucan ;omitthelastfourarguments .PAGE,,5;insertfiveblanklinesatthetop.Note ;thatyoucanomitthelasttwoarguments.

Relatedinformation

.TITLE(Setprogramtitleinheaderofassemblerlistfile) Assembleroption−−list−file(Generatelistfile)inSection5.3,AssemblerOptions,ofChapterToolOptions.

4−33 NiosIIEmbeddedToolsReference

.REPEAT/.ENDREP

Syntax [label].REPEATexpression .... .ENDREP

Description Withthe.REPEAT/.ENDREPdirectiveyoucanrepeatasequenceofassemblysourcelines.Withexpressionyouspecifythe numberoftimestheloopisrepeated. Ifyouspecifylabel,itgetsthevalueofthelocationcounteratthestartofthedirectiveprocessing.

Example Inthisexampletheloopisrepeated3times.Effectively,thepreprocessorrepeatsthesourcelines(.DB10)threetimes,then theassemblerassemblestheresult: .REPEAT3 .DB10;assemblysourcelines .ENDREP

Relatedinformation

.FOR/.ENDFOR(Repeatsequenceofsourcelinesntimes)

4−34 AssemblyLanguage

.RESUME

Syntax .RESUMEname[,attribute]...

Description Withthe.SECTIONdirectiveyoualwaysstartanewsection.Withthe.RESUMEdirectiveyoucanreactivateapreviously definedsection.Seethe.SECTIONdirectiveforalistofavailablesectionattributes.Ifyouomittheattribute,thepreviously definedsectionwiththesamenameisreactivated(ignoringtheattribute(s)).Ifyouspecifyanattributeyoureactivatethesection withthatsameattribute.

Example .SECTION.text;First.textsection ... .SECTION.data;First.datasection ... .SECTION.text;Second.textsection ... .SECTION.data,at(0x0);Second.datasection ... .RESUME.text;Resumeinthesecond.textsection ... .RESUME.data;Resumeinthefirst.datasection ... .RESUME.data,at(0x0);Resumeinthesecond.datasection

Relatedinformation

.SECTION(Startanewsection)

4−35 NiosIIEmbeddedToolsReference

.SECTION

Syntax .SECTIONname[,at(address)] .... [.ENDSEC]

Description Withthe.SECTIONdirectiveyoudefineanewsection.Eachtimeyouusethe.SECTIONdirective,anewsectioniscreated.It ispossibletocreatemultiplesectionswithexactlythesamename. Toresumeapreviouslydefinedsection,usethe.RESUMEdirective. Ifyoudefineasection,youmustalwaysspecifythesectionname.Thenameshaveaspecialmeaningtothelocatingprocess andhavetostartwithapredefinedname,optionallyextendedbyadot’.’andauserdefinedname.Thepredefinedsection namealsodeterminesthetypeofthesection(code,dataordebug).Optionally,youcanspecifytheat()attributetolocatea sectionataspecificaddress. Youcanusethefollowingpredefinedsectionnames:

SectionName Description SectionType .text Codesections code .data Initializeddata data .sdata Initializeddatainread−writesmalldataarea data .bss Uninitializeddata(cleared) data .sbss Uninitializeddatainread−writesmalldataarea(cleared) data .rodata ROMdata(constants) data .debug Debugsections debug

Table4−4:Predefinedsectionnames Sectionsofaspecifiedtypearelocatedbythelinkerinamemoryspace.Thespacenamesaredefinedinaso−called’linker scriptfile’(fileswiththeextension.lsl)deliveredwiththeproductinthedirectory\ProgramFiles\Altium Designer\System\Tasking\include.lsl. Youcanspecifythefollowingsectionattributes:

Example .SECTION.data;Declarea.datasection

.SECTION.data.abs,at(0x0);Declarea.data.abssectionat ;anabsoluteaddress

.RESUME(Resumeapreviouslydefinedsection)

4−36 AssemblyLanguage

.SET

Syntax symbol .SETexpression .SETsymbolexpression

Description Withthe.SETdirectiveyouassignthevalueofexpressiontosymboltemporarily.Ifasymbolwasdefinedwiththe.SET directive,youcanredefinethatsymbolinanotherpartoftheassemblysource,usingthe.SETdirectiveagain.Symbolsthatyou definewiththe.SETdirectivearealwayslocal:youcannotdefinethesymbolglobalwiththe.GLOBALdirective. The.SETdirectiveisusefulinestablishingtemporaryorreusablecounterswithinmacros.expressionmustbeabsoluteand cannotincludeasymbolthatisnotyetdefined(noforwardreferencesareallowed).

Example COUNT.SET0;Initializecount.Lateronyoucan ;assignothervaluestothesymbol

Relatedinformation

.EQU(Setapermanentvaluetoasymbol)

4−37 NiosIIEmbeddedToolsReference

.SIZE

Syntax .SIZEsymbol,expression

Description Withthe.SIZEdirectiveyousetthesizeofthespecifiedsymboltothevaluerepresentedbyexpression. The.SIZEdirectivemayoccuranywhereinthesourcefileunlessthespecifiedsymbolisafunction.Inthiscase,the.SIZE directivemustoccurafterthefunctionhasbeendefined.

Example .section.text .align4 .global_main ;Function_main _main:.typefunc ; .SIZE_main,$−_main .endsec

Relatedinformation

.TYPE(SetSymbolType)

4−38 AssemblyLanguage

.SOURCE

Syntax .SOURCEstring

Description Withthe.SOURCEdirectiveyouspecifythenameoftheoriginalCsourcemodule.ThisdirectiveisgeneratedbytheCcompiler. Youdonotneedthisdirectiveinhand−writtenassembly.

Example .SOURCE"test.c"

Relatedinformation

4−39 NiosIIEmbeddedToolsReference

.TITLE

Syntax .TITLE[title]

Description Ifyougeneratealistfile(seeassembleroption−−list−file),youcanusethe.TITLEdirectivetospecifytheprogramtitlewhich isprintedatthetopofeachpageintheassemblerlistfile. Ifyouusethe.TITLEdirectivewithouttheargument,thetitlebecomesempty.Thisisalsothedefault.Thespecifiedtitleisvalid untiltheassemblerencoutersanew.TITLEdirective.

Example .TITLE"Thebestprogram"

Intheheaderofeachpageintheassemblerlistfile,thetitleoftheprogamisprinted.Inthiscase:Thebestprogram

Relatedinformation

.PAGE(Formattheassemblerlistfile) Assembleroption−−list−file(Generatelistfile)inSection5.3,AssemblerOptions,ofChapterToolOptions.

4−40 AssemblyLanguage

.TYPE

Syntax symbol.TYPEtypeid

Description Withthe.TYPEdirectiveyousetasymbol’stypetothespecifiedvalueintheELFsymboltable.Validsymboltypesare: FUNC Thesymbolisassociatedwithafunctionorotherexecutablecode. OBJECT Thesymbolisassociatedwithanobjectsuchasavariable,anarray,orastructure. FILE Thesymbolnamerepresentsthefilenameofthecompilationunit. LabelsincodesectionshavethedefaulttypeFUNC.LabelsindatasectionshavethedefaulttypeOBJECT.

Example _Afunc:.TYPEFUNC

Relatedinformation

.SIZE(SetSymbolSize)

4−41 NiosIIEmbeddedToolsReference

.UNDEF

Syntax .UNDEFsymbol

Description Withthe.UNDEFdirectiveyoucanundefineasubstitutionstringthatwaspreviouslydefinedwiththe.DEFINEdirective.The substitutionstringassociatedwithsymbolisreleased,andsymbolwillnolongerrepresentavalid.DEFINEsubstitution. Theassemblerissuesawarningifyouredefineanexistingsymbol.

Example .UNDEFLEN

UndefinestheLENsubstitutionstringthatwaspreviouslydefinedwiththe.DEFINEdirective.

Relatedinformation

.DEFINE(Definesubstitutionstring)

4−42 AssemblyLanguage

.WEAK

Syntax .WEAKsymbol[,symbol]...

Description Withthe.WEAKdirectiveyoumarkoneormoresymbolsas’weak’.Thesymbolcanbedefinedinthesamemodulewiththe .GLOBALdirectiveorthe.EXTERNdirective.Ifthesymboldoesnotalreadyexist,itwillbecreated. A’weak’externalreferenceisresolvedbythelinkerwhenaglobal(orweak)definitionisfoundinoneoftheobjectfiles. However,aweakreferencewillnotcausetheextractionofamodulefromalibrarytoresolvethereference. Youcanoverruleaweakdefinitionwitha.GLOBALdefinitioninanothermodule.Thelinkerwillnotcomplainabouttheduplicate definition,andignoretheweakdefinition. Onlyprogramlabelsandsymbolsdefinedwith.EQUcanbemadeweak.

Example LOOPA.EQU1;definitionofsymbolLOOPA .GLOBALLOOPA;LOOPAwillbeglobally ;accessiblebyothermodules .WEAKLOOPA;marksymbolLOOPAasweak

Relatedinformation

.EXTERN(Importglobalsectionsymbol) .GLOBAL(Declareglobalsectionsymbol)

4−43 NiosIIEmbeddedToolsReference

4.9 MacroOperations

Macrosprovideashorthandmethodforinsertingarepeatedpatternofcodeorgroupofinstructions.Youcandefinethepattern asamacro,andthencallthemacroatthepointsintheprogramwherethepatternwouldrepeat. Somepatternscontainvariableentrieswhichchangeforeachrepetitionofthepattern.Othersaresubjecttoconditional assembly. Whenamacroiscalled,theassemblerexecutesthemacroandreplacesthecallbytheresultingin−linesourcestatements. ’In−line’meansthatallreplacementsactasiftheyareonthesamelineasthemacrocall.Thegeneratedstatementsmay containsubstitutablearguments.Thestatementsproducedbyamacrocanbeanyprocessorinstruction,almostanyassembler directive,oranypreviously−definedmacro.Sourcestatementsresultingfromamacrocallaresubjecttothesameconditions andrestrictionsasanyotherstatements. Macroscanbenested.Theassemblerprocessesnestedmacroswhentheoutermacroisexpanded.

4.9.1 DefiningaMacro

Thefirststepinusingamacroistodefineit. Thedefinitionofamacroconsistsofthreeparts: • Header,whichassignsanametothemacroanddefinesthearguments. • Body,whichcontainsthecodeorinstructionstobeinsertedwhenthemacroiscalled. • Terminator,whichindicatestheendofthemacrodefinition(.ENDMdirective). Amacrodefinitiontakesthefollowingform: macro_name.MACRO[arg[,arg]...][;comment] . sourcestatements . .ENDM Ifthemacronameisthesameasanexistingassemblerdirectiveormnemonicopcode,theassemblerreplacesthedirectiveor mnemonicopcodewiththemacroandissuesawarning. Theargumentsaresymbolicnamesthatthemacropreprocessorreplaceswiththeliteralargumentswhenthemacrois expanded(called).Eachargumentmustfollowthesamerulesasglobalsymbolnames.Argumentnamescannotstartwitha percentsign(%).

Example Considerthefollowingmacrodefinition:

RESERV.MACROval;reservespace .DSval .ENDM

Afterthefollowingmacrocall: .section.text RESERV8 .endsec

Themacroexpandsto: .DS8

4.9.2 CallingaMacro

Toinvokeamacro,constructasourcestatementwiththefollowingformat: [label]macro_name[arg[,arg...]][;comment] where: label Anoptionallabelthatcorrespondstothevalueofthelocationcounteratthestartofthemacroexpansion.

4−44 AssemblyLanguage macro_name Thenameofthemacro.Thismaynotstartinthefirstcolumn. arg Oneormoreoptional,substitutablearguments.Multipleargumentsmustbeseparatedbycommas. comment Anoptionalcomment. Thefollowingappliestomacroarguments: • Eachargumentmustcorrespondone−to−onewiththeformalargumentsofthemacrodefinition.Ifthemacrocalldoesnot containthesamenumberofargumentsasthemacrodefinition,theassemblerissuesawarning. • Ifanargumenthasanembeddedcommaorspace,youmustsurroundtheargumentbysinglequotes(’). • Youcandeclareamacrocallargumentasnullinthreeways: − enterdelimitingcommasinsuccessionwithnointerveningspaces macronameARG1,,ARG3;thesecondargumentisanullargument − terminatetheargumentlistwithacomma,theargumentsthatnormallywouldfollow,arenowconsiderednull macronameARG1,;thesecondandallfollowingargumentsarenull − declaretheargumentasanullstring • Nocharacterissubstitutedinthegeneratedstatementsthatreferenceanullargument.

4.9.3 UsingOperatorsforMacroArguments

Theassemblerrecognizescertaintextoperatorswithinmacrodefinitionswhichallowtextsubstitutionofargumentsduring macroexpansion.Youcanusetheseoperatorsfortextconcatenation,numericconversion,andstringhandling.

Operator Name Description \ Macroargument Concatenatesamacroargumentwithadjacentalphanumericcharacters. concatenation ? Returndecimal Substitutesthe?symbolsequencewithacharacterstringthatrepresentsthedecimalvalue valueofsymbol ofthesymbol. % Returnhex Substitutesthe%symbolsequencewithacharacterstringthatrepresentsthehexadecimal valueofsymbol valueofthesymbol. " Macrostring Allowstheuseofmacroargumentsasliteralstrings. delimiter ^ Macrolocallabel Preventsnamemanglingonlabelsinmacros. override

Example:ArgumentConcatenationOperator−\ Considerthefollowingmacrodefinition: MAC_A.MACROreg,val addir\reg,r\reg,val .ENDM

Themacroiscalledasfollows: MAC_A2,1

Themacroexpandsasfollows: addir2,r2,1

Themacropreprocessorsubstitutesthecharacter’2’fortheargumentreg,andthecharacter’1’fortheargumentval.The concatenationoperator(\)indicatestothemacropreprocessorthatthesubstitutioncharactersfortheargumentsaretobe concatenatedwiththecharacters’r’. Withoutthe’\’operatorthemacrowouldexpandas: addirreg,rreg,1 whichresultsinanassemblererror(invalidoperand).

4−45 NiosIIEmbeddedToolsReference

Example:DecimalValueOperator−? Insteadofsubstitutingtheformalargumentswiththeactualmacrocallarguments,youcanalsousethevalueofthemacrocall arguments. ConsiderthefollowingsourcecodethatcallsthemacroMAC_AaftertheargumentAVALhasbeensetto1. AVAL.SET1 MAC_A2,AVAL

IfyouwanttoreplacetheargumentvalwiththevalueofAVALratherthanwiththeliteralstring’AVAL’,youcanusethe? operatorandmodifythemacroasfollows: MAC_A.MACROreg,val addir\reg,r\reg,?val .ENDM

Example:HexValueOperator−%

Thepercentsign(%)issimilartothestandarddecimalvalueoperator(?)exceptthatitreturnsthehexadecimalvalueofa symbol. Considerthefollowingmacrodefinition: GEN_LAB.MACROLAB,VAL,STMT LAB\%VALSTMT .ENDM

ThemacroiscalledafterNUMhasbeensetto10: NUM.SET10 GEN_LABHEX,NUM,NOP

Themacroexpandsasfollows: HEXANOP

The%VALargumentisreplacedbythecharacter’A’whichrepresentsthehexadecimalvalue10oftheargumentVAL.

Example:ArgumentStringOperator−" Togeneratealiteralstring,enclosedbysinglequotes(’),youmustusetheargumentstringoperator(")inthemacrodefinition. Considerthefollowingmacrodefinition: STR_MAC.MACROSTRING .DB"STRING" .ENDM

Themacroiscalledasfollows: STR_MACABCD

Themacroexpandsasfollows: .DB’ABCD’

Withindoublequotes.DEFINEdirectivedefinitionscanbeexpanded.Takecarewhenusingconstructionswithquotesand doublequotestoavoidinappropriateexpansions.Since.DEFINEexpansionoccursbeforemacrosubstitution,any.DEFINE symbolsarereplacedfirstwithinamacroargumentstring: .DEFINELONG’short’ STR_MAC.MACROSTRING .MESSAGEI’ThisisaLONGSTRING’ .MESSAGEI"ThisisaLONGSTRING" .ENDM

Ifthemacroiscalledasfollows: STR_MACsentence

4−46 AssemblyLanguage itexpandsas: .MESSAGEI’ThisisaLONGSTRING’ .MESSAGEI’Thisisashortsentence’

MacroLocalLabelOverrideOperator−^ Ifyouuselabelsinmacros,theassemblernormallygeneratesanotheruniquenameforthelabels(suchas LOCAL__M_L000001). Themacro^−operatorpreventsnamemanglingonmacrolocallabels. Considerthefollowingmacrodefinition: INIT.MACROaddr LOCAL:ldwr2,@gprel(^addr)(gp) .ENDM

Themacroiscalledasfollows: LOCAL: INITLOCAL

Themacroexpandsas: LOCAL__M_L000001:ldwr2,@gprel(LOCAL)(gp)

Ifyouwouldnothaveusedthe^operator,themacropreprocessorwouldchooseanothernameforLOCALbecausethelabel alreadyexists.Themacrowouldexpandlike: LOCAL__M_L000001:ldwr2,@gprel(LOCAL__M_L000001)(gp)

4.9.4 Usingthe.FORand.REPEATDirectivesasMacros

The.FORand.REPEATdirectivesarespecializedmacroformstorepeatablockofsourcestatements.Youcanthinkofthem asasimultaneousdefinitionandcallofanunnamedmacro.Thesourcestatementsbetweenthe.FORand.ENDFORdirectives and.REPEATand.ENDREPdirectivesfollowthesamerulesasmacrodefinitions.

Foradetaileddescriptionofthesedirectives,seesection4.8,AssemblerDirectives.

4.9.5 ConditionalAssembly

Withtheconditionalassemblydirectivesyoucaninstructthemacropreprocessortouseapartofthecodethatmatchesa certaincondition. Youcanspecifyassemblyconditionswithargumentsinthecaseofmacros,orthroughdefinitionofsymbolsviathe.DEFINE, .SET,and.EQUdirectives. Thebuilt−infunctionsoftheassemblerprovideaversatilemeansoftestingmanyconditionsoftheassemblyenvironment. Youcanuseconditionaldirectivesalsowithinamacrodefinitiontocheckatexpansiontimeifargumentsfallwithinarangeof allowablevalues.Inthiswaymacrosbecomeself−checkingandcangenerateerrormessagestoanydesiredlevelofdetail. Theconditionalassemblydirective.IF/.ENDIFhasthefollowingform: .IFexpression . . [.ELIFexpression];(the.ELIFdirectiveisoptional) . . [.ELSE];(the.ELSEdirectiveisoptional) . . .ENDIF

4−47 NiosIIEmbeddedToolsReference

Asectionofaprogramthatistobeconditionallyassembledmustbeboundedbyan.IF−.ENDIFdirectivepair.Iftheoptional .ELSEand/or.ELIFdirectivesarenotpresent,thenthesourcestatementsfollowingthe.IFdirectiveanduptothenext .ENDIFdirectivewillbeincludedaspartofthesourcefilebeingassembledonlyiftheexpressionhadanon−zeroresult. Iftheexpressionhasavalueofzero,thesourcefilewillbeassembledasifthosestatementsbetweenthe.IFandthe.ENDIF directiveswereneverencountered. Ifthe.ELSEdirectiveispresentandexpressionhasanonzeroresult,thenthestatementsbetweenthe.IFand.ELSE directiveswillbeassembled,andthestatementbetweenthe.ELSEand.ENDIFdirectiveswillbeskipped.Alternatively,if expressionhasavalueofzero,thenthestatementsbetweenthe.IFand.ELSEdirectiveswillbeskipped,andthestatements betweenthe.ELSEand.ENDIFdirectiveswillbeassembled.

4−48 AssemblyLanguage

4.10 GenericInstructions

Theassemblersupportsso−called’genericinstructions’.Genericinstructionsarepseudoinstructions(noinstructionsfromthe instructionset).Dependingonthesituationinwhichagenericinstructionisused,theassemblerreplacesthegenericinstruction withappropriaterealassemblyinstruction(s). TheNiosIIassemblerrecognizesthefollowinggenericinstructions:

Instruction Replacement BGTrA,rB,label BLTrB,rA,label BGTUrA,rB,label BLTUrB,rA,label BLErA,rB,label BGErB,rA,label BLEUrA,rB,label BGEUrB,rA,label CMPGTrC,rA,rB CMPLTrC,rB,rA CMPGTIrB,rA,imm16 CMPGEIrB,rA,(imm16+1) CMPGTUrC,rA,rB CMPLTUrC,rB,rA CMPGTUIrB,rA,imm16 CMPGEUIrB,rA,(imm16+1) CMPLErC,rA,rB CMPGErC,rB,rA CMPLEIrB,rA,imm16 CMPLTIrB,rA,(imm16+1) CMPLEUrC,rA,rB CMPGEUrC,rB,rA CMPLEUIrB,rA,imm16 CMPLTUIrB,rA,(imm16+1) ldstmnemrB,label ORHIAT,R0,@HIADJ(label) whereldstmnemcanbe: ldstmnemrB,@LO(label)(AT) LDB,LDBIO,LDBU,LDBUIO, LDH,LDHIO,LDHU,LDHUIO, LDW,LDWIO,STB,STBIO, STH,STHIO,STW,STWIO MOVrC,rA ADDrC,rA,R0 MOVHIrB,imm16 ORHIrB,R0,imm16 MOVIrB,imm16 ADDIrB,R0,imm16 MOVIArB,label ORHIrB,R0,@HI(label) ORIrB,rB,@LO(label) MOVUIrB,imm16 ORIrB,R0,imm16 NOP ADDR0,R0,R0 RORIrC,rA,imm5 ROLIrC,rA,(32−imm5) SUBIrB,rA,imm16 ADDIrB,rA,−(imm16)

4−49 NiosIIEmbeddedToolsReference

4−50 5 ToolOptions

Summary ThischapterprovidesadetaileddescriptionoftheoptionsfortheCcompiler,C++ compiler,assembler,linker,controlprogram,makeprogramandthelibrarian.

5.1 CCompilerOptions

AltiumDesignerusesamakefiletobuildyourentireproject.ThismeansthatinAltiumDesigneryoucannotrunthecompiler separately.IfyoucompileasingleCsourcefilefromwithinAltiumDesigner,thefileisalsoassembled.However,youcanset optionsspecificforthecompiler.

OptionsinAltiumDesignerversusoptionsonthecommandline MostcommandlineoptionshaveanequivalentoptioninAltiumDesignerbutsomeoptionsareonlyavailableonthecommand line(forexampleinaWindowsCommandPrompt).IfthereisnoequivalentoptioninAltiumDesigner,youcanspecifya commandlineoptioninAltiumDesignerasfollows: 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheCCompilerentryandselectMiscellaneous. 3. EnteroneormorecommandlineoptionsintheAdditionalCcompileroptionsfield.

Invocationsyntaxonthecommandline(WindowsCommandPrompt) Tocallthecompilerfromthecommandline,usethefollowingsyntax: cnios[[option]...[file]...]...

TheinputfilemustbeaCsourcefile(.cor.ic).

5−1 NiosIIEmbeddedToolsReference

Shortandlongoptionnames Optionscanhavebothshortandlongnames.Shortoptionnamesalwaysbeginwithasingleminus(−)character,longoption namesalwaysbeginwithdoubleminus(−−)characters.Youcanabbreviatelongoptionnamesaslongasthenameisunique. Youcanmixshortandlongoptionnamesonthecommandline. Optionscanhaveflagsorsub−options.Toswitchaflag’on’,usealowercaseletterora+longflag.Toswitchaflagoff,usean uppercaseletterora−longflag.Separatelongflagswithcommas.Thefollowingtwoinvocationsareequivalent: cnios−Oactest.c cnios−−optimize=+coalesce,+csetest.c

Whenyoudonotspecifyanoption,adefaultvaluemaybecomeactive.

5−2 ToolOptions−CCompiler

CCompiler:−−align−composites

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheCCompilerentryandselectCodeGeneration. 3. SelecttheAlignmentofcompositetypes:NaturalalignmentorOptimalalignment

Commandlinesyntax −−align−composites=alignment Youcanspecifythefollowingalignments: n Naturalalignment(default) o Optimalalignment

Description Withthisoptionyoucansetthealignmentforcompositetypes(structs,unionsandarrays). Naturalalignment(n)usesthenaturalalignmentofthemost−alignedmemberofthecompositetype. Optimalalignment(o)setsthealignmentto8,16,or32bitsdependingonthesizeofthecompositetype.

Relatedinformation

5−3 NiosIIEmbeddedToolsReference

CCompiler:−−bypass−cache

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheCCompilerentryandselectCodeGeneration. 3. EnabletheoptionBypassdatacache.

Commandlinesyntax −−bypass−cache

Description Withthisoptionyoutellthecompilertouseiovariantsforloadandstoreinstructionsthatbypassthedatacache.

Relatedinformation

Ccompileroption−−nocache−volatile(Bypassdatacacheforvolatiles)

5−4 ToolOptions−CCompiler

CCompiler:−−call(−m)

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheCCompilerentryandselectCodeGeneration. 3. SettheoptionSelectcallmodetoUse28−bitPC−regioncalls(default)or toUse32−bitindirectcalls.

Commandlinesyntax −−call={far|near} −m{f|n}

Description ToaddressthememoryoftheNiosII,youcanusetwodifferentcallmodes: far 32−bitindirectcalls.Thoughyoucanaddressthefullrangeofmemory,theaddressisfirstloadedintoaregisterafter whichthecallisexecuted. near 28−bitPC−regioncall.ThePC−regioncallisdirectlycodedintotheCALLinstruction.Thiswayofcallingresultsinhigher executionspeed.However,notthefullrangeofmemorycanbeaddressedwithnearcalls.TheCALLinstructiononthe NiosIIcanonlytargetaddressesinthecurrent256MB−alignedregion.

IfyoucompileyourCsourcewithnearcallsbutthecalledaddresscannotbereachedwithanearcall,thelinkerwill generateanerror. Itisrecommendedtousethenearaddressingmodeunlessyourapplicationneedscallstoaddressesthatfalloutsidea256MB region.

Relatedinformation

5−5 NiosIIEmbeddedToolsReference

CCompiler:−−cert

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheCCompilerentryandselectCERTCSecureCodeChecking. 3. MakeaselectionfromtheCERTCsecurecodecheckinglist. 4. IfyouselectCustomconfiguration,expandtheCustomConfigurationentryandenableoneormoreindividual recommendations/rules.

Commandlinesyntax −−cert={all|name[−name],...}

Description WiththisoptionyoucanenableoneormorechecksforCERTCSecureCodingStandardrecommendations/rules.Whenyou omittheargument,allchecksareenabled.nameisthenameofaCERTrecommendation/rule,consistingofthreelettersand twodigits.Specifyonlythethree−lettermnemonictoselectawholecategory.Forthelistofnamesyoucanuse,seeChapter9, CERTCSecureCodingStandard. Onthecommandlineyoucanuse−−diag=certtoseealistoftheavailablechecks,oryoucanuseathree−lettermnemonicto listonlythechecksinaparticularcategory.Forexample,−−diag=prelistsallsupportedpreprocessorchecks.

Example ToenablethecheckforCERTruleSTR30−C,enter: cnios−−cert=str30test.c

Relatedinformation

Chapter9,CERTCSecureCodingStandard Ccompileroption−−diag(Explanationofdiagnosticmessages)

5−6 ToolOptions−CCompiler

CCompiler:−−check

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheCCompilerentryandselectMiscellaneous. 3. Addtheoption−−checktotheAdditionalCcompileroptionsfield.

Commandlinesyntax −−check

Description Withthisoptionyoucancheckthesourcecodeforsyntaxerrors,withoutgeneratingcode.Thissavestimeindevelopingyour applicationbecausethecodewillnotactuallybecompiled. Thecompilerreportsanywarningsand/orerrors.

Relatedinformation

Assembleroption−−check(Checksyntax)

5−7 NiosIIEmbeddedToolsReference

CCompiler:−−cpu(−C)

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheProcessorentryandselectProcessorDefinition. 3. SelectaprocessorfromtheSelectprocessorbox.

Commandlinesyntax −−cpu=[nios2e|nios2f|nios2s] −C[nios2e|nios2f|nios2s]

Description WiththisoptionyoudefinetheCPUcoreforwhichyoucreateyourapplication.TheNiosIItargethasmorethanoneprocessor typeandthereforeyouneedtospecifyforwhichprocessortypethecompilershouldcompile. Theeffectofthisoptionisthatthecompilerusestheappropriateinstructionset.YouchooseoneofthefollowingCPU’s:Nios II/e,NiosII/forNiosII/s.

Example Tocompilethefiletest.cfortheNiosII/eprocessortype,enterthefollowingonthecommandline: cnios−−cpu=nios2etest.c

Whenyoucallthecompilerfromthecommandline,makesureyouspecifythesamecoretypetotheassemblertoavoid conflicts!

Relatedinformation

5−8 ToolOptions−CCompiler

CCompiler:−−custom−instruction

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheCCompilerentryandselectMiscellaneous. 3. Addtheoption−−custom−instructiontotheAdditionalCcompileroptionsfield.

Commandlinesyntax −−custom−instruction=name:number,...

Description Withthisoptionyoutellthecompilertoselectacustominstructionandassignanumber(0−255)toit. WithAlteraNiosIIyoucanusethefollowingcustomfloating−pointinstructions: fmuls:252 fadds:253 fsubs:254 fdivs:255

Relatedinformation

NiosIICustomInstructionUserGuide[AlteraCorporation]

5−9 NiosIIEmbeddedToolsReference

CCompiler:−−debug−info(−g)

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheCCompilerentryandselectDebugInformation. 3. EnabletheoptionGeneratesymbolicdebuginformation. 4. Enableordisablethesuboptions.

Commandlinesyntax −−debug−info[=suboption] −g[suboption] Youcansetthefollowingsuboptions(whenyouspecify−gwithoutsuboption,thedefaultis−gd): small (1|c) Emitsmallsetofdebuginformation. default (2|d) Emitdefaultsymbolicdebuginformation. all (3|a) Emitfullsymbolicdebuginformation.

Description Withthisoptionyoutellthecompilertoadddirectivestotheoutputfileforincludingsymbolicinformation.Thisfacilitateshigh leveldebuggingbutincreasesthesizeoftheresultingassemblerfile(andthusthesizeoftheobjectfile).Forthefinal application,compileyourCfileswithoutdebuginformation. Whenyouspecifyahighoptimizationlevel,debugcomfortmaydecrease.Therefore,thecompilerissuesawarningifthe chosenoptimizationsexpecttoaffecteaseofdebugging. Smallsetofdebuginformation WiththissuboptiononlyDWARFcallframeinformationandtypeinformationaregenerated.Thisenablesyoutoinspect parametersofnestedfunctions.Thetypeinformationimprovesdebugging.Youcanperformastacktrace,butsteppingisnot possiblebecausedebuginformationonfunctionbodiesisnotgenerated.Youcanusethissuboption,forexample,to compactlibraries. Defaultdebuginformation Thisprovidesalldebuginformationyouneedtodebugyourapplication.Itmeetsthedebuggingrequirementsinmostcases withoutresultinginover−sizedassembler/objectfiles. Fulldebuginformation Withthisinformationextradebuginformationisgenerated.Inextra−ordinarycasesyoumayusethisdebuginformation(for instance,ifyouuseyourowndebuggerwhichmakesuseofthisinformation).Withthissuboption,theresulting assembler/objectfileincreasessignificantly.

Relatedinformation

5−10 ToolOptions−CCompiler

CCompiler:−−define(−D)

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheCCompilerentryandselectPreprocessing. 3. SelectUsermacroandclickonthedownarrowintherightpanetoexpandmacroinput. 4. ClickonanemptyMacrofieldandenteramacroname.(Thenclickanemptytoconfirm) 5. Optionally,clickintheValuefieldandenteradefinition.(Thenclickanemptycelltoconfirm)

Commandlinesyntax

−−define=macro_name[=macro_definition] −Dmacro_name[=macro_definition]

Description Withthisoptionyoucandefineamacroandspecifyittothepreprocessor.Ifyouonlyspecifyamacroname(nomacro definition),themacroexpandsas’1’.Youcanspecifyasmanymacrosasyoulike. Onthecommandline,youcanusetheoption−−define(−D)multipletimes.Ifthecommandlineexceedsthelengthlimitofthe operatingsystem,youcandefinethemacrosinanoptionfilewhichyouthenmustspecifytothecompilerwiththeoption −−option−file=file(−f). Definingmacroswiththisoption(insteadofintheCsource)is,forexample,usefultocompileconditionalCsourceasshownin theexamplebelow.

Example ConsiderthefollowingCprogramwithconditionalcodetocompileademoprogramandarealprogram: voidmain(void) { #ifDEMO==1 demo_func();/*compileforthedemoprogram*/ #else real_func();/*compilefortherealprogram*/ #endif }

YoucannowuseamacrodefinitiontosettheDEMOflag: Macro Value DEMO 1(orempty) Onthecommandline,usetheoptionasfollows: cnios−−define=DEMOtest.c cnios−−define=DEMO=1test.c

Notethatbothinvocationshavethesameeffect. Thenextexampleshowshowtospecifyamacrowitharguments.Macrodefinitionsfollowexactlythesamerulesasthe #definestatementintheClanguage. Macro Value MAX(A,B) ((A)>(B)?(A):(B))

Onthecommandline,usetheoption−Dasfollows: cnios−D"MAX(A,B)=((A)>(B)?(A):(B))"test.c

5−11 NiosIIEmbeddedToolsReference

Notethatthemacronameanddefinitionareplacedbetweendoublequotesbecauseotherwisethespaceswouldindicateanew option.

Relatedinformation

Ccompileroption−−undefine(Undefinepreprocessormacro) Ccompileroption−−option−file(Readoptionsfromfile)

5−12 ToolOptions−CCompiler

CCompiler:−−dep−file

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheCCompilerentryandselectMiscellaneous. 3. Addtheoption−−dep−filetotheAdditionalCcompileroptionsfield.

Commandlinesyntax −−dep−file[=file]

Description WiththisoptionyoutellthecompilertogeneratedependencylinesthatcanbeusedinaMakefile.Incontrasttotheoption −−preprocess=+make(−Em),thedependencyinformationwillbegeneratedinadditiontothenormaloutputfile. Bydefault,theinformationiswrittentoafilewithextension.d(oneforeveryinputfile).Whenyouspecifyafilename,all dependencieswillbecombinedinthespecifiedfile.

Example cnios−−dep−file=test.deptest.c

Thecompilercompilesthefiletest.c,whichresultsintheoutputfiletest.src,andgeneratesdependencylinesinthefile test.dep.

Relatedinformation

Ccompileroption−−preprocess=+make(Generatedependenciesformake)

5−13 NiosIIEmbeddedToolsReference

CCompiler:−−diag

Menuentry 1. FromtheViewmenu,selectWorkspace»Panels»SystemMessages. TheMessagepannelappears. 2. IntheMessagepanel,right−clickonthemessageyouwantmoreinformationon. Apopupmenuappears. 3. SelectMoreInfo. AMessageInfoboxappearswithadditionalinformation.

Commandlinesyntax

−−diag=[format:]{all|msg[−msg],...}

Description Withthisoptionyoucanaskforanextendeddescriptionoferrormessagesintheformatyouchoose.Theoutputisdirectedto stdout(normallyyourscreen)andintheformatyouspecify.Youcanspecifythefollowingformats:html,rtfortext(default). Tocreateafilewiththedescriptions,youmustredirecttheoutput. Withthesuboptionall,thedescriptionsofallerrormessagesaregiven(exceptfortheCERTchecks).Ifyouwantthe descriptionofoneormoreselectederrormessages,youcanspecifytheerrormessagenumbers,separatedbycommas,oryou canspecifyarange. With−−diag=certyoucanseealistoftheavailableCERTchecks,oryoucanuseathree−lettermnemonictolistonlythe checksinaparticularcategory.Forexample,−−diag=prelistsallsupportedpreprocessorchecks. Withthisoptionthecompilerdoesnotcompileanyfiles.

Example Todisplayanexplanationofmessagenumber282,enter: cnios−−diag=282

Thisresultsinthefollowingmessageandexplanation: E282:unterminatedcomment Makesurethateverycommentstartingwith/*hasamatching*/.Nestedcommentsarenot possible.

TowriteanexplanationofallerrorsandwarningsinHTMLformattofilecerrors.html,useredirectionandenter: cnios−−diag=html:all>cerrors.html

Relatedinformation

Ccompileroption−−cert(EnableindividualCERTchecks)

5−14 ToolOptions−CCompiler

CCompiler:−−endianness

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheProcessorentryandselectProcessorDefinition. 3. EnabletheoptionBig−endianmode.

Commandlinesyntax −−endianness=endianness −B −−big−endian Youcanspecifythefollowingendianness: big (b) Bigendian little (l) Littleendian(default)

Description Bydefault,thecompilergeneratescodeforalittle−endiantarget(leastsignificantbyteofawordatlowestbyteaddress).With −−endianness=bigthecompilergeneratescodeforabig−endiantarget(mostsignificantbyteofawordatlowestbyte address).−Bisanaliasforoption−−endianness=big.

Relatedinformation

5−15 NiosIIEmbeddedToolsReference

CCompiler:−−error−file

Menuentry Commandlineonly.

Commandlinesyntax

−−error−file[=file]

Description Withthisoptionthecompilerredirectserrormessagestoafile. Ifyoudonotspecifyafilename,theerrorfilewillbenamedaftertheinputfilewithextension.err.

Example Towriteerrorstoerrors.errinsteadofstderr,enter: cnios−−error−file=errors.errtest.c

Relatedinformation

5−16 ToolOptions−CCompiler

CCompiler:−−extern−sdata

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheCCompilerentryandselectCodeGeneration. 3. EnabletheoptionEnableallocationinsdata. 4. SpecifyasizeforAllocationinsdataforobjectssmallerthanthreshold(default:4) 5. EnabletheoptionAssumeexternaldataobjectswillalsobeplacedinsdata.

Commandlinesyntax −−extern−sdata

Description Withthisoptionyoutellthecompilertousesmalldataaddressingforexternaldataaswellasforsymbolsdefinedinthecurrent module. Thisoptionisanadditiontotheoption−−sdata.Externaldatathatfallswithinthethresholdofoption−−sdata,isnotconsidered partofsdata.Ifyouwantexternaldatatobepartofthistoo,alsospecifyoption−−extern−sdata.

Ifyouuseoption−−extern−sdata,youmustusetheoption−−sdatawiththesamevalueforallmodulesinyour application.

Example Toputallglobal,staticandexternaldataobjectswithasizeof8bytesorsmallerintothesdatasection: cnios−−sdata=8−−extern−datatest.c

Relatedinformation

Ccompileroption−−sdata=size

5−17 NiosIIEmbeddedToolsReference

CCompiler:−−global−type−checking

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheCCompilerentryandselectDiagnostics. 3. EnabletheoptionPerformglobaltypecheckingonCcode.

Commandlinesyntax −−global−type−checking

Description TheCcompileralreadyperformstypecheckingwithineachmodule.Usethisoptionwhenyouwantthelinkertoperformtype checkingbetweenmodules.

Relatedinformation

5−18 ToolOptions−CCompiler

CCompiler:−−help(−?)

Menuentry Commandlineonly.

Commandlinesyntax

−−help[=item,...] −? Youcanspecifythefollowingarguments: intrinsics (i) Showthelistofintrinsicfunctions options (o) Showextendedoptiondescriptions pragmas (p) Showthelistofsupportedpragmas typedefs (t) Showthelistofpredefinedtypedefs

Description Displaysanoverviewofallcommandlineoptions.Withanargumentyoucanspecifywhichextendedinformationisshown.

Example Thefollowinginvocationsalldisplayalistoftheavailablecommandlineoptions: cnios−? cnios−−help cnios

Thefollowinginvocationdisplaysalistoftheavailablepragmas: cnios−−help=pragmas

5−19 NiosIIEmbeddedToolsReference

CCompiler:−−include−directory(−I)

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. SelectBuildOptions. 3. AddapathnameintheIncludefilespathfield. Ifyouentermultiplepaths,separatethemwithasemicolon(;).

Commandlinesyntax −−include−directory=path,... −Ipath,...

Description Withthisoptionyoucanspecifythepathwhereyourincludefilesarelocated.Arelativepathwillberelativetothecurrent directory. Theorderinwhichthecompilersearchesforincludefilesis: 1. ThepathnameintheCsourcefileandthedirectoryoftheCsource (onlyfor#includefilesthatareenclosedin""). 2. Thepaththatisspecifiedwiththisoption. 3. ThepaththatisspecifiedintheenvironmentvariableCNIOSINCwhentheproductwasinstalled. 4. Thedefaultincludedirectoryrelativetotheinstallationdirectory (unlessyouspecifiedoption−−no−stdinc).

Example SupposethattheCsourcefiletest.ccontainsthefollowinglines: #include #include"myinc.h"

YoucanspecifytheincludedirectorymyincludetotheCcompiler: cnios−−include−directory=myincludetest.c

Firstthecompilerlooksforthefilestdio.hinthedirectorymyincluderelativetothecurrentdirectory.Ifitwasnotfound,the compilersearchesintheenvironmentvariableandtheninthedefaultincludedirectory. Thecompilernowlooksforthefilemyinc.h,inthedirectorywheretest.cislocated.Ifthefileisnottherethecompiler searchesinthedirectorymyinclude.Ifitwasstillnotfound,thecompilersearchesintheenvironmentvariableandtheninthe defaultincludedirectory.

Relatedinformation

Ccompileroption−−include−file(Includefileatthestartofacompilation) Ccompileroption−−no−stdinc(Skipstandardincludefilesdirectory)

5−20 ToolOptions−CCompiler

CCompiler:−−include−file(−H)

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheCCompilerentryandselectPreprocessing. 3. EnterthenameofthefileintheIncludethisfilebeforesourcefieldorclick...andselectafile.

Commandlinesyntax −−include−file=file,... −Hfile,...

Description Withthisoption(setatprojectlevel)youincludeoneextrafileatthebeginningofeachCsourcefileinyourproject.Ona documentlevel(Project»DocumentOptions),youcanoverrulethisoptionwithanotherfileornofileatall. Thespecifiedincludefileisincludedbeforeallotherincludes.Thisisthesameasspecifying#include"file"atthevery beginningof(eachof)yourCsourcefiles.

Example cnios−−include−file=stdio.htest1.ctest2.c

Thefilestdio.hisincludedatthebeginningofbothtest1.candtest2.c.

Relatedinformation

Ccompileroption−−include−directory(Adddirectorytoincludefilesearchpath) Section2.4,HowtheCompilerSearchesIncludeFiles,inchapterUsingtheCompileroftheuser’smanual.

5−21 NiosIIEmbeddedToolsReference

CCompiler:−−inline

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheCCompilerentryandselectOptimization. 3. EnabletheoptionAlwaysinlinefunctioncalls.

Commandlinesyntax −−inline

Description Withthisoptionyouinstructthecompilertoinlinecallstofunctionswithoutthe__noinlinefunctionqualifierwhenever possible.Thisoptionhasthesameeffectasa#pragmainlineatthestartofthesourcefile.

Thisoptioncanbeusefultoincreasethepossibilitiesforcodecompaction (compileroption−−optimize=+compact).

Relatedinformation

Ccompileroption−−optimize=+compact(Codecompaction)

5−22 ToolOptions−CCompiler

CCompiler:−−inline−max−incr/−−inline−max−size

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheCCompilerentryandselectOptimization. 3. SettheoptionMaximumcodesizeincreasecausedbyinliningtoavalue. 4. SettheoptionMaximumsizeforfunctionstoalwaysinlinetoavalue.

Commandlinesyntax −−inline−max−incr=percentage (Default:−1) −−inline−max−size=threshold (Default:−1)

Description Withtheseoptionsyoucancontroltheautomaticfunctioninliningoptimizationprocessofthecompiler.Theseoptionshaveonly effectwhenyouhaveenabledtheinliningoptimization(option−Oi).

Regardlessoftheoptimizationprocess,thecompileralwaysinlinesallfunctionsthathavethefunctionqualifierinline. Withtheoption−−inline−max−sizeyoucanspecifythemaximumsizeoffunctionsthatthecompilerinlinesaspartofthe optimizationprocess.Thecompileralwaysinlinesallfunctionsthataresmallerthanthespecifiedthreshold.Thethresholdis measuredincompilerinternalunitsandthecompilerusesthismeasuretodecidewhichfunctionsaresmallenoughtoinline. Thedefaultthresholdis−1,whichmeansthatthethresholddependsontheoption−−tradeoff. Afterthecompilerhasinlinedallfunctionsthathavethefunctionqualifierinlineandallfunctionsthataresmallerthanthe specifiedthreshold,thecompilerlookswhetheritcaninlinemorefunctionswithoutincreasingthecodesizetoomuch.Withthe option−−inline−max−incryoucanspecifyhowmuchthecodesizeisallowedtoincrease.Thedefaultvalueis−1,which meansthatthevaluedependsontheoption−−tradeoff.

Example cnios−−inline−max−incr=40−−inline−max−size=15test.c

Thecompilerfirstinlinesallfunctionswiththefunctionqualifierinlineandallfunctionsthataresmallerthanthespecified thresholdof15.Ifthecodesizehasstillnotincreasedwith40%,thecompilerdecideswhichotherfunctionsitcaninline.

Relatedinformation

Ccompileroption−−optimize=+inline(Optimization:automaticfunctioninlining) Section1.7.3,InliningFunctions,inchapterCLanguage. Section2.6.3,OptimizeforSizeorSpeed,inchapterUsingtheCompileroftheuser’smanual.

5−23 NiosIIEmbeddedToolsReference

CCompiler:−−iso(−c)

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheCCompilerentryandselectLanguage. 3. SelecttheISOCstandardC90orC99.

Commandlinesyntax −−iso={90|99} −c{90|99}

Description WiththisoptionyouselecttheISOCstandard.ThecompilercheckstheCsourceagainstthisstandardandmaygenerate warningsorerrorsifyouuseClanguagethatisnotdefinedinthestandard. C90isalsoreferredtoasthe"ANSICstandard".C99referstothenewerISO/IEC9899:1999(E)standard.C99isthedefault. cnios−−iso=90test.c

Relatedinformation

Ccompileroption−−language(Languageextensions)

5−24 ToolOptions−CCompiler

CCompiler:−−keep−output−files(−k)

Menuentry AltiumDesigneralwaysremovesthe.srcfilewhenerrorsoccurduringcompilation.

Commandlinesyntax −−keep−output−files −k

Description Ifanerroroccursduringcompilation,theresulting.srcfilemaybeincompleteorincorrect.Withthisoptionyoukeepthe generatedoutputfile(.src)whenanerroroccurs. Bydefaultthecompilerremovesthegeneratedoutputfile(.src)whenanerroroccurs.Thisisusefulwhenyouusethemake utility.Iftheerroneousfilesarenotremoved,themakeutilitymayprocesscorruptfilesonasubsequentinvocation. Usethisoptionwhenyoustillwanttoinspectthegeneratedassemblysource.Evenifitisincompleteorincorrect.

Relatedinformation

5−25 NiosIIEmbeddedToolsReference

CCompiler:−−language(−A)

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheCCompilerentryandselectLanguage. 3. Enableordisablethefollowingoptions: • AllowGNUCextensions • AllowC++stylecommentsinISOC90mode(onlyavailablewhenISOC90isselected) • Checkassignmentofstringliteraltonon−conststringpointer • Allowoptimizationacrossvolatileaccess Commandlinesyntax

−−language=[flags] −A[flags] Youcansetthefollowingflags: +/−gcc (g/G) Enableanumberofgccextensions +/−comments (p/P) AllowC++stylecommentsinCsourcecode +/−volatile (v/V) Donotoptimizeacrossvolatileaccess +/−strings (x/X) Relaxedconstcheckforstringliterals Theoption−−language(−A)istheequivalentof−AGPVXwhichdisablesalllanguageextensions. Thedefaultis−AGpVx.

Description Withthisoptionyoucontrolthelanguageextensionsthecompileraccepts.DefaulttheCcompilerallowsalllanguage extensions. WithAllowC++stylecommentsinISOC90mode(−−language=+comments),youtellthecompilertoallowC++style comments(//)inISOC90mode(option−c90).InISOC99modethisstyleofcommentsisalwaysaccepted. WithCheckassignmentofstringliteraltonon−conststringpointer(−−language=−strings)youtellthecompilerto generateawarningwhenyouassignaconstantstringtoanon−constantstringpointer.Whenyoudisablethisoptionthe followingexampleproducesnowarning: char*p; voidmain(void){p="hello";}

WithoptionAllowGNUCextensions(−−language=+gcc)youtellthecompilertoenablethefollowinggcclanguages extensions: • Theidentifier__FUNCTION__expandstothecurrentfunctionname • Alternativesyntaxforvariadicmacros • Alternativesyntaxfordesignatedinitializers • Allowzerosizedarrays • Allowemptystruct/union • Allowemptyinitializerlist • Allowinitializationofstaticobjectsbycompoundliterals • Themiddleoperandofa?:operatormaybeomitted • Allowacompoundstatementinsidebracesasexpression • Allowarithmeticonvoidpointersandfunctionpointers • Allowarangeofvaluesafterasinglecaselabel • Additionalpreprocessordirective#warning • Allowcommaoperator,conditionaloperatorandcastaslvalue • Aninlinefunctionwithout"static"or"extern"willbeglobal

5−26 ToolOptions−CCompiler

• An"externinline"functionwillnotbecompiledonitsown • An__attribute__directlyfollowingastruct/uniondefinitionrelatestothattaginsteadoftotheobjectsinthedeclaration. Foranexactdescriptionofthesegccextensions,pleaserefertothegccinfopages(infogcc). WhenyoudisabletheoptionAllowoptimizationacrossvolatileaccess(with−−language=+volatile),youtellthecompilerto blockoptimizationswhenreadingorwritingavolatileobject,bytreatingtheaccessasacalltoanunknownfunction.Thisway youcanpreventforexamplethatcodebelowthevolatileobjectisoptimizedawaytosomewhereabovethevolatileobject. Example: externunsignedintvariable; externvolatileunsignedintaccess;

voidTestFunc(unsignedintflag) { access=0; variable|=flag; if(variable==3) { variable=0; } variable|=0x8000; access=1; }

Resultwith−−language=−volatile(default): Resultwith−−language=+volatile:

Example cnios−AGPx−c90test.c cnios−−language=−ggc,−comments,+strings−−iso=90test.c

Ccompileroption−−iso(ISOCstandard)

5−27 NiosIIEmbeddedToolsReference

CCompiler:−−make−target

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheCCompilerentryandselectMiscellaneous. 3. Addtheoption−−make−targettotheAdditionalCcompileroptionsfield.

Commandlinesyntax −−make−target=name

Description Withthisoptionyoucanoverrulethedefaulttargetnameinthemakedependenciesgeneratedbytheoptions −−preprocess=+make(−Em)and−−dep−file.Thedefaulttargetnameisthebasenameoftheinputfile,withextension.obj.

Relatedinformation

Ccompileroption−−preprocess=+make(Generatedependenciesformake) Ccompileroption−−dep−file(Generatedependenciesinafile)

5−28 ToolOptions−CCompiler

CCompiler:−−mil/−−mil−split

Menuentry Commandlineonly.

Commandlinesyntax −−mil −−mil−split[=file,...]

Description Withoption−−miltheCcompilerskipsthecodegeneratorphaseandwritestheoptimizedintermediaterepresentation(MIL)to afilewiththesuffix.mil.TheCcompileraccepts.milfilesasinputfilesonthecommandline. Option−−mil−splitdoesthesameasoption−−mil,butinaddition,theCcompilersplitstheMILrepresentationandwritesitto separatefileswithsuffix.ms.OnefileiswrittenforeachinputfileorMILlibraryspecifiedonthecommandline.The.msfiles areonlyupdatedonachange.TheCcompileraccepts.msfilesasinputfilesonthecommandline. Withoption−−mil−splityoucanperformapplication−wideoptimizationsduringthefrontendphasebyspecifyingallmodulesat once,andstillinvokethebackendphaseonemoduleatatimetoreducethetotalcompilationtime. Optionally,youcanspecifyanotherfilenameforthe.msfiletheCcompilergenerates.Withoutanargument,thebasenameof theCsourcefileisusedtocreatethe.msfilename.Notethatifyouspecifyafilename,youhavetospecifyonefilenamefor everyinputfile.

Relatedinformation

Controlprogramoption−−mil−link/−−mil−split

5−29 NiosIIEmbeddedToolsReference

CCompiler:−−misrac

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheCCompilerentryandselectMISRA−C. 3. IntheMISRA−CcheckingboxselectaMISRA−Cconfiguration. IfyouselectCustomMISRA−Cconfiguration: 4. Intheleftpane,expandtheMISRA−CentryandselectCustom2004orCustom1998. 5. Enableordisabletheindividualrules.

Commandlinesyntax

−−misrac={all|number[−number],...}

Description

WiththisoptionyouspecifytothecompilerwhichMISRA−Crulesmustbechecked.Withtheoption−−misrac=allthecompiler checksforallsupportedMISRA−Crules.

Example cnios−−misrac=9−13test.c

ThecompilergeneratesanerrorforeachMISRA−Crule9,10,11,12or13violationinfiletest.c.

Relatedinformation

Ccompileroption−−misrac−advisory−warnings Ccompileroption−−misrac−required−warnings Linkeroption−−misrac−report

5−30 ToolOptions−CCompiler

CCompiler:−−misrac−advisory−warnings/−−misrac−required−warnings

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheCCompilerentryandselectMISRA−C. 3. EnableoneorbothoptionsTurnadvisoryruleviolationintowarningandTurnrequiredruleviolationintowarning.

Commandlinesyntax −−misrac−advisory−warnings −−misrac−required−warnings

Description Normally,ifanadvisoryruleorrequiredruleisviolated,thecompilergeneratesanerror.Asaconsequence,nooutputfileis generated.Withthisoption,thecompilergeneratesawarninginsteadofanerror.

Relatedinformation

Ccompileroption−−misrac Linkeroption−−misrac−report

5−31 NiosIIEmbeddedToolsReference

CCompiler:−−misrac−version

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogappears. 2. ExpandtheCCompilerentryandselectMISRA−C. 3. SelecttheMISRA−Cstandard:1998or2004.

Commandlinesyntax −−misrac−version={1998|2004}

Description MISRA−Crulesexistintwoversions:MISRA−C:1998andMISRA−C:2004.Bydefault,theCsourceischeckedagainstthe MISRA−C:2004rules.WiththisoptionyoucanspecifytocheckagainsttheMISRA−C:1998rules.

Relatedinformation

SeeChapter10,MISRA−CRules,foralistofallsupportedMISRA−Crules. Ccompileroption−−misrac

5−32 ToolOptions−CCompiler

CCompiler:−−nocache−volatile

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheCCompilerentryandselectCodeGeneration. 3. EnabletheoptionBypassdatacacheforvolatiles.

Commandlinesyntax −−nocache−volatile

Description Withthisoptionyoutellthecompilertouseiovariantsforloadandstoreinstructionsforaccessingvolatiles.Thisoptionhasno effectwhentheoption−−bypass−cacheisgivenaswell.

Relatedinformation

Ccompileroption−−bypass−cache(Bypassdatacache)

5−33 NiosIIEmbeddedToolsReference

CCompiler:−−no−double(−F)

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheCCompilerentryandselectFloating−Point. 3. EnabletheoptionUsesingleprecisionfloating−pointonly.

Commandlinesyntax −−no−double −F

Description

Withthisoptionyoutellthecompilertotreatvariablesofthetypedoubleasfloat.Becausethefloattypetakeslessspace, executionspeedincreasesandcodesizedecreases,bothatthecostoflessprecision.

Relatedinformation

5−34 ToolOptions−CCompiler

CCompiler:−−no−jmpi

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheCCompilerentryandselectCodeGeneration. 3. DisabletheoptionAllowJMPIinstruction.

Commandlinesyntax −−no−jmpi

Description IfyouhaveaNiosIIcorethatdoesnotsupportthejmpiinstruction,youcanusethisoptiontotellthecompilernottogenerate it.

Relatedinformation

5−35 NiosIIEmbeddedToolsReference

CCompiler:−−no−stdinc

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheCCompilerentryandselectMiscellaneous. 3. Addtheoption−−no−stdinctotheAdditionalCcompileroptionsfield.

Commandlinesyntax −−no−stdinc

Description Withthisoptionyoutellthecompilernottolookinthedefaultincludedirectoryrelativetotheinstallationdirectory,when searchingforincludefiles.Thiswaythecompileronlysearchesintheincludefilesearchpathsyouspecified.

Relatedinformation

Ccompileroption−−include−directory(Adddirectorytoincludefilesearchpath)

5−36 ToolOptions−CCompiler

CCompiler:−−no−warnings(−w)

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheCCompilerentryandselectDiagnostics. 3. IntheErrorreportingfield,selectoneofthefollowingoptions: • Reportallwarnings • Suppressallwarnings • Suppressspecificwarningsn IfyouselectSuppressspecificwarnings: 4. Enterthenumbers,separatedbycommasorasarange,ofthewarningsyouwanttosuppress.

Commandlinesyntax −−no−warnings[=number[−number],...] −w[number[−number],...]

Description Withthisoptionyoucansuppressallwarningmessagesorspecificwarningmessages. Onthecommandlinethisoptionworksasfollows: • Ifyoudonotspecifythisoption,allwarningsarereported. • Ifyouspecifythisoptionbutwithoutnumbers,allwarningsaresuppressed. • Ifyouspecifythisoptionwithanumberorarange,onlythespecifiedwarningissuppressed. Youcanspecifytheoption−−no−warnings=numbermultipletimes. Example Tosuppresswarnings135and136,enter135,136intheSpecificwarningstosuppressfield,orenterthefollowingonthe commandline: cniostest.c−−no−warnings=135,136

Relatedinformation

Ccompileroption−−warnings−as−errors(Treatwarningsaserrors)

5−37 NiosIIEmbeddedToolsReference

CCompiler:−−optimize(−O)

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheCCompilerentryandselectOptimization. 3. SelectanoptimizationlevelintheOptimizationlevelbox. 4. IfyouselectCustomOptimization,enableordisabletheoptimizationsyouwant. 5. Inaddition,intheSize/speedtrade−offfield,selectalevelbetweenfullyoptimizeforsizeorfullyoptimizeforspeed.

Commandlinesyntax

−−optimize[=flags] −O[flags] Usethefollowingoptionsforpredefinedsetsofflags: −−optimize=0 (−O0) Nooptimization Aliasfor:−OaBCEFGIKLOPRSUY −−optimize=1 (−O1) Fewoptimizations Aliasfor:−OabcefgIKLOPRSUy −−optimize=2 (−O2) Mediumoptimization(default) Aliasfor:−OabcefgIkloprsUy −−optimize=3 (−O3) Fulloptimization Aliasfor:−Oabcefgikloprsuy Youcanenablethefollowingindividualoptimizations: +/−coalesce (a/A) Coalescer(removeunnecessarymoves) +/−ipro (b/B) InterproceduralRegisterOptimization +/−cse (c/C) Commonsubexpressionelimination(CSE) +/−expression (e/E) Expressionsimplification +/−flow (f/F) Controlflowsimplification(optimizationandcodereordering) +/−glo (g/G) Genericassemblycodeoptimizations +/−inline (i/I) Functioninlining +/−schedule (k/K) Instructionscheduler +/−loop (l/L) Looptransformations +/−forward (o/O) Forwardstore +/−propagate (p/P) Constantpropagation +/−compact (r/R) Codecompaction(reverseinlining) +/−subscript (s/S) Subscriptstrengthreduction +/−unroll (u/U) Unrollsmallloops +/−peephole (y/Y) Peepholeoptimizations Foranextensivedescriptionoftheseoptimizations,pleaserefertosection2.6,CompilerOptimizationsinchapterUsingthe Compileroftheuser’smanual.

Description TheTASKINGCcompilersofferfouroptimizationlevelsandacustomlevel,ateachlevelaspecificsetofoptimizationsis enabled. • Nooptimization(−O0):Nooptimizationsareperformedexceptforthecoalescer(toallowbetterdebuginformation).The compilertriestoachievea1−to−1resemblancebetweensourcecodeandproducedcode.Expressionsareevaluatedinthe orderwritteninthesourcecode,associativeandcommutativepropertiesarenotused. • Fewoptimizations(−O1):Enablesoptimizationsthatdonotaffectthedebug−abilityofthesourcecode.Usethislevelwhen youencounterproblemsduringdebuggingyoursourcecodewithoptimizationlevel2.

5−38 ToolOptions−CCompiler

• Mediumoptimization(−O2):Enablesmoreoptimizationstoreducecodesizeand/orexecutiontime.Thisisthedefault optimizationlevel. • Fulloptimization(−O3):Thisisthehighestoptimizationlevel.Usethisleveltodecreaseexecutiontimetomeetyour real−timerequirements. • Customoptimization(−Ox/X):youcanenable/disablespecificoptimizations. Withtheseoptionsyoucancontrolthelevelofoptimization.ThedefaultoptimizationlevelisMediumoptimization(option−O2 or−Oor−OabcefgIkloprsUy). YoucanoverrulethesesettingsinyourCsourcefilewiththepragmapair#pragmaoptimizeflagand#pragma endoptimize.

Inadditiontothecommandlineoption−−optimize(−O),youcanspecifytheoption−−tradeoff(−t).Withthisoptionyou specifywhethertheusedoptimizationsshouldoptimizeformorespeed(regardlessofcodesize)orforsmallercodesize (regardlessofspeed).

Example Thefollowinginvocationsareequivalentandresultallinthedefaultoptimizationset: cniostest.c cnios−O2test.c cnios−−optimize=2test.c cnios−Otest.c cnios−−optimizetest.c cnios−OabcefgIkloprsUytest.c cnios−−optimize=+coalesce,+ipro,+cse,+expression,+flow,+glo, −inline,+schedule,+loop,+forward,+propagate,+compact,+subscript, −unroll,+peepholetest.c

Relatedinformation

Section2.6,CompilerOptimizations,inchapterUsingtheCompileroftheuser’smanual. Ccompileroption−−tradeoff(−t)(Tradeoffbetweenspeed(−t0)andsize(−t4))

5−39 NiosIIEmbeddedToolsReference

CCompiler:−−option−file(−f)

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheCCompilerentryandselectMiscellaneous. 3. Addtheoption−−option−filetotheAdditionalCcompileroptionsfield. BeawarethattheoptionsintheoptionfileareaddedtotheCcompileroptionsyouhavesetintheotherdialogs.Onlyin extraordinarycasesyoumaywanttousethemincombination.AltiumDesignerautomaticallysavestheoptionswithyour project.

Commandlinesyntax −−option−file=file,... −ffile,...

Description

Thisoptionisprimarilyintendedforcommandlineuse.Insteadoftypingalloptionsonthecommandline,youcancreatean optionfilewhichcontainsalloptionsandflagsyouwanttospecify.Withthisoptionyouspecifytheoptionfiletothecompiler. Useanoptionfilewhenthecommandlinewouldexceedthelimitsoftheoperatingsystem,orjusttostoreoptionsandsave typing. Youcanspecifytheoption−−option−filemultipletimes. Formatofanoptionfile • Multipleargumentsononelineintheoptionfileareallowed. • Toincludewhitespaceinanargument,surroundtheargumentwithsingleordoublequotes. • Ifyouwanttousesinglequotesaspartoftheargument,surroundtheargumentbydoublequotesandviseversa: "Thishasasinglequote’embedded" ’Thishasadoublequote"embedded’ ’Thishasadoublequote"andasinglequote’"’embedded" • Whenatextlinereachesitslengthlimit,usea\tocontinuetheline.Whitespacebetweenquotesispreserved. "Thisisacontinuation\ line"

−>"Thisisacontinuationline" • Itispossibletonestcommandlinefilesupto25levels. Example Supposethefilemyoptionscontainsthefollowinglines: −g −DDEMO=1 test.c

SpecifytheoptionfiletotheCcompiler: cnios−−option−file=myoptions

Thisisequivalenttothefollowingcommandline: cnios−g−DDEMO=1test.c

Relatedinformation

5−40 ToolOptions−CCompiler

CCompiler:−−output(−o)

Menuentry AltiumDesignernamestheoutputfilealwaysaftertheCsourcefile.

Commandlinesyntax

−−output=file −ofile

Description Withthisoptionyoucanspecifyanotherfilenamefortheoutputfileofthecompiler.WithoutthisoptionthebasenameoftheC sourcefileisusedwithextension.src.

Example Tocreatethefileoutput.srcinsteadoftest.src,enter: cnios−−output=output.srctest.c

Relatedinformation

5−41 NiosIIEmbeddedToolsReference

CCompiler:−−preprocess(−E)

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheCCompilerentryandselectPreprocessing. 3. EnabletheoptionStoretheCCompilerpreprocessoutput(.pre).

Commandlinesyntax −−preprocess[=flags] −E[flags] Youcansetthefollowingflags(whenyouspecify−Ewithoutflags,thedefaultis−ECILMP): +/−comments (c/C) KeepcommentsfromtheCsourceinthepreprocessedoutput +/−includes (i/I) Generatealistofincludedsourcefiles +/−list (l/L) Generatealistofmacrodefinitions +/−make (m/M) Generatedependencylinesthatcanbeusedforthemakefile +/−noline (p/P) Strip#linesourcepositioninfo(linesstartingwith#line) Thecompilersendsthepreprocessedfiletostdout.Tocapturetheinformationinafile,specifyanoutputfilewiththeoption −−output.

Description Whencompiling,eachfileispreprocessedfirst.WiththisoptionyoucanstoretheresultofpreprocessedCfiles.Altium Designerstoresthepreprocessedfileinafilecalledname.pre(wherenameisthenameoftheCsourcefilebeingcompiled).C commentsarenotpreserved(similarto−ECILMP) With−−preprocess=+commentsyoutellthepreprocessortokeepthecommentsfromtheCsourcefileinthepreprocessed output. With−−preprocess=+includesthecompilerwillgeneratealistofallincludedsourcefiles.Thepreprocessoroutputis discarded. With−−preprocess=+listthecompilerwillgeneratealistofallmacrodefinitions.Thepreprocessoroutputisdiscarded. With−−preprocess=+makethecompilerwillgeneratedependencylinesthatcanbeusedinaMakefile.Thepreprocessor outputisdiscarded.Thedefaulttargetnameisthebasenameoftheinputfile,withtheextension.obj.Withtheoption −−make−targetyoucanspecifyatargetnamewhichoverrulesthedefaulttargetname. With−−preprocess=+nolineyoutellthepreprocessortostripthe#linesourcepositioninformation(linesstartingwith#line). Theselinesarenormallyprocessedbytheassemblerandnotneededinthepreprocessedoutput.Whenyouleavetheselines out,theoutputiseasiertoread.

Relatedinformation

Ccompileroption−−make−target(Specifytargetnamefor−Emoutput)

5−42 ToolOptions−CCompiler

CCompiler:−−profile(−p)

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheCCompilerentryandselectDebugInformation. 3. EnabletheoptionGenerateprofilinginformation. 4. Enableoneormoreofthefollowingsuboptionstoselectwhichprofilesshouldbeobtained: • Blockcounters(notincombinationwithwithCallgraphorFunctiontimers) • Callgraph • Functioncounters • Functiontimers

Notethatthemoredetailledinformationyourequest,thelargertheoverheadintermsofexecutiontime,codesizeand heapspaceneeded.TheoptionGenerateDebuginformation(−−debugor−g)doesnotaffectprofiling,executiontime orcodesize.

Commandlinesyntax −−profile[=flags] −p[flags] Usethefollowingoptionforapredefinedsetofflags: −−profile=g (−pg) profilingwithcallgraphandfunctiontimers Aliasfor:−pBcFt Youcansetthefollowingflags(whenyouspecify−pwithoutflags,thedefaultis−pBCfST): +/−block (b/B) blockcounters +/−callgraph (c/C) callgraph +/−function (f/F) functioncounters +/−static (s/S) staticprofilegeneration +/−time (t/T) functiontimers

Description Profilingistheprocessofcollectingstatisticaldataaboutarunningapplication.Withthesedatayoucananalyzewhichfunctions arecalled,howoftentheyarecalledandwhattheirexecutiontimeis. Severalmethodsofprofilingexist.Onemethodiscodeinstrumentationwhichaddscodetoyourapplicationthattakescareof theprofilingprocesswhentheapplicationisexecuted.

ForanextensivedescriptionofprofilingrefertoChapter4,Profiling,intheuser’smanual.

Withthisoption,thecompileraddstheextracodetoyourapplicationthattakescareoftheprofilingprocess.Youcanobtainthe followingprofilingdata(seeflagsabove): Blockcounters(notincombinationwithCallgraphorFunctiontimers) Thiswillinstrumentthecodetoperformbasicblockcounting.Astheprogramruns,itcountsthenumberofexecutionsof eachbranchinanifstatement,eachiterationofaforloop,andsoon.NotethatthoughyoucancombineBlockcounters withFunctioncounters,thishasnoeffectbecauseFunctioncountersisonlyasubsetofBlockcounters. Callgraph(notincombinationwithBlockcounters) Thiswillinstrumentthecodetoreconstructtherun−timecallgraph.Astheprogramrunsitassociatesthecallerwiththe gatheredprofilingdata.

5−43 NiosIIEmbeddedToolsReference

Functioncounters Thiswillinstrumentthecodetoperformfunctioncallcounting.ThisisasubsetofthebasicBlockcounters. Functiontimers(notincombinationwithBlockcounters/Functioncounters) Thiswillinstrumentthecodetomeasurethetimespentinafunction.Thisincludesthetimespentinallsubfunctions (callees). Staticprofiling Withthisoptionyoudonotneedtoruntheapplicationtogetprofilingresults.Thecompilergeneratesprofilinginformationat compiletime.

Ifyouusetheprofilingoption,youmustlinkthecorrespondinglibrariestoo!RefertoSection6.4,LinkingwithLibrariesin ChapterUsingtheLinkeroftheuser’smanual,foranoverviewofthe(profiling)libraries.WhenyouuseAltiumDesigner, automaticallythecorrectlibrariesarelinked.

Example Togenerateblockcountinformationforthemoduletest.cduringexecution,compileasfollows: cnios−−profile=+blocktest.c

Inthiscaseyoumustlinkthelibrarypbniosmd.lib. Relatedinformation

Chapter4,Profilingintheuser’smanual.

5−44 ToolOptions−CCompiler

CCompiler:−−rename−sections(−R)

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheCCompilerentryandselectMiscellaneous. 3. Addtheoption−−rename−sectionstotheAdditionalCcompileroptionsfield.

Commandlinesyntax −−rename−sections=[name]={suffix|−f|−m|−fm} −R[name]={suffix|−f|−m|−fm}

Description

Incaseamodulemustbeloadedatafixedaddress,oradatasectionneedsaspecialplaceinmemory,youcanusethisoption togeneratedifferentsectionnames.Youcanthenusethisuniquesectionnameinthelinkerscriptfileforlocating.Because sectionshavereservednames,thecompilerwillnotactuallychangethesectionname,butwilladdasuffixtothename.

Withthesectionnameyouselectwhichsectionsarerenamed.Withsuffixyouspecifythesuffixpartwhichwillbeattachedto theexistingname.Thefollowingnamevalueshavespecialmeaning:

Withthesuboption−f,thecompilerusesthefunctionname(onlyforcode).

Withthesuboption−m,thecompilerusesthenameofthecurrentmodule.

Withthesuboption−fm(or−mf),thecompilerusesthenameofthecurrentmodulefordatasectionsandthefunctionnamefor codesections.

Ifyoudonotspecifyasectionname,allsectionswillreceivethespecifiedsuffix.

Example Tochangeallsectionsnamed.datainto.data.NEW: cnios−−rename−sections=.data=NEWtest.c

Toaddthenameofthecurrentmodulenameassuffixtoalldatasections,resultingin.data.test): cnios−−rename−sections=.data=−mtest.c

Relatedinformation

Assemblerdirective.SECTION

5−45 NiosIIEmbeddedToolsReference

CCompiler:−−runtime(−r)

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheCCompilerentryandselectDebugInformation. 3. EnabletheoptionRun−timechecks. 4. Enableoneormoreofthefollowingsuboptionstoselectwhichrun−timechecksshouldbeperformed: • Boundschecking • Reportunhandledcaseinaswitch • Mallocconsistencychecks Commandlinesyntax −−runtime[=flags] −r[flags] Youcansetthefollowingflags(whenyouspecify−rwithoutflags,thedefaultis−rbcm): +/−bounds (b/B) boundschecking +/−case (c/C) reportunhandledcaseinaswitch +/−malloc (m/M) mallocconsistencychecks

Description Thisoptioncontrolsanumberofrun−timecheckstodetecterrorsduringprogramexecution.Someofthesechecksrequire additionalcodetobeinsertedintheoriginalapplicationcode,andmaythereforeslowdowntheprogramexecution.The followingchecksareavailable: Boundschecking Everypointerupdateanddereferencewillbecheckedtodetectout−of−boundsaccesses,nullpointersanduninitialized automaticpointervariables.Thischeckwillincreasethecodesizeandslowdowntheprogramconsiderably.Inaddition,some heapmemoryisallocatedtostoretheboundsinformation.Youmayenableboundscheckingforindividualmodulesoreven partsofmodulesonly(see#pragmaruntime). Reportunhandledcaseinaswitch Reportanunhandledcasevalueinaswitchwithoutadefaultpart.Thischeckwilladdonefunctioncalltoeveryswitchwithouta defaultpart,butitwillhavelittleimpactontheexcutionspeed. Mallocconsistencychecks Thisoptionenablestheuseofwrappersaroundthefunctionsmalloc/realloc/freethatwillcheckforcommondynamicmemory allocationerrorslike: • bufferoverflow • writetofreedmemory • multiplecallstofree • passinginvalidpointertofree Enablingthischeckwillextractsomeadditionalcodefromthelibrary,butitwillnotenlargeyourapplicationcode.Thedynamic memoryusagewillincreasebyacoupleofbytesperallocation.

Relatedinformation

5−46 ToolOptions−CCompiler

CCompiler:−−sdata

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheCCompilerentryandselectCodeGeneration. 3. EnabletheoptionEnableallocationinsdata. 4. SpecifyasizeforAllocationinsdataforobjectssmallerthanthreshold(default:4)

Commandlinesyntax −−sdata=size (Default:4bytes)

Description Withthisoptionyoutellthecompilertoplaceallglobalandstaticdataobjectssmallerthanthespecifiedsize(bytes)intothe smalldatasection(sdata)orsmallbsssection(sbss).Thisresultsinsmallerandfastercode.Intotal,64kBisavailableforthis kindofaddressing. Withoutthisoption,allglobalandstaticdataobjectsof4bytesandsmallerareplacedintothesmalldatasectionsandsmallbss sections. Youcanstilloverrulethisoptionwiththekeywords__sdataand__no_sdataforindividiualdataobjectsinyoursource. Externaldatathatfallswithinthethreshold,isnotconsideredpartofsdata.Ifyouwantexternaldatatobepartofthistoo,also specifyoption−−extern−sdata.

Ifyouuseoption−−extern−sdata,youmustusetheoption−−sdatawiththesamevalueforallmodulesinyour application.

Example Toputallglobalandstaticdataobjectswithasizeof8bytesorsmallerintothesdatasection: cnios−−sdata=8test.c

Relatedinformation

Ccompileroption−−extern−sdata Section1.3,MemoryQualifiers.

5−47 NiosIIEmbeddedToolsReference

CCompiler:−−signed−bitfields

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheCCompilerentryandselectLanguage. 3. EnabletheoptionTreat’int’bit−fieldsassigned.

Commandlinesyntax −−signed−bitfields

Description Forbit−fieldsitdependsontheimplementationwhetheraplainintistreatedassignedintorunsignedint.By defaultanintbit−fieldistreatedasunsignedint.Thisoffersthebestperformance.Withthisoptionyoutellthecompiler totreatintbit−fieldsassignedint.Inthiscase,youcanstilladdthekeywordunsignedtotreataparticularint bit−fieldasunsigned.

Relatedinformation

5−48 ToolOptions−CCompiler

CCompiler:−−source(−s)

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheCCompilerentryandselectMiscellaneous. 3. EnabletheoptionMergeCsourcecodewithassemblyinoutputfile(.src).

Commandlinesyntax −−source −s

Description WiththisoptionyoutellthecompilertomergeCsourcecodewithgeneratedassemblycodeintheoutputfile.TheCsource linesareincludedascomments.

Relatedinformation

5−49 NiosIIEmbeddedToolsReference

CCompiler:−−static

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheCCompilerentryandselectMiscellaneous. 3. Addtheoption−−statictotheAdditionalCcompileroptionsfield.

Commandlinesyntax −−static

Description Withthisoption,thecompilertreatsexternaldefinitionsatfilescope(exceptformain)asiftheyweredeclaredstatic.Asa result,unusedfunctionswillbeeliminated,andthealiascheckingalgorithmassumesthatobjectswithstaticstoragecannotbe referencedfromfunctionsoutsidethecurrentmodule.

Onthecommandlinethisoptiononlymakessensewhenyouspecifyallmodulesofanapplicationonthecommandline.

Example cnios−−staticmodule1.cmodule2.cmodule3.c...

Relatedinformation

5−50 ToolOptions−CCompiler

CCompiler:−−stdout(−n)

Menuentry Commandlineonly.

Commandlinesyntax −−stdout −n

Description Withthisoptionyoutellthecompilertosendtheoutputtostdout(usuallyyourscreen).Nofilesarecreated.Thisoptionisfor exampleusefultoquicklyinspecttheoutputortoredirecttheoutputtoothertools.

Relatedinformation

5−51 NiosIIEmbeddedToolsReference

CCompiler:−−tradeoff(−t)

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheCCompilerentryandselectOptimization. 3. IntheSize/speedtrade−offfield,selectalevelbetweenfullyoptimizeforsizeorfullyoptimizeforspeed.

Commandlinesyntax −−tradeoff={0|1|2|3|4} −t{0|1|2|3|4}

Description Ifthecompilerusescertainoptimizations(option−−optimize),youcanusethisoptiontospecifywhethertheusedoptimizations shouldoptimizeformorespeed(regardlessofcodesize)orforsmallercodesize(regardlessofspeed). Bydefaultthecompileroptimizesformorespeed(−−tradeoff=0).

Ifyouhavenotusedtheoption−−optimize,thecompilerusesthedefaultoptimization.Inthiscaseitisstillusefulto specifyatrade−offlevel.

Relatedinformation

Ccompileroption−−optimize(Specifyoptimizationlevel)

5−52 ToolOptions−CCompiler

CCompiler:−−uchar(−u)

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheCCompilerentryandselectLanguage. 3. EnabletheoptionTreat’char’variablesasunsigned.

Commandlinesyntax −−uchar −u

Description Bydefaultcharisthesameasspecifyingsignedchar.Withthisoptioncharisthesameasunsignedchar.

Relatedinformation

5−53 NiosIIEmbeddedToolsReference

CCompiler:−−undefine(−U)

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheCCompilerentryandselectMiscellaneous. 3. Addtheoption−−undefinetotheAdditionalCcompileroptionsfield.

Commandlinesyntax −−undefine=macro_name −Umacro_name

Description Withthisoptionyoucanundefineanearlierdefinedmacroaswith#undef. Thisoptionisforexampleusefultoundefinepredefinedmacros. However,thefollowingpredefinedISOCstandardmacroscannotbeundefined: __FILE__ currentsourcefilename __LINE__ currentsourcelinenumber(inttype) __TIME__ hh:mm:ss __DATE__ mmmddyyyy __STDC__ levelofANSIstandard

Example Toundefinethepredefinedmacro__TASKING__: cnios−−undefine=__TASKING__test.c

Relatedinformation

Ccompileroption−−define(Definepreprocessormacro)

5−54 ToolOptions−CCompiler

CCompiler:−−unroll−max−size

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheCCompilerentryandselectMiscellaneous. 3. Addtheoption−−unroll−max−sizetotheAdditionalCcompileroptionsfield.

Commandlinesyntax −−unroll−max−size=value (Default:80)

Description Withthisoptionyouspecifythemaximumsizeforanunrolledloop.

Relatedinformation

Pragmaunroll_max_size

5−55 NiosIIEmbeddedToolsReference

CCompiler:−−use−hardware

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheProcessorentryandselectProcessorDefinition. 3. Enableoneormoreoftheoptions: • MULinstructionsenabled • DIVinstructionsenabled • MULXinstructionsenabled Commandlinesyntax −−use−hardware=flag,... Youcansetthefollowingflags: +/−divide (d/D) Divideinstructions +/−multiply (m/M) Multiplyinstructions +/−mulx (x/X) mulxinstructions(requires’m’) Default:DmX

Description WiththisoptionyoutellthecompilerthattheNiosIItargethasahardwaremultiply/divideunit.Thiswaythecompilercanuse theoptionaldivideandmultiplyinstructions.

Relatedinformation

5−56 ToolOptions−CCompiler

CCompiler:−−version(−V)

Menuentry Commandlineonly.

Commandlinesyntax −−version −V

Description Displaysversioninformationofthecompiler.Thecompilerignoresallotheroptionsorinputfiles.

Relatedinformation

5−57 NiosIIEmbeddedToolsReference

CCompiler:−−warnings−as−errors

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheCCompilerentryandselectDiagnostics. 3. IntheTreatwarningsaserrors.field,selectNone,TreatallwarningsaserrorsorTreatspecificwarningsaserrors. IfyouselectTreatspecificwarningsaserrors: 4. Enterthenumbers,separatedbycommasorasarange,ofthewarningsyouwanttotreataserrors.

Commandlinesyntax

−−warnings−as−errors[=number[−number],...]

Description Ifthecompilerencountersanerror,itstopscompiling.Whenyouusethisoptionwithoutarguments,youtellthecompilertotreat allwarningsaserrors.Thismeansthattheexitstatusofthecompilerwillbenon−zeroafteroneormorecompilerwarnings.As aconsequence,thecompilernowalsostopsafterencounteringawarning. Youcanalsolimitthisoptiontospecificwarningsbyspecifyingacomma−separatedlistofwarningnumbersorranges.

Relatedinformation

Ccompileroption−−no−warnings(Suppresssomeorallwarnings)

5−58 ToolOptions−C++Compiler

5.2 C++CompilerOptions

AltiumDesignerusesamakefiletobuildyourentireproject.ThismeansthatinAltiumDesigneryoucannotruntheC++ compilerseparately.IfyoucompileasingleC++sourcefilefromwithinAltiumDesigner,thefileisalsocompiledandassembled. However,youcansetoptionsspecificfortheC++compiler.

OptionsinAltiumDesignerversusoptionsonthecommandline MostcommandlineoptionshaveanequivalentoptioninAltiumDesignerbutsomeoptionsareonlyavailableonthecommand line(forexampleinaWindowsCommandPrompt).IfthereisnoequivalentoptioninAltiumDesigner,youcanspecifya commandlineoptioninAltiumDesignerasfollows: 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectMiscellaneous. 3. EnteroneormorecommandlineoptionsintheAdditionalC++compileroptionsfield.

Invocationsyntaxonthecommandline(WindowsCommandPrompt) TocalltheC++compilerfromthecommandline,usethefollowingsyntax: cpnios[[option]...[file]...]...

TheinputfilemustbeaC++sourcefile(.cc,.cxxor.cpp).

Shortandlongoptionnames Optionscanhavebothshortandlongnames.Shortoptionnamesalwaysbeginwithasingleminus(−)character,longoption namesalwaysbeginwithdoubleminus(−−)characters.Youcanabbreviatelongoptionnamesaslongasthenameisunique. Youcanmixshortandlongoptionnamesonthecommandline. Ifalongoptionrequiresanargument,theargumentmaybeseparatedfromthekeywordbywhitespace,orthekeywordmaybe immediatelyfollowedby=option.Whenthesecondformisusedtheremaynotbeanywhitespaceoneithersideoftheequal sign. Optionscanhaveflagsorsub−options.Toswitchaflag’on’,usealowercaseletterora+longflag.Toswitchaflagoff,usean uppercaseletterora−longflag.Separatelongflagswithcommas.Thefollowingtwoinvocationsareequivalent: cpnios−Ecptest.cc cpnios−−preprocess=+comments,+nolinetest.cc

Whenyoudonotspecifyanoption,adefaultvaluemaybecomeactive. Thepriorityoftheoptionsisleft−to−right:whentwooptionsconflict,thefirst(mostleft)onetakeseffect.Theoptions−−define and−−undefinearenotconsideredconflictingoptions,sotheyareprocessedleft−to−rightforeachsourcefile.Youcanoverrule thedefaultoutputfilenamewiththeoption−−output−file.

5−59 NiosIIEmbeddedToolsReference

C++Compiler:−−alternative−tokens

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectMiscellaneous. 3. Addtheoption−−alternative−tokenstotheAdditionalC++compileroptionsfield.

Commandlinesyntax −−alternative−tokens

Description Enablerecognitionofalternativetokens.ThiscontrolsrecognitionofthedigraphtokensinC++,andcontrolsrecognitionofthe operatorkeywords(e.g.,not,and,bitand,etc).

Example Toenableoperatorkeywords(e.g.,"not","and")anddigraphs,enter: cpnios−−alternative−tokenstest.cc

Relatedinformation

5−60 ToolOptions−C++Compiler

C++Compiler:−−anachronisms

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectC++Language. 3. EnabletheoptionAnachronisms.

Commandlinesyntax −−anachronisms

Description EnableC++anachronisms.Thisoptionalsoenables−−nonconst−ref−anachronism.Butyoucanturnthisoffindividuallywith option−−no−nonconst−ref−anachronism.

Relatedinformation

C++compileroption−−nonconst−ref−anachronism(Nonconstreferenceanachronism) Section2.3.3,AnachronismsAcceptedinchapterC++Language.

5−61 NiosIIEmbeddedToolsReference

C++Compiler:−−base−assign−op−is−default

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectMiscellaneous. 3. Addtheoption−−base−assign−op−is−defaulttotheAdditionalC++compileroptionsfield.

Commandlinesyntax −−base−assign−op−is−default

Description Enabletheanachronismofacceptingacopyassignmentoperatorthathasaninputparameterthatisareferencetoabase classasadefaultcopyassignmentoperatorforthederivedclass.

Relatedinformation

5−62 ToolOptions−C++Compiler

C++Compiler:−−building−runtime

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectMiscellaneous. 3. Addtheoption−−building−runtimetotheAdditionalC++compileroptionsfield.

Commandlinesyntax −−building−runtime

Description SpecialoptionforbuildingtheC++run−timelibrary.UsedtoindicatethattheC++run−timelibraryisbeingcompiled.This causesadditionalmacrostobepredefinedthatareusedtopassconfigurationinformationfromtheC++compilertothe run−time.

Relatedinformation

5−63 NiosIIEmbeddedToolsReference

C++Compiler:−−c++0x

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectMiscellaneous. 3. Addtheoption−−c++0xtotheAdditionalC++compileroptionsfield.

Commandlinesyntax −−c++0x

Description EnabletheC++extensionsthataredefinedbythelatestC++workingpaper.

Relatedinformation

5−64 ToolOptions−C++Compiler

C++Compiler:−−check

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectMiscellaneous. 3. Addtheoption−−checktotheAdditionalC++compileroptionsfield.

Commandlinesyntax −−check

Description Withthisoptionyoucancheckthesourcecodeforsyntaxerrors,withoutgeneratingcode.Thissavestimeindevelopingyour applicationbecausethecodewillnotactuallybecompiled. TheC++compilerreportsanywarningsand/orerrors.

Relatedinformation

Ccompileroption−−check(Checksyntax) Assembleroption−−check(Checksyntax)

5−65 NiosIIEmbeddedToolsReference

C++Compiler:−−context−limit

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectMiscellaneous. 3. Addtheoption−−context−limittotheAdditionalC++compileroptionsfield.

Commandlinesyntax −−context−limit=number(Default:10)

Description Setthecontextlimittonumber.Thecontextlimitisthemaximumnumberoftemplateinstantiationcontextentriestobe displayedaspartofadiagnosticmessage.Ifthenumberofcontextentriesexceedsthelimit,thefirstandlastNcontextentries aredisplayed,whereNishalfofthecontextlimit.Avalueofzeroisusedtoindicatethatthereisnolimit.

Example Tosetthecontextlimitto5,enter: cpnios−−context−limit=5test.cc

Relatedinformation

5−66 ToolOptions−C++Compiler

C++Compiler:−−cpu(−C)

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheProcessorentryandselectProcessorDefinition. 3. SelectaprocessorfromtheSelectprocessorbox.

Commandlinesyntax −−cpu=[nios2e|nios2f|nios2s] −C[nios2e|nios2f|nios2s]

Description WiththisoptionyoudefinetheCPUcoreforwhichyoucreateyourapplication.TheNiosIItargethasmorethanoneprocessor typeandthereforeyouneedtospecifyforwhichprocessortypetheC++compilershouldcompile. TheeffectofthisoptionisthattheC++compilerusestheappropriateinstructionset.YouchooseoneofthefollowingCPU’s: NiosII/e,NiosII/forNiosII/s. Themacro__CPU__issettothestringsuppliedtothisoption.

Example Tocompilethefiletest.ccfortheNiosII/eprocessortype,enterthefollowingonthecommandline: cpnios−−cpu=nios2etest.cc

Relatedinformation

5−67 NiosIIEmbeddedToolsReference

C++Compiler:−−create−pch

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectPrecompiledHeaders. 3. EnterafilenameintheCreateprecompiledheaderfilefield.

Commandlinesyntax −−create−pch=filename

Description Ifotherconditionsaresatisfied,createaprecompiledheaderfilewiththespecifiedname.If−−pch(automaticPCHmode)or −−use−pchappearsonthecommandlinefollowingthisoption,itseffectiserased.

Example Tocreateaprecompiledheaderfilewiththenametest.pch,enter cpnios−−create−pch=test.pchtest.cc

Relatedinformation

C++compileroption−−pch(AutomaticPCHmode) C++compileroption−−use−pch(Useprecompiledheaderfile) Section2.11,PrecompiledHeadersinchapterC++Language.

5−68 ToolOptions−C++Compiler

C++Compiler:−−define(−D)

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectPreprocessing. 3. SelectUsermacroandclickonthedownarrowintherightpanetoexpandmacroinput. 4. ClickonanemptyMacrofieldandenteramacroname.(Thenclickanemptycelltoconfirm) 5. Optionally,clickintheValuefieldandenteradefinition.(Thenclickanemptycelltoconfirm)

Commandlinesyntax

−−define=macro_name[(parm_list)][=macro_definition] −Dmacro_name[(parm_list)][=macro_definition]

Description Withthisoptionyoucandefineamacroandspecifyittothepreprocessor,asin#define.Ifyouonlyspecifyamacroname(no macrodefinition),themacroexpandsas’1’.Youcanspecifyasmanymacrosasyoulike. Function−stylemacroscanbedefinedbyappendingamacroparameterlisttomacro_name. Onthecommandline,youcanusetheoption−−define(−D)multipletimes.Ifthecommandlineexceedsthelengthlimitofthe operatingsystem,youcandefinethemacrosinanoptionfilewhichyouthenmustspecifytotheC++compilerwiththeoption −−option−file=file(−f). Definingmacroswiththisoption(insteadofintheCsource)is,forexample,usefultocompileconditionalCsourceasshownin theexamplebelow. Thedefinitioncanbetestedbythepreprocessorwith#if,#ifdefand#ifndef,forconditionalcompilations.

Example Considerthefollowingprogramwithconditionalcodetocompileademoprogramandarealprogram: voidmain(void) { #ifDEMO==1 demo_func();/*compileforthedemoprogram*/ #else real_func();/*compilefortherealprogram*/ #endif }

YoucannowuseamacrodefinitiontosettheDEMOflag: cpnios−−define=DEMOtest.cc cpnios−−define=DEMO=1test.cc

Notethatbothinvocationshavethesameeffect. Thenextexampleshowshowtodefineamacrowitharguments.Notethatthemacronameanddefinitionareplacedbetween doublequotesbecauseotherwisethespaceswouldindicateanewoption. cpnios−−define="MAX(A,B)=((A)>(B)?(A):(B))"test.cc

Relatedinformation

C++compileroption−−undefine(Removepreprocessormacro) C++compileroption−−option−file(Specifyanoptionfile)

5−69 NiosIIEmbeddedToolsReference

C++Compiler:−−dep−file

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectMiscellaneous. 3. Addtheoption−−dep−filetotheAdditionalC++compileroptionsfield.

Commandlinesyntax −−dep−file[=file]

Description WiththisoptionyoutelltheC++compilertogeneratedependencylinesthatcanbeusedinaMakefile.Incontrasttotheoption −−preprocess=+make(−Em),thedependencyinformationwillbegeneratedinadditiontothenormaloutputfile. Bydefault,theinformationiswrittentoafilewithextension.d(oneforeveryinputfile).Whenyouspecifyafilename,all dependencieswillbecombinedinthespecifiedfile.

Example cpnios−−dep−file=test.deptest.cc

TheC++compilercompilesthefiletest.cc,whichresultsintheoutputfiletest.ic,andgeneratesdependencylinesinthe filetest.dep.

Relatedinformation

C++compileroption−−preprocess=+make(Generatedependenciesformake)

5−70 ToolOptions−C++Compiler

C++Compiler:−−dollar

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectMiscellaneous. 3. Addtheoption−−dollartotheAdditionalC++compileroptionsfield.

Commandlinesyntax −−dollar Defaultformat:Nodollarsignsareallowedinidentifiers.

Description Acceptdollarsignsinidentifiers.NameslikeA$VARareallowed.

Relatedinformation

5−71 NiosIIEmbeddedToolsReference

C++Compiler:−−embedded−c++

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectC++Language. 3. EnabletheoptionComplytoembeddedC++subset.

Commandlinesyntax −−embedded−c++

Description The"EmbeddedC++"subsetdoesnotsupporttemplates,exceptions,namespaces,new−stylecasts,RTTI,multipleinheritance, virtualbaseclasses,andthemutablekeyword.SelectthisoptionwhenyouwanttheC++compilertogiveanerrorwhenyou useanyoftheminyourC++source.

Relatedinformation

5−72 ToolOptions−C++Compiler

C++Compiler:−−endianness

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheProcessorentryandselectProcessorDefinition. 3. EnabletheoptionBig−endianmode.

Commandlinesyntax −−endianness=endianness −B −−big−endian Youcanspecifythefollowingendianness: big (b) Bigendian little (l) Littleendian(default)

Description Bydefault,theC++compilergeneratescodeforalittle−endiantarget(leastsignificantbyteofawordatlowestbyteaddress). With−−endianness=bigtheC++compilergeneratescodeforabig−endiantarget(mostsignificantbyteofawordatlowest byteaddress).−Bisanaliasforoption−−endianness=big. Themacro__BIG_ENDIAN__isdefinedwhenthisoptionisspecified,otherwisethemacro__LITTLE_ENDIAN__isdefined.

Relatedinformation

5−73 NiosIIEmbeddedToolsReference

C++Compiler:−−error−file

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectMiscellaneous. 3. Addtheoption−−error−filetotheAdditionalC++compileroptionsfield.

Commandlinesyntax −−error−file[=file]

Description WiththisoptiontheC++compilerredirectserrormessagestoafile.Ifyoudonotspecifyafilename,theerrorfilewillbenamed aftertheinputfilewithextension.ecp.

Example Towriteerrorstoerrors.ecpinsteadofstderr,enter: cpnios−−error−file=errors.ecptest.cc

Relatedinformation

5−74 ToolOptions−C++Compiler

C++Compiler:−−error−limit(−e)

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectMiscellaneous. 3. Addtheoption−−error−limittotheAdditionalC++compileroptionsfield.

Commandlinesyntax −−error−limit=number(Default:100) −enumber

Description Settheerrorlimittonumber.TheC++compilerwillabandoncompilationafterthisnumberoferrors(remarksandwarningsare notcounted).Bydefault,thelimitis100.

Example Whenyouwantcompilationtostopwhen10errorsoccurred,enter: cpnios−−error−limit=10test.cc

Relatedinformation

5−75 NiosIIEmbeddedToolsReference

C++Compiler:−−exceptions(−x)

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectC++Language. 3. EnabletheoptionSupportforexceptionhandling.

Commandlinesyntax −−exceptions −x

Description WiththisoptionyouenablesupportforexceptionhandlingintheC++compiler. Themacro__EXCEPTIONSisdefinedwhenexceptionhandlingsupportisenabled.

Relatedinformation

5−76 ToolOptions−C++Compiler

C++Compiler:−−exported−template−file

Menuentry −

Commandlinesyntax

−−exported−template−file=file

Description Thisoptionspecifiesthenametobeusedfortheexportedtemplatefileusedforprocessingofexportedtemplates. ThisoptionissuppliedforusebythecontrolprogramthatinvokestheC++compilerandisnotintendedtobeusedby end−users.

Relatedinformation

5−77 NiosIIEmbeddedToolsReference

C++Compiler:−−extended−variadic−macros

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectMiscellaneous. 3. Addtheoption−−extended−variadic−macrostotheAdditionalC++compileroptionsfield.

Commandlinesyntax −−extended−variadic−macros Default:macroswithavariablenumberofargumentsarenotallowed.

Description Allowmacroswithavariablenumberofarguments(implies−−variadic−macros)andallowthenamingofthevariableargument list.

Relatedinformation

C++compileroption−−variadic−macros(Allowvariadicmacros)

5−78 ToolOptions−C++Compiler

C++Compiler:−−force−vtbl

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectMiscellaneous. 3. IntheVirtualfunctiontablesfield,selectForcedefinitionofvirtualfunctiontables.

Commandlinesyntax −−force−vtbl

Description ForcedefinitionofvirtualfunctiontablesincaseswheretheheuristicusedbytheC++compilertodecideondefinitionofvirtual functiontablesprovidesnoguidance.

Relatedinformation

C++compileroption−−suppress−vtbl(Suppressdefinitionofvirtualfunctiontables)

5−79 NiosIIEmbeddedToolsReference

C++Compiler:−−friend−injection

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectMiscellaneous. 3. Addtheoption−−friend−injectiontotheAdditionalC++compileroptionsfield.

Commandlinesyntax −−friend−injection Default:friendnamesarenotinjected.

Description Controlswhetherthenameofaclassorfunctionthatisdeclaredonlyinfrienddeclarationsisvisiblewhenusingthenormal lookupmechanisms.Whenfriendnamesareinjected,theyarevisibletosuchlookups.Whenfriendnamesarenotinjected (asrequiredbythestandard),functionnamesarevisibleonlywhenusingargument−dependentlookup,andclassnamesare nevervisible.

Relatedinformation

C++compileroption−−no−arg−dep−lookup(Disableargumentdependentlookup)

5−80 ToolOptions−C++Compiler

C++Compiler:−−g++

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectC++Language. 3. EnabletheoptionAllowGNUC++extensions.

Commandlinesyntax −−g++

Description EnableGNUC++compilerlanguageextensions.

Relatedinformation

Section2.4,GNUExtensionsinchapterC++Language.

5−81 NiosIIEmbeddedToolsReference

C++Compiler:−−gnu−version

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectMiscellaneous. 3. Addtheoption−−gnu−versiontotheAdditionalC++compileroptionsfield.

Commandlinesyntax −−gnu−version=version Default:30300(version3.3.0)

Description ItdependsontheGNUC++compilerversionifaparticularGNUextensionissupportedornot.WiththisoptionyousettheGNU C++compilerversionthatshouldbeemulatedinGNUC++mode.Versionx.y.zoftheGNUC++compilerisrepresentedbythe valuex*10000+y*100+z.

Example Tospecifyversion3.4.1oftheGNUC++compiler,enter: cpnios−−g++−−gnu−version=30401test.cc

Relatedinformation

Section2.4,GNUExtensionsinchapterC++Language.

5−82 ToolOptions−C++Compiler

C++Compiler:−−guiding−decls

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectMiscellaneous. 3. Addtheoption−−guiding−declstotheAdditionalC++compileroptionsfield.

Commandlinesyntax −−guiding−decls

Description Enablerecognitionof"guidingdeclarations"oftemplatefunctions.Aguidingdeclarationisafunctiondeclarationthatmatches aninstanceofafunctiontemplatebuthasnoexplicitdefinition(sinceitsdefinitionderivesfromthefunctiontemplate).For example: templatevoidf(T){...} voidf(int);

Whenregardedasaguidingdeclaration,f(int)isaninstanceofthetemplate;otherwise,itisanindependentfunctionfor whichadefinitionmustbesupplied.

Relatedinformation

C++compileroption−−old−specializations(Old−styletemplatespecializations)

5−83 NiosIIEmbeddedToolsReference

C++Compiler:−−help(−?)

Menuentry Commandlineonly.

Commandlinesyntax

−−help[=item,...] −? Youcanspecifythefollowingarguments: options Showextendedoptiondescriptions

Description Displaysanoverviewofallcommandlineoptions.Withanargumentyoucanspecifywhichextendedinformationisshown.

Example Thefollowinginvocationsalldisplayalistoftheavailablecommandlineoptions: cpnios−? cpnios−−help cpnios

Thefollowinginvocationdisplaysanextendedlistoftheavailableoptions: cpnios−−help=options

Relatedinformation

5−84 ToolOptions−C++Compiler

C++Compiler:−−implicit−extern−c−type−conversion

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectMiscellaneous. 3. Addtheoption−−implicit−extern−c−type−conversiontotheAdditionalC++compileroptionsfield.

Commandlinesyntax −−implicit−extern−c−type−conversion

Description Enabletheimplicittypeconversionbetweenpointerstoextern"C"andextern"C++"functiontypes.

Relatedinformation

5−85 NiosIIEmbeddedToolsReference

C++Compiler:−−implicit−include

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectMiscellaneous. 3. EnabletheoptionImplicitinclusionofsourcefilesforfindingtemplates.

Commandlinesyntax −−implicit−include

Description Enableimplicitinclusionofsourcefilesasamethodoffindingdefinitionsoftemplateentitiestobeinstantiated.

Relatedinformation

C++compileroption−−instantiate(Instantiationmode) Section2.6.4,ImplicitInclusioninchapterC++Language.

5−86 ToolOptions−C++Compiler

C++Compiler:−−incl−suffixes

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectMiscellaneous. 3. Addtheoption−−incl−suffixestotheAdditionalC++compileroptionsfield.

Commandlinesyntax −−incl−suffixes=suffixes Default:noextensionand.stdh.

Description Specifiesthelistofsuffixestobeusedwhensearchingforanincludefilewhosenamewasspecifiedwithoutasuffix.Ifanull suffixistobeallowed,itmustbeincludedinthesuffixlist.suffixesisacolon−separatedlistofsuffixes(e.g.,"::stdh").

Example Toallowonlythesuffixes.hand.stdhasincludefileextensions,enter: cpnios−−incl−suffixes=h:stdhtest.cc

Relatedinformation

C++compileroption−−include−file(Includefileatthestartofacompilation) Section3.3,HowtheC++CompilerSearchesIncludeFilesinchapterUsingtheC++Compileroftheuser’smanual.

5−87 NiosIIEmbeddedToolsReference

C++Compiler:−−include−directory(−I)

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. SelectBuildOptions. 3. AddapathnameintheIncludefilespathfield. Ifyouentermultiplepaths,separatethemwithasemicolon(;).

Commandlinesyntax −−include−directory=path,... −Ipath,...

Description Addpathtothelistofdirectoriessearchedfor#includefileswhosenamesdonothaveanabsolutepathname.Youcan specifymultipledirectoriesseparatedbycommas.

Example Toaddthedirectory/proj/includetotheincludefilesearchpath,enter: cpnios−−include−directory=/proj/includetest.cc

Relatedinformation

C++compileroption−−include−file(Includefileatthestartofacompilation) C++compileroption−−sys−include(Adddirectorytosystemincludefilesearchpath) Section3.3,HowtheC++CompilerSearchesIncludeFilesinchapterUsingtheC++Compileroftheuser’smanual.

5−88 ToolOptions−C++Compiler

C++Compiler:−−include−file(−H)

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectPreprocessing. 3. EnterthenameofthefileintheIncludethisfilebeforesourcefieldorclick...andselectafile.

Commandlinesyntax −−include−file=file,... −Hfile,...

Description Withthisoption(setatprojectlevel)youincludeoneextrafileatthebeginningofeachC++sourcefileinyourproject.Ona documentlevel(Project»DocumentOptions),youcanoverrulethisoptionwithanotherfileornofileatall. Thespecifiedincludefileisincludedatthebeginningofthecompilation.Thisisthesameasspecifying#include"file"at theverybeginningof(eachof)yourC++sourcefiles. Allfilesincludedwith−−include−fileareprocessedafteranyofthefilesincludedwith−−include−macros−file. Thefilenameissearchedforinthedirectoriesontheincludesearchlist.

Example cpnios−−include−file=extra.htest1.cctest2.cc

Thefileextra.hisincludedatthebeginningofbothtest1.ccandtest2.cc.

Relatedinformation

C++compileroption−−include−directory(Adddirectorytoincludefilesearchpath) Section3.3,HowtheC++CompilerSearchesIncludeFilesinchapterUsingtheC++Compileroftheuser’smanual.

5−89 NiosIIEmbeddedToolsReference

C++Compiler:−−include−macros−file

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectMiscellaneous. 3. Addtheoption−−include−macros−filetotheAdditionalC++compileroptionsfield.

Commandlinesyntax −−include−macros−file=file

Description Includethemacrosoftheindicatedfileatthebeginningofthecompilation.Onlythepreprocessingdirectivesfromthefileare evaluated.Alloftheactualcodeisdiscarded.Theeffectofthisoptionisthatanymacrodefinitionsfromthespecifiedfilewillbe ineffectwhentheprimarysourcefileiscompiled.Allofthemacro−onlyfilesareprocessedbeforeanyofthenormalincludes (−−include−file).Withineachgroup,thefilesareprocessedintheorderinwhichtheywerespecified.

Relatedinformation

C++compileroption−−include−file(Includefileatthestartofacompilation) Section3.3,HowtheC++CompilerSearchesIncludeFilesinchapterUsingtheC++Compileroftheuser’smanual.

5−90 ToolOptions−C++Compiler

C++Compiler:−−init−priority

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectMiscellaneous. 3. Addtheoption−−init−prioritytotheAdditionalC++compileroptionsfield.

Commandlinesyntax −−init−priority=number(Default:0)

Description Normally,theC++compilerassignsnoprioritytotheglobalinitializationfunctionsandtheexactorderisdeterminedbythe linker.Thisoptionsetsthedefaultpriorityforglobalinitializationfunctions.Defaultvalueis"0".Youcanalsosetthedefault prioritywiththe#pragmainit_priority. Valuesfrom1to100areforinternaluseonlyandshouldnotbeused.Values101to65535areavailableforusercode.Alower numbermeansahigherpriority.

Example cpnios−−init−priority=101test.cc

Relatedinformation

5−91 NiosIIEmbeddedToolsReference

C++Compiler:−−instantiate

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectMiscellaneous. 3. SelectaninstantiationmodeintheInstantiationmodeofexternaltemplateentitiesbox

Commandlinesyntax −−instantiate=mode −tmode Youcanspecifythefollowingmodes: used(default) all local

Description Controlinstantiationofexternaltemplateentities.Externaltemplateentitiesareexternal(thatis,non−inlineandnon−static) templatefunctionsandtemplatestaticdatamembers.Theinstantiationmodedeterminesthetemplateentitiesforwhichcode shouldbegeneratedbasedonthetemplatedefinition.Normally,whenafileiscompiled,templateentitiesareinstantiated wherevertheyareused(thelinkerwilldiscardduplicatedefinitions).Theoverallinstantiationmodecan,however,bechanged withthisoption.Youcanspecifythefollowingmodes: used Instantiatethosetemplateentitiesthatwereusedinthecompilation.Thiswillincludeallstaticdatamembersfor whichtherearetemplatedefinitions.Thisisthedefault. all Instantiatealltemplateentitiesdeclaredorreferencedinthecompilationunit.Foreachfullyinstantiatedtemplate class,allofitsmemberfunctionsandstaticdatamemberswillbeinstantiatedwhetherornottheywereused. Non−membertemplatefunctionswillbeinstantiatedeveniftheonlyreferencewasadeclaration. local Similarto−−instantiate=usedexceptthatthefunctionsaregiveninternallinkage.Thisisintendedtoprovidea verysimplemechanismforthosegettingstartedwithtemplates.Thecompilerwillinstantiatethefunctionsthatare usedineachcompilationunitaslocalfunctions,andtheprogramwilllinkandruncorrectly(barringproblemsdue tomultiplecopiesoflocalstaticvariables).However,onemayendupwithmanycopiesoftheinstantiated functions,sothisisnotsuitableforproductionuse. Youcannotuse−−instantiate=localinconjunctionwithautomatictemplateinstantiation.

Relatedinformation

C++compileroption−−no−auto−instantiation(DisableautomaticC++instantiation) Section2.6,TemplateInstantiationinchapterC++Language.

5−92 ToolOptions−C++Compiler

C++Compiler:−−io−streams

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectC++Language. 3. EnabletheoptionSupportforI/Ostreams.

Commandlinesyntax −−io−streams

Description AsI/Ostreamsrequiresubstantialresourcestheyaredisabledbydefault.UsethisoptiontoenableI/Ostreamssupportinthe C++library. Thisoptionalsoenablesexceptionhandling.

Relatedinformation

5−93 NiosIIEmbeddedToolsReference

C++Compiler:−−late−tiebreaker

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectMiscellaneous. 3. Addtheoption−−late−tiebreakertotheAdditionalC++compileroptionsfield.

Commandlinesyntax −−late−tiebreaker Default:earlytiebreakerprocessing.

Description Selectthewaythattie−breakers(e.g.,cv−qualifierdifferences)applyinoverloadresolution.In"early"tie−breakerprocessing, thetie−breakersareconsideredatthesametimeasothermeasuresofthegoodnessofthematchofanargumentvalueandthe correspondingparametertype(thisisthestandardapproach). In"late"tie−breakerprocessing,tie−breakersareignoredduringtheinitialcomparison,andconsideredonlyiftwofunctionsare otherwiseequallygoodonallarguments;thetie−breakerscanthenbeusedtochooseonefunctionoveranother.

Relatedinformation

5−94 ToolOptions−C++Compiler

C++Compiler:−−list−file(−L)

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectMiscellaneous. 3. Addtheoption−−list−filetotheAdditionalC++compileroptionsfield.

Commandlinesyntax −−list−file=file −Lfile Default:−1

Description Generaterawlistinginformationinthefile.Thisinformationislikelytobeusedtogenerateaformattedlisting.Therawlistingfile containsrawsourcelines,informationontransitionsintoandoutofincludefiles,anddiagnosticsgeneratedbytheC++ compiler. Eachlineofthelistingfilebeginswithakeycharacterthatidentifiesthetypeofline,asfollows: N: Anormallineofsource;therestofthelineisthetextoftheline. X: Theexpandedformofanormallineofsource;therestofthelineisthetextoftheline.ThislineappearsfollowingtheNline, andonlyifthelinecontainsnon−trivialmodifications(commentsareconsideredtrivialmodifications;macroexpansions,line splices,andtrigraphsareconsiderednon−trivialmodifications).Commentsarereplacedbyasinglespaceinthe expanded−formline. S: Alineofsourceskippedbyan#iforthelike;therestofthelineistext.Notethatthe#else,#elif,or#endifthatendsa skipismarkedwithanN. L: Anindicationofachangeinsourceposition.Thelinehasaformatsimilartothe#line−identifyingdirectiveoutputbytheC preprocessor,thatistosay Lline_number"file−name"key wherekeyis, 1 forentryintoanincludefile; 2 forexitfromanincludefile; andomittedotherwise. ThefirstlineintherawlistingfileisalwaysanLlineidentifyingtheprimaryinputfile.Llinesarealsooutputfor#line directives(keyisomitted).Llinesindicatethesourcepositionofthefollowingsourcelineintherawlistingfile. R,W,E,orC:anindicationofadiagnostic(Rforremark,Wforwarning,Eforerror,andCforcatastrophicerror).Thelinehas theform S"file−name"line_numbercolumn−numbermessage−text whereSisR,W,E,orC,asexplainedabove.Errorsattheendoffileindicatethelastlineoftheprimarysourcefileanda columnnumberofzero.Commandlineerrorsarecatastropheswithanemptyfilename("")andalineandcolumnnumberof zero.Internalerrorsarecatastropheswithpositioninformationasusual,andmessage−textbeginningwith(internalerror). Whenadiagnosticdisplaysalist(e.g.,allthecontendingroutineswhenthereisambiguityonanoverloadedcall),theinitial diagnosticlineisfollowedbyoneormorelineswiththesameoverallformat(codeletter,filename,linenumber,column number,andmessagetext),butinwhichthecodeletteristhelowercaseversionofthecodeletterintheinitialline.The sourcepositioninsuchlinesisthesameasthatinthecorrespondinginitialline.

5−95 NiosIIEmbeddedToolsReference

Example Towriterawlistinginformationtothefiletest.lst,enter: cpnios−−list−file=test.lsttest.cc

Relatedinformation

5−96 ToolOptions−C++Compiler

C++Compiler:−−long−lifetime−temps

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectMiscellaneous. 3. Addtheoption−−long−lifetime−tempstotheAdditionalC++compileroptionsfield.

Commandlinesyntax −−long−lifetime−temps

Description Selectthelifetimefortemporaries:shortmeanstoendoffullexpression;longmeanstotheearliestofendofscope,endof switchclause,orthenextlabel.Shortisthedefault.

Relatedinformation

5−97 NiosIIEmbeddedToolsReference

C++Compiler:−−long−long

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectMiscellaneous. 3. Addtheoption−−long−longtotheAdditionalC++compileroptionsfield.

Commandlinesyntax −−long−long

Description Permittheuseoflonglonginstrictmodeindialectsinwhichitisnon−standard.

Relatedinformation

5−98 ToolOptions−C++Compiler

C++Compiler:−−make−target

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheCCompilerentryandselectMiscellaneous. 3. Addtheoption−−make−targettotheAdditionalCcompileroptionsfield.

Commandlinesyntax −−make−target=name

Description Withthisoptionyoucanoverrulethedefaulttargetnameinthemakedependenciesgeneratedbytheoptions −−preprocess=+make(−Em)and−−dep−file.Thedefaulttargetnameisthebasenameoftheinputfile,withextension.obj.

Relatedinformation

C++compileroption−−preprocess=+make(Generatedependenciesformake) C++compileroption−−dep−file(Generatedependenciesinafile)

5−99 NiosIIEmbeddedToolsReference

C++Compiler:−−multibyte−chars

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectMiscellaneous. 3. Addtheoption−−multibyte−charstotheAdditionalC++compileroptionsfield.

Commandlinesyntax −−multibyte−chars Default:multibytecharactersequencesarenotallowed.

Description Enableprocessingformultibytecharactersequencesincomments,stringliterals,andcharacterconstants.Multibyteencodings areusedforcharactersetsliketheJapaneseSJIS.

Relatedinformation

5−100 ToolOptions−C++Compiler

C++Compiler:−−namespaces

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectMiscellaneous. 3. Addtheoption−−namespacestotheAdditionalC++compileroptionsfield.

Commandlinesyntax −−namespaces −−no−namespaces Default:namespacesaresupported.

Description Withoption−−no−namespacesyoudisablesupportfornamespaces. Whenyouusedoption−−embedded−c++,namespacesaredisabled.Withoption−−namespacesyoucanenablesupportfor namespacesinthiscase. Themacro__NAMESPACESisdefinedwhennamespacesupportisenabled.

Relatedinformation

C++compileroption−−embedded−c++(EmbeddedC++compliancytests) C++compileroption−−using−std(Implicituseofthestdnamespace) Section2.5,NamespaceSupportinchapterC++Language.

5−101 NiosIIEmbeddedToolsReference

C++Compiler:−−no−arg−dep−lookup

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectMiscellaneous. 3. Addtheoption−−no−arg−dep−lookuptotheAdditionalC++compileroptionsfield.

Commandlinesyntax −−no−arg−dep−lookup Default:argumentdependentlookupofunqualifiedfunctionnamesisperformed.

Description Withthisoptionyoudisableargumentdependentlookupofunqualifiedfunctionnames.

Relatedinformation

5−102 ToolOptions−C++Compiler

C++Compiler:−−no−array−new−and−delete

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectMiscellaneous. 3. Addtheoption−−no−array−new−and−deletetotheAdditionalC++compileroptionsfield.

Commandlinesyntax −−no−array−new−and−delete Default:arraynewanddeletearesupported.

Description Disablesupportforarraynewanddelete. Themacro__ARRAY_OPERATORSisdefinedwhenarraynewanddeleteisenabled.

Relatedinformation

5−103 NiosIIEmbeddedToolsReference

C++Compiler:−−no−auto−instantiation

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectMiscellaneous. 3. Addtheoption−−no−auto−instantiationtotheAdditionalC++compileroptionsfield.

Commandlinesyntax −−no−auto−instantiation Default:theC++compilerautomaticallyinstantiatestemplates.

Description Withthisoptionautomaticinstantiationoftemplatesisdisabled.

Relatedinformation

C++compileroption−−instantiate(Instantiationmode) Section2.6,TemplateInstantiationinchapterC++Language.

5−104 ToolOptions−C++Compiler

C++Compiler:−−no−bool

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectMiscellaneous. 3. Addtheoption−−no−booltotheAdditionalC++compileroptionsfield.

Commandlinesyntax −−no−bool Default:boolisrecognizedasakeyword.

Description Disablerecognitionoftheboolkeyword. Themacro_BOOLisdefinedwhenboolisrecognizedasakeyword.

Relatedinformation

5−105 NiosIIEmbeddedToolsReference

C++Compiler:−−no−class−name−injection

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectMiscellaneous. 3. Addtheoption−−no−class−name−injectiontotheAdditionalC++compileroptionsfield.

Commandlinesyntax −−no−class−name−injection Default:thenameofaclassisinjectedintothescopeoftheclass(asrequiredbythestandard).

Description Donotinjectthenameofaclassintothescopeoftheclass(aswastrueinearlierversionsoftheC++language).

Relatedinformation

5−106 ToolOptions−C++Compiler

C++Compiler:−−no−const−string−literals

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectMiscellaneous. 3. Addtheoption−−no−const−string−literalstotheAdditionalC++compileroptionsfield.

Commandlinesyntax −−no−const−string−literals Default:C++stringliteralsandwidestringliteralsareconst(asrequiredbythestandard).

Description WiththisoptionC++stringliteralsandwidestringliteralsarenon−const(aswastrueinearlierversionsoftheC++language).

Relatedinformation

5−107 NiosIIEmbeddedToolsReference

C++Compiler:−−no−dep−name

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectMiscellaneous. 3. Addtheoption−−no−dep−nametotheAdditionalC++compileroptionsfield.

Commandlinesyntax −−no−dep−name Default:dependentnameprocessingisenabled.

Description Disabledependentnameprocessing;i.e.,thespeciallookupofnamesusedintemplatesasrequiredbytheC++standard.This optionimpliestheuseof−−no−parse−templates.

Relatedinformation

C++compileroption−−no−parse−templates(Disableparsingofnonclasstemplates)

5−108 ToolOptions−C++Compiler

C++Compiler:−−no−distinct−template−signatures

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectMiscellaneous. 3. Addtheoption−−no−distinct−template−signaturestotheAdditionalC++compileroptionsfield.

Commandlinesyntax −−no−distinct−template−signatures

Description Controlwhetherthesignaturesfortemplatefunctionscanmatchthosefornon−templatefunctionswhenthefunctionsappearin differentcompilationunits.Bydefaultanormalfunctioncannotbeusedtosatisfytheneedforatemplateinstance;e.g.,a function"voidf(int)"couldnotbeusedtosatisfytheneedforaninstantiationofatemplate"voidf(T)"withTsettoint. −−no−distinct−template−signaturesprovidestheolderlanguagebehavior,underwhichanon−templatefunctioncanmatcha templatefunction.Alsocontrolswhetherfunctiontemplatesmayhavetemplateparametersthatarenotusedinthefunction signatureofthefunctiontemplate.

Relatedinformation

5−109 NiosIIEmbeddedToolsReference

C++Compiler:−−no−double(−F)

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectMiscellaneous. 3. Addtheoption−−no−doubletotheAdditionalC++compileroptionsfield.

Commandlinesyntax −−no−double −F

Description WiththisoptionyoutelltheC++compilertotreatvariablesofthetypedoubleasfloat.Becausethefloattypetakesless space,executionspeedincreasesandcodesizedecreases,bothatthecostoflessprecision.

Example cpnios−−no−doubletest.cc

Thefiletest.cciscompiledwherevariablesofthetypedoublearetreatedasfloat.

Relatedinformation

5−110 ToolOptions−C++Compiler

C++Compiler:−−no−enum−overloading

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectMiscellaneous. 3. Addtheoption−−no−enum−overloadingtotheAdditionalC++compileroptionsfield.

Commandlinesyntax −−no−enum−overloading

Description Disablesupportforusingoperatorfunctionstooverloadbuilt−inoperationsonenum−typedoperands

Relatedinformation

5−111 NiosIIEmbeddedToolsReference

C++Compiler:−−no−explicit

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectMiscellaneous. 3. Addtheoption−−no−explicittotheAdditionalC++compileroptionsfield.

Commandlinesyntax −−no−explicit Default:theexplicitspecifierisallowed.

Description Disablesupportfortheexplicitspecifieronconstructordeclarations.

Relatedinformation

5−112 ToolOptions−C++Compiler

C++Compiler:−−no−export

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectMiscellaneous. 3. Addtheoption−−no−exporttotheAdditionalC++compileroptionsfield.

Commandlinesyntax −−no−export Default:exportedtemplates(declaredwiththekeywordexport)areallowed.

Description Disablerecognitionofexportedtemplates.Thisoptionrequiresthatdependentnameprocessingbedone,andcannotbeused withimplicitinclusionoftemplatedefinitions.

Relatedinformation

Section2.6.5,ExportedTemplatesinchapterC++Language.

5−113 NiosIIEmbeddedToolsReference

C++Compiler:−−no−extern−inline

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectMiscellaneous. 3. Addtheoption−−no−extern−inlinetotheAdditionalC++compileroptionsfield.

Commandlinesyntax −−no−extern−inline Default:inlinefunctionsareallowedtohaveexternallinkage.

Description DisablesupportforinlinefunctionswithexternallinkageinC++.Wheninlinefunctionsareallowedtohaveexternallinkage (asrequiredbythestandard),thenexternandinlinearecompatiblespecifiersonanon−memberfunctiondeclaration;the defaultlinkagewheninlineappearsaloneisexternal(thatis,inlinemeansexterninlineonnon−memberfunctions); andaninlinememberfunctiontakesonthelinkageofitsclass(whichisusuallyexternal).However,wheninlinefunctions haveonlyinternallinkage(using−−no−extern−inline),thenexternandinlineareincompatible;thedefaultlinkagewhen inlineappearsaloneisinternal(thatis,inlinemeansstaticinlineonnon−memberfunctions);andinlinemember functionshaveinternallinkagenomatterwhatthelinkageoftheirclass.

Relatedinformation

Section2.8,ExternInlineFunctionsinchapterC++Language.

5−114 ToolOptions−C++Compiler

C++Compiler:−−no−for−init−diff−warning

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectMiscellaneous. 3. Addtheoption−−no−for−init−diff−warningtotheAdditionalC++compileroptionsfield.

Commandlinesyntax −−no−for−init−diff−warning

Description Disableawarningthatisissuedwhenprogramscompiledwithoutthe−−old−for−initoptionwouldhavehaddifferentbehavior undertheoldrules.

Relatedinformation

C++compileroption−−old−for−init(Useoldforscopingrules)

5−115 NiosIIEmbeddedToolsReference

C++Compiler:−−no−implicit−typename

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectMiscellaneous. 3. Addtheoption−−no−implicit−typenametotheAdditionalC++compileroptionsfield.

Commandlinesyntax −−no−implicit−typename Default:implicittypenamedeterminationisenabled.

Description Disableimplicitdetermination,fromcontext,whetheratemplateparameterdependentnameisatypeornontype.

Relatedinformation

C++compileroption−−no−typename(Disablethetypenamekeyword)

5−116 ToolOptions−C++Compiler

C++Compiler:−−no−inlining

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectMiscellaneous. 3. DisabletheoptionMinimalinliningoffunctioncalls.

Commandlinesyntax −−no−inlining

Description Disableminimalinliningoffunctioncalls.

Relatedinformation

5−117 NiosIIEmbeddedToolsReference

C++Compiler:−−nonconst−ref−anachronism

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectMiscellaneous. 3. Addtheoption−−nonconst−ref−anachronismtotheAdditionalC++compileroptionsfield.

Commandlinesyntax −−nonconst−ref−anachronism −−no−nonconst−ref−anachronism(default)

Description Enableordisabletheanachronismofallowingareferencetononconsttobindtoaclassrvalueoftherighttype.This anachronismisalsoenabledbytheoption−−anachronisms.

Relatedinformation

C++compileroption−−anachronisms(EnableC++anachronisms) Section2.3.3,AnachronismsAcceptedinchapterC++Language.

5−118 ToolOptions−C++Compiler

C++Compiler:−−nonstd−qualifier−deduction

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectMiscellaneous. 3. Addtheoption−−nonstd−qualifier−deductiontotheAdditionalC++compileroptionsfield.

Commandlinesyntax −−nonstd−qualifier−deduction

Description Controlswhethernon−standardtemplateargumentdeductionshouldbeperformedinthequalifierportionofaqualifiedname. Withthisfeatureenabled,atemplateargumentforthetemplateparameterTcanbededucedincontextslikeA::BorT::B. Thestandarddeductionmechanismtreatstheseasnon−deducedcontextsthatusethevaluesoftemplateparametersthatwere eitherexplicitlyspecifiedordeducedelsewhere.

Relatedinformation

5−119 NiosIIEmbeddedToolsReference

C++Compiler:−−nonstd−using−decl

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectMiscellaneous. 3. Addtheoption−−nonstd−using−decltotheAdditionalC++compileroptionsfield.

Commandlinesyntax −−nonstd−using−decl Default:non−standardusingdeclarationsarenotallowed

Description Allowanon−memberusingdeclarationthatspecifiesanunqualifiedname.

Relatedinformation

5−120 ToolOptions−C++Compiler

C++Compiler:−−no−parse−templates

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectMiscellaneous. 3. Addtheoption−−no−parse−templatestotheAdditionalC++compileroptionsfield.

Commandlinesyntax −−no−parse−templates Default:parsingofnonclasstemplatesisenabled.

Description Disabletheparsingofnonclasstemplatesintheirgenericform(i.e.,eveniftheyarenotreallyinstantiated).Itisdonebydefault ifdependentnameprocessingisenabled.

Relatedinformation

C++compileroption−−no−dep−name(Disabledependentnameprocessing)

5−121 NiosIIEmbeddedToolsReference

C++Compiler:−−no−pch−messages

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectMiscellaneous. 3. Addtheoption−−no−pch−messagestotheAdditionalC++compileroptionsfield.

Commandlinesyntax −−no−pch−messages Default:amessageisdisplayedindicatingthataprecompiledheaderfilewascreatedorusedinthecurrentcompilation.For example, "test.cc":creatingprecompiledheaderfile"test.pch"

Description Disablethedisplayofamessageindicatingthataprecompiledheaderfilewascreatedorusedinthecurrentcompilation.

Relatedinformation

C++compileroption−−pch(AutomaticPCHmode) C++compileroption−−use−pch(Useprecompiledheaderfile) C++compileroption−−create−pch(Createprecompiledheaderfile) Section2.11,PrecompiledHeadersinchapterC++Language.

5−122 ToolOptions−C++Compiler

C++Compiler:−−no−preprocessing−only

Menuentry AltiumDesigneralwaysdoesafullcompilation.

Commandlinesyntax −−no−preprocessing−only

Description YoucanusethisoptioninconjunctionwiththeoptionsthatnormallycausetheC++compilertodopreprocessingonly(e.g., −−preprocess,etc.)tospecifythatafullcompilationshouldbedone(notjustpreprocessing).Whenusedwiththeimplicit inclusionoption,thismakesitpossibletogenerateapreprocessedoutputfilethatincludesanyimplicitlyincludedfiles.

Example cpnios−−preprocess−−implicit−include−−no−preprocessing−onlytest.cc

Relatedinformation

C++compileroption−−preprocess(Preprocessingonly) C++compileroption−−implicit−include(Implicitsourcefileinclusion)

5−123 NiosIIEmbeddedToolsReference

C++Compiler:−−no−stdinc/−−no−stdstlinc

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectMiscellaneous. 3. Addtheoption−−no−stdincor−−no−stdstlinctotheAdditionalC++compileroptionsfield.

Commandlinesyntax −−no−stdinc −−no−stdstlinc

Description Withoption−−no−stdincyoutelltheC++compilernottolookinthedefaultincludedirectoryrelativetotheinstallation directory,whensearchingforstandardincludefiles. Withoption−−no−stdstlincyoutelltheC++compilernottolookinthedefaultinclude.stldirectoryrelativetothe installationdirectory,whensearchingforstandardSTLincludefiles. ThiswaytheC++compileronlysearchesintheincludefilesearchpathsyouspecified.

Relatedinformation

Section3.3,HowtheC++CompilerSearchesIncludeFilesinchapterUsingtheC++Compileroftheuser’smanual.

5−124 ToolOptions−C++Compiler

C++Compiler:−−no−typename

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectMiscellaneous. 3. Addtheoption−−no−typenametotheAdditionalC++compileroptionsfield.

Commandlinesyntax −−no−typename Default:typenameisrecognizedasakeyword.

Description Disablerecognitionofthetypenamekeyword.

Relatedinformation

C++compileroption−−no−implicit−typename(Disableimplicittypenamedetermination)

5−125 NiosIIEmbeddedToolsReference

C++Compiler:−−no−use−before−set−warnings(−j)

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectDiagnostics. 3. EnabletheoptionSuppressC++compiler"usedbeforeset"warnings.

Commandlinesyntax −−no−use−before−set−warnings −j

Description Suppresswarningsonlocalautomaticvariablesthatareusedbeforetheirvaluesareset.

Relatedinformation

C++compileroption−−no−warnings(Suppressallwarnings)

5−126 ToolOptions−C++Compiler

C++Compiler:−−no−warnings(−w)

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectDiagnostics. 3. EnabletheoptionSuppressallwarnings.

Commandlinesyntax −−no−warnings −w

Description Withthisoptionyousuppressallwarningmessages.Errormessagesarestillissued.

Relatedinformation

C++compileroption−−warnings−as−errors(Treatwarningsaserrors)

5−127 NiosIIEmbeddedToolsReference

C++Compiler:−−old−for−init

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectMiscellaneous. 3. Addtheoption−−old−for−inittotheAdditionalC++compileroptionsfield.

Commandlinesyntax −−old−for−init

Description Controlthescopeofadeclarationinafor−init−statement.Theold(cfront−compatible)scopingrulesmeanthedeclaration isinthescopetowhichtheforstatementitselfbelongs;thedefault(standard−conforming)rulesineffectwraptheentirefor statementinitsownimplicitlygeneratedscope.

Relatedinformation

C++compileroption−−no−for−init−diff−warning(Disablewarningforoldfor−scoping)

5−128 ToolOptions−C++Compiler

C++Compiler:−−old−line−commands

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectMiscellaneous. 3. Addtheoption−−old−line−commandstotheAdditionalC++compileroptionsfield.

Commandlinesyntax −−old−line−commands

Description Whengeneratingsourceoutput,putout#linedirectivesintheform#nnninsteadof#linennn.

Example Todopreprocessingonly,withoutcommentsandwitholdstylelinecontrolinformation,enter: cpnios−−preprocess−−old−line−commandstest.cc

Relatedinformation

C++compileroption−−preprocess(Preprocessingonly)

5−129 NiosIIEmbeddedToolsReference

C++Compiler:−−old−specializations

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectMiscellaneous. 3. Addtheoption−−old−specializationstotheAdditionalC++compileroptionsfield.

Commandlinesyntax −−old−specializations

Description Enableacceptanceofold−styletemplatespecializations(thatis,specializationsthatdonotusethetemplate<>syntax).

Relatedinformation

5−130 ToolOptions−C++Compiler

C++Compiler:−−option−file(−f)

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectMiscellaneous. 3. Addtheoption−−option−filetotheAdditionalCcompileroptionsfield. BeawarethattheoptionsintheoptionfileareaddedtotheC++compileroptionsyouhavesetintheotherdialogs.Onlyin extraordinarycasesyoumaywanttousethemincombination.AltiumDesignerautomaticallysavestheoptionswithyour project.

Commandlinesyntax −−option−file=file,... −ffile,...

Description

Thisoptionisprimarilyintendedforcommandlineuse.Insteadoftypingalloptionsonthecommandline,youcancreatean optionfilewhichcontainsalloptionsandflagsyouwanttospecify.WiththisoptionyouspecifytheoptionfiletotheC++ compiler. Useanoptionfilewhenthecommandlinewouldexceedthelimitsoftheoperatingsystem,orjusttostoreoptionsandsave typing. Youcanspecifytheoption−−option−filemultipletimes. Formatofanoptionfile • Multipleargumentsononelineintheoptionfileareallowed. • Toincludewhitespaceinanargument,surroundtheargumentwithsingleordoublequotes. • Ifyouwanttousesinglequotesaspartoftheargument,surroundtheargumentbydoublequotesandviseversa: "Thishasasinglequote’embedded" ’Thishasadoublequote"embedded’ ’Thishasadoublequote"andasinglequote’"’embedded" • Whenatextlinereachesitslengthlimit,usea\tocontinuetheline.Whitespacebetweenquotesispreserved. "Thisisacontinuation\ line"

−>"Thisisacontinuationline" • Itispossibletonestcommandlinefilesupto25levels. Example Supposethefilemyoptionscontainsthefollowinglines: −−embedded−c++ −−define=DEMO=1 test.cc

SpecifytheoptionfiletotheC++compiler: cpnios−−option−file=myoptions

Thisisequivalenttothefollowingcommandline: cpnios−−embedded−c++−−define=DEMO=1test.cc

5−131 NiosIIEmbeddedToolsReference

Relatedinformation

5−132 ToolOptions−C++Compiler

C++Compiler:−−output(−o)

Menuentry AltiumDesignernamestheoutputfilealwaysaftertheC++sourcefile. 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectMiscellaneous. 3. Addtheoption−−old−specializationstotheAdditionalC++compileroptionsfield.

Commandlinesyntax −−output=file −ofile Default:modulenamewith.icsuffix.

Description WiththisoptionyoucanspecifyanotherfilenamefortheoutputfileoftheC++compiler.Withoutthisoptionthebasenameofthe C++sourcefileisusedwithextension.ic. Youcanalsousethisoptionincombinationwiththeoption−−preprocess(−E)toredirectthepreprocessingoutputtoafile.

Example Tocreatethefileoutput.icinsteadoftest.ic,enter: cpnios−−output=output.ictest.cc

Tousethefilemy.preasthepreprocessingoutputfile,enter: cpnios−−preprocess−−output=my.pretest.cc

Relatedinformation

C++compileroption−−preprocess(Preprocessingonly)

5−133 NiosIIEmbeddedToolsReference

C++Compiler:−−pch

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectPrecompiledHeaders. 3. EnabletheoptionAutomaticallyuseand/orcreateaprecompiledheaderfile.

Commandlinesyntax −−pch

Description Automaticallyuseand/orcreateaprecompiledheaderfile.If−−use−pchor−−create−pch(manualPCHmode)appearsonthe commandlinefollowingthisoption,itseffectiserased.

Relatedinformation

C++compileroption−−use−pch(Useprecompiledheaderfile) C++compileroption−−create−pch(Createprecompiledheaderfile) Section2.11,PrecompiledHeadersinchapterC++Language.

5−134 ToolOptions−C++Compiler

C++Compiler:−−pch−dir

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectPrecompiledHeaders. 3. EnterapathinthePrecompiledheaderfiledirectoryfield.

Commandlinesyntax −−pch−dir=directory−name

Description Specifythedirectoryinwhichtosearchforand/orcreateaprecompiledheaderfile.Thisoptionmaybeusedwithautomatic PCHmode(−−pch)ormanualPCHmode(−−create−pchor−−use−pch).

Example Tousethedirectoryc:\usr\include\pchtoautomaticallycreateprecompiledheaderfiles,enter: cpnios−−pch−dir=c:\usr\include\pch−−pchtest.cc

Relatedinformation

C++compileroption−−pch(AutomaticPCHmode) C++compileroption−−use−pch(Useprecompiledheaderfile) C++compileroption−−create−pch(Createprecompiledheaderfile) Section2.11,PrecompiledHeadersinchapterC++Language.

5−135 NiosIIEmbeddedToolsReference

C++Compiler:−−pch−verbose

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectMiscellaneous. 3. Addtheoption−−pch−verbosetotheAdditionalC++compileroptionsfield.

Commandlinesyntax −−pch−verbose

Description InautomaticPCHmode,foreachprecompiledheaderfilethatcannotbeusedforthecurrentcompilation,amessageis displayedgivingthereasonthatthefilecannotbeused.

Example cpnios−−pch−−pch−verbosetest.cc

Relatedinformation

C++compileroption−−pch(AutomaticPCHmode) Section2.11,PrecompiledHeadersinchapterC++Language.

5−136 ToolOptions−C++Compiler

C++Compiler:−−pending−instantiations

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectMiscellaneous. 3. Addtheoption−−pending−instantiationstotheAdditionalC++compileroptionsfield.

Commandlinesyntax −−pending−instantiations=n wherenisthemaximumnumberofinstantiationsofasingletemplate. Default:64

Description Specifiesthemaximumnumberofinstantiationsofagiventemplatethatmaybeinprocessofbeinginstantiatedatagiventime. Thisisusedtodetectrunawayrecursiveinstantiations.Ifniszero,thereisnolimit.

Example Tospecifyamaximumof32pendinginstantiations,enter: cpnios−−pending−instantiations=32test.cc

Relatedinformation

Section2.6,TemplateInstantiationinchapterC++Language.

5−137 NiosIIEmbeddedToolsReference

C++Compiler:−−preprocess(−E)

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectPreprocessing. 3. EnabletheoptionStoretheC++compilerpreprocessoutput(.pre).

Commandlinesyntax −−preprocess[=flags] −E[flags] Youcansetthefollowingflags(whenyouspecify−Ewithoutflags,thedefaultis−ECMP): +/−comments (c/C) KeepcommentsfromtheCsourceinthepreprocessedoutput +/−make (m/M) Generatedependencylinesthatcanbeusedforthemakefile +/−noline (p/P) Strip#linesourcepositioninfo(linesstartingwith#line)

Description WiththisoptionyoutelltheC++compilertopreprocesstheC++source.UnderAltiumDesignertheC++compilersendsthe preprocessedoutputtothefilename.pre(wherenameisthenameoftheC++sourcefiletocompile).AltiumDesigneralso compilestheC++source. Onthecommandline,theC++compilersendsthepreprocessedfiletostdout.Tocapturetheinformationinafile,specifyan outputfilewiththeoption−−output. With−−preprocess=+commentsyoutellthepreprocessortokeepthecommentsfromtheC++sourcefileinthepreprocessed output. With−−preprocess=+maketheC++compilerwillgeneratedependencylinesthatcanbeusedinaMakefile.Thepreprocessor outputisdiscarded.Thedefaulttargetnameisthebasenameoftheinputfile,withtheextension.obj.Withtheoption −−make−targetyoucanspecifyatargetnamewhichoverrulesthedefaulttargetname. Whenimplicitinclusionoftemplatesisenabled,theoutputmayindicatefalse(butsafe)dependenciesunless −−no−preprocessing−onlyisalsoused. With−−preprocess=+nolineyoutellthepreprocessortostripthe#linesourcepositioninformation(linesstartingwith#line). Theselinesarenormallyprocessedbytheassemblerandnotneededinthepreprocessedoutput.Whenyouleavetheselines out,theoutputiseasiertoread.

Example cpnios−−preprocess=+comments,−make,−nolinetest.cc−−output=test.pre

TheC++compilerpreprocessesthefiletest.ccandsendstheoutputtothefiletest.pre.Commentsareincludedbutno dependenciesaregeneratedandthelinesourcepositioninformationisnotstrippedfromtheoutputfile.

Relatedinformation

C++compileroption−−no−preprocessing−only(Forcefullcompilation) C++compileroption−−make−target(Specifytargetnamefor−Emoutput)

5−138 ToolOptions−C++Compiler

C++Compiler:−−remarks(−r)

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectDiagnostics. 3. EnabletheoptionIssueremarksonC++code.

Commandlinesyntax −−remarks −r

Description Issueremarks,whicharediagnosticmessagesevenmilderthanwarnings

Relatedinformation

Section3.4,C++CompilerErrorMessagesinchapterUsingtheC++Compileroftheuser’smanual.

5−139 NiosIIEmbeddedToolsReference

C++Compiler:−−remove−unneeded−entities

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectMiscellaneous. 3. Addtheoption−−remove−unneeded−entitiestotheAdditionalC++compileroptionsfield.

Commandlinesyntax −−remove−unneeded−entities

Description Enableanoptimizationtoremovetypes,variables,routines,andrelatedconstructsthatarenotreallyneeded.Somethingmay bereferencedbutunneededifitisreferencedonlybysomethingthatisitselfunneeded;certainentities,suchasglobalvariables androutinesdefinedinthetranslationunit,arealwaysconsideredtobeneeded.

Relatedinformation

5−140 ToolOptions−C++Compiler

C++Compiler:−−rtti

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectC++Language. 3. EnabletheoptionSupportforRTTI(run−timetypeinformation).

Commandlinesyntax −−rtti Default:RTTI(run−timetypeinformation)featuresaredisabled.

Description EnablesupportforRTTI(run−timetypeinformation)features:dynamic_cast,typeid. Themacro__RTTIisdefinedwhenRTTIsupportisenabled.

Relatedinformation

5−141 NiosIIEmbeddedToolsReference

C++Compiler:−−schar(−s)

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectMiscellaneous. 3. Addtheoption−−schartotheAdditionalC++compileroptionsfield.

Commandlinesyntax −−schar −s

Description Withthisoptioncharisthesameassignedchar. Whenplaincharissigned,themacro__SIGNED_CHARS__isdefined.

Relatedinformation

C++compileroption−−uchar(Plaincharisunsigned)

5−142 ToolOptions−C++Compiler

C++Compiler:−−signed−bitfields

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectMiscellaneous. 3. Addtheoption−−signed−bitfieldstotheAdditionalC++compileroptionsfield.

Commandlinesyntax −−signed−bitfields

Description Forbit−fieldsitdependsontheimplementationwhetheraplainintistreatedassignedintorunsignedint.Bydefault anintbit−fieldistreatedasunsignedint.Thisoffersthebestperformance.WiththisoptionyoutelltheC++compilerto treatintbit−fieldsassignedint.Inthiscase,youcanstilladdthekeywordunsignedtotreataparticularintbit−fieldas unsigned.

Relatedinformation

Ccompileroption−−signed−bitfields

5−143 NiosIIEmbeddedToolsReference

C++Compiler:−−special−subscript−cost

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectMiscellaneous. 3. Addtheoption−−special−subscript−costtotheAdditionalC++compileroptionsfield.

Commandlinesyntax −−special−subscript−cost

Description Enableaspecialnonstandardweightingoftheconversiontotheintegraloperandofthe[]operatorinoverloadresolution. Thisisacompatibilityfeaturethatmaybeusefulwithsomeexistingcode.Withthisfeatureenabled,thefollowingcodecompiles withouterror: structA{ A(); operatorint*(); intoperator[](unsigned); }; voidmain(){ Aa; a[0];//Ambiguous,butallowedwiththisoption //operator[]ischosen }

Relatedinformation

5−144 ToolOptions−C++Compiler

C++Compiler:−−strict(−A)

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectC++Language. 3. DisabletheoptionAllownon−ANSI/ISOC++features.

Commandlinesyntax −−strict −A Default:non−ANSI/ISOC++featuresareenabled.

Description EnablestrictANSI/ISOmode,whichprovidesdiagnosticmessageswhennon−standardfeaturesareused,anddisables featuresthatconflictwithANSI/ISOCorC++.AllANSI/ISOviolationsareissuedaserrors.

Example ToenablestrictANSImode,witherrordiagnosticmessages,enter: cpnios−−stricttest.cc

Relatedinformation

C++compileroption−−strict−warnings(StrictANSI/ISOmodewithwarnings)

5−145 NiosIIEmbeddedToolsReference

C++Compiler:−−strict−warnings(−a)

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectMiscellaneous. 3. Addtheoption−−strict−warningstotheAdditionalC++compileroptionsfield.

Commandlinesyntax −−strict−warnings −a Default:non−ANSI/ISOC++featuresareenabled.

Description Thisoptionissimilartotheoption−−strict,butallviolationsareissuedaswarningsinsteadoferrors.

Example ToenablestrictANSImode,withwarningdiagnosticmessages,enter: cpnios−−strict−warningstest.cc

Relatedinformation

C++compileroption−−strict(StrictANSI/ISOmodewitherrors)

5−146 ToolOptions−C++Compiler

C++Compiler:−−suppress−vtbl

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectMiscellaneous. 3. IntheVirtualfunctiontablesfield,selectSuppressdefinitionofvirtualfunctiontables.

Commandlinesyntax −−suppress−vtbl

Description SuppressdefinitionofvirtualfunctiontablesincaseswheretheheuristicusedbytheC++compilertodecideondefinitionof virtualfunctiontablesprovidesnoguidance.Thevirtualfunctiontableforaclassisdefinedinacompilationifthecompilation containsadefinitionofthefirstnon−inlinenon−purevirtualfunctionoftheclass.Forclassesthatcontainnosuchfunction,the defaultbehavioristodefinethevirtualfunctiontable(buttodefineitasalocalstaticentity).The−−suppress−vtbloption suppressesthedefinitionofthevirtualfunctiontablesforsuchclasses,andthe−−force−vtbloptionforcesthedefinitionofthe virtualfunctiontableforsuchclasses.−−force−vtbldiffersfromthedefaultbehaviorinthatitdoesnotforcethedefinitiontobe local.

Relatedinformation

C++compileroption−−force−vtbl(Forcedefinitionofvirtualfunctiontables)

5−147 NiosIIEmbeddedToolsReference

C++Compiler:−−sys−include

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectMiscellaneous. 3. Addtheoption−−sys−includetotheAdditionalC++compileroptionsfield.

Commandlinesyntax −−sys−include=directory,...

Description Changethealgorithmforsearchingsystemincludefileswhosenamesdonothaveanabsolutepathnametolookindirectory.

Example Toaddthedirectoryc:\proj\includetothesystemincludefilesearchpath,enter: cpnios−−sys−include=c:\proj\includetest.cc

Relatedinformation

C++compileroption−−include−directory(Adddirectorytoincludefilesearchpath) Section3.3,HowtheC++CompilerSearchesIncludeFilesinchapterUsingtheC++Compileroftheuser’smanual.

5−148 ToolOptions−C++Compiler

C++Compiler:−−template−directory

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectMiscellaneous. 3. Addtheoption−−template−directorytotheAdditionalC++compileroptionsfield.

Commandlinesyntax −−template−directory=directory,...

Description Specifiesadirectorynametobeplacedontheexportedtemplatesearchpath.Thedirectoriesareusedtofindthedefinitionsof exportedtemplates(.etfiles)andaresearchedintheorderinwhichtheyarespecifiedonthecommandline.Thecurrent directoryisalwaysthefirstentryonthesearchpath.

Example Toaddthedirectoryexporttotheexportedtemplatesearchpath,enter: cpnios−−template−directory=exporttest.cc

Relatedinformation

Section2.6.5,ExportedTemplatesinchapterC++Language.

5−149 NiosIIEmbeddedToolsReference

C++Compiler:−−timing

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectMiscellaneous. 3. Addtheoption−−timingtotheAdditionalC++compileroptionsfield.

Commandlinesyntax −−timing Default:notiminginformationisgenerated.

Description Generatecompilationtiminginformation.ThisoptioncausestheC++compilertodisplaytheamountofCPUtimeandelapsed timeusedbyeachphaseofthecompilationandatotalfortheentirecompilation.

Example cpnios−−timingtest.cc processed180linesat8102lines/min

Relatedinformation

5−150 ToolOptions−C++Compiler

C++Compiler:−−trace−includes

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectDiagnostics. 3. EnabletheoptionListallvisited#includedfiles.

Commandlinesyntax −−trace−includes

Description Outputalistofthenamesoffiles#includedtotheerroroutputfile.Thesourcefileiscompilednormally(i.e.itisnotjust preprocessed)unlessanotheroptionthatcausespreprocessingonlyisspecified.

Example cpnios−−trace−includestest.cc iostream.h string.h

Relatedinformation

5−151 NiosIIEmbeddedToolsReference

C++Compiler:−−type−traits−helpers

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectMiscellaneous. 3. Addtheoption−−type−traits−helperstotheAdditionalC++compileroptionsfield.

Commandlinesyntax −−type−traits−helpers −−no−type−traits−helpers Default:inC++modetypetraitshelpersareenabledbydefault.InGNUC++mode,typetraitshelpersareneverenabledby default.

Description Enableordisabletypetraitshelpers(like__is_unionand__has_virtual_destructor).Typetraitshelpersaremeantto easetheimplementationofISO/IECTR19768. Themacro__TYPE_TRAITS_ENABLEDisdefinedwhentypetraitspseudo−functionsareenabled.

Relatedinformation

5−152 ToolOptions−C++Compiler

C++Compiler:−−uchar(−u)

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectMiscellaneous. 3. Addtheoption−−uchartotheAdditionalC++compileroptionsfield.

Commandlinesyntax −−uchar −u

Description Bydefaultcharisthesameasspecifyingsignedchar.Withthisoptioncharisthesameasunsignedchar.

Relatedinformation

C++compileroption−−schar(Plaincharissigned)

5−153 NiosIIEmbeddedToolsReference

C++Compiler:−−undefine(−U)

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectMiscellaneous. 3. Addtheoption−−undefinetotheAdditionalC++compileroptionsfield.

Commandlinesyntax −−undefine=macro_name −Umacro_name

Description Removeanyinitialdefinitionofidentifiernameasin#undef.−−undefineoptionsareprocessedafterall−−defineoptionshave beenprocessed. Youcannotundefineapredefinedmacroasspecifiedinsection2.10,PredefinedMacros,exceptfor: __STDC__ __cplusplus __SIGNED_CHARS__

Example Toundefinethepredefinedmacro__cplusplus: cpnios−−undefine=__cplusplustest.cc

Relatedinformation

C++compileroption−−define(Definepreprocessormacro) Section2.10,PredefinedMacrosinchapterC++Language.

5−154 ToolOptions−C++Compiler

C++Compiler:−−use−pch

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectPrecompiledHeaders. 3. EnterafilenameintheUseprecompiledheaderfilefield.

Commandlinesyntax −−use−pch=filename

Description Useaprecompiledheaderfileofthespecifiednameaspartofthecurrentcompilation.If−−pch(automaticPCHmode)or −−create−pchappearsonthecommandlinefollowingthisoption,itseffectiserased.

Example Tousetheprecompiledheaderfilewiththenametest.pch,enter: cpnios−−use−pch=test.pchtest.cc

Relatedinformation

C++compileroption−−pch(AutomaticPCHmode) C++compileroption−−create−pch(Createprecompiledheaderfile) Section2.11,PrecompiledHeadersinchapterC++Language.

5−155 NiosIIEmbeddedToolsReference

C++Compiler:−−using−std

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectMiscellaneous. 3. Addtheoption−−using−stdtotheAdditionalC++compileroptionsfield.

Commandlinesyntax −−using−std Default:implicituseofthestdnamespaceisdisabled.

Description Enableimplicituseofthestdnamespacewhenstandardheaderfilesareincluded.Notethatthisdoesnotdotheequivalentof puttinga"usingnamespacestd;"intheprogramtoallowoldprogramstobecompiledwithnewheaderfiles;ithasa specialandlocalizedmeaningrelatedtotheTASKINGversionsofcertainheaderfiles,andisunlikelytobeofmuchuseto end−usersoftheTASKINGC++compiler.

Relatedinformation

C++compileroption−−namespaces(Supportfornamespaces) Section2.5,NamespaceSupportinchapterC++Language.

5−156 ToolOptions−C++Compiler

C++Compiler:−−variadic−macros

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectMiscellaneous. 3. Addtheoption−−variadic−macrostotheAdditionalC++compileroptionsfield.

Commandlinesyntax −−variadic−macros Default:macroswithavariablenumberofargumentsarenotallowed.

Description Allowmacroswithavariablenumberofarguments.

Relatedinformation

C++compileroption−−extended−variadic−macros(Allowextendedvariadicmacros)

5−157 NiosIIEmbeddedToolsReference

C++Compiler:−−version(−V)

Menuentry Commandlineonly.

Commandlinesyntax −−version −V

Description Displayversioninformation.TheC++compilerignoresallotheroptionsorinputfiles.

Relatedinformation

5−158 ToolOptions−C++Compiler

C++Compiler:−−warnings−as−errors

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectDiagnostics. 3. EnabletheoptionTreatwarningsaserrors.

Commandlinesyntax −−warnings−as−errors

Description IftheC++compilerencountersanerror,itstopscompiling.WiththisoptionyoutelltheC++compilertotreatallwarningsas errors.ThismeansthattheexitstatusoftheC++compilerwillbenon−zeroafteroneormorecompilerwarnings.Asa consequence,theC++compilernowalsostopsafterencounteringawarning.

Relatedinformation

C++compileroption−−no−warnings(Suppressallwarnings)

5−159 NiosIIEmbeddedToolsReference

C++Compiler:−−wchar_t−keyword

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectC++Language. 3. EnabletheoptionAllowthe’wchar_t’keyword.

Commandlinesyntax −−wchar_t−keyword Default:wchar_tisnotrecognizedasakeyword.

Description Enablerecognitionofwchar_tasakeyword. Themacro_WCHAR_Tisdefinedwhenwchar_ttisrecognizedasakeyword.

Relatedinformation

5−160 ToolOptions−C++Compiler

C++Compiler:−−xref−file(−X)

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheC++CompilerentryandselectMiscellaneous. 3. Addtheoption−−xref−filetotheAdditionalC++compileroptionsfield.

Commandlinesyntax −−xref−file=file −Xfile

Description Generatecross−referenceinformationinafile.Foreachreferencetoanidentifierinthesourceprogram,alineoftheform symbol_idnameXfile−nameline−numbercolumn−number iswritten,whereXis D fordefinition; d fordeclaration(thatis,adeclarationthatisnotadefinition); M formodification; A foraddresstaken; U forused; C forchanged(butactuallymeaningusedandmodifiedinasingleoperation,suchasanincrement); R foranyotherkindofreference,or E foranerrorinwhichthekindofreferenceisindeterminate. symbol−idisauniquedecimalnumberforthesymbol.Thefieldsoftheabovelineareseparatedbytabcharacters.

Relatedinformation

5−161 NiosIIEmbeddedToolsReference

5.3 AssemblerOptions

AltiumDesignerusesamakefiletobuildyourentireproject.ThismeansthatinAltiumDesigneryoucannotruntheassembler separately.Ifyouwantassemblyresults,youmustcompileasingleCsourcefilefromwithinAltiumDesigner,thefileisthen alsoassembled.However,youcansetoptionsspecificfortheassembler.

OptionsinAltiumDesignerversusoptionsonthecommandline MostcommandlineoptionshaveanequivalentoptioninAltiumDesignerbutsomeoptionsareonlyavailableonthecommand line(forexampleinaWindowsCommandPrompt).IfthereisnoequivalentoptioninAltiumDesigner,youcanspecifya commandlineoptioninAltiumDesignerasfollows: 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheAssemblerentryandselectMiscellaneous. 3. EnteroneormorecommandlineoptionsintheAdditionalassembleroptionsfield.

Invocationsyntaxonthecommandline(WindowsCommandPrompt) Tocalltheassemblerfromthecommandline,usethefollowingsyntax: asnios[[option]...[file]...]...

Theinputfilemustbeanassemblysourcefile(.asmor.src).

Shortandlongoptionnames Optionscanhavebothshortandlongnames.Shortoptionnamesalwaysbeginwithasingleminus(−)character,longoption namesalwaysbeginwithdoubleminus(−−)characters.Youcanabbreviatelongoptionnamesaslongasthenameisunique. Youcanmixshortandlongoptionnamesonthecommandline. Optionscanhaveflagsorsub−options.Toswitchaflag’on’,usealowercaseletterora+longflag.Toswitchaflagoff,usean uppercaseletterora−longflag.Separatelongflagswithcommas.Thefollowingtwoinvocationsareequivalent: asnios−Ogstest.src asnios−−optimize=+generics,+instr−sizetest.src

Whenyoudonotspecifyanoption,adefaultvaluemaybecomeactive.

5−162 ToolOptions−Assembler

Assembler:−−case−insensitive(−c)

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheAssemblerentryandselectMiscellaneous. 3. DisabletheoptionAssemblecasesensitive.

Commandlinesyntax −−case−insensitive −c

Description Withthisoptionyoutelltheassemblernottodistinguishbetweenupperandlowercasecharacters.Bydefaulttheassembler considersupperandlowercasecharactersasdifferentcharacters.

DisablingtheoptionAssemblecasesensitiveinAltiumDesigneristhesameasspecifyingtheoption −−case−insensitiveonthecommandline. Assemblysourcefilesthataregeneratedbythecompilermustalwaysbeassembledcasesensitive.Whenyouarewritingyour ownassemblycode,youmaywanttospecifythecaseinsensitivemode.

Example Whenassemblingcaseinsensitive,thelabelLabelNameisthesamelabelaslabelname.

Relatedinformation

5−163 NiosIIEmbeddedToolsReference

Assembler:−−check

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheAssemblerentryandselectMiscellaneous. 3. Addtheoption−−checktotheAdditionalassembleroptionsfield.

Commandlinesyntax −−check

Description Withthisoptionyoucancheckthesourcecodeforsyntaxerrors,withoutgeneratingcode.Thissavestimeindevelopingyour application. Theassemblerreportsanywarningsand/orerrors.

Relatedinformation

Ccompileroption−−check(Checksyntax)

5−164 ToolOptions−Assembler

Assembler:−−cpu(−C)

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheProcessorentryandselectProcessorDefinition. 3. SelectaprocessorfromtheSelectprocessorbox.

Commandlinesyntax −−cpu=[nios2e|nios2f|nios2s] −C[nios2e|nios2f|nios2s]

Description WiththisoptionyoudefinetheCPUcoreforwhichyoucreateyourapplication.TheNiosIItargethasmorethanoneprocessor typeandthereforeyouneedtospecifyforwhichprocessortypetheassemblershouldassemble.Youchooseoneofthe followingCPU’s:NiosII/e,NiosII/forNiosII/s. Assemblycodecancheckthevalueoftheoptionbymeansofthebuilt−infunction@CPU().

Whenyoucalltheassemblerfromthecommandline,makesureyouspecifythesamecoretypetothecompilertoavoid conflicts!

Relatedinformation

Assemblyfunction@CPU()

5−165 NiosIIEmbeddedToolsReference

Assembler:−−debug−info(−g)

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheAssemblerentryandselectDebugInformation. 3. Selectwhichdebuginformationtoinclude:AutomaticHLLorassemblyleveldebuginformation,Customdebug informationorNodebuginformation. IfyouselectCustomdebuginformation: 4. SelectwhichCustomdebuginformationtoinclude:Assemblersourcelineinformation,PassHLLdebuginformation,or None. 5. EnableordisabletheoptionAssemblerlocalsymbolsinformation.

Commandlinesyntax −−debug−info[=flag] −g[flag] Youcansetthefollowingflags: +/−asm (a/A) Assemblysourcelineinformation +/−hll (h/H) Passhighlevellanguagedebuginformation(HLL) +/−local (l/L) Assemblerlocalsymbolsdebuginformation +/−smart (s/S) Smartdebuginformation

Description Withthisoptionyoutelltheassemblerwhichkindofdebuginformationtoemitintheobjectfile. Ifyoudonotusethisoption,thedefaultis−−debug−info=+hll.Ifyouspecify−−debug−infowithoutanyflags,thedefaultis −−debug−info=+smart. Youcannotspecify−−debug−info=+asm,+hll.Eithertheassemblergeneratesassemblysourcelineinformation,oritpasses HLLdebuginformation. Whenyouspecify−−debug−info=+smart,theassemblerselectswhichflagstouse.Ifhighlevellanguageinformationis availableinthesourcefile,theassemblerpassesthisinformation(sameas−−debug−info=−asm,+hll,−local).Ifnot,the assemblergeneratesassemblysourcelineinformation(sameas−−debug−info=+asm,−hll,+local). With−−debug−info=AHLStheassemblerdoesnotgenerateanydebuginformation.

Relatedinformation

5−166 ToolOptions−Assembler

Assembler:−−define(−D)

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheAssemblerentryandselectPreprocessing. 3. ClickonUsermacro,clickonthedownarrowintherightpanetoexpandmacroinput. 4. ClickonanemptyMacrofieldandenteramacroname.(Thenclickoutsidethecelltoconfirm) 5. Optionally,clickintheValuefieldandenteradefinition.(Thenclickoutsidethecelltoconfirm)

Commandlinesyntax

−−define=macro_name[=macro_definition] −Dmacro_name[=macro_definition]

Description Withthisoptionyoucandefineamacroandspecifyittotheassemblerpreprocessor.Ifyouonlyspecifyamacroname(no macrodefinition),themacroexpandsas’1’. Youcanspecifyasmanymacrosasyoulike.Onthecommandlineyoucanusetheoption−−define(−D)multipletimes.Ifthe commandlineexceedsthelimitoftheoperatingsystem,youcandefinethemacrosinanoptionfilewhichyouthenmustspecify totheassemblerwiththeoption−−option−file=file(−f). Definingmacroswiththisoption(insteadofintheassemblysource)is,forexample,usefulincombinationwithconditional assemblyasshownintheexamplebelow.

Thisoptionhasthesameeffectasdefiningsymbolsviathe.DEFINE,.SET,and.EQUdirectives.(similarto#definein theClanguage).Withthe.MACROdirectiveyoucandefinemorecomplexmacros.

Example Considerthefollowingassemblyprogramwithconditionalcodetoassembleademoprogramandarealprogram: .IFDEMO==1 ...;instructionsfordemoapplication .ELSE ...;instructionsfortherealapplication .ENDIF

YoucannowuseamacrodefinitiontosettheDEMOflag: Macro Value DEMO 1(orempty) asnios−−define=DEMOtest.src asnios−−define=DEMO=1test.src

Notethatbothinvocationshavethesameeffect.

Relatedinformation

Assembleroption−−option−file(Readoptionsfromfile)

5−167 NiosIIEmbeddedToolsReference

Assembler:−−diag

Menuentry 1. FromtheViewmenu,selectWorkspacePanels»System»Messages. TheMessagespanelappears. 2. IntheMessagespanel,right−clickonthemessageyouwantmoreinformationon. Apopupmenuappears. 3. SelectMoreInfo. AMessageInfoboxappearswithadditionalinformation.

Commandlinesyntax

−−diag=[format:]{all|nr,...}

Description Withthisoptionyoucanaskforanextendeddescriptionoferrormessagesintheformatyouchoose.Theoutputisdirectedto stdout(normallyyourscreen)andintheformatyouspecify.Youcanspecifythefollowingformats:html,rtfortext(default). Tocreateafilewiththedescriptions,youmustredirecttheoutput. Withthesuboptionall,thedescriptionsofallerrormessagesaregiven.Ifyouwantthedescriptionofoneormoreselectederror messages,youcanspecifytheerrormessagenumbers,separatedbycommas. Withthisoptiontheassemblerdoesnotassembleanyfiles.

Example Todisplayanexplanationofmessagenumber241,enter: asnios−−diag=241

Thisresultsinthefollowingmessageandexplanation: W241:additionalinputfileswillbeignored Theassemblersupportsonlyasingleinputfile.Allotherinputfilesareignored.

TowriteanexplanationofallerrorsandwarningsinHTMLformattofileaserrors.html,useredirectionandenter: asnios−−diag=html:all>aserrors.html

Relatedinformation

5−168 ToolOptions−Assembler

Assembler:−−emit−locals

Menuentry Commandlineonly.

Commandlinesyntax

−−emit−locals[=flag,...] Youcansetthefollowingflags(whenyouspecifynoflags,thedefaultisEs):: +/−equs (e/E) emitlocalEQUsymbols +/−symbols (s/S) emitlocalnon−EQUsymbols

Description Withtheoption−−emit−locals=+equstheassembleralsoemitslocalEQUsymbolstotheobjectfile.Normally,onlyglobal symbolsandnon−EQUlocalsymbolsareemitted.Havinglocalsymbolsintheobjectfilecanbeusefulfordebugging.

Relatedinformation

5−169 NiosIIEmbeddedToolsReference

Assembler:−−endianness

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheProcessorentryandselectProcessorDefinition. 3. EnabletheoptionBig−endianmode.

Commandlinesyntax −−endianness=endianness −B −−big−endian Youcanspecifythefollowingendianness: big (b) Bigendian little (l) Littleendian(default)

Description Bydefault,theassemblergeneratesobjectfileswithinstructionsanddatainlittle−endianformat(leastsignificantbyteofaword atlowestbyteaddress).With−−endianness=bigtheassemblergeneratesobjectfilesinbig−endianformat(mostsignificant byteofawordatlowestbyteaddress).−Bisanaliasforoption−−endianness=big. Theendiannessisreflectedinthelistfile. Assemblycodecancheckthesettingofthisoptionbymeansofthebuilt−inassemblyfunction@BIGENDIAN().

Relatedinformation

Assemblyfunction@BIGENDIAN()

5−170 ToolOptions−Assembler

Assembler:−−error−file

Menuentry Commandlineonly.

Commandlinesyntax

−−error−file[=file]

Description Withthisoptiontheassemblerredirectserrormessagestoafile. Ifyoudonotspecifyafilename,theerrorfilewillbenamedaftertheinputfilewithextension.ers.

Example Towriteerrorstoerrors.errinsteadofstderr,enter: asnios−−error−file=errors.errtest.src

Relatedinformation

5−171 NiosIIEmbeddedToolsReference

Assembler:−−error−limit

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheAssemblerentryandselectMiscellaneous. 3. Addtheoption−−error−limittotheAdditionalassembleroptionsfield.

Commandlinesyntax −−error−limit=number

Description Withthisoptionyoutelltheassemblertoonlyemitthespecifiedmaximumnumberoferrors.Withoutthisoption(sameas0)the assembleremitsallerrors.

Relatedinformation

5−172 ToolOptions−Assembler

Assembler:−−gp−relative

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheAssemblerentryandselectMiscellaneous. 3. EnabletheoptionAutomaticallygenerateGP−relativeoffsets.

Commandlinesyntax −−gp−relative

Description WhenthisoptionisenabledtheassemblerautomaticallyemitsaGP−relativerelocationforsymbolicoffsetsinloadandstore instructionsifthebaseregisteristheGP−register(r26). Whenthisoptionisdisabled(default)youmustusethebuilt−inassemblyfunction@GPREL()onthesymbolicoffsetinorderto forcetheassemblertoemitaGP−relativerelocation.Assemblycodegeneratedbythecompileralwaysusesthe@GPREL() function.

Relatedinformation

Assemblyfunction@GPREL()

5−173 NiosIIEmbeddedToolsReference

Assembler:−−help(−?)

Menuentry Commandlineonly.

Commandlinesyntax

−−help[=options] −?

Description Displaysanoverviewofallcommandlineoptions.Whenyouspecifytheargumentoptionsyoucanlistdetailedoption descriptions.

Example Thefollowinginvocationsalldisplayalistoftheavailablecommandlineoptions: asnios−? asnios−−help asnios

Toseeadetaileddescriptionoftheavailableoptions,enter: asnios−−help=options

5−174 ToolOptions−Assembler

Assembler:−−include−directory(−I)

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. SelectBuildOptions. 3. AddapathnameintheIncludeFilesPathfield. Ifyouentermultiplepaths,separatethemwithasemicolon(;).

Commandlinesyntax −−include−directory=path,... −Ipath,...

Description Withthisoptionyoucanspecifythepathwhereyourincludefilesarelocated.Arelativepathwillberelativetothecurrent directory. Theorderinwhichtheassemblersearchesforincludefilesis: 1. Thepathnameintheassemblyfileandthedirectoryoftheassemblysource. 2. Thepaththatisspecifiedwiththisoption. 3. ThepaththatisspecifiedintheenvironmentvariableASNIOSINCwhentheproductwasinstalled. 4. Thedefaultincludedirectoryrelativetotheinstallationdirectory.

Example Supposethatyourassemblysourcefiletest.srccontainsthefollowingline: .INCLUDE’myinc.inc’

Youcancalltheassemblerasfollows: asnios−−include−directory=c:\proj\includetest.src

Firsttheassemblerlooksinthedirectorywheretest.srcislocatedforthefilemyinc.inc.Ifitdoesnotfindthefile,itlooksin thedirectoryc:\proj\includeforthefilemyinc.inc(thisoption).Ifthefileisstillnotfound,theassemblersearchesinthe environmentvariableandtheninthedefaultincludedirectory.

Relatedinformation

Assembleroption−−include−file(−H)(Includefilebeforesource)

5−175 NiosIIEmbeddedToolsReference

Assembler:−−include−file(−H)

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheAssemblerentryandselectPreprocessing. 3. EnterthenameofthefileintheIncludethisfilebeforesourcefieldorclick...andselectafile.

Commandlinesyntax −−include−file=file,... −Hfile,...

Description Withthisoption(setatprojectlevel)youincludeoneextrafileatthebeginningoftheassemblysourcefile.Thespecifiedinclude fileisincludedbeforeallotherincludes.Thisisthesameasspecifying.INCLUDE’file’atthebeginningofyourassembly source.

Example asnios−−include−file=myinc.inctest1.src

Thefilemyinc.incisincludedatthebeginningoftest1.srcbeforeitisassembled.

Relatedinformation

Assembleroption−−include−directory(Includefilespath) Section5.4,HowtheAssemblerSearchesIncludeFiles,inchapterUsingtheAssembleroftheuser’smanual.

5−176 ToolOptions−Assembler

Assembler:−−keep−output−files(−k)

Menuentry AltiumDesigneralwaysremovestheobjectfilewhenerrorsoccurduringassembling.

Commandlinesyntax −−keep−output−files −k

Description Ifanerroroccursduringassembling,theresultingobjectfile(.obj)maybeincompleteorincorrect.Withthisoptionyoukeep thegeneratedobjectfilewhenanerroroccurs. Bydefaulttheassemblerremovesthegeneratedobjectfilewhenanerroroccurs.Thisisusefulwhenyouusethemakeutility.If theerroneousfilesarenotremoved,themakeutilitymayprocesscorruptfilesonasubsequentinvocation. Usethisoptionwhenyoustillwanttousethegeneratedobject.Forexamplewhenyouknowthataparticularerrordoesnot resultinacorruptobjectfile.

Relatedinformation

5−177 NiosIIEmbeddedToolsReference

Assembler:−−list−file(−l)

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheAssemblerentryandselectListFile. 3. EnableGeneratelistfile. 4. IntheListfileformatsection,enableordisablethetypesofinformationtobeincluded.

Commandlinesyntax −−list−file[=file] −l[file]

Description Withthisoptionyoutelltheassemblertogeneratealistfile.Alistfileshowsthegeneratedobjectcodeandtherelative addresses.Notethattheassemblergeneratesarelocatableobjectfilewithrelativeaddresses. Withtheoptionalfileyoucanspecifyanalternativenameforthelistfile.Bydefault,thenameofthelistfileisthebasenameof thesourcefilewiththeextension.lst.

Relatedinformation

Onthecommandlineyoucanusetheoption−−list−format(−L)tospecifywhichtypesofinformationshouldbeincluded inthelistfile.

5−178 ToolOptions−Assembler

Assembler:−−list−format(−L)

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheAssemblerentryandselectListFile. 3. EnableGeneratelistfile. 4. IntheListfileformatsection,enableordisablethetypesofinformationtobeincluded.

Commandlinesyntax −−list−format=flags −Lflags Youcansetthefollowingflags: 0 Sameas−LDEGILMNPQRSVWXYZ(alloptionsdisabled) 1 Sameas−Ldegilmnpqrsvwxyz(alloptionsenabled) +/−section (d/D) Sectiondirectives(.SECTION) +/−symbol (e/E) Symboldefinitiondirectives +/−generic−expansion (g/G) Genericinstructionexpansion +/−generic (i/I) Genericinstructions +/−line (l/L) Cpreprocessor#linedirectives +/−macro (m/M) Macro/dupdefinitions(e.g..MACRO) +/−empty−line (n/N) Emptysourcelines(newline) +/−conditional (p/P) Conditionalassembly(.IF,.ELSE,.ENDIF) +/−equate (q/Q) Assembler.EQUand.SETdirectives +/−relocations (r/R) Relocationcharacters(’r’) +/−hll (s/S) HLLsymbolicdebuginformation(.SYMB) +/−equate−values (v/V) Assembler.EQUand.SETvalues +/−wrap−lines (w/W) Wrappedsourcelines +/−macro−expansion (x/X) Macroexpansions +/−cycle−count (y/Y) Cyclecounts +/−macro−expansion (z/Z) Defineexpansions

Default:−LdEGilMnPqrsVwXyZ

Description Withthisoptionyouspecifywhichinformationyouwanttoincludeinthelistfile.

Onthecommandlineyoumustusethisoptionincombinationwiththeoption−−list−file(−l).

Relatedinformation

Assembleroption−−list−file(Generatelistfile) Assembleroption−−section−info=+list(Displaysectioninformationinlistfile)

5−179 NiosIIEmbeddedToolsReference

Assembler:−−nested−sections(−N)

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheAssemblerentryandselectMiscellaneous. 3. Addtheoption−NtotheAdditionalassembleroptionsfield.

Commandlinesyntax −−nested−sections −N

Description Withthisoptionitisallowedtohavenestedsectionsinyourassemblysourcefile.Whenyouusethisoptionevery.SECTION directivemusthaveacorresponding.ENDSECdirective.

Example .SECTION.text ;code .SECTION.data ;anestedsection .ENDSEC ;code .ENDSEC

Relatedinformation

5−180 ToolOptions−Assembler

Assembler:−−no−warnings(−w)

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheAssemblerentryandselectDiagnostics. 3. Enableoneoftheoptions: • Reportallwarnings • Suppressallwarnings • Suppressspecificwarnings IfyouselectSuppressspecificwarnings: 4. Enterthenumbers,separatedbycommas,ofthewarningsyouwanttosuppress.

Commandlinesyntax −−no−warnings[=number,...] −w[number,...]

Description Withthisoptionyoucansuppressesallwarningmessagesorspecificwarningmessages. • Ifyoudonotspecifythisoption,allwarningsarereported. • Ifyouspecifythisoptionbutwithoutnumbers,allwarningsaresuppressed. • Ifyouspecifythisoptionwithanumber,onlythespecifiedwarningissuppressed. Youcanspecifytheoption−−no−warnings=numbermultipletimes. Example Tosuppresswarnings135and136,enter135,136intheSpecificwarningstosuppressfield,orenterthefollowingonthe commandline: asniostest.src−−no−warnings=135,136

Relatedinformation

Assembleroption−−warnings−as−errors(Treatwarningsaserrors)

5−181 NiosIIEmbeddedToolsReference

Assembler:−−optimize(−O)

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheAssemblerentryandselectOptimization. 3. Enableordisabletheoptimizationoptions: • Genericinstructions • Jumpchains • Instructionsize Commandlinesyntax −Oflags −−optimize=flags Youcansetthefollowingflags: +/−generics (g/G) Allowgenericinstructions +/−jumpchains (j/J) Jumpchains +/−instr−size (s/S) Optimizeinstructionsize Default:−−optimize=gJs

Description Allowgenericinstructions Ifyouusegenericinstructionsinyourassemblysource,theassemblercanoptimizethembyreplacingitwiththefastestor shortestpossiblevariantofthatinstruction.Bydefaultthisoptionisenabled.Ifyouturnoffthisoptimization,theassembler generatesanerrorongenericinstructions.Beawarethatthecompileralsogeneratesgenericinstructions! Jumpchains Withthisoptimization,theassemblerreplaceschainedjumpsbyasinglejumpinstruction.Forexample,ajumpfromatob immediatelyfollowedbyajumpfrombtoc,isreplacedbyajumpfromatoc. Optimizeinstructionsize Withthisoptimizationtheassemblertriestofindtheshortestpossibleoperandencodingforinstructions.

Relatedinformation

Section5.5,AssemblerOptimizationsinchapterUsingtheAssembleroftheuser’smanual.

5−182 ToolOptions−Assembler

Assembler:−−option−file(−f)

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheAssemblerentryandselectMiscellaneous. 3. Addtheoption−−option−filetotheAdditionalassembleroptionsfield. Beawarethattheoptionsintheoptionfileareaddedtotheassembleroptionsyouhavesetintheotherdialogs.Onlyin extraordinarycasesyoumaywanttousethemincombination.

Commandlinesyntax −−option−file=file,... −ffile,...

Description Thisoptionisprimarilyintendedforcommandlineuse.Insteadoftypingalloptionsonthecommandline,youcancreatean optionfilewhichcontainsalloptionsandflagsyouwanttospecify.Withthisoptionyouspecifytheoptionfiletotheassembler. Useanoptionfilewhenthecommandlinewouldexceedthelimitsoftheoperatingsystem,orjusttostoreoptionsandsave typing. Optionfilescanalsobegeneratedonthefly,forexamplebythemakeutility.Youcanspecifytheoption−−option−filemultiple times. Formatofanoptionfile • Multipleargumentsononelineintheoptionfileareallowed. • Toincludewhitespaceinanargument,surroundtheargumentwithsingleordoublequotes. • Ifyouwanttousesinglequotesaspartoftheargument,surroundtheargumentbydoublequotesandviseversa: "Thishasasinglequote’embedded" ’Thishasadoublequote"embedded’ ’Thishasadoublequote"andasinglequote’"’embedded" • Whenatextlinereachesitslengthlimit,usea’tocontinuetheline.Whitespacebetweenquotesispreserved. "Thisisacontinuation\ line"

−>"Thisisacontinuationline" • Itispossibletonestcommandlinefilesupto25levels. Example Supposethefilemyoptionscontainsthefollowinglines: −gaL test.src

Specifytheoptionfiletotheassembler: asnios−−option−file=myoptions

Thisisequivalenttothefollowingcommandline: asnios−gaLtest.src

Relatedinformation

5−183 NiosIIEmbeddedToolsReference

Assembler:−−output(−o)

Menuentry AltiumDesignernamestheoutputfilealwaysafterthesourcefile.

Commandlinesyntax

−−output=file −ofile

Description Withthisoptionyoucanspecifyanotherfilenamefortheoutputfileoftheassembler.Withoutthisoption,thebasenameofthe assemblysourcefileisusedwithextension.obj.

Example Tocreatethefilerelobj.objinsteadofasm.obj,enter: asnios−−output=relobj.objasm.src

Relatedinformation

5−184 ToolOptions−Assembler

Assembler:−−page−length

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheAssemblerentryandselectMiscellaneous. 3. Addtheoption−−page−lengthtotheAdditionalassembleroptionsfield.

Commandlinesyntax −−page−length=number Default:72

Description Ifyougeneratealistfilewiththeassembleroption−−list−file,(−l),thisoptionsetsthenumberoflinesinapageinthelistfile. Thedefaultis72,theminimumis10.Asaspecialcase,apagelengthof0turnsoffpagebreaks.

Relatedinformation

Assembleroption−−list−file(Generatelistfile)

5−185 NiosIIEmbeddedToolsReference

Assembler:−−page−width

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheAssemblerentryandselectMiscellaneous. 3. Addtheoption−−page−widthtotheAdditionalassembleroptionsfield.

Commandlinesyntax −−page−width=number Default:132

Description Ifyougeneratealistfilewiththeassembleroption−−list−file,(−l),thisoptionsetsthenumberofcolumnsperlineonapagein thelistfile.Thedefaultis132,theminimumis40.

Relatedinformation

Assembleroption−−list−file(Generatelistfile)

5−186 ToolOptions−Assembler

Assembler:−−preprocess(−E)

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheAssemblerentryandselectMiscellaneous. 3. Addtheoption−−preprocesstotheAdditionalassembleroptionsfield.

Commandlinesyntax −−preprocess −E

Description Withthisoptiontheassemblerwillonlypreprocesstheassemblysourcefile.Theassemblersendsthepreprocessedfileto stdout.

Relatedinformation

5−187 NiosIIEmbeddedToolsReference

Assembler:−−preprocessor−type(−m)

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheAssemblerentryandselectMiscellaneous. 3. Addtheoption−−preprocessor−typetotheAdditionalassembleroptionsfield.

Commandlinesyntax −−preprocessor−type={none|tasking} −m{n|t} Default:−mt

Description Withthisoptionyouselectthepreprocessorthattheassemblerwilluse.Bydefault,theassemblerusestheTASKING preprocessor. Whentheassemblysourcefiledoesnotcontainanypreprocessorsymbols,youcanspecifytotheassemblernottousea preprocessor.

Relatedinformation

5−188 ToolOptions−Assembler

Assembler:−−section−info(−t)

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheAssemblerentryandselectListFile. 3. EnableGeneratelistfile. 4. EnabletheoptionDisplaysectioninformation.

Commandlinesyntax −−section−info[=flags] −t[flags] Youcansetthefollowingflags: +/−console (c/C) Displaysectioninformationonstdout. +/−list (l/L) Writesectioninformationtothelistfile.

Description Withthisoptionyoutelltheassemblertodisplaysectioninformation.Foreachsectionitsmemoryspace,size,totalcyclecounts andnameislistedonstdoutand/orinthelistfile. Thecyclecountconsistsoftwoparts:thetotalaccumulatedcountforthesectionandthetotalaccumulatedcountforall repeatedinstructions.Inthecaseofnestedloopsitispossiblethatthetotalsupersedesthesectiontotal. Withoutargumentsthisoptionisthesameas−−section−info=cl.

With−−section−info=l,theassemblerwritesthesectioninformationtothelistfile.Youmustspecifythisoptionin combinationwiththeoption−−list−file(generatelistfile).

Example asnios−−list−file−−section−info=+console,+listtest.src

Theassemblergeneratesalistfileandwritesthesectioninformationtothisfile.Thesectioninformationisalsodisplayedon stdout.

Relatedinformation

Assembleroption−−list−file(generatelistfile)

5−189 NiosIIEmbeddedToolsReference

Assembler:−−symbol−scope(−i)

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheAssemblerentryandselectMiscellaneous. 3. Selectthedefaultlabelmode:LocalorGlobal.

Commandlinesyntax −−symbol−scope={global|local} −i{g|l} (Default: −il)

Description Withthisoptionyoutelltheassemblerhowtotreatsymbolsthatyouhavenotspecifiedexplicitlyasglobalorlocal.Bydefault theassemblertreatsallsymbolsaslocalsymbolsunlessyouhavedefinedthemexplicitlyasglobal.

Relatedinformation

5−190 ToolOptions−Assembler

Assembler:−−use−hardware

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheProcessorentryandselectProcessorDefinition. 3. Enableoneormoreoftheoptions: • MULinstructionsenabled • DIVinstructionsenabled • MULXinstructionsenabled Commandlinesyntax −−use−hardware=flag,... Youcansetthefollowingflags: +/−divide (d/D) Divideinstructions +/−multiply (m/M) Multiplyinstructions +/−mulx (x/X) mulxinstructions(requires’m’) Default:DmX

Description WiththisoptionyoutelltheassemblerthattheNiosIItargethasahardwaremultiply/divideunit.Thiswaytheassemblercan usetheoptionaldivideandmultiplyinstructions.

Relatedinformation

5−191 NiosIIEmbeddedToolsReference

Assembler:−−version(−V)

Menuentry Commandlineonly.

Commandlinesyntax −−version −V

Description Displaysversioninformationoftheassembler.Theassemblerignoresallotheroptionsorinputfiles.

Relatedinformation

5−192 ToolOptions−Assembler

Assembler:−−verbose(−v)

Menuentry Commandlineonly.

Commandlinesyntax −−verbose −v

Description Withthisoptionyouputtheassemblerinverbosemode.Theassemblerprintsthefilenamesandtheassemblypasseswhileit processesthefilessoyoucanmonitorthecurrentstatusoftheassembler.

Relatedinformation

5−193 NiosIIEmbeddedToolsReference

Assembler:−−warnings−as−errors

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheAssemblerentryandselectDiagnostics. 3. EnabletheoptionTreatwarningsaserrors.

Commandlinesyntax −−warnings−as−errors[=number,...]

Description Iftheassemblerencountersanerror,itstopsassembling.Whenyouusethisoptionwithoutarguments,youtelltheassemblerto treatallwarningsaserrors.Thismeansthattheexitstatusoftheassemblerwillbenon−zeroafteroneormorecompiler warnings.Asaconsequence,theassemblernowalsostopsafterencounteringawarning. Youcanalsolimitthisoptiontospecificwarningsbyspecifyingacomma−separatedlistofwarningnumbers.

Relatedinformation

Assembleroption−−no−warnings(Suppresssomeorallwarnings)

5−194 ToolOptions−Linker

5.4 LinkerOptions

AltiumDesignerusesamakefiletobuildyourentireproject.Thismeansthatyoucannotrunthelinkerseparately.However,you cansetoptionsspecificforthelinker.

OptionsinAltiumDesignerversusoptionsonthecommandline MostcommandlineoptionshaveanequivalentoptioninAltiumDesignerbutsomeoptionsareonlyavailableonthe commandline(forexampleinaWindowsCommandPrompt).IfthereisnoequivalentoptioninAltiumDesigner,youcan specifyacommandlineoptioninAltiumDesignerasfollows: 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheLinkerentryandselectMiscellaneous. 3. EnteroneormorecommandlineoptionsintheAdditionalLinkeroptionsfield.

Invocationsyntaxonthecommandline(WindowsCommandPrompt) Theinvocationsyntaxonthecommandlineis: lknios[[option]...[file]...]...

Whenyouarelinkingmultiplefiles,eitherrelocatableobjectfiles(.objor.o),.outfilesorlibraries(.libor.a),itisimportant tospecifythefilesintherightorder.Fileswithextensionsotherthan.obj,.o,.out,.libor.aarenotrecognizedasinput files.

Shortandlongoptionnames Optionscanhavebothshortandlongnames.Shortoptionnamesalwaysbeginwithasingleminus(−)character,longoption namesalwaysbeginwithdoubleminus(−−)characters.Youcanabbreviatelongoptionnamesaslongasthenameisunique. Youcanmixshortandlongoptionnamesonthecommandline. Optionscanhaveflagsorsub−options.Toswitchaflag’on’,usealowercaseletterora+longflag.Toswitchaflagoff,usean uppercaseletterora−longflag.Separatelongflagswithcommas.Thefollowingtwoinvocationsareequivalent: lknios−mfktest.obj lknios−−map−file−format=+files,+linktest.obj

Whenyoudonotspecifyanoption,adefaultvaluemaybecomeactive.

5−195 NiosIIEmbeddedToolsReference

Linker:−−case−insensitive

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheLinkerentryandselectMiscellaneous. 3. DisabletheoptionLinkcasesensitive.

Commandlinesyntax −−case−insensitive

Description Withthisoptionyoutellthelinkernottodistinguishbetweenupperandlowercasecharactersinsymbols.Bydefaultthelinker considersupperandlowercasecharactersasdifferentcharacters.

DisablingtheoptionLinkcasesensitiveinAltiumDesigneristhesameasspecifyingtheoption−−case−insensitiveon thecommandline. Assemblysourcefilesthataregeneratedbythecompilermustalwaysbeassembledandthuslinkedcasesensitive.Whenyou havewrittenyourownassemblycodeandspecifiedtoassembleitcaseinsensitive,youmustalsolinkthe.objfilecase insensitive.

Relatedinformation

5−196 ToolOptions−Linker

Linker:−−chip−output(−c)

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheLinkerentryandselectOutputFormat. 3. EnabletheoptionsIntelHEXrecordsand/orMotorolaS−records.

Commandlinesyntax −−chip−output=[basename]:format[:addr_size],... −c[basename]:format[:addr_size],... Youcanspecifythefollowingformats: IHEX IntelHex SREC MotorolaS−records Theaddr_sizespecifiesthesizeoftheaddressesinbytes(recordlength).ForIntelHexyoucanusethevalues1,2or4bytes (default).ForMotorola−Syoucanspecify:2(S1records),3(S2records)or4bytes(S3records,default).InAltiumDesigneryou cannotspecifytheaddresssizebecauseAltiumDesigneralwaysusesthedefaultvalues.

Description WiththisoptionyouspecifytheIntelHexorMotorolaS−recordoutputformatforloadingintoaPROM−programmer.Thelinker generatesafileforeachROMmemorydefinedintheLSLfile,wheresectionsarelocated: memorymemname {type=rom;}

ThenameofthefileisthenameoftheAltiumDesignerprojector,onthecommandline,thenameofthememorydevicethat wasemittedwithextension.hexor.sre.Optionally,youcanspecifyabasenamewhichprependsthegeneratedfilename.

ThelinkeralwaysoutputsadebuggingfileinELF/DWARFformatandoptionallyanabsoluteobjectfileinIntel Hex−formatand/orMotorolaS−recordformat.

Example TogenerateIntelHexoutputfilesforeachdefinedmemory,enterthefollowingonthecommandline: lknios−−chip−output=myfile:IHEXtest1.obj

Inthiscase,thisgeneratesthefilemyfile_memname.hex

Relatedinformation

Linkeroption−−output(Outputfile) Section7.2,MotorolaS−RecordFormat, Section7.3,IntelHexRecordFormat,inChapterObjectFileFormats.

5−197 NiosIIEmbeddedToolsReference

Linker:−−define(−D)

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheLinkerentryandselectMiscellaneous. 3. ClickonUsermacro,clickonthedownarrowintherightpanetoexpandmacroinput. 4. ClickonanemptyMacrofieldandenteramacroname.(Thenclickoutsidethecelltoconfirm) 5. Optionally,clickintheValuefieldandenteradefinition.(Thenclickoutsidethecelltoconfirm)

Commandlinesyntax

−−define=macro_name[=macro_definition] −Dmacro_name[=macro_definition]

Description WiththisoptionyoucandefineamacroandspecifyittothelinkerLSLfilepreprocessor.Ifyouonlyspecifyamacroname(no macrodefinition),themacroexpandsas’1’. Youcanspecifyasmanymacrosasyoulike;justusetheoption−−definemultipletimes.Ifthecommandlineexceedsthelimit oftheoperatingsystem,youcandefinethemacrosinanoptionfilewhichyouthenmustspecifytothelinkerwiththeoption −−option−file=file(−f). Thedefinitioncanbetestedbythepreprocessorwith#if,#ifdefand#ifndef,forconditionallocating.

Example Todefinethestacksizeandstartaddresswhichareusedinthelinkerscriptfilenios.lsl,enter: lkniostest.obj−otest.abs−dnios.lsl−D__STACK=32k −D__START=0x00000000 orusingthelongoptionnames: lknios−otest.abs−lsl−file=nios.lsl−−define=__STACK=32k −−define=__START=0x00000000

Relatedinformation

Linkeroption−−option−file(Readoptionsfromfile)

5−198 ToolOptions−Linker

Linker:−−diag

Menuentry 1. FromtheViewmenu,selectWorkspacePanels»System»Messages. TheMessagespanelappears. 2. IntheMessagespanel,right−clickonthemessageyouwantmoreinformationon. Apopupmenuappears. 3. SelectMoreInfo. AMessageInfoboxappearswithadditionalinformation.

Commandlinesyntax

−−diag=[format:]{all|nr,...]

Description Withthisoptionyoucanaskforanextendeddescriptionoferrormessagesintheformatyouchoose.Theoutputisdirectedto stdout(normallyyourscreen)andintheformatyouspecify.Youcanspecifythefollowingformats:html,rtfortext(default). Tocreateafilewiththedescriptions,youmustredirecttheoutput. Withthesuboptionall,thedescriptionsofallerrormessagesaregiven.Ifyouwantthedescriptionofoneormoreselectederror messages,youcanspecifytheerrormessagenumbers,separatedbycommas. Withthisoptionthelinkerdoesnotlink/locateanyfiles.

Example Todisplayanexplanationofmessagenumber106,enter: lknios−−diag=106

Thisresultsinthefollowingmessageandexplanation: E106:unresolvedexternal: Thelinkercouldnotresolveallexternalsymbols.Thisisanerrorwhentheincremental linkingoptionisdisabled.Theindicatesthesymbolthatisunresolved.

TowriteanexplanationofallerrorsandwarningsinHTMLformattofilelerrors.html,enter: lknios−−diag=html:all>lerrors.html

Relatedinformation

5−199 NiosIIEmbeddedToolsReference

Linker:−−endianness

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheProcessorentryandselectProcessorDefinition. 3. EnabletheoptionBig−endianmode.

Commandlinesyntax −−endianness=endianness −B −−big−endian Youcanspecifythefollowingendianness: big (b) Bigendian little (l) Littleendian(default)

Description Bydefault,thelinkerlinksobjectsinlittle−endianmode.With−−endianness=bigyoutellthelinkertolinktheinputfilesin big−endianmode.Theendianessusedmustbevalidforthearchitectureyouarelinkingfor.Dependingontheendianessused, thelinkerlinksdifferentlibraries. −Bisanaliasforoption−−endianness=big.

Relatedinformation

5−200 ToolOptions−Linker

Linker:−−error−file

Menuentry −

Commandlinesyntax

−−error−file[=file]

Description Withthisoptionthelinkerredirectserrormessagestoafile. Ifyoudonotspecifyafilename,theerrorfileislknios.elk.

Example Towriteerrorstoerrors.elkinsteadofstderr,enter: lknios−−error−file=errors.elktest.obj

Relatedinformation

5−201 NiosIIEmbeddedToolsReference

Linker:−−error−limit

Menuentry −

Commandlinesyntax

−−error−limit=number

Description Withthisoptionyoutellthelinkertoonlyemitthespecifiedmaximumnumberoferrors.When0(null)isspecified,thelinker emitsallerrors.Withoutthisoptionthemaximumnumberoferrorsis42.

Relatedinformation

5−202 ToolOptions−Linker

Linker:−−extern(−e)

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheLinkerentryandselectMiscellaneous. 3. Addtheoption−−externtotheAdditionallinkeroptionsfield.

Commandlinesyntax −−extern=symbol −esymbol

Description Withthisoptionyouforcethelinkertoconsiderthegivensymbolasanundefinedreference.Thelinkertriestoresolvethis symbol,eitherthesymbolisdefinedinanobjectfileorthelinkerextractsthecorrespondingsymboldefinitionfromalibrary. Thisoptionis,forexample,usefulifthestartupcodeispartofalibrary.Becauseyourownapplicationdoesnotrefertothe startupcode,youcanforcethestartupcodetobeextractedbyspecifyingthesymbol_STARTasanunresolvedexternal.

Example Considerthefollowinginvocation: lkniosmylib.lib

Nothingislinkedandnooutputfilewillbeproduced,becausetherearenounresolvedsymbolswhenthelinkersearches throughmylib.lib. lknios−−extern=_STARTmylib.lib

Inthiscasethelinkersearchesforthesymbol_STARTinthelibraryand(iffound)extractstheobjectthatcontains_START,the startupcode.Ifthismodulecontainsnewunresolvedsymbols,thelinkerlooksagaininmylib.lib.Thisprocessrepeatsuntil nonewunresolvedsymbolsarefound.

Relatedinformation

Section6.4,LinkingwithLibraries,inchapterUsingtheLinkeroftheuser’smanual.

5−203 NiosIIEmbeddedToolsReference

Linker:−−first−libraryfirst

Menuentry −

Commandlinesyntax −−first−library−first

Description Whenthelinkerprocessesalibraryitsearchesforsymbolsthatarereferencedbytheobjectsandlibrariesprocessedsofar.If thelibrarycontainsadefinitionforanunresolvedreferencethelinkerextractstheobjectthatcontainsthedefinitionfromthe library. Bydefaultthelinkerprocessesobjectfilesandlibrariesintheorderinwhichtheyappearonthecommandline.Ifyouspecifythe option−−first−library−firstthelinkeralwaystriestotakethesymboldefinitionfromthelibrarythatappearsfirstonthe commandlinebeforescanningsubsequentlibraries. Thisisforexampleusefulwhenyouareworkingwithanewerversionofalibrarythatpartiallyoverlapstheolderversion. Becausetheydonotcontainexactlythesamefunctions,youhavetolinkthemboth.However,whenafunctionispresentin bothlibraries,youmaywantthelinkertoextractthemostrecentfunction.

Example Considerthefollowingexample: lknios−−first−library−firsta.libtest.objb.lib

Ifthefiletest.objcallsafunctionwhichisbothpresentina.libandb.lib,normallythefunctioninb.libwouldbe extracted.Withthisoptionthelinkerfirsttriestoextractthesymbolfromthefirstlibrarya.lib. Notethatroutinesinb.libthatcallotherroutinesthatarepresentinbotha.libandb.libarenowalsoresolvedfrom a.lib.

Relatedinformation

Linkeroption−−no−rescan(Rescanlibrariestosolveunresolvedexternals)

5−204 ToolOptions−Linker

Linker:−−global−type−checking

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheLinkerentryandselectMiscellaneous. 3. Addtheoption−−global−type−checkingtotheAdditionallinkeroptionsfield.

Commandlinesyntax −−global−type−checking

Description Usethisoptionwhenyouwantthelinkertocheckthetypesofvariableandfunctionreferencesagainsttheirdefinitions,using DWARF2orDWARF3debuginformation. ThischeckshouldgivethesameresultastheCcompilerwhenyouuseMILlinking.

Relatedinformation

5−205 NiosIIEmbeddedToolsReference

Linker:−−help(−?)

Menuentry −

Commandlinesyntax

−−help[=options] −?

Description Displaysanoverviewofallcommandlineoptions.Whenyouspecifytheargumentoptionsyoucanlistdetailedoption descriptions.

Example Thefollowinginvocationsalldisplayalistoftheavailablecommandlineoptions: lknios−? lknios−−help lknios

Toseeadetaileddescriptionoftheavailableoptions,enter: lknios−−help=options

5−206 ToolOptions−Linker

Linker:−−hex−format

Menuentry −

Commandlinesyntax

−−hex−format=flag,... Youcansetthefollowingflag: +/−start−address (s/S) Emitstartaddressrecord Default:−−hex−format=s

Description Withthisoptionyoucanspecifytoemitoromitthestartaddressrecordfromthehexfile.

Relatedinformation

Linkeroption−−output(Outputfile)

5−207 NiosIIEmbeddedToolsReference

Linker:−−hex−record−size

Menuentry −

Commandlinesyntax

−−hex−record−size=size Default:32

Description Withthisoptionyoucansetthesize(width)oftheIntelHexdatarecords.

Relatedinformation

Linkeroption−−output(Outputfile) Section7.3,IntelHexRecordFormat,inChapterObjectFileFormats.

5−208 ToolOptions−Linker

Linker:−−import−object

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheLinkerentryandselectMiscellaneous. 3. AddoneormorefilestotheImportthefollowingdataobjectfilesfield.

Commandlinesyntax −−import−object=file,...

Description Withthisoptionthelinkerimportsabinaryfilecontainingrawdataandplacesitinasection.Thesectionnameisderivedfrom thefilename,inwhichdotsarereplacedbyanunderscore.So,whenimportingafilecalledmy.jpg,asectionwiththename my_jpgiscreated.Inyourapplicationyoucanrefertothecreatedsectionbyusinglinkerlabels.

Relatedinformation

Section6.7,ImportingBinaryFiles.

5−209 NiosIIEmbeddedToolsReference

Linker:−−include−directory(−I)

Menuentry −

Commandlinesyntax

−−include−directory=path,... −Ipath,...

Description WiththisoptionyoucanspecifythepathwhereyourLSLincludefilesarelocated.Arelativepathwillberelativetothecurrent directory. TheorderinwhichthelinkersearchesforLSLincludefilesis: 1. ThepathnameintheLSLfileandthedirectorywheretheLSLfileislocated (onlyfor#includefilesthatareenclosedin"") 2. Thepaththatisspecifiedwiththisoption. 3. Thedefaultdirectory$(PRODDIR)\include.lsl.

Example Supposethatyourlinkerscriptfilemylsl.lslcontainsthefollowingline: #include"myinc.inc"

Youcancallthelinkerasfollows: lknios−−include−directory=c:\proj\include−−lsl−file=mylsl.lsltest.obj

Firstthelinkerlooksinthedirectorywheremylsl.lslislocatedforthefilemyinc.inc.Ifitdoesnotfindthefile,itlooksinthe directoryc:\proj\includeforthefilemyinc.inc(thisoption).Finallyitlooksinthedirectory$(PRODDIR)\include.lsl.

Relatedinformation

5−210 ToolOptions−Linker

Linker:−−incremental(−r)

Menuentry −

Commandlinesyntax −−incremental −r

Description Normallythelinkerlinksandlocatesthespecifiedobjectfiles.Withthisoptionyoutellthelinkeronlytolinkthespecifiedfiles. Thelinkercreatesalinkeroutputfile.out.Youthencanlinkthisfileagainwithotherobjectfilesuntilyouhavereachedthefinal linkeroutputfilethatisreadyforlocating. Inthelastpass,youcallthelinkerwithoutthisoptionwiththefinallinkeroutputfile.out.Thelinkerwillnowlocatethefile.

Example Inthisexample,thefilestest1.obj,test2.objandtest3.objareincrementallylinked: 1. lknios−−incrementaltest1.objtest2.obj−otest.out test1.objandtest2.objarelinked 2. lknios−−incrementaltest3.objtest.out test3.objandtest.outarelinked,task1.outiscreated 3. lkniostask1.out task1.outislocated

Relatedinformation

Section6.5,IncrementalLinkinginchapterUsingtheLinkeroftheuser’smanual.

5−211 NiosIIEmbeddedToolsReference

Linker:−−keep−output−files(−k)

Menuentry AltiumDesigneralwaysremovestheoutputfileswhenerrorsoccurred.

Commandlinesyntax −−keep−output−files −k

Description Ifanerroroccursduringlinking,theresultingoutputfilemaybeincompleteorincorrect.Withthisoptionyoukeepthegenerated outputfileswhenanerroroccurs. Bydefaultthelinkerremovesthegeneratedoutputfilewhenanerroroccurs.Thisisusefulwhenyouusethemakeutility.Ifthe erroneousfilesarenotremoved,themakeutilitymayprocesscorruptfilesonasubsequentinvocation. Usethisoptionwhenyoustillwanttousethegeneratedfile.Forexamplewhenyouknowthataparticularerrordoesnotresult inacorruptobjectfile,orwhenyouwanttoinspecttheoutputfile,orsendittoAltiumsupport.

Relatedinformation

5−212 ToolOptions−Linker

Linker:−−library(−l)

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheLinkerentryandselectLibraries. 3. EnabletheoptionLinkdefaultClibraries.

Commandlinesyntax −−library=name −lname

Description Withthisoptionyoutellthelinkertousesystemlibraryname.lib,wherenameisastring.Thelinkerfirstsearchesfor systemlibrariesinanydirectoriesspecifiedwith−−library−directory,theninthedirectoriesspecifiedwiththeenvironment variableLIBNIOSII,unlessyouusedtheoption−−ignore−default−library−path.

Example Tosearchinthesystemlibrarycnios.lib(Clibrary): lkniostest.objmylib.lib−−library=cnios

Thelinkerlinksthefiletest.objandfirstlooksinmylib.lib(inthecurrentdirectoryonly),theninthesystemlibrary cnios.libtoresolveunresolvedsymbols.

Relatedinformation

Linkeroption−−library−directory(Additionalsearchpathforsystemlibraries) Section6.4,LinkingwithLibraries,inchapterUsingtheLinkeroftheuser’smanual.

5−213 NiosIIEmbeddedToolsReference

Linker:−−library−directory(−L)/−−ignore−default−library−path

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. OpentheBuildOptionspage. 3. AddapathnameintheLibraryfilespathfield. Ifyouentermultiplepaths,separatethemwithasemicolon(;).

Commandlinesyntax −−library−directory=dir −Ldir −−ignore−default−library−path −L

Description Withthisoptionyoucanspecifythepath(s)whereyoursystemlibraries,specifiedwiththe−−libraryoption,arelocated.Ifyou wanttospecifymultiplepaths,usetheoption−−library−directoryforeachseparatepath. Thedefaultpathis$(PRODDIR)\cnios\lib. Ifyouspecifyonly−L(withoutapathname)orthelongoption−−ignore−default−library−path,thelinkerwillnotsearchthe defaultpathandalsonotinthepathsspecifiedintheenvironmentvariableLIBNIOSII.So,thelinkerignoressteps2and3as listedbelow. Thepriorityorderinwhichthelinkersearchesforsystemlibrariesspecifiedwiththe−−libraryoptionis: 1. Thepaththatisspecifiedwiththe−−library−directoryoption. 2. ThepaththatisspecifiedintheenvironmentvariableLIBNIOSII. 3. Thedefaultdirectory$(PRODDIR)\cnios\lib(oraprocessorspecificsub−directory).

Example Supposeyoucallthelinkerasfollows: lkniostest.obj−−library−directory=c:\mylibs−−library=cnios

Firstthelinkerlooksinthedirectoryc:\mylibsforlibrarycnios.lib(thisoption). Ifitdoesnotfindtherequestedlibraries,itlooksinthedirectorythatissetwiththeenvironmentvariableLIBNIOSII. Thenthelinkerlooksinthedefaultdirectory$(PRODDIR)\cnios\libforlibraries.

Relatedinformation

Linkeroption−−library(Linksystemlibrary) Section6.4.1,HowthelinkersearcheslibrariesinchapterUsingtheLinkeroftheuser’smanual.

5−214 ToolOptions−Linker

Linker:−−link−only

Menuentry −

Commandlinesyntax −−link−only

Description Withthisoptionyousuppressthelocatingphase.Thelinkerstopsafterlinkingandinformsyouaboutunresolvedreferences.

Relatedinformation

Controlprogramoption−cl(Stopafterlinking)

5−215 NiosIIEmbeddedToolsReference

Linker:−−lsl−check

Menuentry −

Commandlinesyntax −−lsl−check

Description WiththisoptionthelinkerjustchecksthesyntaxoftheLSLfile(s)andexits.Nolinkingorlocatingisperformed.Usetheoption −−lsl−file=filetospecifythenameoftheLinkerScriptFileyouwanttotest.

Relatedinformation

Linkeroption−−lsl−file(Linkerscriptfile) Linkeroption−−lsl−dump(DumpLSLinfo) Section6.9,ControllingtheLinkerwithaScript,inchapterUsingtheLinkeroftheuser’smanual.

5−216 ToolOptions−Linker

Linker:−−lsl−dump

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheLinkerentryandselectMiscellaneous. 3. EnabletheoptionDumpprocessorandmemoryinfofromLSLfile.

Commandlinesyntax −−lsl−dump[=file]

Description WiththisoptionyoutellthelinkertodumptheLSLpartofthemapfileinaseparatefile,independentoftheoption−−map−file (generatemapfile).Ifyoudonotspecifyafilename,thefilelktarget.ldfisused.

Relatedinformation

Linkeroption−−map−file−format(Mapfileformatting)

5−217 NiosIIEmbeddedToolsReference

Linker:−−lsl−file(−d)

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheLinkerentryandselectMiscellaneous. 3. EnabletheoptionUseprojectspecificLSLfile. 4. IntheLSLfilefield,typeanameorclick...andselectanLSLfile.

Commandlinesyntax −−lsl−file=file −dfile

Description Alinkerscriptfilecontainsvitalinformationaboutthecoreforthelocatingphaseofthelinker.AlinkerscriptfileiscodedinLSL andcontainsthefollowingtypesofinformation: • thearchitecturedefinitiondescribesthecore’shardwarearchitecture. • thememorydefinitiondescribesthephysicalmemoryavailableinthesystem. • thesectionlayoutdefinitiondescribeshowtolocatesectionsinmemory. Withthisoptionyouspecifyalinkerscriptfiletothelinker.Ifyoudonotspecifythisoption,thelinkerusesadefaultscriptfile. Youcanspecifytheexistingfilenios.lslorthenameofamanuallywrittenlinkerscriptfile.Youcanusethisoptionmultiple times.ThelinkerprocessestheLSLfilesintheorderinwhichtheyappearonthecommandline.

Relatedinformation

Linkeroption−−lsl−check(CheckLSLfile(s)andexit) Section6.9,ControllingtheLinkerwithaScript,inchapterUsingtheLinkeroftheuser’smanual.

5−218 ToolOptions−Linker

Linker:−−map−file(−M)

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheLinkerentryandselectMapFile. 3. EnabletheoptionGenerateamemorymapfile(.map). 4. IntheMapfileformatsection,enableordisabletheinformationyouwanttobeincludedinthemapfile.

Commandlinesyntax −−map−file[=file] −M[file]

Description Withthisoptionyoutellthelinkertogeneratealinkermapfile.Ifyoudonotspecifyafilenameandyouspecfiedthe−ooption, thelinkerusesthesamebasenameastheoutputfilewiththeextension.map.Ifyoudidnotspecifythe−ooption,thelinker usesthefiletask1.map.AltiumDesignernamesthe.mapfileaftertheproject. Alinkermapfileisatextfilethatshowshowthelinkerhasmappedthesectionsandsymbolsfromthevariousobjectfiles (.obj)tothelinkedobjectfile.Alocatepartshowstheabsolutepositionofeachsection.Externalsymbolsarelistedperspace withtheirabsoluteaddress,bothsortedonsymbolandsortedonaddress.

Relatedinformation

Withtheoption−−map−file−format(mapfileformatting)youcanspecifywhichpartsyouwanttoplaceinthemapfile. Section6.2,LinkerMapFileFormat,inChapterListFileFormats.

5−219 NiosIIEmbeddedToolsReference

Linker:−−map−file−format(−m)

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheLinkerentryandselectMapFile. 3. EnabletheoptionGenerateamapfile(.map). 4. IntheMapfileformatsection,enableordisabletheinformationyouwanttobeincludedinthemapfile.

Commandlinesyntax −−map−file−format=flags −mflags Youcanspecifythefollowingformats: 0 Sameas−mcDfikLMNoQrSU(linkinformation) 1 Sameas−mCDfiKlMNoQRSU(locateinformation) 2 Sameas−mcdfiklmNoQrSu(mostinformation) +/−callgraph (c/C) Callgraphinformation +/−removed (d/D) Removedsectionsinformation +/−files (f/F) Processedfilesinformation +/−invocation (i/I) Invocationandtoolinformation +/−link (k/K) Linkresultinformation +/−locate (l/L) Locateresultinformation +/−memory (m/M) Memoryusageinformation +/−nonalloc (n/N) Nonallocinformation +/−overlay (o/O) Overlayinformation +/−statics (q/Q) Modulelocalsymbols +/−crossref (r/R) Crossreferencesinformation +/−lsl (s/S) Processorandmemoryinformation +/−rules (u/U) Locaterules

Description Withthisoptionyouspecifywhichinformationyouwanttoincludeinthemapfile.Usethisoptionincombinationwiththeoption −−map−file(−M). Ifyoudonotspecifythisoption,thelinkerusesthedefault:−−map−file−format=2.

Relatedinformation

Linkeroption−−map−file(Generatemapfile)

5−220 ToolOptions−Linker

Linker:−−misra−c−report

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheCCompilerentryandselectMISRA−C. 3. SelectaMISRA−Cconfiguration. 4. EnabletheoptionProduceaMISRA−Creport.

Commandlinesyntax −−misra−c−report[=file]

Description WiththisoptionyoutellthelinkertocreateaMISRA−CQualityAssurancereport.Thisreportliststhevariousmodulesinthe projectwiththerespectiveMISRA−Csettingsatthetimeofcompilation.Ifyoudonotspecifyafilename,thefilename.mcris used.

Relatedinformation

Compileroption−−misrac

5−221 NiosIIEmbeddedToolsReference

Linker:−−munch

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogappears. 2. ExpandtheLinkerentryandselectMiscellaneous. 3. Addtheoption−−munchtotheAdditionallinkeroptionsfield.

Commandlinesyntax

−−munch

Description Withthisoptionyoutellthelinkertoactivatethemuncherinthepre−locatephase.

Relatedinformation

5−222 ToolOptions−Linker

Linker:−−non−romable

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheLinkerentryandselectMiscellaneous. 3. Addtheoption−−non−romabletotheAdditionallinkeroptionsfield.

Commandlinesyntax −−non−romable

Description WiththisoptionyoutellthelinkerthattheapplicationmustnotbelocatedinROM.ThelinkerwilllocateallROMsections, includingacopytableifpresent,inRAM.Whentheapplicationisstarted,thedatasectionsarere−initializedandtheBSS sectionsareclearedasusual. Thisoptionis,forexample,usefulwhenyouwanttotesttheapplicationinRAMbeforeyouputthefinalapplicationinROM.This savesyouthetimeofflashingtheapplicationinROMoverandoveragain.

Relatedinformation

5−223 NiosIIEmbeddedToolsReference

Linker:−−no−rescan

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheLinkerentryandselectLibraries. 3. DisabletheoptionRescanlibrariestosolveunresolvedexternals.

Commandlinesyntax −−no−rescan

Description Whenthelinkerprocessesalibraryitsearchesforsymboldefinitionsthatarereferencedbytheobjectsandlibrariesprocessed sofar.Ifthelibrarycontainsadefinitionforanunresolvedreferencethelinkerextractstheobjectthatcontainsthedefinitionfrom thelibrary.Thelinkerprocessesobjectfilesandlibrariesintheorderinwhichtheyappearonthecommandline. Whenallobjectsandlibrariesareprocessedthelinkerchecksifthereareunresolvedsymbolsleft.Ifso,thedefaultbehaviorof thelinkeristorescanalllibrariesintheordergivenatthecommandline.Thelinkerstopsrescanningthelibrarieswhenall symbolsareresolved,orwhenthelinkercouldnotresolveanysymbol(s)duringtherescanofalllibraries.Noticethatresolving onesymbolmayintroducenewunresolvedsymbols. Withthisoption,youtellthelinkertoscantheobjectfilesandlibrariesonlyonce.Whenthelinkerhasnotresolvedallsymbols afterthefirstscan,itreportswhichsymbolsarestillunresolved.Thisoptionisusefulifyouarebuildingyourownlibraries.The librariesaremostefficientlyorganizedifthelinkerneedsonlyonepasstoresolveallsymbols.

Relatedinformation

Linkeroption−−first−library−first(Scanlibrariesingivenorder)

5−224 ToolOptions−Linker

Linker:−−no−rom−copy(−N)

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheLinkerentryandselectMiscellaneous. 3. Addtheoption−−no−rom−copytotheAdditionallinkeroptionsfield.

Commandlinesyntax −−no−rom−copy −N

Description WiththisoptionthelinkerwillnotgenerateaROMcopyfordatasections.Acopytableisgeneratedandcontainsentriesto clearBSSsection.However,noentriestocopydatasectionsfromROMtoRAMareplacedinthecopytable. Thedatasectionsareinitializedwhentheapplicationisdownloaded.Thedatasectionsarenotre−initializedwhenthe applicationisrestarted.

Relatedinformation

5−225 NiosIIEmbeddedToolsReference

Linker:−−no−warnings(−w)

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheLinkerentryandselectDiagnostics. 3. SetErrorreportingtooneofthefollowingvalues: • Reportallwarnings • Suppressallwarnings • Suppressspecificwarnings. IfyouselectSuppressspecificwarnings: 4. Enterthenumbers,separatedbycommas,ofthewarningsyouwanttosuppress.

Commandlinesyntax −−no−warnings[=number,...] −w[number,...]

Description Withthisoptionyoucansuppressesallwarningmessagesorspecificwarningmessages. • Ifyoudonotspecifythisoption,allwarningsarereported. • Ifyouspecifythisoptionbutwithoutnumbers,allwarningsaresuppressed. • Ifyouspecifythisoptionwithanumber,onlythespecifiedwarningissuppressed.Youcanspecifytheoption −−no−warnings=numbermultipletimes. Example Tosuppresswarnings135and136,enter135,136intheSpecificwarningstosuppressfield,orenterthefollowingonthe commandline: lknios−−no−warnings=135,136test.obj

Relatedinformation

Linkeroption−−warnings−as−errors(Treatwarningsaserrors)

5−226 ToolOptions−Linker

Linker:−−optimize(−O)

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheLinkerentryandselectOptimization. 3. SelectanoptimizationlevelintheOptimizationlevelbox. IfyouselectCustomOptimization: 4. Enabletheoptimizationsyouwant.

Commandlinesyntax

−−optimize[=flags] −O[flags] Usethefollowingoptionsforpredefinedsetsofflags: −−optimize=0 (−O0) Nooptimization Aliasfor:−OCLTXYZ −−optimize=1 (−O1) Defaultoptimization Aliasfor:−OcLtXYZ −−optimize=2 (−O2) Alloptimizations Aliasfor:−Ocltxyz Youcansetthefollowingflags: +/−delete−unreferenced−sections (c/C) Deleteunreferencedsectionsfromtheoutputfile +/−first−fit−decreasing (l/L) Usea’firstfitdecreasing’algorithmtolocate unrestrictedsectionsinmemory. +/−copytable−compression (t/T) Emitsmartrestrictionstoreducecopytablesize +/−delete−duplicate−code (x/X) Deleteduplicatecodesectionsfromtheoutputfile +/−delete−duplicate−data (y/Y) Deleteduplicateconstantdatafromtheoutputfile +/−copytable−item−compression (z/Z) TrytocompressROMsectionsofcopytableitems

Description Withthisoptionyoucancontrolthelevelofoptimizationthelinkerperforms.Ifyoudonotusethisoption,−−optimize=1isthe default.

Relatedinformation

Section6.8,LinkerOptimizations,inchapterUsingtheLinkeroftheuser’smanual.

5−227 NiosIIEmbeddedToolsReference

Linker:−−option−file(−f)

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheLinkerentryandselectMiscellaneous. 3. Addtheoption−−option−filetotheAdditionallinkeroptionsfield. Beawarethattheoptionsintheoptionfileareaddedtothelinkeroptionsyouhavesetintheotherdialogs.Onlyin extraordinarycasesyoumaywanttousethemincombination.AltiumDesignerautomaticallysavestheoptionswithyour project.

Commandlinesyntax −−option−file=file −ffile

Description

Thisoptionisprimarilyintendedforcommandlineuse.Insteadoftypingalloptionsonthecommandline,youcancreatean optionfilewhichcontainsalloptionsandflagsyouwanttospecify.Withthisoptionyouspecifytheoptionfiletothelinker. Useanoptionfilewhenthelengthofthecommandlinewouldexceedthelimitsoftheoperatingsystem,orjusttostoreoptions andsavetyping. Youcanspecifytheoption−−option−filemultipletimes. Formatofanoptionfile • Multipleargumentsononelineintheoptionfileareallowed. • Toincludewhitespaceinanargument,surroundtheargumentwithsingleordoublequotes. • Ifyouwanttousesinglequotesaspartoftheargument,surroundtheargumentbydoublequotesandviseversa: "Thishasasinglequote’embedded" ’Thishasadoublequote"embedded’ ’Thishasadoublequote"andasinglequote’"’embedded" • Whenatextlinereachesitslengthlimit,usea\tocontinuetheline.Whitespacebetweenquotesispreserved. "Thisisacontinuation\ line"

−>"Thisisacontinuationline" • Itispossibletonestcommandlinefilesupto25levels. Example Supposethefilemyoptionscontainsthefollowinglines: −Mmymap(generateamapfile) test.obj(inputfile) −Lc:\mylibs(additionalsearchpathforsystemlibraries) Specifytheoptionfiletothelinker: lknios−−option−file=myoptions

Thisisequivalenttothefollowingcommandline: lknios−Mmymaptest.obj−Lc:\mylibs

Relatedinformation

5−228 ToolOptions−Linker

Linker:−−output(−o)

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheLinkerentryandselectOutputFormat. 3. Enableoneormoreoutputformats

Commandlinesyntax −−output=[filename][:format[:addr_size]]... −o[filename][:format[:addr_size]]... Youcanspecifythefollowingformats: ELF ELF/DWARF IHEX IntelHex SREC MotorolaS−records

Description Bydefault,thelinkergeneratesanoutputfileinELF/DWARFformat,namedafterthefirstinputfilewithextension.abs. Withthisoptionyoucanspecifyanalternativefilename,andanalternativeoutputformat.Thedefaultoutputformatistheformat ofthefirstinputfile. Youcanusethe−−outputoptionmultipletimes.Thisisusefultogeneratemultipleoutputformats.Withthefirstoccurrenceof the−−outputoptionyouspecifythebasename(thefilenamewithoutextension),whichisusedforsubsequent−−output optionswithnofilenamespecified.Ifyoudonotspecifyafilename,oryoudonotspecifythe−−outputoptionatall,thelinker usesthedefaultbasenametaskn.

IHEXandSRECformats IfyouspecifytheIntelHexformatortheMotorolaS−recordsformat,youcanusetheargumentaddr_sizetospecifythesizeof addressesinbytes(recordlength).ForIntelHexyoucanusethevalues:1,2,and4(default).ForMotorolaS−recordsyoucan specify:2(S1records),3(S2records)or4bytes(S3records,default). Thenameoftheoutputfilewillbefilenamewiththeextension.hexor.sreandcontainsthecodeanddataallocatedinthe defaultaddressspace.Iftheyexist,anyotheraddressspacesarealsoemittedwhereastheiroutputfilesarenamed filename_spacename.hex(.sre).

Useoption−−chip−output(−c)tocreateIntelHexorMotorolaS−recordoutputfilesforeachchipdefinedintheLSLfile (suitableforloadingintoaPROM−programmer).

Example Tocreatetheoutputfilemyfile.hexofthedefaultaddressspace: lkniostest.obj−−output=myfile.hex:IHEX

Iftheyexist,anyotheraddressspacesareemittedaswellandarenamedmyfile_spacename.hex.

Relatedinformation

Linkeroption−−chip−output(Generateanoutputfileforeachchip)

5−229 NiosIIEmbeddedToolsReference

Linker:−−print−mangled−symbols(−P)

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogappears. 2. ExpandtheLinkerentryandselectMiscellaneous. 3. Addtheoption−−print−mangled−symbolstotheAdditionallinkeroptionsfield.

Commandlinesyntax −−print−mangled−symbols −P

Description C++compilersgenerateunreadablesymbolnames.ThesesymbolscannoteasilyberelatedtoyourC++sourcefileanymore. ThereforethelinkerwillbydefaultdecodethesesymbolsconformtheIA64ABIwhenprintedtostdout.Withthisoptionyou canoverridethisdefaultsettingandprintthemanglednamesinstead.

Relatedinformation

5−230 ToolOptions−Linker

Linker:−−strip−debug(−S)

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheLinkerentryandselectMiscellaneous. 3. DisabletheoptionIncludesymbolicdebuginformation.

Commandlinesyntax −−strip−debug −S

Description Withthisoptionyouspecifynottoincludesymbolicdebuginformationintheresultingoutputfile.

Relatedinformation

5−231 NiosIIEmbeddedToolsReference

Linker:−−user−provided−initialization−code(−i)

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheLinkerentryandselectMiscellaneous. 3. Addtheoption−−user−provided−initialization−codetotheAdditionallinkeroptionsfield.

Commandlinesyntax −−user−provided−initialization−code −i

Description Itispossibletouseyourowninitializationcode,forexample,tosaveROMspace.Withthisoptionyoutellthelinkernotto generateacopytableforinitialize/clearsections.Uselinkerlabelsinyoursourcecodetoaccessthepositionsofthesections whenlocated. IfthelinkerdetectsreferencestotheTASKINGinitializationcode,anerrorisemitted:itiseithertheTASKINGinitialization routineoryourown,notboth. Notethattheoptions−−no−rom−copyand−−non−romable,mayvaryindependently.The’copytable−compression’ optimization(−−optimize=t)isautomaticallydisabledwhenyouenablethisoption.

Relatedinformation

5−232 ToolOptions−Linker

Linker:−−verbose(−v)/−−extra−verbose(−vv)

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheLinkerentryandselectMiscellaneous. 3. Addtheoption−−verboseor−−extra−verbosetotheAdditionallinkeroptionsfield.

Commandlinesyntax −−verbose/−−extra−verbose −v/−vv

Description Withthisoptionyouputthelinkerinverbosemode.Thelinkerprintsthelinkphaseswhileitprocessesthefiles.Intheextra verbosemode,thelinkeralsoprintsthefilenamesanditshowswhichobjectsareextractedfromlibraries.Withthisoptionyou canmonitorthecurrentstatusofthelinker.

Relatedinformation

5−233 NiosIIEmbeddedToolsReference

Linker:−−version(−V)

Menuentry −

Commandlinesyntax −−version −V

Description Displayversioninformation.Thelinkerignoresallotheroptionsorinputfiles.

Relatedinformation

5−234 ToolOptions−Linker

Linker:−−warnings−as−errors

Menuentry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. ExpandtheLinkerentryandselectDiagnostics. 3. EnabletheoptionTreatwarningsaserrors.

Commandlinesyntax −−warnings−as−errors[=number,...]

Description Whenthelinkerdetectsanerrororwarning,ittriestocontinuethelinkprocessandreportsothererrorsandwarnings.When youusethisoptionwithoutarguments,youtellthelinkertotreatallwarningsaserrors.Thismeansthattheexitstatusofthe linkerwillbenon−zeroafterthedetectionofoneormorelinkerwarnings.Asaconsequence,thelinkerwillnotproduceany outputfiles. Youcanalsolimitthisoptiontospecificwarningsbyspecifyingacomma−separatedlistofwarningnumbers.

Relatedinformation

Linkeroption−−no−warnings(Suppresssomeorallwarnings)

5−235 NiosIIEmbeddedToolsReference

5.5 ControlProgramOptions

Thecontrolprogramisatooltofacilitateuseofthetoolsetfromthecommandline.Thereforeyoucanonlycallthecontrol programfromthecommandline.Theinvocationsyntaxis: ccnios[option]...[file]...

Options Thecontrolprogramprocessescommandlineoptionseitherbyitself,or,whentheoptionisunknowntothecontrolprogram,it lookswhetheritcanpasstheoptiontooneoftheothertools.However,fordirectlypassinganoptiontotheC++compiler,C compiler,assemblerorlinker,itisrecommendedtousethecontrolprogramoptions−−pass−c++,−−pass−c, −−pass−assembler,−−pass−linker.

Shortandlongoptionnames Optionscanhavebothshortandlongnames.Shortoptionnamesalwaysbeginwithasingleminus(−)character,longoption namesalwaysbeginwithdoubleminus(−−)characters.Youcanabbreviatelongoptionnamesaslongasthenameisunique. Youcanmixshortandlongoptionnamesonthecommandline. Optionscanhaveflagsorsub−options.Toswitchaflag’on’,usealowercaseletterora+longflag.Toswitchaflagoff,usean uppercaseletterora−longflag.Separatelongflagswithcommas.Thefollowingtwoinvocationsareequivalent: ccnios−Wc−Oactest.c ccnios−−pass−c=−−optimize=+coalescer,+csetest.c

Whenyoudonotspecifyanoption,adefaultvaluemaybecomeactive.

5−236 ToolOptions−ControlProgram

ControlProgram:−−address−size

Commandlinesyntax −−address−size=addr_size

Description

IfyouspecifyIHEXorSRECwiththecontroloption−−format,youcanadditionallyspecifytherecordlengthtobeemittedinthe outputfiles. Withthisoptionyoucanspecifythesizeofaddressesinbytes(recordlength).ForIntelHexyoucanusethevalues:1,2,and4 (default).ForMotorolaS−recordsyoucanspecify:2(S1records),3(S2records)or4bytes(S3records,default). Ifyoudonotspecifyaddr_size,thedefaultaddresssizeisgenerated.

Example TocreatetheSRECfiletest.srewithS1records,type: ccnios−−format=SREC−−address−size=2test.c

Relatedinformation

Controlprogramoption−−format(Setlinkeroutputformat) Linkeroption−−output(Specifyanoutputobjectfile)

5−237 NiosIIEmbeddedToolsReference

ControlProgram:−−check

Commandlinesyntax

−−check

Description Withthisoptionyoucancheckthesourcecodeforsyntaxerrors,withoutgeneratingcode.Thissavestimeindevelopingyour application. Thecompiler/assemblerreportsanywarningsand/orerrors.

Relatedinformation

Ccompileroption−−check(Checksyntax)

Assembleroption−−check(Checksyntax)

5−238 ToolOptions−ControlProgram

ControlProgram:−−cpu(−C)

Commandlinesyntax −−cpu=[nios2e|nios2f|nios2s] −C[nios2e|nios2f|nios2s]

Description

WiththisoptionyoudefinetheCPUcoreforwhichyoucreateyourapplication.TheNiosIItargethasmorethanoneprocessor typeandthereforeyouneedtospecifyfforwhichprocessortypeyouwanttocreateyourapplication.Youchooseoneofthe followingCPU’s:NiosII/e,NiosII/forNiosII/s. Assemblycodecancheckthevalueoftheoptionbymeansofthebuilt−infunction@CPU().

Relatedinformation

Ccompileroption−−cpu(SelectCPUcoretype) Assembleroption−−cpu(SelectCPUcoretype)

5−239 NiosIIEmbeddedToolsReference

ControlProgram:−−create(−cc/−cl/−cm/−co/−cs)

Commandlinesyntax −−create[=stage] −c[stage] Youcanspecifythefollowingstages(ifyouomitthestage,thedefaultis−−create=object): intermediate−c (c) StopafterC++filesarecompiledtointermediateCfiles(.ic) relocatable (l) Stopafterthefilesarelinkedtoalinkerobjectfile(.out) mil (m) StopafterCfilesarecompiledtoMIL(.mil) object (o) Stopafterthefilesareassembledtoobjects(.obj) assembly (s) StopafterCfilesarecompiledtoassembly(.src)

Description Normallythecontrolprogramgeneratesanabsoluteobjectfileofthespecifiedoutputformatfromthefileyousuppliedasinput. Withthisoptionyoutellthecontrolprogramtostopafteracertainnumberofphases.

Relatedinformation

Linkeroption−−link−only(Linkonly,nolocating)

5−240 ToolOptions−ControlProgram

ControlProgram:−−debug−info(−g)

Commandlinesyntax −−debug−info −g

Description

Withthisoptionyoutellthecontrolprogramtoincludedebuginformationinthegeneratedobjectfile.

Relatedinformation

5−241 NiosIIEmbeddedToolsReference

ControlProgram:−−define(−D)

Commandlinesyntax −−define=macro_name[=macro_definition] −Dmacro_name[=macro_definition]

Description

Withthisoptionyoucandefineamacroandspecifyittothepreprocessor.Ifyouonlyspecifyamacroname(nomacro definition),themacroexpandsas’1’. Youcanspecifyasmanymacrosasyoulike.Onthecommandline,usetheoption−−definemultipletimes.Ifthecommandline exceedsthelengthlimitoftheoperatingsystem,youcandefinethemacrosinanoptionfilewhichyouthenmustspecifytothe controlprogramwiththeoption−−option−file=file(−f). Definingmacroswiththisoption(insteadofintheCsource)is,forexample,usefultocompileorassembleconditionalsourceas shownintheexamplebelow. Thecontrolprogrampassestheoption−−define(−D)tothecompilerandtheassembler.

Example ConsiderthefollowingCprogramwithconditionalcodetocompileademoprogramandarealprogram: voidmain(void) { #ifDEMO==1 demo_func();/*compileforthedemoprogram*/ #else real_func();/*compilefortherealprogram*/ #endif }

YoucannowuseamacrodefinitiontosettheDEMOflag.Withthecontrolprogramthislooksasfollows: ccnios−−define=DEMOtest.c ccnios−−define=DEMO=1test.c

Notethatbothinvocationshavethesameeffect. Thenextexampleshowshowtodefineamacrowitharguments.Notethatthemacronameanddefinitionareplacedbetween doublequotesbecauseotherwisethespaceswouldindicateanewoption. ccnios−D"MAX(A,B)=((A)>(B)?(A):(B))"test.c

Relatedinformation

ControlProgramoption−−undefine(Undefinepreprocessormacro) ControlProgramoption−−option−file(Readoptionsfromfile)

5−242 ToolOptions−ControlProgram

ControlProgram:−−dep−file

Commandlinesyntax −−dep−file[=file]

Description

WiththisoptionyoutellthecompilertogeneratedependencylinesthatcanbeusedinaMakefile.Incontrasttotheoption −−preprocess=+make,thedependencyinformationwillbegeneratedinadditiontothenormaloutputfile. Bydefault,theinformationiswrittentoafilewithextension.d(oneforeveryinputfile).Whenyouspecifyafilename,all dependencieswillbecombinedinthespecifiedfile.

Example ccnios−−dep−file=test.dep−ttest.c

Thecompilercompilesthefiletest.c,whichresultsintheoutputfiletest.src,andgeneratesdependencylinesinthefile test.dep.

Relatedinformation

Controlprogramoption−−preprocess=+make(Generatedependenciesformake)

5−243 NiosIIEmbeddedToolsReference

ControlProgram:−−diag

Commandlinesyntax −−diag=[format:]{all|nr,...]

Description

Withthisoptionyoucanaskforanextendeddescriptionoferrormessagesintheformatyouchoose.Theoutputisdirectedto stdout(normallyyourscreen)andintheformatyouspecify.Youcanspecifythefollowingformats:html,rtfortext(default). Tocreateafilewiththedescriptions,youmustredirecttheoutput. Withthesuboptionall,thedescriptionsofallerrormessagesaregiven.Ifyouwantthedescriptionofoneormoreselectederror messages,youcanspecifytheerrormessagenumbers,separatedbycommas. Withthisoptionthecontrolprogramdoesnotprocessanyfiles.

Example Todisplayanexplanationofmessagenumber103,enter: ccnios−−diag=103

Thisresultsinmessage103withexplanation. TowriteanexplanationofallerrorsandwarningsinHTMLformattofileccerrors.html,enter: ccnios−−diag=html:all>ccerrors.html

Relatedinformation

5−244 ToolOptions−ControlProgram

ControlProgram:−−dry−run(−n)

Commandlinesyntax −−dry−run −n

Description

Withthisoptionyouputthecontrolprogramverbosemode.Thecontrolprogramprintstheinvocationsofthetoolsitwoulduse toprocessthefileswithoutactuallyperformingthesteps.

Relatedinformation

ControlProgramoption−−verbose(−v)(Verboseoutput)

5−245 NiosIIEmbeddedToolsReference

ControlProgram:−−endianness

Commandlinesyntax −−endianness=endianness −B −−big−endian Youcanspecifythefollowingendianness: big (b) Bigendian little (l) Littleendian(default)

Description

Bydefault,thecompilergeneratescodeforalittle−endiantarget(leastsignificantbyteofawordatlowestbyteaddress).With −−endianness=bigthecompilergeneratescodeforabig−endiantarget(mostsignificantbyteofawordatlowestbyte address).−Bisanaliasforoption−−endianness=big.

Relatedinformation

5−246 ToolOptions−ControlProgram

ControlProgram:−−error−file

Commandlinesyntax −−error−file

Description

Withthisoptionthecontrolprogramtellsthecompiler,assemblerandlinkertoredirecterrormessagestoafile. Theerrorfilewillbenamedaftertheinputfilewithextension.err(forcompiler)or.ers(forassembler).Forthelinker,the errorfileislknios.elk.

Example Towriteerrorstoerrorfilesinsteadofstderr,enter: ccnios−−error−file−ttest.c

Relatedinformation

ControlProgramoption−−warnings−as−errors(Treatwarningsaserrors)

5−247 NiosIIEmbeddedToolsReference

ControlProgram:−−exceptions

Commandlinesyntax −−exceptions

Description

WiththisoptionyouenablesupportforexceptionhandlingintheC++compiler.

Relatedinformation

5−248 ToolOptions−ControlProgram

ControlProgram:−−force−c

Commandlinesyntax −−force−c

Description

Withthisoptionyoutellthecontrolprogramtotreatall.ccfilesasCfilesinsteadofC++files.Thismeansthatthecontrol programdoesnotcalltheC++compilerandforcesthelinkertolinkClibraries.

Relatedinformation

Controlprogramoption−−force−c++(ForceC++compilationandlinking)

5−249 NiosIIEmbeddedToolsReference

ControlProgram:−−force−c++

Commandlinesyntax −−force−c++

Description

Withthisoptionyoutellthecontrolprogramtotreatall.cfilesasC++filesinsteadofCfiles.Thismeansthatthecontrol programcallstheC++compilerpriortotheCcompilerandforcesthelinkertolinkC++libraries.

Relatedinformation

Controlprogramoption−−force−c(TreatC++filesasCfiles)

5−250 ToolOptions−ControlProgram

ControlProgram:−−force−munch

Commandlinesyntax −−force−munch

Description

Withthisoptionyouforcethecontrolprogramtoactivatethemuncherinthepre−locatephase.

Relatedinformation

5−251 NiosIIEmbeddedToolsReference

ControlProgram:−−format

Commandlinesyntax −−format=format Youcanspecifythefollowingformats: IEEE IEEE−695 ELF ELF/DWARF IHEX IntelHex SREC MotorolaS−records

Description Withthisoptionyouspecifytheoutputformatfortheresulting(absolute)objectfile.ThedefaultoutputformatisELF/DWARF, whichcandirectlybeusedbythedebugger. IfyouchooseIHEXorSREC,youcanadditionallyspecifytheaddresssizeofthechosenformat(option−−address−size).

Example TogenerateanMotorolaS−recordoutputfile: ccnios−−format=SRECtest1.ctest2.c−−output=test.sre

Relatedinformation

Controlprogramoption−−address−size(SetaddresssizeforlinkerIHEX/SRECfiles) Linkeroption−−output(Specifyanoutputobjectfile) Linkeroption−−chip−output(Generatehexfileforeachchip)

5−252 ToolOptions−ControlProgram

ControlProgram:−−global−type−checking

Commandlinesyntax −−global−type−checking

Description

TheCcompileralreadyperformstypecheckingwithineachmodule.Usethisoptionwhenyouwantthelinkertoperformtype checkingbetweenmodules.

Relatedinformation

Ccompileroption−−global−type−checking(Globaltypechecking)

5−253 NiosIIEmbeddedToolsReference

ControlProgram:−−help(−?)

Commandlinesyntax −−help[=options] −?

Description

Displaysanoverviewofallcommandlineoptions.Whenyouspecifytheargumentoptionsyoucanlistdetailedoption descriptions.

Example Thefollowinginvocationsalldisplayalistoftheavailablecommandlineoptions: ccnios−? ccnios−−help ccnios

Toseeadetaileddescriptionoftheavailableoptions,enter: ccnios−−help=options

5−254 ToolOptions−ControlProgram

ControlProgram:−−include−directory(−I)

Commandlinesyntax −−include−directory=path,... −Ipath,...

Description

Withthisoptionyoucanspecifythepathwhereyourincludefilesarelocated.Arelativepathwillberelativetothecurrent directory.

Example SupposethattheCsourcefiletest.ccontainsthefollowinglines: #include #include"myinc.h"

Youcancallthecontrolprogramasfollows: ccnios−−include−directory=myincludetest.c

Firstthecompilerlooksforthefilestdio.hinthedirectorymyincluderelativetothecurrentdirectory.Ifitwasnotfound,the compilersearchesintheenvironmentvariableandtheninthedefaultincludedirectory. Thecompilernowlooksforthefilemyinc.h,inthedirectorywheretest.cislocated.Ifthefileisnottherethecompiler searchesinthedirectorymyinclude.Ifitwasstillnotfound,thecompilersearchesintheenvironmentvariableandtheninthe defaultincludedirectory.

Relatedinformation

Ccompileroption−−include−directory(Adddirectorytoincludefilesearchpath) Ccompileroption−−include−file(Includefileatthestartofacompilation) Section2.4,HowtheCompilerSearchesIncludeFiles,inchapterUsingtheCompileroftheuser’smanual.

5−255 NiosIIEmbeddedToolsReference

ControlProgram:−−instantiate

Commandlinesyntax −−instantiate=mode Youcanspecifythefollowingmodes: used(default) all local

Description Controlinstantiationofexternaltemplateentities.Externaltemplateentitiesareexternal(thatis,non−inlineandnon−static) templatefunctionsandtemplatestaticdatamembers.Theinstantiationmodedeterminesthetemplateentitiesforwhichcode shouldbegeneratedbasedonthetemplatedefinition.Normally,whenafileiscompiled,templateentitiesareinstantiated wherevertheyareused(thelinkerwilldiscardduplicatedefinitions).Theoverallinstantiationmodecan,however,bechanged withthisoption.Youcanspecifythefollowingmodes: used Instantiatethosetemplateentitiesthatwereusedinthecompilation.Thiswillincludeallstaticdatamembersfor whichtherearetemplatedefinitions.Thisisthedefault. all Instantiatealltemplateentitiesdeclaredorreferencedinthecompilationunit.Foreachfullyinstantiatedtemplate class,allofitsmemberfunctionsandstaticdatamemberswillbeinstantiatedwhetherornottheywereused. Non−membertemplatefunctionswillbeinstantiatedeveniftheonlyreferencewasadeclaration. local Similarto−−instantiate=usedexceptthatthefunctionsaregiveninternallinkage.Thisisintendedtoprovidea verysimplemechanismforthosegettingstartedwithtemplates.Thecompilerwillinstantiatethefunctionsthatare usedineachcompilationunitaslocalfunctions,andtheprogramwilllinkandruncorrectly(barringproblemsdue tomultiplecopiesoflocalstaticvariables).However,onemayendupwithmanycopiesoftheinstantiated functions,sothisisnotsuitableforproductionuse. Youcannotuse−−instantiate=localinconjunctionwithautomatictemplateinstantiation.

Relatedinformation

Controlprogramoption−−no−auto−instantiation(DisableautomaticC++instantiation) Section2.6,TemplateInstantiationinchapterC++Language.

5−256 ToolOptions−ControlProgram

ControlProgram:−−io−streams

Commandlinesyntax −−io−streams

Description

AsI/Ostreamsrequiresubstantialresourcestheyaredisabledbydefault.UsethisoptiontoenableI/Ostreamssupportinthe C++library. Thisoptionalsoenablesexceptionhandling.

Relatedinformation

5−257 NiosIIEmbeddedToolsReference

ControlProgram:−−iso

Commandlinesyntax −−iso={90|99}

Description

WiththisoptionyouspecifytothecontrolprogramagainstwhichISOstandarditshouldcheckyourCsource.C90isalso referredtoasthe"ANSICstandard".C99referstothenewerISO/IEC9899:1999(E)standardandisthedefault.

IndependantofthechosenISOstandard,thecontrolprogramalwayslinkslibrarieswithC99support.

Example Tocompilethefiletest.cconformtheISOC90standard: ccnios−−iso=90test.c

Relatedinformation

Ccompileroption−−iso(ISOCstandard)

5−258 ToolOptions−ControlProgram

ControlProgram:−−keep−output−files(−k)

Commandlinesyntax −−keep−output−files −k

Description

Ifanerroroccursduringthecompilation,assemblingorlinkingprocess,theresultingoutputfilemaybeincompleteorincorrect. Withthisoptionyoukeepthegeneratedoutputfileswhenanerroroccurs. Bydefaultthecontrolprogramremovesgeneratedoutputfileswhenanerroroccurs.Thisisusefulwhenyouusethemake utility.Iftheerroneousfilesarenotremoved,themakeutilitymayprocesscorruptfilesonasubsequentinvocation. Usethisoptionwhenyoustillwanttousethegeneratedfiles.Forexamplewhenyouknowthataparticularerrordoesnotresult inacorruptfile,orwhenyouwanttoinspecttheoutputfile,orsendittoAltiumsupport.

Relatedinformation

5−259 NiosIIEmbeddedToolsReference

ControlProgram:−−keep−temporary−files(−t)

MenuEntry 1. FromtheProjectmenu,selectProjectOptions... TheProjectOptionsdialogboxappears. 2. SelectBuildOptions. 3. EnabletheoptionKeeptemporaryfilesthataregeneratedduringacompile.

Commandlinesyntax −−keep−temporary−files −t

Description Bydefault,thecontrolprogramremovesintermediatefileslikethe.srcfile(resultofthecompilerphase)andthe.objfile (resultoftheassemblerphase). Withthisoptionyoutellthecontrolprogramtokeeptemporaryfilesitgeneratesduringthecreationoftheabsoluteobjectfile.

Relatedinformation

5−260 ToolOptions−ControlProgram

ControlProgram:−−library(−l)

Commandlinesyntax −−library=name −lname

Description

Withthisoptionyoutellthelinkerviathecontrolprogramtousesystemlibraryname.lib,wherenameisastring.The linkerfirstsearchesforsystemlibrariesinanydirectoriesspecifiedwith−−library−directory,theninthedirectoriesspecified withtheenvironmentvariableLIBNIOSII,unlessyouusedtheoption−−ignore−default−library−path.

Example Tosearchinthesystemlibrarycnios.lib(Clibrary): ccniostest.objmylib.lib−−library=cnios

Thelinkerlinksthefiletest.objandfirstlooksinmylib.lib(inthecurrentdirectoryonly),theninthesystemlibrary cnios.libtoresolveunresolvedsymbols.

Relatedinformation

Linkeroption−−library−directory(Additionalsearchpathforsystemlibraries) Section6.4,LinkingwithLibraries,inchapterUsingtheLinkeroftheuser’smanual.

5−261 NiosIIEmbeddedToolsReference

ControlProgram:−−library−directory(−L)/−−ignore−default−library−path

Commandlinesyntax −−library−directory=dir −Ldir −−ignore−default−library−path −L

Description Withthisoptionyoucanspecifythepath(s)whereyoursystemlibraries,specifiedwiththe−−libraryoption,arelocated.Ifyou wanttospecifymultiplepaths,usetheoption−−library−directoryforeachseparatepath. Bydefaultpaththisis$(PRODDIR)\cnios\libdirectory. Ifyouspecifyonly−L(withoutapathname)orthelongoption−−ignore−default−library−path,thelinkerwillnotsearchthe defaultpathandalsonotinthepathsspecifiedintheenvironmentvariableLIBNIOSII.So,thelinkerignoressteps2and3as listedbelow. Thepriorityorderinwhichthelinkersearchesforsystemlibrariesspecifiedwiththe−−libraryoptionis: 1. Thepaththatisspecifiedwiththe−−library−directoryoption. 2. ThepaththatisspecifiedintheenvironmentvariableLIBNIOSII. 3. Thedefaultdirectory$(PRODDIR)\cnios\lib(oraprocessorspecificsub−directory).

Example Supposeyoucallthecontrolprogramasfollows: ccniostest.c−−library−directory=c:\mylibs−−library=cnios

Firstthelinkerlooksinthedirectoryc:\mylibsforlibrarycnios.lib(thisoption). Ifitdoesnotfindtherequestedlibraries,itlooksinthedirectorythatissetwiththeenvironmentvariableLIBNIOSII. Thenthelinkerlooksinthedefaultdirectory$(PRODDIR)\cnios\libforlibraries.

Relatedinformation

Linkeroption−−library(Linksystemlibrary)

5−262 ToolOptions−ControlProgram

ControlProgram:−−list−files

Commandlinesyntax −−list−files[=name]

Description

Withthisoptionyoutelltheassemblerviathecontrolprogrammatogeneratealistfileforeachspecifiedinputfile.Alistfile showsthegeneratedobjectcodeandtherelativeaddresses.Notethattheassemblergeneratesarelocatableobjectfilewith relativeaddresses. Withnameyoucanspecifyanameforthelistfile.Thisisonlypossibleifyouspecifyonlyoneinputfiletothecontrol program.Ifyoudonotspecifyname,oryouspecifymorethanoneinputfiles,thecontrolprogramnamesthegeneratedlist file(s)afterthespecifiedinputfile(s)withextension.lst.

Example Thisexamplegeneratesthelistfiles1.lstand2.lstfor1.cand2.c.Ifinthisexamplealsoanamehadbeenspecified,it wouldbeignoredbecausetwoinputfilesarespecified. ccnios1.c2.c−−list−files

Relatedinformation

Assembleroption−−list−file(Generatelistfile) Assembleroption−−list−format(Listfileformattingoptions)

5−263 NiosIIEmbeddedToolsReference

ControlProgram:−−lsl−file(−d)

Commandlinesyntax −−lsl−file=file,... −dfile,...

Description

Alinkerscriptfilecontainsvitalinformationaboutthecoreforthelocatingphaseofthelinker.AlinkerscriptfileiscodedinLSL andcontainsthefollowingtypesofinformation: • thearchitectureandderivativedefinitiondescribethecore’shardwarearchitectureanditsinternalmemory. • theboardspecificationdescribesthephysicalmemoryavailableinthesystem. • thesectionlayoutdefinitiondescribeshowtolocatesectionsinmemory. Withthisoptionyouspecifyalinkerscriptfileviathecontrolprogramtothelinker.Ifyoudonotspecifythisoption,thelinker doesnotuseascriptfile.Youcanspecifytheexistingfilenios.lslorthenameofamanuallywrittenlinkerscriptfile.Youcan usethisoptionmultipletimes.ThelinkerprocessestheLSLfilesintheorderinwhichtheyappearonthecommandline.

Relatedinformation

Section6.9,ControllingtheLinkerwithaScript,inchapterUsingtheLinkeroftheuser’smanual.

5−264 ToolOptions−ControlProgram

ControlProgram:−−make−target

Commandlinesyntax −−make−target=name

Description

Withthisoptionyoucanoverrulethedefaulttargetnameinthemakedependenciesgeneratedbytheoptions −−preprocess=+make(−Em)and−−dep−file.Thedefaulttargetnameisthebasenameoftheinputfile,withextension.obj.

Example ccnios−−preprocess=+make−−make−target=../mytarget.objtest.c

Thecompilergeneratesdependencylineswiththedefaulttargetname../mytarget.objinsteadoftest.obj.

Relatedinformation

Controlprogramoption−−preprocess=+make(Generatedependenciesformake) Controlprogramoption−−dep−file(Generatedependenciesinafile)

5−265 NiosIIEmbeddedToolsReference

ControlProgram:−−mil−link/−−mil−split

Commandlinesyntax −−mil−link −−mil−split

Description

Withoption−−mil−linktheCcompilerlinkstheoptimizedintermediaterepresentation(MIL)ofallinputfilesandMILlibraries specifiedonthecommandlineinthecompiler.Theresultisonesinglemodulethatisoptimizedanothertime. Option−−mil−splitdoesthesameasoption−−mil−link,butinaddition,theresultingMILrepresentationiswrittentoafilewith thesuffix.milandtheCcompileralsosplitstheMILrepresentationandwritesittoseparatefileswithsuffix.ms.Onefileis writtenforeachinputfileorMILlibraryspecifiedonthecommandline.The.msfilesareonlyupdatedonachange. Withoption−−mil−splityoucanperformapplication−wideoptimizationsduringthefrontendphasebyspecifyingallmodulesat once,andstillinvokethebackendphaseonemoduleatatimetoreducethetotalcompilationtime.

Relatedinformation

Ccompileroption−−mil/−−mil−split

5−266 ToolOptions−ControlProgram

ControlProgram:−−no−auto−instantiation

Commandlinesyntax −−no−auto−instantiation Default:theC++compilerautomaticallyinstantiatestemplates.

Description

Withthisoptionautomaticinstantiationoftemplatesisdisabled.

Relatedinformation

Controlprogramoption−−instantiate(Setinstantiationmode) Section2.6,TemplateInstantiationinchapterC++Language.

5−267 NiosIIEmbeddedToolsReference

ControlProgram:−−no−default−libraries

Commandlinesyntax −−no−default−libraries

Description

BydefaultthecontrolprogramspecifiesthestandardClibraries(C99)andrun−timelibrarytothelinker.Withthisoptionyoutell thecontrolprogramnottospecifythestandardClibrariesandrun−timelibrarytothelinker. Inthiscaseyoumustspecifythelibrariesyouwanttolinktothelinkerwiththeoption−llibrary_name.Thecontrolprogram recognizestheoption−lasanoptionforthelinkerandpassesitassuch.

Example ccnios−−no−default−librariestest.c

Thecontrolprogramdoesnotspecifyanylibrariestothelinker.Innormalcasesthiswouldresultinunresovedexternals. Tospecifyyourownlibraries(libmy.a)andavoidunresolvedexternals: ccnios−−no−default−libraries−lmytest.c

Relatedinformation

Linkeroption−−library(−l)(Addlibrary)

5−268 ToolOptions−ControlProgram

ControlProgram:−−no−double(−F)

Commandlinesyntax −−no−double −F

Description

Withthisoptionyoutellthecompilertotreatvariablesofthetypedoubleasfloat.Becausethefloattypetakeslessspace, executionspeedincreasesandcodesizedecreases,bothatthecostoflessprecision.

Relatedinformation

5−269 NiosIIEmbeddedToolsReference

ControlProgram:−−no−map−file

Commandlinesyntax −−no−map−file

Description

Bydefaultthecontrolprogramtellsthelinkertogeneratealinkermapfile. Alinkermapfileisatextfilethatshowshowthelinkerhasmappedthesectionsandsymbolsfromthevariousobjectfiles (.obj)tothelinkedobjectfile.Alocatepartshowstheabsolutepositionofeachsection.Externalsymbolsarelistedperspace withtheirabsoluteaddress,bothsortedonsymbolandsortedonaddress. Withthisoptionyoupreventthegenerationofamapfile.

Relatedinformation

5−270 ToolOptions−ControlProgram

ControlProgram:−−no−preprocessing−only

Commandlinesyntax −−no−preprocessing−only

Description

Onthecommandline,thecontrolprogramstopsafterpreprocessing.IfyoualsowanttocompiletheCsourceyoucanspecify theoption−−no−preprocessing−only.Inthiscasethecontrolprogramcallsthecompilertwice,oncewithoption −−preprocessandonceforaregularcompilation.

Relatedinformation

Controlprogramoption−−preprocess/−E

5−271 NiosIIEmbeddedToolsReference

ControlProgram:−−no−warnings(−w)

Commandlinesyntax −−no−warnings[=number[−number],...] −w[number[−number],...]

Description

WiththisoptionyoucansuppressallwarningmessagesorspecificCcompilerwarningmessages: • Ifyoudonotspecifythisoption,allwarningsarereported. • Ifyouspecifythisoptionbutwithoutnumbers,allwarningsaresuppressed. • Ifyouspecifythisoptionwithanumberorarange,onlythespecifiedCcompilerwarningissuppressed. Youcanspecifytheoption−−no−warnings=numbermultipletimes. Relatedinformation

5−272 ToolOptions−ControlProgram

ControlProgram:−−option−file(−f)

Commandlinesyntax −−option−file=file −ffile

Description

Insteadoftypingalloptionsonthecommandline,youcancreateanoptionfilewhichcontainsalloptionsandflagsyouwantto specify.Withthisoptionyouspecifytheoptionfiletothecontrolprogram. Useanoptionfilewhenthecommandlinewouldexceedthelimitsoftheoperatingsystem,orjusttostoreoptionsandsave typing. Youcanspecifytheoption−−option−filemultipletimes. Formatofanoptionfile • Multipleargumentsononelineintheoptionfileareallowed. • Toincludewhitespaceinanargument,surroundtheargumentwithsingleordoublequotes. • Ifyouwanttousesinglequotesaspartoftheargument,surroundtheargumentbydoublequotesandviseversa: "Thishasasinglequote’embedded" ’Thishasadoublequote"embedded’ ’Thishasadoublequote"andasinglequote’"’embedded" • Whenatextlinereachesitslengthlimit,usea’tocontinuetheline.Whitespacebetweenquotesispreserved. "Thisisacontinuation\ line"

−>"Thisisacontinuationline" • Itispossibletonestcommandlinefilesupto25levels. Example Supposethefilemyoptionscontainsthefollowinglines: −DDEMO=1 test.c

Specifytheoptionfiletothecontrolprogram: ccnios−−option−file=myoptions

Thisisequivalenttothefollowingcommandline: ccnios−DDEMO=1test.c

Relatedinformation

5−273 NiosIIEmbeddedToolsReference

ControlProgram:−−output(−o)

Commandlinesyntax −−output=file −ofile

Description

Default,thecontrolprogramgeneratesafilewiththesamebasenameasthefirstspecifiedinputfile.Withthisoptionyouspecify anothernamefortheresultingabsoluteobjectfile.

Example ccniostest.cprog.c

ThecontrolprogramgeneratesanELF/DWARFobjectfile(default)withthenametest.abs. Togeneratethefileresult.abs: ccnios−−output=result.abstest.cprog.c

Relatedinformation

5−274 ToolOptions−ControlProgram

ControlProgram:−−pass(−W)

Commandlinesyntax −−pass−assembler=option (−Waoption) Passoptiondirectlytotheassembler −−pass−c=option (−Wcoption) PassoptiondirectlytotheCcompiler −−pass−c++=option (−Wcpoption) PassoptiondirectlytotheC++compiler −−pass−linker=option (−Wloption) Passoptiondirectlytothelinker

Description Withthisoptionyoutellthecontrolprogramtocallatoolwiththespecifiedoption.Thecontrolprogramdoesnotuseorinterpret theoptionitself,butspecifiesitdirectlytothetoolwhichitcalls.

Relatedinformation

5−275 NiosIIEmbeddedToolsReference

ControlProgram:−−preprocess(−E)

Commandlinesyntax −−preprocess[=flags] −E[flags] Youcansetthefollowingflags(whenyouspecify−Ewithoutflags,thedefaultis−ECILMP): +/−comments (c/C) KeepcommentsfromtheCsourceinthepreprocessedoutput +/−includes (i/I) Generatealistofincludedsourcefiles +/−list (l/L) Generatealistofmacrodefinitions +/−make (m/M) Generatedependencylinesthatcanbeusedforthemakefile +/−noline (p/P) Strip#linesourcepositioninfo(linesstartingwith#line)

Description WiththisoptionyoutellthecontrolprogramtopreprocesstheCsource. TheCcompilersendsthepreprocessedoutputtothefilename.pre(wherenameisthenameoftheCsourcefilebeing compiled).AltiumDesigneralsocompilestheCsource. Onthecommandline,thecontrolprogramstopsafterpreprocessing.IfyoualsowanttocompiletheCsourceyoucanspecify theoption−−no−preprocessing−only.Inthiscasethecontrolprogramcallsthecompilertwice,oncewithoption −−preprocessandonceforaregularcompilation. With−−preprocess=+commentsyoutellthepreprocessortokeepthecommentsfromtheC++sourcefileinthepreprocessed output. With−−preprocess=+includesthecompilerwillgeneratealistofallincludedsourcefiles.Thepreprocessoroutputis discarded. With−−preprocess=+listthecompilerwillgeneratealistofallmacrodefinitions.Thepreprocessoroutputisdiscarded. With−−preprocess=+makethecompilerwillgeneratedependencylinesthatcanbeusedinaMakefile.Theinformationis writtentoafilewithextension.d.Thepreprocessoroutputisdiscarded.Thedefaulttargetnameisthebasenameoftheinput file,withtheextension.obj.Withtheoption−−make−targetyoucanspecifyatargetnamewhichoverrulesthedefaulttarget name. With−−preprocess=+nolineyoutellthepreprocessortostripthe#linesourcepositioninformation(linesstartingwith#line). Theselinesarenormallyprocessedbytheassemblerandnotneededinthepreprocessedoutput.Whenyouleavetheselines out,theoutputiseasiertoread.

Example ccnios−−preprocess=+comments,−make,−noline−−no−preprocessing−onlytest.c

Thecompilerpreprocessesthefiletest.candsendstheoutputtothefiletest.pre.Commentsareincludedbutno dependenciesaregeneratedandthelinesourcepositioninformationisnotstrippedfromtheoutputfile.Next,thecontrol programcallsthecompiler,assemblerandlinkertocreatethefinalobjectfiletest.abs.

Relatedinformation

Controlprogramoption−−no−preprocessing−only Controlprogramoption−−make−target(Specifytargetnamefor−Emoutput) Controlprogramoption−−dep−file(Generatedependenciesinafile)

5−276 ToolOptions−ControlProgram

ControlProgram:−−profile(−p)

Commandlinesyntax −−profile[=flags] −p[flags] Usethefollowingoptionforapredefinedsetofflags: −−profile=g (−pg) profilingwithcallgraphandfunctiontimers Aliasfor:−pBcFt Youcansetthefollowingflags(whenyouspecify−pwithoutflags,thedefaultis−pBCfST): +/−block (b/B) blockcounters +/−callgraph (c/C) callgraph +/−function (f/F) functioncounters +/−static (s/S) staticprofilegeneration +/−time (t/T) functiontimers

Description Profilingistheprocessofcollectingstatisticaldataaboutarunningapplication.Withthesedatayoucananalyzewhichfunctions arecalled,howoftentheyarecalledandwhattheirexecutiontimeis. Severalmethodsofprofilingexist.Onemethodiscodeinstrumentationwhichaddscodetoyourapplicationthattakescareof theprofilingprocesswhentheapplicationisexecuted.

ForanextensivedescriptionofprofilingrefertoChapter4,Profilingintheuser’smanual. Withthisoption,thecompileraddstheextracodetoyourapplicationthattakescareoftheprofilingprocess.Youcanobtainthe followingprofilingdata(seeflagsabove): Blockcounters(notincombinationwithCallgraphorTime) Thiswillinstrumentthecodetoperformbasicblockcounting.Astheprogramruns,itcountsthenumberofexecutionsof eachbranchinanifstatement,eachiterationofaforloop,andsoon.NotethatthoughyoucancombineBlockcounters withFunctioncounters,thishasnoeffectbecauseFunctioncountersisonlyasubsetofBlockcounters. Callgraph(notincombinationwithBlockcounters) Thiswillinstrumentthecodetoreconstructtherun−timecallgraph.Astheprogramrunsitassociatesthecallerwiththe gatheredprofilingdata. Functioncounters Thiswillinstrumentthecodetoperformfunctioncallcounting.ThisisasubsetofthebasicBlockcounters. Time(notincombinationwithBlockcounters) Thiswillinstrumentthecodetomeasurethetimespentinafunction.Thisincludesthetimespentinallsubfunctions (callees).

Notethatthemoredetailledinformationyourequest,thelargertheoverheadintermsofexecutiontime,codesizeand heapspaceneeded.TheoptionGenerateDebuginformation(−gor−−debug)doesnotaffectprofiling,executiontime orcodesize.

Thecontrolprogramautomaticallyspecifiesthecorrespondingprofilinglibrariestothelinker.

Example

Togenerateblockcountinformationforthemoduletest.cduringexecution,compileasfollows: ccnios−−profile=+blocktest.c

Inthiscasethelibrarypbniosmd.libislinked.

5−277 NiosIIEmbeddedToolsReference

Relatedinformation

Chapter4,Profilingintheuser’smanual.

5−278 ToolOptions−ControlProgram

ControlProgram:−−show−c++−warnings

Commandlinesyntax −−show−c++−warnings

Description

TheC++compilermaygenerateacompiledC++file(.ic)thatcauseswarningsduringcompilationorassembling.Withthis optionyoutellthecontrolprogramtoshowthesewarnings.Bydefault,warningsinC++generatedfilesaresuppressed.

Relatedinformation

5−279 NiosIIEmbeddedToolsReference

ControlProgram:−−static

Commandlinesyntax −−static

Description

Thisoptionisdirectlypassedtothecompiler. Withthisoption,thecompilertreatsexternaldefinitionsatfilescope(exceptformain)asiftheyweredeclaredstatic.Asa result,unusedfunctionswillbeeliminated,andthealiascheckingalgorithmassumesthatobjectswithstaticstoragecannotbe referencedfromfunctionsoutsidethecurrentmodule. Thisoptiononlymakessensewhenyouspecifyallmodulesofanapplicationonthecommandline.

Example ccnios−−staticmodule1.cmodule2.cmodule3.c

Relatedinformation

5−280 ToolOptions−ControlProgram

ControlProgram:−−undefine(−U)

Commandlinesyntax −−undefine=macro_name −Umacro_name

Description

Withthisoptionyoucanundefineanearlierdefinedmacroaswith#undef. Thisoptionisforexampleusefultoundefinepredefinedmacros.However,youcannotundefinepredefinedISOCstandard macros. Thecontrolprogrampassestheoption−−undefine(−U)tothecompiler.

Example Toundefinethepredefinedmacro__TASKING__: ccnios−−undefine=__TASKING__test.c

Relatedinformation

ControlPogramoption−−define(Definepreprocessormacro)

5−281 NiosIIEmbeddedToolsReference

ControlProgram:−−verbose(−v)

Commandlinesyntax −−verbose −v

Description

Withthisoptionyouputthecontrolprograminverbosemode.Withtheoption−vthecontrolprogramperformsittaskswhileit printsthestepsitperformstostdout.

Relatedinformation

ControlProgramoption−n(−−dry−run)(Verboseoutputandsuppressexecution)

5−282 ToolOptions−ControlProgram

ControlProgram:−−version(−V)

Commandlinesyntax −−version −V

Description

Displayversioninformation.Thecontrolprogramignoresallotheroptionsorinputfiles.

Relatedinformation

5−283 NiosIIEmbeddedToolsReference

ControlProgram:−−warnings−as−errors

Commandlinesyntax −−warnings−as−errors[=number[−number],...]

Description

Ifoneofthetoolsencountersanerror,itstopsprocessingthefile(s).Withthisoptionyoutellthetoolstotreatwarningsaserrors ortreatspecificcontrolprogramwarningmessagesaserrors: • Ifyouspecifythisoptionbutwithoutnumbers,allwarningsaretreatedaserrors. • Ifyouspecifythisoptionwithanumber,onlythespecifiedcontrolprogramwarningistreatedasanerror. Youcanspecifytheoption−−warnings−as−errors=numbermultipletimes. Useoneofthe−−pass−tooloptionstopassthisoptiondirectlytoatoolwhenaspecificwarningforthattoolmustbetreated asanerror.Forexample,use−−pass−c=−−warnings−as−errors=numbertotreataspecificCcompilerwarningasanerror.

Relatedinformation

Controlprogramoption−−no−warnings(Suppressallwarnings) Controlprogramoption−−pass(Passoptiontotool)

5−284 ToolOptions−MakeUtility

5.6 MakeUtilityOptions

WhenyoubuildaprojectinAltiumDesigner,AltiumDesignergeneratesamakefileandusesthemakeutilitytmktobuildall yourfiles.However,youcanalsousethemakeutilitydirectlyfromthecommandlinetobuildyourproject. Theinvocationsyntaxis: tmk[option...][target...][macro=def]

Thissectiondescribesalloptionsforthemakeutility.Themakeutilityisacommandlinetoolsotherearenoequivalentoptions inAltiumDesigner.

5−285 NiosIIEmbeddedToolsReference

DefiningMacros

Commandlinesyntax macro=definition

Description

Withthisargumentyoucandefineamacroandspecifyittothemakeutility. Amacrodefinitionremainsinexistenceduringtheexecutionofthemakefile,evenwhenthemakefilerecursivelycallsthemake utilityagain.Intherecursivecall,themacroactsasanenvironmentvariable.Thismeansthatitisoverruledbydefinitionsinthe recursivecall.Usetheoption−etopreventthis.

Youcanspecifyasmanymacrosasyoulike.Ifthecommandlineexceedsthelimitoftheoperatingsystem,youcandefinethe macrosinanoptionfilewhichyouthenmustspecifytothemakeutilitywiththeoption−mfile.

Definingmacrosonthecommandlineis,forexample,usefulincombinationwithconditionalprocessingasshowninthe examplebelow.

Example Considerthefollowingmakefilewithconditionalrulestobuildademoprogramandarealprogram: ifdefDEMO#thevalueofDEMOisofnoimportance real.abs:real.objmain.obj lkniosdemo.objmain.obj−dnios.lsl−lcnios−lfpnios else real.abs:real.objmain.obj lkniosreal.objmain.obj−dnios.lsl−lcnios−lfpnios endif

YoucannowuseamacrodefinitiontosettheDEMOflag: tmkreal.absDEMO=1

Inbothcasestheabsoluteobjectfilereal.absiscreatedbutdependingontheDEMOflagitislinkedwithdemo.objorwith real.obj.

Relatedinformation

Makeutilityoption−e(Environmentvariablesoverridemacrodefinitions) Makeutilityoption−m(Nameofinvocationfile)

5−286 ToolOptions−MakeUtility

MakeUtility:−?

Commandlinesyntax

−?

Description Displaysanoverviewofallcommandlineoptions.

Example Thefollowinginvocationdisplaysalistoftheavailablecommandlineoptions: tmk−?

Relatedinformation

5−287 NiosIIEmbeddedToolsReference

MakeUtility:−a

Commandlinesyntax

−a

Description Normallythemakeutilityrebuildsonlythosefilesthatareoutofdate.Withthisoptionyoutellthemakeutilitytorebuildallfiles, withoutcheckingwhethertheyareoutofdate.

Example tmk−a

Rebuildsallyourfiles,regardlessofwhethertheyareoutofdateornot.

Relatedinformation

5−288 ToolOptions−MakeUtility

MakeUtility:−c

Commandlinesyntax

−c

Description AltiumDesignerusesthisoptionforthegraphicalversionofthemakeutilitywhenyoucreatesub−projects.Inthiscasethe makeutilitycallsanotherinstanceofthemakeutilityforthesub−project.Withtheoption−c,themakeutilityrunsasachild processofthecurrentmake. Theoption−coverrulestheoption−err.

Example tmk−c

Themakeutilityrunsitscommandsasachildprocesses.

Relatedinformation

5−289 NiosIIEmbeddedToolsReference

MakeUtility:−D/−DD

Commandlinesyntax

−D −DD

Description

Withtheoption−Dthemakeutilityprintseverylineofthemakefiletostandardoutputasitisreadbytmk.

Withtheoption−DDnotonlythelinesofthemakefileareprintedbutalsothelinesofthetmk.mkfile(implicitrules).

Example tmk−D

Eachlineofthemakefilethatisreadbythemakeutilityisprintedtostandardoutput(usuallyyourscreen).

Relatedinformation

5−290 ToolOptions−MakeUtility

MakeUtility:−d/−dd

Commandlinesyntax

−d −dd

Description

Withtheoption−dthemakeutilityshowswhichfilesareoutofdateandthusneedtoberebuild.Theoption−ddgivesmore detailthantheoption−d.

Example tmk−d

Showswhichfilesareoutofdateandrebuildsthem.

Relatedinformation

5−291 NiosIIEmbeddedToolsReference

MakeUtility:−e

Commandlinesyntax

−e

Description Ifyouusemacrodefinitions,theymayoverrulethesettingsoftheenvironmentvariables.

Withtheoption−e,thesettingsoftheenvironmentvariablesareusedevenifmacrosdefineotherwise.

Example tmk−e

Themakeutilityusesthesettingsoftheenvironmentvariablesregardlessofmacrodefinitions.

Relatedinformation

5−292 ToolOptions−MakeUtility

MakeUtility:−err

Commandlinesyntax

−errfile

Description Withthisoptionthemakeutilityredirectserrormessagesandverbosemessagestoaspecifiedfile. Withtheoption−sthemakeutilityonlydisplayserrormessages.

Example tmk−errerror.txt

Themakeutilitywritesmessagestothefileerror.txt.

Relatedinformation

Makeutilityoption−s(Donotprintcommandsbeforeexecution)

5−293 NiosIIEmbeddedToolsReference

MakeUtility:−f

Commandlinesyntax

−fmy_makefile

Description Defaultthemakeutilityusesthefilemakefiletobuildyourfiles.

Withthisoptionyoutellthemakeutilitytousethespecifiedfileinsteadofthefilemakefile.Multiple−foptionsactasifallthe makefileswereconcatenatedinaleft−to−rightorder.

Example tmk−fmymake

Themakeutilityusesthefilemymaketobuildyourfiles.

Relatedinformation

5−294 ToolOptions−MakeUtility

MakeUtility:−G

Commandlinesyntax

−Gpath

Description Normallyyoumustcallthemakeutilitytmkfromthedirectorywhereyourmakefileandotherfilesarestored.

Withtheoption−Gyoucancallthemakeutilityfromwithinanotherdirectory.Thepathisthepathtothedirectorywhereyour makefileandotherfilesarestoredandcanbeabsoluteorrelativetoyourcurrentdirectory.

Example Supposeyourmakefileandotherfilesarestoredinthedirectory..\myfiles.Youcancallthemakeutility,forexample,as follows: tmk−G..\myfiles

Relatedinformation

5−295 NiosIIEmbeddedToolsReference

MakeUtility:−i

Commandlinesyntax

−i

Description Whenanerroroccursduringthemakeprocess,themakeutilityexitswithacertainexitcode.

Withtheoption−i,themakeutilityexitswithoutanerrorcode,evenwhenerrorsoccurred.

Example tmk−i

Themakeutilityexitswithoutanerrorcode,evenwhenanerroroccurs.

Relatedinformation

5−296 ToolOptions−MakeUtility

MakeUtility:−K

Commandlinesyntax

−K

Description Withthisoptionthemakeutilitykeepstemporaryfilesitcreatesduringthemakeprocess.Themakeutilitystorestemporaryfiles inthedirectorythatyouhavespecifiedwiththeenvironmentvariableTMPDIRorinthedefault’temp’directoryofyoursystem whentheTMPDIRenvironmentvariableisnotspecified.

Example tmk−K

Themakeutilitypreservesalltemporaryfiles.

Relatedinformation

5−297 NiosIIEmbeddedToolsReference

MakeUtility:−k

Commandlinesyntax

−k

Description Whenduringthemakeprocessthemakeutilityencountersanerror,itstopsrebuildingyourfiles.

Withtheoption−k,themakeutilityonlystopsbuildingthetargetthatproducedtheerror.Allothertargetsdefinedinthemakefile arebuilt.

Example tmk−k

Ifthemakeutilityencountersanerror,itstopsbuildingthecurrenttargetbutproceedswiththeothertargetsthataredefinedin themakefile.

Relatedinformation

Makeutilityoption−S(Undotheeffectof−k)

5−298 ToolOptions−MakeUtility

MakeUtility:−m

Commandlinesyntax

−mfile

Description Insteadoftypingalloptionsonthecommandline,youcancreateanoptionfilewhichcontainsalloptionsandflagsyouwantto specify.Withthisoptionyouspecifytheoptionfiletothemakeutility. Useanoptionfilewhenthecommandlinewouldexceedthelimitsoftheoperatingsystem,orjusttostoreoptionsandsave typing. Youcanspecifytheoption−mmultipletimes.

Formatofanoptionfile • Multipleargumentsononelineintheoptionfileareallowed. • Toincludewhitespaceinanargument,surroundtheargumentwithsingleordoublequotes. • Ifyouwanttousesinglequotesaspartoftheargument,surroundtheargumentbydoublequotesandviseversa: "Thishasasinglequote’embedded" ’Thishasadoublequote"embedded’ ’Thishasadoublequote"andasinglequote’"’embedded" • Whenatextlinereachesitslengthlimit,usea’\’tocontinuetheline.Whitespacebetweenquotesispreserved. "Thisisacontinuation\ line" −>"Thisisacontinuationline" • Itispossibletonestcommandlinefilesupto25levels. Example Supposethefilemyoptionscontainsthefollowinglines: −k −errerrors.txt test.abs

Specifytheoptionfiletothemakeutility: tmk−mmyoptions

Thisisequivalenttothefollowingcommandline: tmk−k−errerrors.txttest.abs

Relatedinformation

5−299 NiosIIEmbeddedToolsReference

MakeUtility:−n

Commandlinesyntax

−n

Description Withthisoptionyoutellthemakeutilitytoperformadryrun.Themakeutilityshowswhatitwoulddobutdoesnotactually performthesetasks. Thisoptionisforexampleusefultoquicklyinspectwhatwouldhappenifyoucallthemakeutility.

Example tmk−n

Themakeutilitydoesnotperformanytasksbutdisplayswhatitwoulddoifcalledwithouttheoption−n.

Relatedinformation

Makeutilityoption−s(Donotprintcommandsbeforeexecution)

5−300 ToolOptions−MakeUtility

MakeUtility:−p

Commandlinesyntax

−p

Description Normally,ifacommandinatargetruleinamakefilereturnsanerrororwhenthetargetconstructionisinterrupted,themake utilityremovesthattargetfile.Withthisoptionyoutellthemakeutilitytomakealltargetfilesprecious.Thismeansthat dependencyfilesareneverremoved.

Example tmk−p

Themakeutilityneverremovestargetdependencyfiles.

Relatedinformation

5−301 NiosIIEmbeddedToolsReference

MakeUtility:−q

Commandlinesyntax

−q

Description Withthisoptionthemakeutilitydoesnotperformanytasksbutonlyreturnsanexitcode.Azerostatusindicatesthatalltarget filesareuptodate,anon−zerostatusindicatesthatsomeoralltargetfilesareoutofdate.

Example tmk−q

Themakeutilityonlyreturnsanexitcodethatindicateswhetheralltargetfilesareuptodateornot.Itdoesnotrebuildanyfiles.

Relatedinformation

5−302 ToolOptions−MakeUtility

MakeUtility:−r

Commandlinesyntax

−r

Description Whenyoucallthemakeutility,itfirstreadstheimplicitrulesfromthefiletmk.mk,thenitreadsthemakefilewiththerulesto buildyourfiles.(Thefiletmk.mkislocatedinthe\etcdirectoryofthetoolset.) Withthisoptionyoutellthemakeutilitynottoreadtmk.mkandtorelyfullyonthemakerulesinthemakefile.

Example tmk−r

Themakeutilitydoesnotreadtheimplicitmakerulesintmk.mk.

Relatedinformation

5−303 NiosIIEmbeddedToolsReference

MakeUtility:−S

Commandlinesyntax

−S

Description

Withthisoptionyoucanceltheeffectoftheoption−k.Thisisonlynecessaryinarecursivemakewheretheoption−kmightbe inheritedfromthetop−levelmakeviaMAKEFLAGSorifyousettheoption−kintheenvironmentvariableMAKEFLAGS.

Example tmk−S

Theeffectoftheoption−kiscancelledsothemakeutilitystopswiththemakeprocessafteritencountersanerror.

Theoption−kinthisexamplemayhavebeensetwiththeenvironmentvariableMAKEFLAGSorinarecursivecalltotmkinthe makefile.

Relatedinformation

Makeutilityoption−k(Onerror,abandontheworkforthecurrenttargetonly)

5−304 ToolOptions−MakeUtility

MakeUtility:−s

Commandlinesyntax

−s

Description Withthisoptionyoutellthemakeutilitytoperformitstaskswithoutprintingthecommandsitexecutes.Errormessagesare normallyprinted.

Example tmk−s

Themakeutilityrebuildsyourfilesbutdoesnotprintthecommandsitexecutesduringthemakeprocess.

Relatedinformation

Makeutilityoption−n(Performadryrun)

5−305 NiosIIEmbeddedToolsReference

MakeUtility:−t

Commandlinesyntax

−t

Description Withthisoptionyoutellthemakeutilitytotouchthetargetfiles,bringingthemuptodate,ratherthanperformingtherulesto rebuildthem.

Example tmk−t

Themakeutilityupdatesout−of−datefilesbygivingthemanewdateandtimestamp.Thefilesarenotactuallyrebuild.

Relatedinformation

5−306 ToolOptions−MakeUtility

MakeUtility:−time

Commandlinesyntax

−time

Description Withthisoptionyoutellthemakeutilitytodisplaythecurrentdateandtimeonstandardoutput.

Example tmk−time

Themakeutilitydisplaysthecurrentdateandtimeandupdatesout−of−datefiles.

Relatedinformation

5−307 NiosIIEmbeddedToolsReference

MakeUtility:−V

Commandlinesyntax

−V

Description Displayversioninformation.Themakeutilityignoresallotheroptionsorinputfiles.

Example tmk−V

Themakeutilitydisplaystheversioninformationbutdoesnotperformanytasks.

Relatedinformation

5−308 ToolOptions−MakeUtility

MakeUtility:−W

Commandlinesyntax

−Wtarget

Description Withthisoptionthemakeutilityconsidersthespecifiedtargetfilealwaysasuptodateandwillnotrebuildit.

Example tmk−Wtest.abs

Themakeutilityrebuildsoutofdatetargetsinthemakefileexceptthefiletest.abswhichisconsiderednowasuptodate.

Relatedinformation

5−309 NiosIIEmbeddedToolsReference

MakeUtility:−x

Commandlinesyntax

−x

Description Withthisoptionthemakeutilityshowsextendederrormessages.Extendederrormessagesgivemoredetailedinformation abouttheexitstatusofthemakeutilityaftererrors.AltiumDesignerusesthisoptionforthegraphicalversionofmake.

Example tmk−x

Iferrorsoccur,themakeutilitygivesextendedinformation.

Relatedinformation

5−310 ToolOptions−Librarian

5.7 LibrarianOptions

Thelibrariantlbisatooltobuildlibraryfilesanditoffersthepossibilitytoreplace,extractandremovemodulesfromanexisting library. Youcanonlycallthelibrarianfromthecommandline.Theinvocationsyntaxis: tlbkey_option[sub_option...]library[object_file] Thissectiondescribesalloptionsforthemakeutility.Suboptionscanonlybeusedincombinationwithcertainkeyoptions. Keyoptionsandtheirsuboptionsaretherefordescribedtogether.Themiscellaneousoptionscanalwaysbeusedandarealso describedseparately. ThelibrarianisacommandlinetoolsotherearenoequivalentoptionsinAltiumDesigner.

Description Option Suboption Mainfunctions(keyoptions) Replaceoraddanobjectmodule −r −a−b−c−u−v Extractanobjectmodulefromthelibrary −x −o−v Deleteobjectmodulefromlibrary −d −v Moveobjectmoduletoanotherposition −m −a−b−v Printatableofcontentsofthelibrary −t −s0−s1 Printobjectmoduletostandardoutput −p Suboptions Appendormovenewmodulesafterexistingmodulename −aname Appendormovenewmodulesbeforeexistingmodulename −bname Createlibrarywithoutnotificationiflibrarydoesnotexist −c Preservelast−modifieddatefromthelibrary −o Printsymbolsinlibrarymodules −s{0|1} Replaceonlynewermodules −u Verbose −v Miscellaneous Displayoptions −? Displayversionheader −V Readoptionsfromfile −ffile Suppresswarningsaboveleveln −wn

Table5−1:Overviewoflibrarianoptionsandsuboptions

5−311 NiosIIEmbeddedToolsReference

Librarian:−?

Commandlinesyntax

−?

Description Displaysanoverviewofallcommandlineoptions.

Example Thefollowinginvocationsdisplayalistoftheavailablecommandlineoptions: tlb−? tlb

Relatedinformation

5−312 ToolOptions−Librarian

Librarian:−d

Commandlinesyntax −d[−v]

Description

Deletethespecifiedobjectmodulesfromalibrary.Withthesuboption−vthelibrarianshowswhichfilesareremoved.

−v Verbose:thelibrarianshowswhichfilesareremoved.

Example tlb−dmylib.libobj1.objobj2.obj

Thelibrariandeletesobj1.objandobj2.objfromthelibrarymylib.lib. tlb−d−vmylib.libobj1.objobj2.obj

Thelibrariandeletesobj1.objandobj2.objfromthelibrarymylib.libanddisplayswhichfilesareremoved.

Relatedinformation

5−313 NiosIIEmbeddedToolsReference

Librarian:−f

Commandlinesyntax −ffile

Description

Insteadoftypingalloptionsonthecommandline,youcancreateanoptionfilewhichcontainsalloptionsandflagsyouwantto specify.Withthisoptionyouspecifytheoptionfiletothelibrariantlb. Useanoptionfilewhenthecommandlinewouldexceedthelimitsoftheoperatingsystem,orjusttostoreoptionsandsave typing. Optionfilescanalsobegeneratedonthefly,forexamplebythemakeutility.Youcanspecifytheoption−fmultipletimes. Formatofanoptionfile • Multipleargumentsononelineintheoptionfileareallowed. • Toincludewhitespaceinanargument,surroundtheargumentwithsingleordoublequotes. • Ifyouwanttousesinglequotesaspartoftheargument,surroundtheargumentbydoublequotesandviseversa: "Thishasasinglequote’embedded" ’Thishasadoublequote"embedded’ ’Thishasadoublequote"andasinglequote’"’embedded" • Whenatextlinereachesitslengthlimit,usea’tocontinuetheline.Whitespacebetweenquotesispreserved. "Thisisacontinuation\ line" −>"Thisisacontinuationline" • Itispossibletonestcommandlinefilesupto25levels. Example Supposethefilemyoptionscontainsthefollowinglines: −xmylib.libobj1.obj −w5

Specifytheoptionfiletothelibrarian: tlb−fmyoptions

Thisisequivalenttothefollowingcommandline: tlb−xmylib.libobj1.obj−w5

5−314 ToolOptions−Librarian

Librarian:−m

Commandlinesyntax

−m[−aposname][−bposname]

Description Movethespecifiedobjectmodulestoanotherpositioninthelibrary. Theorderingofmembersinalibrarycanmakeadifferenceinhowprogramsarelinkedifasymbolisdefinedinmorethanone member.

Default,thespecifiedmembersaremovedtotheendofthearchive.Usethesuboptions−aor−btomovethemtoaspecified placeinstead.

−aposname Movethespecifiedobjectmodule(s)aftertheexistingmoduleposname.

−bposname Movethespecifiedobjectmodule(s)beforetheexistingmoduleposname.

Example

Supposethelibrarymylib.libcontainsthefollowingobjects(seeoption−t): obj1.obj obj2.obj obj3.obj

Tomoveobj1.objtotheendofmylib.lib: tlb−mmylib.libobj1.obj

Tomoveobj3.objjustbeforeobj2.obj: tlb−m−bobj3.objmylib.libobj2.obj

Thelibrarymylib.libafterthesetwoinvocationsnowlookslike: obj3.obj obj2.obj obj1.obj

Relatedinformation

Librarianoption−t(Printlibrarycontents)

5−315 NiosIIEmbeddedToolsReference

Librarian:−p

Commandlinesyntax −p

Description

Printthespecifiedobjectmodule(s)inthelibrarytostandardoutput. Thisoptionisonlyusefulwhenyouredirectorpipetheoutputtootherfilesortoolsthatserveyourownpurposes.Normallyyou donotneedthisoption.

Example tlb−pmylib.libobj1.obj>file.obj

Thelibrarianprintsthefileobj1.objtostandardoutputwhereitisredirectedtothefilefile.obj.Theeffectofthisexample isverysimilartoextractingafilefromthelibrarybutinthiscasethe’extracted’filegetsanothername.

Relatedinformation

5−316 ToolOptions−Librarian

Librarian:−r

Commandlinesyntax

−r[−aposname][−bposname][−c][−u][−v]

Description

Youcanusetheoption−rforseveralpurposes: • Addingnewobjectstothelibrary • Replacingobjectsinthelibrarywiththesameobjectofanewerdate • Creatinganewlibrary Theoption−rnormallyaddsanewmoduletothelibrary.However,ifthelibraryalreadycontainsamodulewiththespecified name,theexistingmoduleisreplaced.Ifyouspecifyalibrarythatdoesnotexist,thelibrariancreatesanewlibrarywiththe specifiedname.

Ifyouaddamoduletothelibrarywithoutspecifyingthesuboption−aor−b,thespecifiedmoduleisaddedattheendofthe archive.Usethesuboptions−aor−btoinsertthemtoaspecifiedplaceinstead.

−aposname Addthespecifiedobjectmodule(s)aftertheexistingmoduleposname.

−bposname Addthespecifiedobjectmodule(s)beforetheexistingmoduleposname.

−c Createanewlibrarywithoutcheckingwhetheritalreadyexists.Ifthelibraryalreadyexists,itisoverwritten.

−u Insertthespecifiedobjectmoduleonlyifitisnewerthanthemoduleinthelibrary.

−v Verbose:thelibrarianshowswhichfilesareremoved.

Thesuboptions−aor−bhavenoeffectwhenanobjectisaddedtothelibrary.

Examples

Supposethelibrarymylib.libcontainsthefollowingobjects(seeoption−t): obj1.obj

Toaddobj2.objtotheendofmylib.lib: tlb−rmylib.libobj2.obj

Toinsertobj3.objjustbeforeobj2.obj: tlb−r−bobj2.objmylib.libobj3.obj

Thelibrarymylib.libafterthesetwoinvocationsnowlookslike: obj1.obj obj3.obj obj2.obj

Creatinganewlibrary Tocreateanewlibraryfile,addanobjectfileandspecifyalibrarythatdoesnotyetexist: tlb−robj1.objnewlib.lib

Thelibrariancreatesthelibrarynewlib.libandaddstheobjectobj1.objtoit. Tocreateanewlibraryfileandoverwriteanexistinglibrary,addanobjectfileandspecifyanexistinglibrarywiththesupoption −c: tlb−r−cobj1.objmylib.lib

5−317 NiosIIEmbeddedToolsReference

Thelibrarianoverwritesthelibrarymylib.libandaddstheobjectobj1.objtoit.Thenewlibrarymylib.libonlycontains obj1.obj.

Relatedinformation

Librarianoption−t(Printlibrarycontents)

5−318 ToolOptions−Librarian

Librarian:−t

Commandlinesyntax

−t[−s0|−s1]

Description

Printatableofcontentsofthelibrarytostandardout.Withthesuboption−sthelibrariandisplaysallsymbolsperobjectfile.

−s0 Displaysperobjectthelibraryinwhichitresides,thenameoftheobjectitselfandallsymbolsintheobject.

−s1 Displaysonlythesymbolsofallobjectfilesinthelibrary.

Example tlb−tmylib.lib

Thelibrarianprintsalistofallobjectmodulesinthelibarymylib.lib. tlb−t−s0mylib.lib

Thelibrarianprintsperobjectallsymbolsinthelibrary.Thislookslike: prolog.obj symbols: mylib.lib:prolog.obj:___Qabi_callee_save mylib.lib:prolog.obj:___Qabi_callee_restore div16.obj symbols: mylib.lib:div16.obj:___udiv16 mylib.lib:div16.obj:___div16 mylib.lib:div16.obj:___urem16 mylib.lib:div16.obj:___rem16

Relatedinformation

5−319 NiosIIEmbeddedToolsReference

Librarian:−V

Commandlinesyntax

−V

Description Displayversioninformation.Thelibrarianignoresallotheroptionsorinputfiles.

Example tlb−V

Thelibrariandisplaysversioninformationbutdoesnotperformanytasks.

Relatedinformation

5−320 ToolOptions−Librarian

Librarian:−w

Commandlinesyntax −wlevel

Description

Withthissuboptionyoutellthelibrariantosuppressallwarningsabovethespecifiedlevel.Thelevelisanumberbetween0−9.

Thelevelofamessageisprintedbetweenparenthesesafterthewarningnumber.Ifyoudonotusethe−woption,thedefault warninglevelis8.

Example Tosuppresseswarningsabovelevel5: tlb−x−w5mylib.libobj1.obj

Relatedinformation

5−321 NiosIIEmbeddedToolsReference

Librarian:−x

Commandlinesyntax −x[−o][−v]

Description

Extractanexistingmodulefromthelibrary.

−o Givetheextractedobjectmodulethesamedateasthelast−modifieddatethatwasrecordedinthelibrary.

Withoutthissuboptionitreceivesthelast−modifieddateofthemomentitisextracted.

−v Verbose:thelibrarianshowswhichfilesareextracted.

Examples Toextractthefileobj1.objfromthelibrarymylib.lib: tlb−xmylib.libobj1.obj

Ifyoudonotspecifyanobjectmodule,allobjectmodulesareextracted: tlb−xmylib.lib

Relatedinformation

5−322 6 ListFileFormats

Summary Thischapterdescribestheformatoftheassemblerlistfileandthelinkermapfile.

6.1 AssemblerListFileFormat

Theassemblerlistfileisanadditionaloutputfileoftheassemblerthatcontainsinformationaboutthegeneratedcode. Thelistfileconsistsofapageheaderandasourcelisting.

Pageheader Thepageheaderisrepeatedoneverypage:

TASKINGtargetAssemblervx.yrzBuildnnnSN00000000 TitlePage1

ADDRCODECYCLESLINESOURCELINE

Thefirstlinecontainsversioninformation. Thesecondlinecancontainatitlewhichyoucanspecifywiththeassemblerdirective.TITLEandalwayscontainsapage number.Withtheassemblerdirectives.LIST/.NOLISTand.PAGE,andwiththeassembleroption−Lflag(−−list−format)you canformatthelistfile.

SeeSection4.8.2,AssemblerDirectivesinChapterAssemblyLanguageandSection5.3,AssemblerOptionsinChapter ToolsOptions. Thefourthlinecontainstheheadingsofthecolumnsforthesourcelisting.

Sourcelisting Thefollowingisasamplepartofalisting.Anexplanationofthedifferentcolumnsfollowsbelow.

ADDRCODECYCLESLINESOURCELINE 1;Modulestart . . 0008r4rrrr001317movhir2,@hiadj(_2_str) 000Cr4rrrr111418addir4,r2,@lo(_2_str) 0010r7rrrrD11519ldwr5,@gprel(world)(gp) 0014r0rrrrrr1620callprintf . . 000038.ds2 |RESERVED 0001

Themeaningofthedifferentcolumnsis: ADDR Thiscolumncontainsthememoryaddress.Theaddressisahexadecimalnumberthatrepresentsthe offsetfromthebeginningofarelocatablesectionortheabsoluteaddressforanabsolutesection.The addressonlyappearsonlinesthatgenerateobjectcode.

6−1 NiosIIEmbeddedToolsReference

CODE Thisistheobjectcodegeneratedbytheassemblerforthissourceline,displayedinhexadecimalformat. Thedisplayedcodeneednotbethesameasthegeneratedcodethatisenteredintheobjectmodule.The codecanalsoberelocatablecode.Inthiscasetheletter’r’isprintedfortherelocatablecodepartinthe listing.Forlinesthatallocatespace,thecodefieldcontainsthetext"RESERVED".Forlinesthatinitializea buffer,thecodefieldlistsonevaluefollowedbytheword"REPEATS". CYCLES Thefirstnumberinthiscolumnisthenumberofinstructioncyclesneededtoexecutetheinstruction(s)as generatedintheCODEfield.Thesecondnumberistheaccumulatedcyclecountofthissection. LINE Thiscolumncontainsthelinenumber.Thisisadecimalnumberindicatingeachinputline,startingfrom1 andincrementingwitheachsourceline. SOURCELINE Thiscolumncontainsthesourcetext.Thisisacopyofthesourcelinefromtheassemblysourcefile.

Forthe.SETand.EQUdirectivestheADDRandCODEcolumnsdonotapply.Thesymbolvalueislistedinstead.

Relatedinformation

Seesection5.6,GeneratingaListFile,inChapterUsingtheAssembleroftheuser’smanualformoreinformationon howtogeneratealistfileandspecifytheamountoflistfileinformation.

6−2 ListFileFormats

6.2 LinkerMapFileFormat

Thelinkermapfileisanadditionaloutputfileofthelinkerthatshowshowthelinkerhasmappedthesectionsandsymbolsfrom thevariousobjectfiles(.obj)tooutputsections.Thelocatepartshowstheabsolutepositionofeachsection.Externalsymbols arelistedperspacewiththeirabsoluteaddress,bothsortedonsymbolandsortedonaddress. Withthelinkeroption−−map−file−format(mapfileformatting)youcanspecifywhichpartsofthemapfileyouwanttosee.

Example(partof)linkermapfile

********************************************************** Tool and Invocation *********************************************************** +−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+ | tool | TASKING NIOS object linker vx.yrz Build 009 | | path | \System\Tasking\cnios\bin\lknios.exe | | arguments | −o hello.abs −fmk2052c.tmp | | task | task1 | +−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+

************************************************************* Used Resources *************************************************************

* Memory usage in bytes ======+−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+ | Memory | Code | Data | Reserved | Free | Total | |======| | system:xram | 0x0 | 0x00280 | 0x08000 | 0x77d80 | 0x80000 | | system:xrom | 0x0147c | 0x00146 | 0x0 | 0x0ea3e | 0x10000 | |−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−| | Total | 0x0147c | 0x003c6 | 0x08000 | 0x867be | 0x90000 | +−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+

* Space usage in bytes ======+−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+ | Space | Native used Rom | Native used Ram | Foreign used | Reserved | Free Rom | Free Ram | Total | |======| | system:sw:main | 0x015c2 | 0x00280 | 0x0 | 0x08000 | 0x0ea3e | 0x77d80 | 0x90000 | |−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−| | Total | 0x015c2 | 0x00280 | − | − | − | − | − | | Largest gap | − | − | − | − | 0x0ea3c | 0x77d7c | − | +−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+

Note: When spaces share memory with each other, some space can be consumed by sections located in other spaces. In the table above we call this foreign used space as opposed to native used space.

* Estimated stack usage ======+−−−−−−−−−−−−−−−−−−−−−−−−−+ | Stack Name | Used | |======| | stack 0 | 0x000001dc | |−−−−−−−−−−−−−−−−−−−−−−−−−| | recursive | no | +−−−−−−−−−−−−−−−−−−−−−−−−−+

************************************************************ Processed Files ************************************************************* +−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+ | File | From archive | Symbol causing the extraction | |======| | cstart.obj | cniosm.lib | _START | | hello.obj | | | | printf.obj | cniosm.lib | printf | +−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+

6−3 NiosIIEmbeddedToolsReference

************************************************************** Link Result *************************************************************** +−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+ | [in] File | [in] Section | [in] Size (MAU) | [out] Offset | [out] Section | [out] Size (MAU) | |======| | hello.obj | .text (2) | 0x00000024 | 0x00000000 | .text (2) | 0x00000024 | |−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−| | cstart.obj | .text.cstart (27) | 0x00000094 | 0x00000000 | .text.cstart (27) | 0x00000094 | |−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−| | printf.obj | .text.libc (58) | 0x00000054 | 0x00000000 | .text.libc (58) | 0x00000054 | +−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+

********************************************************** Module Local Symbols **********************************************************

* Scope "hello.c" ======+−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+ | Name | Space addr | Space | |======| | hello.c | 0x0 | − | |−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−| | .rodata | 0x0000015c | system:sw:main | | .sbss | 0x01000004 | | | .sdata | 0x01000000 | | | .text | 0x00000178 | | +−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+

************************************************************ Cross References ************************************************************

+−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+ | Definition file | Definition section | Symbol | Referenced in | |======| | cstart.obj | .text.cstart (27) | _START | hello.obj | | hello.obj | .text (2) | main | cstart.obj | +−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+

* Undefined symbols ======+−−−−−−−−−−−−−−−−−−−−−−−−+ | Symbol | Referenced in | |======| | _init | hello.obj | +−−−−−−−−−−−−−−−−−−−−−−−−+

*************************************************************** Call Graph *************************************************************** main | +−− printloop | | | +−− printf * | +−− printf * printf | +−− _doprint | +−− _doprint_int.c:_emitchar * | +−− _doprint_int.c:_putnumber | | | +−− _doprint_int.c:_emitchar * | | | +−− _doprint_int.c:_putstring * | | | +−− strlen * | | | +−− _doprint_int.c:_ltoa | +−− _doprint_int.c:_putstring * | +−− _doflt

6−4 ListFileFormats

************************************************************* Locate Result **************************************************************

* Task entry address ======+−−−−−−−−−−−−−−−−−−−−−−−−−−−+ | symbol | _START | | absolute address | 0x0 | +−−−−−−−−−−−−−−−−−−−−−−−−−−−+

* Sections ======

+ Space system:sw:main (MAU = 8bit)

+−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+ | Chip | Group | Section | Size (MAU) | Space addr | Chip addr | |======| | system:xrom | | .text.cstart (27) | 0x00000094 | 0x0 | 0x0 | | system:xrom | | [.data.libc] (275) | 0x000000c8 | 0x00000094 | 0x00000094 | | system:xrom | | .rodata (4) | 0x0000000e | 0x0000015c | 0x0000015c | | system:xrom | | .text (2) | 0x00000024 | 0x00000178 | 0x00000178 | | system:xrom | | [.sdata] (274) | 0x00000004 | 0x00001560 | 0x00001560 | | system:xrom | | table (273) | 0x00000060 | 0x00001564 | 0x00001564 | | system:xram | sda | .sdata (3) | 0x00000004 | 0x01000000 | 0x0 | | system:xram | | stack (271) | 0x00008000 | 0x01000284 | 0x00000284 | +−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+

* Symbols (sorted on name) ======+−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+ | Name | Space addr | Space | |======| | _Exit | 0x000001e8 | system:sw:main | | _START | 0x0 | | | main | 0x00000178 | | +−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+

* Symbols (sorted on address) ======+−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+ | Space addr | Name | Space | |======| | 0x0 | _START | system:sw:main | | 0x00000178 | main | | | 0x000001e8 | _Exit | | +−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+

********************************************************** Processor and Memory **********************************************************

************************************************************** Locate Rules ************************************************************** +−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+ | Address space | Type | Properties | Sections | |======| | system:sw:main | absolute | 0x00000000 | .text.cstart (27) | | system:sw:main | contiguous | | .sdata (3) | .sbss (5) | .sbss.libc (147) | .sbss.libc (181) | | system:sw:main | clustered | | .data.libc (66) | | system:sw:main | clustered | | [.data.libc] (275) | | system:sw:main | unrestricted | | .rodata (4) , .rodata.libc (182) , .text (2) , .text (1) | | system:sw:main | unrestricted | | stack (271) | +−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+

************************************************************ Removed Sections ************************************************************ +−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+ | Section | File | Library | Symbol | Reason | |======| | .text.libc (26) | printf_int.obj | cniosm.lib | dummy | unreferenced | | .text.libc (78) | fgetc.obj | cniosm.lib | fgetc | unreferenced | | .text.libc (92) | ungetc.obj | cniosm.lib | ungetc | unreferenced | | .text.libc (99) | _filbuf.obj | cniosm.lib | _filbuf | unreferenced | +−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+

6−5 NiosIIEmbeddedToolsReference

Themeaningofthedifferentpartsis:

ToolandInvocation Thispartofthemapfilecontainsinformationaboutthelinker,itsversionheaderinformation,binarylocationandwhichoptions areusedtocallit.

UsedResources Thispartofthemapfileshowsthememoryusageatmemorylevelandspacelevel.Thelargestfreeblockofmemory(Largest gap)isalsoshown.Thispartalsocontainsanestimationofthestackusage. Memory Thenamesofthememoryasdefinedinthelinkerscriptfile(*.lsl). Code Thesizeofallexecutablesections. Data Thesizeofallnon−executablesections(notincludingstacks,heaps,debugsectionsinnon−alloc space). Reserved Thetotalsizeofreservedmemories,reservedranges,reservedspecialsections,stacks,heaps, alignmentprotections,sectionslocatedinnon−allocspace(debugsections).Infact,thissizeisthe sameasthesizeintheTotalcolumnminusthesizeofallothercolumns. Free Thefreememoryareaaddressablebythiscore.Thisareaisaccessibleforunrestricteditems. Total Thetotalmemoryareaaddressablebythiscore. Space Thenamesoftheaddressspacesasdefinedinthelinkerscriptfile(*.lsl).Thenamesare constructedofthederivativenamefollowedbyacolon’:’,thecorename,anothercolon’:’andthe spacename. Nativeused... Thesizeofsectionslocatedinthisspace. Foreignused Thesizeofallsectionsdestinedfor/locatedinotherspaces,butbecauseofoverlapinspaces consumememoryinthisspace. StackName Thename(s)ofthestack(s)asdefinedinthelinkerscriptfile(*.lsl). Used Anestimationofthestackusage.Thelinkercalculatestherequiredstacksizebyusinginformation (.CALLSdirectives)generatedbythecompiler.Ifforexamplerecursionisdetected,thecalculated stacksizeisinaccurate,thereforethisisanestimationonly.Thecalculatedstacksizeissupposed tobesmallerthantheactualallocatedstacksize.Ifthatisnotthecase,thenawarningisgiven.

ProcessedFiles Thispartofthemapfileshowsallprocessedfiles.Thisalsoincludesobjectfilesthatareextractedfromalibrary,withthe symbolthatledtotheextraction.

LinkResult Thispartofthemapfileshowsperobjectfilehowthelinkphasehasmappedthesectionsfromthevariousobjectfiles(.obj)to outputsections. [in]File Thenameofaninputobjectfile. [in]Section Asectionnameandidfromtheinputobjectfile.Thenumberbetween’()’uniquelyidentifiesthesection. [in]Size Thesizeoftheinputsection. [out]Offset Theoffsetrelativetothestartoftheoutputsection. [out]Section Theresultingoutputsectionnameandid. [out]Size Thesizeoftheoutputsection.

ModuleLocalSymbols Thispartofthemapfileshowsatableforeachlocalscopewithinanobjectfile.Eachtablehasthreecolumns,1thesymbol name,2theaddressofthesymboland3thespacewherethesymbolresidesin.Thetableissortedonsymbolnamewithin eachspace.

6−6 ListFileFormats

Bydefaultthispartisnotshowninthemapfile.Youhavetoturnthispartonmanuallywithlinkeroption −−map−file−format=+statics(modulelocalsymbols).

CrossReferences Thispartofthemapfilelistsallsymbolsdefinedintheobjectmodulesandforeachsymboltheobjectmodulesthatcontaina referencetothesymbolareshown.Also,symbolsthatremainundefinedareshown.

CallGraph

Thispartofthemapfilecontainsaschematicoverviewthatshowshow(library)functionscalleachother.

LocateResult:Sections Thispartofthemapfileshowstheabsolutepositionofeachsectionintheabsoluteobjectfile.Itisorganizedperaddress space,memorychipandgroupandsortedonspaceaddress. +Space Thenamesoftheaddressspacesasdefinedinthelinkerscriptfile(*.lsl).Thenamesareconstructed ofthederivativenamefollowedbyacolon’:’,thecorename,anothercolon’:’andthespacename. Chip Thenamesofthememorychipsasdefinedinthelinkerscriptfile(*.lsl)inthememorydefinitions. Group Sectionscanbeorderedingroups.Thesearethenamesofthegroupsasdefinedinthelinkerscriptfile (*.lsl)withthekeywordgroupinthesection_layoutdefinition.Thenamethatisdisplayedisthe nameofthedeepestnestedgroup. Section Thenameandidofthesection.Thenumberbetween’()’uniquelyidentifiesthesection.Nameswithin squarebrackets[]willbecopiedduringinitializationfromROMtothecorrespondingsectionnamein RAM. Size(MAU) Thesizeofthesectioninminimumaddressableunits. Spaceaddr Theabsoluteaddressofthesectionintheaddressspace. Chipaddr Theabsoluteoffsetofthesectionfromthestartofamemorychip.

LocateResult:Symbols Thispartofthemapfilelistsallexternalsymbolsperaddressspacename,bothsortedonaddressandsortedonsymbolname. Name Thenameofthesymbol. Spaceaddr Theabsoluteaddressofthesectionintheaddressspace. Space Thenamesoftheaddressspacesasdefinedinthelinkerscriptfile(*.lsl).Thenamesareconstructed ofthederivativenamefollowedbyacolon’:’,thecorename,anothercolon’:’andthespacename.

ProcessorandMemory Thispartofthemapfileshowstheprocessorandmemoryinformationofthelinkerscriptfile. Bydefaultthispartisnotshowninthemapfile.Youhavetoturnthispartonmanuallywithlinkeroption −−map−file−format=+lsl(processorandmemoryinfo).Youcanprintthisinformationtoaseparatefilewithlinkeroption −−lsl−dump.

LocateRules Thispartofthemapfileshowstherulesthelinkerusestolocatesections. Addressspace Thenamesoftheaddressspacesasdefinedinthelinkerscriptfile(*.lsl).Thenamesareconstructed ofthederivativenamefollowedbyacolon’:’,thecorename,anothercolon’:’andthespacename. Type Theruletype: ordered/contiguous/clustered/unrestricted Specifieshowsectionsaregrouped.Bydefault,agroupis’unrestricted’whichmeansthatthelinker hastotalfreedomtoplacethesectionsofthegroupintheaddressspace. absolute ThesectionmustbelocatedattheaddressshowninthePropertiescolumn.

6−7 NiosIIEmbeddedToolsReference

ranged ThesectionmustbelocatedanywhereintheaddressrangesshowninthePropertiescolumn;end addressesarenotincludedintherange. floating Thesectionsmustbelocatedinsomeaddressrangewithasizenotlargerthanshowninthe Propertiescolumn;thefirstnumberisthepagesize,thesecondpartistheaddressrange restrictionwithinthepage. rangedfloat Boththerangedandthefloatingrestrictionapply.InthePropertiescolumntherangerestrictionis listedfirst,followedbythefloatingrestrictionbetweenparenthesis. ballooned Afterlocatingallsections,thelargestremaininggapinthespaceisusedcompletelyforthestack and/orheap. Properties ThecontentsdependsontheTypecolumn. Sections Thesectionstowhichtheruleapplies; restrictionsbetweensectionsareshowninthiscolumn: < ordered | contiguous + clustered Forcontiguoussections,thelinkerusesthesectionorderasshownhere.Clusteredsectionscanbe locatedinanyrelativeorder.

RemovedSections Thispartofthemapfilecontainsinformationaboutthesectionsthatareremovedfromtheabsoluteobjectfile.Forexample, unreferencedsections.

Relatedinformation

Section6.11,GeneratingaMapFile,inChapterUsingtheLinkeroftheuser’smanual. Linkeroption−−map−file(Generatemapfile)

6−8 7 ObjectFileFormats

Summary Thischapterdescribestheformatsofseveralobjectfiles.

7.1 ELF/DWARFObjectFormat

TheTASKINGNiosIItoolsetbydefaultproducesobjectsintheELF/DWARF2format. ForacompletedescriptionoftheELFandDWARFformats,pleaserefertotheToolInterfaceStandard(TIS).

7−1 NiosIIEmbeddedToolsReference

7.2 MotorolaS−RecordFormat

Withthelinkeroption−ofilename:SRECoptionthelinkerproducesoutputinMotorolaS−recordformatwiththreetypesof S−records:S0,S3andS7.Withtheoptions−ofilename:SREC:2or−ofilename:SREC:3optionyoucanforceothertypesof S−records.Theyhavethefollowinglayout:

S0−record ’S’’0’<2bytes0> AlinkergeneratedS−recordfilestartswithaS0recordwiththefollowingcontents: length_byte :$09 comment :lknios checksum :$66 lknios S00900006C6B6E696F7366

TheS0recordisacommentrecordanddoesnotcontainrelevantinformationforprogramexecution. Thelength_byterepresentsthenumberofbytesintherecord,notincludingtherecordtypeandlengthbyte. Thechecksumiscalculatedbyfirstaddingthebinaryrepresentationofthebytesfollowingtherecordtype(startingwiththe length_byte)tojustbeforethechecksum.Thentheone’scomplementiscalculatedofthissum.Theleastsignificantbyteofthe resultisthechecksum.Thesumofallbytesfollowingtherecordtypeis0FFH.

S1−record Withthelinkeroption−ofilename:SREC:2,theactualprogramcodeanddataissuppliedwithS1records,withthefollowing layout: ’S’’1’

Thisrecordisusedfor2−byteaddresses. Example: S1130250F03EF04DF0ACE8A408A2A013EDFCDB00E6 ||||_checksum |||_code ||_address |_length

ThelinkerhasanoptionthatcontrolsthelengthoftheoutputbufferforgeneratingS1records.Thedefaultbufferlengthis32 codebytes. ThechecksumcalculationofS1recordsisidenticaltoS0.

S2−record Withthelinkeroption−ofilename:SREC:3,theactualprogramcodeanddataissuppliedwithS2records,withthefollowing layout: ’S’’2’

Thisrecordisusedfor3−byteaddresses. Example: S213FF002000232222754E00754F04AF4FAE4E22BF ||||_checksum |||_code ||_address |_length

ThelinkerhasanoptionthatcontrolsthelengthoftheoutputbufferforgeneratingS2records.Thedefaultbufferlengthis32 codebytes.

7−2 ObjectFileFormats

ThechecksumcalculationofS2recordsisidenticaltoS0.

S3−record Withthelinkeroption−ofilename:SREC:4,whichisthedefault,theactualprogramcodeanddataissuppliedwithS3records, withthefollowinglayout: ’S’’3’

Thelinkergenerates4−byteaddressesbydefault. Example: S3070000FFFE6E6825 ||||_checksum |||_code ||_address |_length

ThelinkerhasanoptionthatcontrolsthelengthoftheoutputbufferforgeneratingS3records. ThechecksumcalculationofS3recordsisidenticaltoS0.

S7−record Withthelinkeroption−ofilename:SREC:4,whichisthedefault,attheendofanS−recordfile,thelinkergeneratesanS7record, whichcontainstheprogramstartaddress.S7isthecorrespondingterminationrecordforS3records. Layout: ’S’’7’

Example: S70500000000FA |||_checksum ||_address |_length

ThechecksumcalculationofS7recordsisidenticaltoS0.

S8−record Withthelinkeroption−ofilename:SREC:3,attheendofanS−recordfile,thelinkergeneratesanS8record,whichcontainsthe programstartaddress. Layout: ’S’’8’

Example: S804FF0003F9 |||_checksum ||_address |_length

ThechecksumcalculationofS8recordsisidenticaltoS0.

S9−record

Withthelinkeroption−ofilename:SREC:2,attheendofanS−recordfile,thelinkergeneratesanS9record,whichcontainsthe programstartaddress.S9isthecorrespondingterminationrecordforS1records. Layout: ’S’’9’

7−3 NiosIIEmbeddedToolsReference

Example: S9030210EA |||_checksum ||_address |_length

ThechecksumcalculationofS9recordsisidenticaltoS0.

7−4 ObjectFileFormats

7.3 IntelHexRecordFormat

IntelHexrecordsdescribethehexadecimalobjectfileformatfor8−bit,16−bitand32−bit.Thehexadecimal objectfileisanASCIIrepresentationofanabsolutebinaryobjectfile.Therearesixdifferenttypesofrecords: • DataRecord(8−,16,or32−bitformats) • EndofFileRecord(8−,16,or32−bitformats) • ExtendedSegmentAddressRecord(16,or32−bitformats) • StartSegmentAddressRecord(16,or32−bitformats) • ExtendedLinearAddressRecord(32−bitformatonly) • StartLinearAddressRecord(32−bitformatonly) Bydefaultthelinkergeneratesrecordsinthe32−bitformat(4−byteaddresses).

GeneralRecordFormat

Intheoutputfile,therecordformatis:

ÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁ

ÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁ

Á Á Á Á Á

Á : length offset type content checksum

ÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁ

Á Á Á Á Á Á

ÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁ Where:ÁÁÁ : istherecordheader. length istherecordlengthwhichspecifiesthenumberofbytesofthecontentfield.Thisvalueoccupiesonebyte(two hexadecimaldigits).Thelinkeroutputsrecordsof255bytes(32hexadecimaldigits)orless;thatis,lengthis nevergreaterthanFFH. offset isthestartingloadoffsetspecifyinganabsoluteaddressinmemorywherethedataistobelocatedwhenloaded byatool.Thisfieldistwobyteslong.ThisfieldisonlyusedforDataRecords.Inotherrecordsthisfieldiscoded asfourASCIIzerocharacters(’0000’). type istherecordtype.Thisvalueoccupiesonebyte(twohexadecimaldigits).Therecordtypesare:

ByteType Recordtype 00 Data 01 EndofFile 02 Extendedsegmentaddress(notused) 03 Startsegmentaddress(notused) 04 Extendedlinearaddress(32−bit) 05 Startlinearaddress(32−bit) content istheinformationcontainedintherecord.Thisdependsontherecordtype. checksum istherecordchecksum.Thelinkercomputesthechecksumbyfirstaddingthebinaryrepresentationofthe previousbytes(fromlengthtocontent).Thelinkerthencomputestheresultofsummodulo256andsubtractsthe remainderfrom256(two’scomplement).Therefore,thesumofallbytesfollowingtheheaderiszero.

ExtendedLinearAddressRecord TheExtendedLinearAddressRecordspecifiesthetwomostsignificantbytes(bits16−31)oftheabsoluteaddressofthefirst

databyteinasubsequentDataRecord:

ÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁ

ÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁ

Á Á Á Á Á

Á : 02 0000 04 upper_address checksum

ÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁ

7−5 NiosIIEmbeddedToolsReference

The32−bitabsoluteaddressofabyteinaDataRecordiscalculatedas: (address+offset+index)modulo4G where: address isthebaseaddress,wherethetwomostsignificantbytesaretheupper_addressandthetwoleastsignificant bytesarezero. offset isthe16−bitoffsetfromtheDataRecord. index istheindexofthedatabytewithintheDataRecord(0forthefirstbyte). Example: :0200000400FFFB |||||_checksum ||||_upper_address |||_type ||_offset |_length

DataRecord

TheDataRecordspecifiestheactualprogramcodeanddata.

ÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁ

: length offset 00 data checksum

ÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁ

Á Á Á Á Á Á

ÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁ Thelengthbytespecifiesthenumberofdatabytes.Thelinkerhasanoptionthatcontrolsthelengthoftheoutputbufferfor generatingDatarecords.Thedefaultbufferlengthis32bytes. Theoffsetisthe16−bitstartingloadoffset.TogetherwiththeaddressspecifiedintheExtendedAddressRecorditspecifiesan absoluteaddressinmemorywherethedataistobelocatedwhenloadedbyatool. Example: :0F00200000232222754E00754F04AF4FAE4E22C3 |||||_checksum ||||_data |||_type ||_offset |_length

StartLinearAddressRecord TheStartLinearAddressRecordcontainsthe32−bitprogramexecutionstartaddress.

Layout:

ÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁ

ÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁ

Á Á Á Á Á

Á : 04 0000 05 address checksum

ÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁÁ

Example: :0400000500FF0003F5 |||||_checksum ||||_address |||_type ||_offset |_length

7−6 ObjectFileFormats

EndofFileRecord Thehexadecimalfilealwaysendswiththefollowingend−of−filerecord: :00000001FF ||||_checksum |||_type ||_offset |_length

7−7 NiosIIEmbeddedToolsReference

7−8 8 LinkerScriptLanguage

Summary Thischapterdescribesthesyntaxofthelinkerscriptlanguage(LSL)

8.1 Introduction

Tomakefulluseofthelinker,youcanwriteascriptwithinformationaboutthearchitectureofthetargetprocessorandlocating information.ThelanguageforthescriptiscalledtheLinkerScriptLanguage(LSL).Thischapterfirstdescribesthestructureof anLSLfile.ThenextsectioncontainsasummaryoftheLSLsyntax.Finally,intheremainingsections,thesemanticsofthe LinkerScriptLanguageisexplained. TheTASKINGlinkerisatargetindependentlinker/locatorthatcansimultaneouslylinkandlocateallprogramsforallcores availableonatargetboard.Thetargetboardmaybeofarbitrarycomplexity.Asimpletargetboardmaycontainonestandard processorwithsomeexternalmemorythatexecutesonetask.Acomplextargetboardmaycontainmultiplestandard processorsandDSPscombinedwithconfigurableIP−coresloadedinanFPGA.Eachcoremayexecuteadifferentprogram, andexternalmemorymaybesharedbymultiplecores. LSLservestwopurposes.Firstitenablesyoutospecifythecharacteristics(thatareofinteresttothelinker)ofyourspecific targetboardandofthecoresinstalledontheboard.Seconditenablesyoutospecifyhowsectionsshouldbelocatedin memory.

8.2 StructureofaLinkerScriptFile

Ascriptfileconsistsofseveraldefinitions.Thedefinitionscanappearinanyorder.

Thearchitecturedefinition(required) Inessenceanarchitecturedefinitiondescribeshowthelinkershouldconvertlogicaladdressesintophysicaladdressesfora giventypeofcore.Ifthecoresupportsmultipleaddressspaces,thenforeachspacethelinkermustknowhowtoperformthis conversion.Inthiscontextaphysicaladdressisanoffsetonagiveninternalorexternalbus.Additionallythearchitecture definitioncontainsinformationaboutitemssuchasthe(hardware)stackandthevectortable. ThisspecificationisnormallywrittenbyAltium.ThearchitecturedefinitionoftheLSLfileshouldnotbechangedbyyouunless youalsomodifythecore’shardwarearchitecture.IftheLSLfiledescribesamulti−coresystemanarchitecturedefinitionmustbe availableforeachdifferenttypeofcore.

Seesection8.5,SemanticsoftheArchitectureDefinitionfordetaileddescriptionsofLSLinthearchitecturedefinition.

Thederivativedefinition Thederivativedefinitiondescribestheconfigurationoftheinternal(on−chip)busandmemorysystem.Basicallyittellsthelinker howtoconvertoffsetsonthebusesspecifiedinthearchitecturedefinitionintooffsetsininternalmemory.Aderivativedefinition mustbepresentinanLSLfile.andDSPsoftenhaveinternalmemoryandI/Osub−systemsapartfromoneor morecores.Thedesignofsuchachipiscalledaderivative. WhenyoudesignanFPGAtogetherwithaPCB,thecomponentsontheFPGAbecomepartoftheboarddesignandthereisno needtodistinguishbetweeninternalandexternalmemory.Forthisreasonyouprobablydonotneedtoworkwithderivative definitionsatall.Thereare,however,twosituationswherederivativedefinitionsareuseful: 1. Whenyoure−useanFPGAdesignforseveralboarddesignsitmaybepracticaltowriteaderivativedefinitionfortheFPGA designandincludeitintheprojectLSLfile. 2. Whenyouwanttousemultiplecoresofthesametype,youmustinstantiatethecoresinaderivativedefinition,sincethe linkerautomaticallyinstantiatesonlyasinglecoreforanunusedarchitecture.

8−1 NiosIIEmbeddedToolsReference

Seesection8.6,SemanticsoftheDerivativeDefinitionforadetaileddescriptionofLSLinthederivativedefinition.

Theprocessordefinition Theprocessordefinitiondescribesaninstanceofaderivative.Typicallytheprocessordefinitioninstantiatesonederivativeonly (single−coreprocessor).Aprocessorthatcontainsmultiplecoreshavingthesame(homogeneous)ordifferent(heterogeneous) architecturecanalsobedescribedbyinstantiatingmultiplederivativesofthesameordifferenttypesinseparateprocessor definitions. Ifforaderivative’A’noprocessorisdefinedintheLSLfile,thelinkerautomaticallycreatesaprocessornamed’A’ofderivative ’A’.Thisiswhyforsingle−processorapplicationsitisenoughtospecifythederivativeintheLSLfile.

Seesection8.7,SemanticsoftheBoardSpecificationforadetaileddescriptionofLSLintheprocessordefinition.

Thememoryandbusdefinitions(optional) Memoryandbusdefinitionareusedwithinthecontextofaderivativedefinitiontospecifyinternalmemoryandon−chipbuses.In thecontextofaboardspecificationthememoryandbusdefinitionsareusedtodefineexternal(off−chip)memoryandbuses. Giventheabovedefinitionsthelinkercanconvertalogicaladdressintoanoffsetintoanon−chiporoff−chipmemorydevice.

Seesection8.7.3,DefiningExternalMemoryandBuses,formoreinformationonhowtospecifytheexternalphysical memorylayout.Internalmemoryforaprocessorshouldbedefinedinthederivativedefinitionforthatprocessor.

Theboardspecification Theprocessordefinitionandmemoryandbusdefinitionstogetherformaboardspecification.LSLprovideslanguageconstructs toeasilydescribesingle−coreandheterogeneousorhomogeneousmulti−coresystems.Theboardspecificationdescribesall characteristicsofyourtargetboard’ssystembuses,memorydevices,I/Osub−systems,andcoresthatareofinteresttothe linker.Basedontheinformationprovidedintheboardspecificationthelinkercanforeachcore: • convertalogicaladdresstoanoffsetwithinamemorydevice • locatesectionsinphysicalmemory • maintainanoverallviewoftheusedandfreephysicalmemorywithinthewholesystemwhilelocating Thesectionlayoutdefinition(optional) Theoptionalsectionlayoutdefinitionenablesyoutoexactlycontrolwhereinputsectionsarelocated.Featuresareprovided suchas:theabilitytoplacesectionsatagivenload−addressorrun−timeaddress,toplacesectionsinagivenorder,andto overlaycodeand/ordatasections. Whichobjectfiles(sections)constitutethetaskthatwillrunonagivencoreisspecifiedonthecommandlinewhenyouinvoke thelinker.Thelinkerwilllinkandlocateallsectionsofalltaskssimultaneously.Fromthesectionlayoutdefinitionthelinkercan deducewhereagivensectionmaybelocatedinmemory,formtheboardspecificationthelinkercandeducewhichphysical memoryis(still)availablewhilelocatingthesection.

Seesection8.9,SemanticsoftheSectionLayoutDefinition,formoreinformationonhowtolocateasectionataspecific placeinmemory.

SkeletonofaLinkerScriptFile Theskeletonofalinkerscriptfilenowlooksasfollows: architecturearchitecture_name { architecturedefinition } derivativederivative_name { derivativedefinition }

8−2 LinkerScriptLanguage

processorprocessor_name { processordefinition } memorydefinitionsand/orbusdefinitions section_layoutspace_name { sectionplacementstatements }

8.3 SyntaxoftheLinkerScriptLanguage

8.3.1 Preprocessing

WhenthelinkerloadsanLSLfile,thelinkerprocessesitwithaC−styleprepocessor.Assuch,itstripsCandC++comments. YoucanusethestandardISOCpreprocessordirectives,suchas#include,#define,#if/#else/#endif. Forexample: #include"arch.lsl"

Preprocessandincludethefilearch.lslatthispointintheLSLfile.

8.3.2 LexicalSyntax

ThefollowinglexiconisusedtodescribethesyntaxoftheLinkerScriptLanguage: A::=B =AisdefinedasB A::=BC =AisdefinedasBandC;BisfollowedbyC A::=B|C= AisdefinedasBorC 0|1 =zerooroneoccurrenceofB >=0 =zeroofmoreoccurrencesofB >=1 =oneofmoreoccurrencesofB IDENTIFIER=acharactersequencestartingwith’a’−’z’,’A’−’Z’or’_’. Followingcharactersmayalsobedigitsanddots’.’ STRING=sequenceofcharactersnotstartingwith\n,\ror\t DQSTRING="STRING"(doublequotedstring) OCT_NUM=octalnumber,startingwithazero(06,045) DEC_NUM=decimalnumber,notstartingwithazero(14,1024) HEX_NUM=hexadecimalnumber,startingwith’0x’(0x0023,0xFF00) OCT_NUM,DEC_NUMandHEX_NUMcanbefollowedbyak(kilo),M(mega),orG(giga). Charactersinboldarecharactersthatoccurliterally.Wordsinitalicsarehigherordertermsthataredefinedinthesameorin oneoftheothersections. TowritecommentsinLSLfile,youcanusetheCstyle’/**/’orC++style’//’.

8−3 NiosIIEmbeddedToolsReference

8.3.3 Identifiers arch_name::=IDENTIFIER bus_name::=IDENTIFIER core_name::=IDENTIFIER derivative_name::=IDENTIFIER file_name::=DQSTRING group_name::=IDENTIFIER mem_name::=IDENTIFIER proc_name::=IDENTIFIER section_name::=DQSTRING space_name::=IDENTIFIER stack_name::=section_name symbol_name::=DQSTRING

8.3.4 Expressions

TheexpressionsandoperatorsinthissectionworkthesameasinISOC. number::=OCT_NUM |DEC_NUM |HEX_NUM expr::=number |symbol_name |unary_opexpr |exprbinary_opexpr |expr?expr:expr |(expr) |function_call unary_op::=!//logicalNOT |~//bitwisecomplement |−//negativevalue binary_op::=^//exclusiveOR |*//multiplication |///division |%//modulus |+//addition |−//subtraction |>>//rightshift |<<//leftshift |==//equalto |!=//notequalto |>//greaterthan |<//lessthan |>=//greaterthanorequalto |<=//lessthanorequalto |&//bitwiseAND ||//bitwiseOR |&&//logicalAND |||//logicalOR

8−4 LinkerScriptLanguage

8.3.5 Built−inFunctions function_call::=absolute(expr) |addressof(addr_id) |exists(section_name) |max(expr,expr) |min(expr,expr) |sizeof(size_id) addr_id::=sect:section_name |group:group_name size_id::=sect:section_name |group:group_name |mem:mem_name • Everyspace,bus,memory,sectionorgroupyourreferto,mustbedefinedintheLSLfile. • Theaddressof()andsizeof()functionswiththegrouporsectargumentcanonlybeusedintherighthandsideofan assignment.Thesizeof()functionwiththememargumentcanbeusedanywhereinsectionlayouts. Youcanusethefollowingbuilt−infunctionsinexpressions.Allfunctionsreturnanumericalvalue.Thisvalueisa64−bitsigned integer. absolute()

intabsolute(expr)

Convertsthevalueofexprtoapositiveinteger. absolute("labelA"−"labelB") addressof()

intaddressof(addr_id)

Returnstheaddressofaddr_id,whichisanamedsectionorgroup.Togettheoffsetofthesectionwiththenameasect: addressof(sect:"asect")

Thisfunctiononlyworksinassignments. exists()

intexists(section_name)

Thefunctionreturns1ifthesectionsection_nameexistsinoneormoreobjectfile,0otherwise.Ifthesectionisnotpresentin inputobjectfiles,butgeneratedfromLSL,theresultofthisfunctionisundefined. Tocheckwhetherthesectionmysectionexistsinoneoftheobjectfilesthatisspecifiedtothelinker: exists("mysection") max()

intmax(expr,expr)

Returnsthevalueoftheexpressionthathasthelargestvalue.Togetthehighestvalueoftwosymbols: max("sym1","sym2")

8−5 NiosIIEmbeddedToolsReference min()

intmin(expr,expr)

Returnsthevalueoftheexpressionhathasthesmallestvalue.Togetthelowestvalueoftwosymbols: min("sym1","sym2") sizeof()

intsizeof(size_id)

Returnsthesizeoftheobject(group,sectionormemory)theidentifierrefersto.Togetthesizeofthesection"asection": sizeof(sect:"asection")

Thegroupandsectargumentsonlyworksinassignments.Thememargumentcanbeusedanywhereinsection layouts.

8.3.6 LSLDefinitionsintheLinkerScriptFile description::=>=1 definition::=architecture_definition |derivative_definition |board_spec |section_definition |section_setup • Atleastonearchitecture_definitionmustbepresentintheLSLfile.

8.3.7 MemoryandBusDefinitions mem_def::=memorymem_name{>=0} • Amem_defdefinesamemorywiththemem_nameasauniquename. mem_descr::=type=0|1mem_type |mau=expr |size=expr |speed=number |fill<=fill_values>0|1 |mapping • Amem_defcontainsexactlyonetypestatement. • Amem_defcontainsexactlyonemaustatement(non−zerosize). • Amem_defcontainsexactlyonesizestatement. • Amem_defcontainszerooronespeedstatement(ifabsent,thedefaultspeedvalueis1). • Amem_defcontainszerooronefillstatement. • Amem_defcontainsatleastonemapping. mem_type::=rom//attrs=rx |ram//attrs=rw |nvram//attrs=rwx fill_values::=expr |[expr<,expr>>=0] bus_def::=busbus_name{>=0} • Abus_defstatementdefinesabuswiththegivenbus_nameasauniquenamewithinacorearchitecture.

8−6 LinkerScriptLanguage bus_descr::=mau=expr |width=expr//buswidth,nr |//ofdatabits |mapping//legaldestination //’bus’only • Themauandwidthstatementsappearexactlyonceinabus_descr.Thedefaultvalueforwidthisthemausize. • ThebuswidthmustbeanintegertimesthebusMAUsize. • TheMAUsizemustbenon−zero. • Abuscanonlyhaveamappingonadestinationbus(throughdest=bus:). mapping::=map(map_descr<,map_descr>>=0) map_descr::=dest=destination |dest_dbits=range |dest_offset=expr |size=expr |src_dbits=range |src_offset=expr • Amappingrequiresatleastthesizeanddeststatements. • Eachmap_descrcanoccuronlyonce. • Youcandefinemultiplemappingsfromasinglesource. • Overlapbetweensourcerangesordestinationrangesisnotallowed. • Ifthesrc_dbitsordest_dbitsstatementisnotpresent,itsvaluedefaultstothewidthvalueifthesource/destinationis abus,andtothemausizeotherwise. destination::=space:space_name |bus:0|1bus_name • Aspace_namereferstoadefinedaddressspace. • Aproc_namereferstoadefinedprocessor. • Acore_namereferstoadefinedcore. • Abus_namereferstoadefinedbus. • Thefollowingmappingsareallowed(sourcetodestination) − space=>space − space=>bus − bus=>bus − memory=>bus range::=expr..expr • Withaddressranges,theendaddressisnotpartoftherange.

8.3.8 ArchitectureDefinition architecture_definition ::=architecturearch_name <(parameter_list)>0|1 0|1>0|1 {arch_spec>=0} • Anarchitecture_definitiondefinesacorearchitecturewiththegivenarch_nameasauniquename. • Atleastonespace_defandatleastonebus_defhavetobepresentinanarchitecture_definition. • Anarchitecture_definitionthatusestheextendsconstructdefinesanarchitecturethatinheritsallelementsofthe architecturedefinedbythesecondarch_name.TheparentarchitecturemustbedefinedintheLSLfileaswell. parameter_list::=parameter<,parameter>>=0 parameter::=IDENTIFIER<=expr>0|1

8−7 NiosIIEmbeddedToolsReference argument_list::=expr<,expr>>=0 arch_spec::=bus_def |space_def |endianness_def space_def::=spacespace_name{>=0} • Aspace_defdefinesanaddressspacewiththegivenspace_nameasauniquenamewithinanarchitecture. space_descr::=space_property; |section_definition//nospaceref |vector_table_statement |reserved_range space_property::=id=number//asusedinobject |mau=expr |align=expr |page_size=expr<[range]<|[range]>>=0>0|1 |page |direction=direction |stack_def |heap_def |copy_table_def |start_address |mapping • Aspace_defcontainsexactlyoneidandonemaustatement. • Aspace_defcontainsatmostonealignstatement. • Aspace_defcontainsatmostonepage_sizestatement. • Aspace_defcontainsatleastonemapping. stack_def::=stackstack_name(stack_heap_descr <,stack_heap_descr>>=0) • Astack_defdefinesastackwiththestack_nameasauniquename. heap_def::=heapheap_name(stack_heap_descr <,stack_heap_descr>>=0) • Aheap_defdefinesaheapwiththeheap_nameasauniquename. stack_heap_descr::=min_size=expr |grows=direction |align=expr |fixed |id=expr • Themin_sizestatementmustbepresent. • Youcanspecifyatmostonealignstatementandonegrowsstatement. • Eachstackdefinitionhasitsownuniqueid,thenumberspecifiedcorrespondstotheindexinthe.CALLSdirectiveas generatedbythecompiler.Iftheidisomitted,theidis0(zero). direction::=low_to_high |high_to_low • Ifyoudonotspecifythegrowsstatement,thestackandgrowlow−to−high. copy_table_def::=copytable<(copy_table_descr <,copy_table_descr>>=0)>0|1 • Aspace_defcontainsatmostonecopytablestatement. • Ifthearchitecturedefinitioncontainsmorethanoneaddressspace,exactlyonecopytablemustbedefinedinoneofthe spaces.Ifthearchitecturedefinitioncontainsonlyoneaddressspace,acopytabledefinitionisoptional(itwillbegenerated inthespace).

8−8 LinkerScriptLanguage copy_table_descr::=align=expr |copy_unit=expr |dest0|1=space_name |page • Thecopy_unitisdefinedbythesizeinMAUsinwhichthestartupcodemovesdata. • Thedeststatementisonlyrequiredwhenthestartupcodeinitializesmemoryusedbyanotherprocessorthathasno accesstoROM. • Aspace_namereferstoadefinedaddressspace. start_addr::=start_address(start_addr_descr <,start_addr_descr>>=0) start_addr_descr::=run_addr=expr |symbol=symbol_name • Asymbol_namereferstothesectionthatcontainsthestartupcode. vector_table_statement ::=vector_tablesection_name (vecttab_spec<,vecttab_spec>>=0) {>=0} vecttab_spec::=vector_size=expr |size=expr |id_symbol_prefix=symbol_name |run_addr=addr_absolute |template=section_name |template_symbol=symbol_name |vector_prefix=section_name |fill=vector_value |no_inline |copy vector_def::=vector(vector_spec<,vector_spec>>=0) vector_spec::=id=vector_id_spec |fill=vector_value vector_id_spec::=number |[range]<,[range]>>=0 vector_value::=symbol_name |[number<,number>>=0] |loop<[expr]>0|1 reserved_range::=reservedexpr..expr; • Theendaddressisnotpartoftherange. endianness_def::=endianness{>=1} endianness_type::=big |little

8.3.9 DerivativeDefinition derivative_definition ::=derivativederivative_name <(parameter_list)>0|1 0|1>0|1 {>=0} • Aderivative_definitiondefinesaderivativewiththegivenderivative_nameasauniquename.

8−9 NiosIIEmbeddedToolsReference derivative_spec::=core_def |bus_def |mem_def |section_definition//noprocessorname |section_setup core_def::=corecore_name{>=0} • Acore_defdefinesacorewiththegivencore_nameasauniquename. • Atleastonecore_defmustbepresentinaderivative_definition. core_descr::=architecture=arch_name <(argument_list)>0|1 |endianness=(endianness_type <,endianness_type>>=0) • Anarch_namereferstoadefinedcorearchitecture. • Exactlyonearchitecturestatementmustbepresentinacore_def.

8.3.10 ProcessorDefinitionandBoardSpecification board_spec::=proc_def |bus_def |mem_def proc_def::=processorproc_name {proc_descr;} proc_descr::=derivative=derivative_name <(argument_list)>0|1 • Aproc_defdefinesaprocessorwiththeproc_nameasauniquename. • IfyoudonotexplicitlydefineaprocessorforaderivativeinanLSLfile,thelinkerdefinesaprocessorwiththesamenameas thatderivative. • Aderivative_namereferstoadefinedderivative. • Aproc_defcontainsexactlyonederivativestatement.

8.3.11 SectionLayoutDefinitionandSectionSetup section_definition::=section_layout0|1 <(locate_direction)>0|1 {>=0} • Asectiondefinitioninsideaspacedefinitiondoesnothaveaspace_ref. • Allglobalsectiondefinitionshaveaspace_ref. space_ref::=0|1:0|1 :space_name • Ifmorethanoneprocessorispresent,theproc_namemustbegivenforaglobalsectionlayout. • Ifthesectionlayoutreferstoaprocessorthathasmorethanonecore,thecore_namemustbegiveninthespace_ref. • Aproc_namereferstoadefinedprocessor. • Acore_namereferstoadefinedcore. • Aspace_namereferstoadefinedaddressspace. locate_direction::=direction=direction direction::=low_to_high |high_to_low • Asectionlayoutcontainsatmostonedirectionstatement. • Ifyoudonotspecifythedirectionstatement,thelocatedirectionofthesectionlayoutislow−to−high. section_statement ::=simple_section_statement; |aggregate_section_statement

8−10 LinkerScriptLanguage simple_section_statement ::=assignment |select_section_statement |special_section_statement assignment::=symbol_nameassign_opexpr assign_op::== |:= select_section_statement ::=select0|10|1 0|1 • Eitherasection_nameoratleastonesection_selectionmustbedefined. section_selections ::=(section_selection <,section_selection>>=0) section_selection ::=attributes=<<+|−>attribute>>0 • +attributemeans:selectallsectionsthathavethisattribute. • −attributemeans:selectallsectionsthatdonothavethisattribute. special_section_statement ::=heapstack_name0|1 |stackstack_name0|1 |copytable |reservedsection_name0|1 • Specialsectionscannotbeselectedinload−timegroups. size_spec::=(size=expr) reserved_specs::=(reserved_spec<,reserved_spec>>=0) reserved_spec::=attributes |fill_spec |size=expr |alloc_allowed=absolute|ranged • Ifareservedsectionhasattributesr,rw,x,rxorrwx,andnofillpatternisdefined,thesectionisfilledwithzeros.Ifno attributesareset,thesectioniscreatedasascratchsection(attributesws,noimage). fill_spec::=fill=fill_values fill_values::=expr |[expr<,expr>>=0] aggregate_section_statement ::={>=0} |group_descr |if_statement |section_creation_statement group_descr::=group0|1<(group_specs)>0|1 section_statement • Foreverygroupwithaname,thelinkerdefinesalabel. • Notwogroupsforaddressspacesofacorecanhavethesamegroup_name. group_specs::=group_spec<,group_spec>>=0

8−11 NiosIIEmbeddedToolsReference group_spec::=group_alignment |attributes |copy |nocopy |group_load_address |fill<=fill_values>0|1 |group_page |group_run_address |group_type |allow_cross_references |priority=number • Theallow−cross−referencespropertyisonlyallowedforoverlaygroups. • Subgroupsinheritallpropertiesfromaparentgroup. group_alignment::=align=expr attributes::=attributes=>=1 attribute::=r//readablesections |w//writablesections |x//executablecodesections |i//initializedsections |s//scratchsections |b//blanked(cleared)sections group_load_address ::=load_addr<=load_or_run_addr>0|1 group_page::=page<=expr>0|1 |page_size=expr<[range]<|[range]>>=0>0|1 group_run_address::=run_addr<=load_or_run_addr>0|1 group_type::=clustered |contiguous |ordered |overlay • Fornon−contiguousgroups,youcanonlyspecifygroup_alignmentandattributes. • Theoverlaykeywordalsosetsthecontiguousproperty. • Theclusteredpropertycannotbesettogetherwithcontiguousororderedonasinglegroup. load_or_run_addr::=addr_absolute |addr_range<|addr_range>>=0 addr_absolute::=expr |memory_reference[expr] • Anabsoluteaddresscanonlybesetonorderedgroups. addr_range::=[expr..expr] |memory_reference |memory_reference[expr..expr] • Theparentofagroupwithanaddr_rangeorpagerestrictioncannotbeordered,contiguousorclustered. • Theendaddressisnotpartoftherange. memory_reference::=mem:0|1mem_name • Aproc_namereferstoadefinedprocessor. • Amem_namereferstoadefinedmemory. if_statement::=if(expr)section_statement 0|1

8−12 LinkerScriptLanguage section_creation_statement ::=sectionsection_name(section_specs) {>=0} section_specs::=section_spec<,section_spec>>=0 section_spec::=attributes |fill_spec |size=expr |blocksize=expr |overflow=section_name section_statement2 ::=select_section_statement; |group_descr2 |{>=0} group_descr2::=group0|1 (group_specs2) section_statement2 group_specs2::=group_spec2<,group_spec2>>=0 group_spec2::=group_alignment |attributes |load_addr section_setup::=section_setupspace_ref {>=0} section_setup_item ::=vector_table_statement |reserved_range |stack_def; |heap_def;

8.4 ExpressionEvaluation

Onlyconstantexpressionsareallowed,includingsizes,butnotaddresses,ofsectionsinobjectfiles. Allexpressionsareevaluatedwith64−bitprecisionintegerarithmetic.Theresultofanexpressioncanbeabsoluteor relocatable.Asymbolyouassigniscreatedasanabsolutesymbol.

8−13 NiosIIEmbeddedToolsReference

8.5 SemanticsoftheArchitectureDefinition

Keywordsinthearchitecturedefinition architecture extends endiannessbiglittle bus mau width map space id mau align page_size page directionlow_to_highhigh_to_low stack min_size growslow_to_highhigh_to_low align fixed id heap min_size growslow_to_highhigh_to_low align fixed id copytable align copy_unit dest page vector_table vector_size size id_symbol_prefix run_addr template template_symbol vector_prefix fill no_inline copy vector id fillloop reserved start_address run_addr symbol map

8−14 LinkerScriptLanguage

map destbusspace dest_dbits dest_offset size src_dbits src_offset

8.5.1 DefininganArchitecture

Withthekeywordarchitectureyoudefineanarchitectureandassignauniquenametoit.Thenameisusedtorefertoitat otherplacesintheLSLfile: architecturename { definitions }

Ifyouaredefiningmultiplecorearchitecturesthatshowgreatresemblance,youcandefinethecommonfeaturesinaparent corearchitectureandextendthiswithachildcorearchitecturethatcontainsspecificfeatures.Thechildinheritsallfeaturesof theparent.Withthekeywordextendsyoucreateachildcorearchitecture: architecturename_child_archextendsname_parent_arch { definitions }

Acorearchitecturecanhaveanynumberofparameters.Theseareidentifierswhichgetvaluesassignedoninstantiationor extensionofthearchitecture.Youcanusetheminanyexpressionwithinthecorearchitecture.Parameterscanhavedefault values,whichareusedwhenthecorearchitectureisinstantiatedwithlessargumentsthanthereareparametersdefinedforit. Whenyouextendacorearchitectureyoucanpassargumentstotheparentarchitecture.Argumentsareexpressionsthatset thevalueoftheparametersofthesub−architecture. architecturename_child_arch(parm1,parm2=1) extendsname_parent_arch(arguments) { definitions }

8.5.2 DefiningInternalBuses

Withthebuskeywordyoudefineabus(thecombinationofdataandcorrespondingaddressbus).Thebusnameisusedto identifyabusanddoesnotconflictwithotheridentifiers.Busdescriptionsinanarchitecturedefinitionorderivativedefinition defineinternalbuses.Someinternalbusesareusedtocommunicatewiththecomponentsoutsidethecoreorprocessor.Such busesonaprocessorhavephysicalpinsreservedforthenumberofbitsspecifiedwiththewidthstatements. • ThemaufieldspecifiestheMAUsize(MinimumAddressableUnit)ofthedatabus.Thisfieldisrequired. • Thewidthfieldspecifiesthewidth(numberofaddresslines)ofthedatabus.ThedefaultvalueistheMAUsize. • Themapkeywordspecifieshowthisbusmapsontoanotherbus(ifso).Mappingsaredescribedinsection8.5.4,Mappings. busbus_name { mau=8; width=8; map(map_description); }

8.5.3 DefiningAddressSpaces

Withthespacekeywordyoudefinealogicaladdressspace.Thespacenameisusedtoidentifytheaddressspaceanddoes notconflictwithotheridentifiers.

8−15 NiosIIEmbeddedToolsReference

• Theidfielddefineshowtheaddressingspaceisidentifiedinobjectfiles.Ingeneral,eachaddressspacehasauniqueID. ThelinkerlocatessectionswithacertainIDintheaddressspacewiththesameID.Thisfieldisrequired.InIEEEthisIDis specifiedexplicitlyforsectionsandsymbols,ELFsectionsmapbydefaulttotheaddressspacewithID1.Sectionswithone ofthespecialnamesdefinedintheABI(ApplicationBinaryInterface)maymaptodifferentaddressspaces. • ThemaufieldspecifiestheMAUsize(MinimumAddressableUnit)ofthespace.Thisfieldisrequired. • Thealignvaluemustbeapoweroftwo.Thelinkerusesthisvaluetocomputethestartaddresseswhensectionsare concatenated.AnalignvalueofnmeansthatobjectsintheaddressspacehavetobealignedonnMAUs. • Thepage_sizefieldsetsthepagealignmentandpagesizeinMAUsfortheaddressspace.Itmustbeapowerof2.The defaultvalueis1.Ifoneormorepagerangesaresuppliedthesuppliedvalueonlysetsthepagealignment.Theranges specifytheavailablespaceineachpage,asoffsetstothepagestart,whichisalignedatthepagealignment. SeealsothepagekeywordinsubsectionLocatingagroupinsection8.9.2,CreatingandLocatingGroupsofSections. • Withtheoptionaldirectionfieldyoucanspecifyhowallsectionsinthisspaceshouldbelocated.Thiscanbeeitherfrom low_to_highaddresses(thisisthedefault)orfromhigh_to_lowaddresses. • Themapkeywordspecifieshowthisaddressspacemapsontoaninternalbusorontoanotheraddressspace.Mappingsare describedinsection8.5.4,Mappings. Stacksandheaps • Thestackkeyworddefinesastackintheaddressspaceandassignsanametoit.Thearchitecturedefinitionmustcontain atleastonestackdefinition.Eachstackofacorearchitecturemusthaveauniquename.Seealsothestackkeywordin section8.9.3,CreatingorModifyingSpecialSections. Thestackisdescribedintermsofaminimumsize(min_size)andthedirectioninwhichthestackgrows(grows).This canbeeitherfromlow_to_highaddresses(stackgrowsupwards,thisisthedefault)orfromhigh_to_lowaddresses (stackgrowsdownwards).Themin_sizeisrequired. Bydefault,thelinkertriestomaximizethesizeofthestacksandheaps.Afterlocatingallsections,thelargestremaininggap inthespaceisusedcompletelyforthestacksandheaps.Ifyouspecifythekeywordfixed,youcandisablethisso−called ’balloonbehavior’.Thesizeisalsofixedifyouusedastackorheapinthesoftwarelayoutdefinitioninarestrictedway.For examplewhenyouoverrideastackwithanothersizeorselectastackinanorderedgroupwithothersections. TheidkeywordmatchesstackinformationgeneratedbythecompilerwithastacknamespecifiedinLSL.Thisvalue assignedtothiskeywordisstronglyrelatedtothecompiler’soutput,sousersarenotsupposedtochangethisconfiguration. Optionallyyoucanspecifyanalignmentforthestackwiththeargumentalign.Thisalignmentmustbeequalorlargerthan thealignmentthatyouspecifyfortheaddressspaceitself. • Theheapkeyworddefinesaheapintheaddressspaceandassignsanametoit.Thedefinitionofaheapissimilartothe definitionofastack.Seealsotheheapkeywordinsection8.9.3,CreatingorModifyingSpecialSections.

Seesection8.9,SemanticsoftheSectionLayoutDefinition,forinformationoncreatingandplacingstacksections.

Copytables • Thecopytablekeyworddefinesacopytableintheaddressspace.Thecontentofthecopytableiscreatedbythelinker andcontainsthestartaddressandsizeofallsectionsthatshouldbeinitializedbythestartupcode.Youmustdefineexactly onecopytableinoneoftheaddressspaces(foracore). Optionallyyoucanspecifyanalignmentforthecopytablewiththeargumentalign.Thisalignmentmustbeequalorlarger thanthealignmentthatyouspecifyfortheaddressspaceitself.Ifsmaller,thealignmentfortheaddressspaceisused. Thecopy_unitargumentspecifiesthesizeinMAUsofinformationchunksthatarecopied.Ifyoudonotspecifythecopy unit,theMAUsizeoftheaddressspaceitselfisused. Thedestargumentspecifiesthedestinationaddressspacethatthecodeusesforthecopytable.Thelinkerusesthis informationtogeneratethecorrectaddressesinthecopytable.Thememoryintowherethesectionsmustbecopiedat run−time,mustbeaccessiblefromthisdestinationspace. Sectionsgeneratedforthecopytablemaygetapagerestrictionwiththeaddressspace’spagesize,byaddingthepage argument.

8−16 LinkerScriptLanguage

Vectortable • Thevector_tablekeyworddefinesavectortablewithnvectorsofsizem(ThisisaninternalLSLobjectsimilartoanLSL group.)Therun_addrargumentspecifiesthelocationofthefirstvector(id=0).Thiscanbeasimpleaddressoranoffsetin memory(seethedescriptionoftherun−timeaddressinsubsectionLocatingagroupinsection8.9.2,CreatingandLocating GroupsofSections).Avectortabledefinessymbols_lc_ub_fooand_lc_ue_foopointingtostartandendofthetable. vector_table"vtable"(vector_size=m,size=n,run_addr=x,...)

Seethefollowingexampleofavectortabledefinition: vector_table"vtable"(vector_size=4,size=256,run_addr=0, template=".text.vector_template", template_symbol="_lc_vector_target", vector_prefix="_vector_", id_symbol_prefix="foo", no_inline, /*default:empty,or*/ fill="foo",/*or*/ fill=[1,2,3,4],/*or*/ fill=loop) { vector(id=0,fill="_START"); vector(id=12,fill=[0xab,0x21,0x32,0x43]); vector(id=[1..11],fill=[0]); vector(id=[18..23],fill=loop); }

Thetemplateargumentdefinesthenameofthesectionthatholdsthecodetojumptoahandlerfunctionfromthevector table.Thistemplatesectiondoesnotgetlocatedandisremovedwhenthelocatephaseiscompleted.Thisargumentis required. Thetemplate_symbolargumentisthesymbolreferenceinthetemplatesectionthatmustbereplacedbytheaddressof thehandlerfunction.Thissymbolnameshouldstartwiththelinkerprefixforthesymboltobeignoredinthelinkphase.This argumentisrequired. Thevector_prefixargumentdefinesthenamesofvectorsections:thesectionforavectorwithidvector_idis $(vector_prefix)$(vector_id).VectorsdefinedinCorassemblysourcefilesthatshouldbeincludedinthevectortablemust havethecorrectsymbolname.ThecompilerusestheprefixthatisdefinedinthedefaultLSLfile(s);ifthisattributeis changed,thevectorsdeclaredinCsourcefilesarenotincludedinthevectortable.Whenavectorsuppliedinanobjectfile hasexactlyonerelocation,thelinkerwillassumeitisabranchtoahandlerfunction,andcanberemovedwhenthehandler isinlinedinthevectortable.Otherwise,noinliningisdone.Thisargumentisrequired. Withtheoptionalno_inlineargumentthevectorshandlersarenotinlinedinthevectortable. WiththeoptionalcopyargumentaROMcopyofthevectortableismadeandthevectortableiscopiedtoRAMatstartup. Withtheoptionalid_symbol_prefixargumentyoucansetaninternalstringrepresentingasymbolnameprefixthatmay befoundonsymbolsinvectorhandlercode.Whenthelinkerdetectssuchasymbolinahandler,thesymbolisassignedthe vectornumber.Ifthesymbolwasalreadyassignedavectornumber,awarningisissued. Thefillargumentsetsthedefaultcontentsofvectors.Ifnothingisspecifiedforavector,thissettingisused.Seebelow. Whennodefaultisprovided,emptyvectorsmaybeusedtolocatelargevectorhandlersandothersections.Onlyonefill argumentisallowed. Thevectorfielddefinesthecontentofvectorwiththenumberspecifiedbyid.Ifarangeisspecifiedforid([p..q,s..t])all vectorsintheranges(inclusive)aredefinedthesameway. Withfill=symbol_name,thevectormustjumptothissymbol.Ifthesectioninwhichthesymbolisdefinedfitsinthevector table(sizemaybe>m),locatethesectionatthelocationofthevector.Otherwise,insertcodetojumptothesymbol’svalue. Atemplatehandlersectionname+symbolnameforthetargetcodemustbesuppliedintheLSLfile. fill=[value(s)],fillsthevectorwiththespecifiedMAUvalues. Withfill=loopthevectorjumpstoitself.Withtheoptional[offset]youcanspecifyanoffsetfromthevectortableentry.

8−17 NiosIIEmbeddedToolsReference

Reservedaddressranges • Thereservedkeywordspecifiestoreserveapartofanaddressspaceevenifnotalloftherangeiscoveredbymemory. Seealsothereservedkeywordinsection8.9.3,CreatingorModifyingSpecialSections. Startaddress • Thestart_addresskeywordspecifiesthestartaddressforthepositionwheretheCstartupcodeislocated.Whena processorisreset,itinitializesitsprogramcountertoacertainstartaddress,sometimescalledtheresetvector.Inthe architecturedefinition,youmustspecifythisstartaddressinthecorrectaddressspaceincombinationwiththenameofthe labelintheapplicationcodewhichmustbelocatedhere. Therun_addrargumentspecifiesthestartaddress(resetvector).Ifthecorestartsexecutingusinganentryfromavector table,anddirectlyjumpstothestartlabel,youshouldomitthisargument. Thesymbolargumentspecifiesthenameofthelabelintheapplicationcodethatshouldbelocatedatthespecifiedstart address.Thesymbolargumentisrequired.Thelinkerwillresolvethestartsymbolanduseitsvalueafterlocatingforthe startaddressfieldinIEEE−695filesandIntelHexfiles.Ifyoualsospecifiedtherun_addrargument,thestartsymbol (label)mustpointtoasection.Thelinkerlocatesthissectionsuchthatthestartsymbolendsuponthestartaddress. spacespace_name { id=1; mau=8; align=8; page_size=1; stackname(min_size=1k,grows=low_to_high); reservedstart_address..end_address; start_address(run_addr=0x0000, symbol="start_label") map(map_description); }

8.5.4 Mappings

Youcanuseamappingwhenyoudefineaspace,busormemory.Withthemapfieldyouspecifyhowaddressesfromthe source(space,busormemory)aretranslatedtoaddressesofadestination(space,bus).Thefollowingmappingsarepossible: • space=>space • space=>bus • bus=>bus • memory=>bus Withamappingyouspecifyarangeofsourceaddressesyouwanttomap(specifiedbyasourceoffsetandasize),the destinationtowhichyouwanttomapthem(abusoranotheraddressspace),andtheoffsetaddressinthedestination. • Thedestargumentspecifiesthedestination.Thiscanbeabusoranotheraddressspace(onlyforaspacetospace mapping).Thisargumentisrequired. • Thesrc_offsetargumentspecifiestheoffsetofthesourceaddresses.Incombinationwithsize,thisspecifiestherangeof addressthataremapped.Bydefaultthesourceoffsetis0x0000. • Thesizeargumentspecifiesthenumberofaddressesthataremapped.Thisargumentisrequired. • Thedest_offsetargumentspecifiesthepositioninthedestinationtowhichthespecifiedrangeofaddressesismapped. Bydefaultthedestinationoffsetis0x0000. Ifyouaremappingabustoanotherbus,thenumberofdatalinesofeachbusmaydiffer.Inthiscaseyouhavetospecifya rangeofsourcedatalinesyouwanttomap(src_dbits=begin..end)andtherangeofdestinationdatalinesyouwantto mapthemto(dest_dbits=first..last). • Thesrc_dbitsargumentspecifiesarangeofdatalinesofthesourcebus.Bydefaultalldatalinesaremapped. • Thedest_dbitsargumentspecifiesarangeofdatalinesofthedestinationbus.Bydefault,alldatalinesfromthesource busaremappedonthedatalinesofthedestinationbus(startingwithline0).

8−18 LinkerScriptLanguage

Fromspacetospace Ifyoumapanaddressspacetoanotheraddressspace(nesting),youcandothisbymappingthesubspacetothecontaining largerspace.Inthisexampleasmallspaceof64kismappedonalargespaceof16M. spacesmall { id=2; mau=4; map(src_offset=0,dest_offset=0, dest=space:large,size=64k); }

Fromspacetobus Allspacesthatarenotmappedtoanotherspacemustmaptoabusinthearchitecture: spacelarge { id=1; mau=4; map(src_offset=0,dest_offset=0, dest=bus:bus_name,size=16M); }

Frombustobus Thenextexamplemapsanexternalbuscallede_bustoaninternalbuscalledi_bus.Thisinternalbusresidesonacore calledmycore.Thesourcebushas16datalineswhereasthedestinationbushasonly8datalines.Therefore,thekeywords src_dbitsanddest_dbitsspecifywhichsourcedatalinesaremappedonwhichdestinationdatalines. architecturemycore { busi_bus { mau=4; }

spacei_space { map(dest=bus:i_bus,size=256); } } buse_bus { mau=16; width=16; map(dest=bus:mycore:i_bus,src_dbits=0..7,dest_dbits=0..7) }

Itisnotpossibletomapaninternalbustoanexternalbus.

8−19 NiosIIEmbeddedToolsReference

8.6 SemanticsoftheDerivativeDefinition

Keywordsinthederivativedefinition derivative extends core architecture bus mau width map memory typereservedromramnvram mau size speed fill map section_layout section_setup map destbusspace dest_dbits dest_offset size src_dbits src_offset

8.6.1 DefiningaDerivative

Withthekeywordderivativeyoudefineaderivativeandassignauniquenametoit.Thenameisusedtorefertoitatother placesintheLSLfile: derivativename { definitions }

Ifyouaredefiningmultiplederivativesthatshowgreatresemblance,youcandefinethecommonfeaturesinaparentderivative andextendthiswithachildderivativethatcontainsspecificfeatures.Thechildinheritsallfeaturesoftheparent(coresand memories).Withthekeywordextendsyoucreateachildderivative: derivativename_child_derivextendsname_parent_deriv { definitions }

Aswithacorearchitecture,aderivativecanhaveanynumberofparameters.Theseareidentifierswhichgetvaluesassigned oninstantiationorextensionofthederivative.Youcanusetheminanyexpressionwithinthederivativedefinition. derivativename_child_deriv(parm1,parm2=1) extendsname_parent_derivh(arguments) { definitions }

8.6.2 InstantiatingCoreArchitectures

Withthekeywordcoreyouinstantiateacorearchitectureinaderivative.

8−20 LinkerScriptLanguage

• Withthekeywordarchitectureyoutellthelinkerthatthegivencorehasacertainarchitecture.Thearchitecturename referstoanexistingarchitecturedefinitioninthesameLSLfile. Forexample,ifyouhavetwocores(calledmycore_1andmycore_2)thathavethesamearchitecture(called mycorearch),youmustinstantiatebothcoresasfollows: coremycore_1 { architecture=mycorearch; } coremycore_2 { architecture=mycorearch; }

Ifthearchitecturedefinitionhasparametersyoumustspecifytheargumentsthatcorrespondwiththeparameters.For examplemycorearch1expectstwoparameterswhichareusedinthearchitecturedefinition: coremycore { architecture=mycorearch1(1,2); }

8.6.3 DefiningInternalMemoryandBuses

Withthememorykeywordyoudefinephysicalmemorythatispresentonthetargetboard.Thememorynameisusedtoidentify thememoryanddoesnotconflictwithotheridentifiers.Itiscommontodefineinternalmemory(on−chip)inthederivative definition.Externalmemory(off−chipmemory)isusuallydefinedintheboardspecification(Seesection8.7.3,DefiningExternal MemoryandBuses). • Thetypefieldspecifiesamemorytype: − rom: readonlymemory−itcanonlybewrittenatload−time − ram: randomaccessvolatilewritablememory−writingatrun−timeispossible whilewritingatload−timehasnousesincethedataisnotretainedafter apower−down − nvram: nonvolatileram−writingispossiblebothatload−timeandrun−time Theoptionalreservedqualifierbeforethememorytype,tellsthelinkernottolocateanysectioninthememorybydefault. Youcanlocatesectionsinsuchmemoriesusinganabsoluteaddressorrangerestriction(seesubsectionLocatingagroup insection8.9.2,CreatingandLocatingGroupsofSections). • ThemaufieldspecifiestheMAUsize(MinimumAddressableUnit)ofthememory.Thisfieldisrequired. • ThesizefieldspecifiesthesizeinMAUofthememory.Thisfieldisrequired. • Thespeedfieldspecifiesasymbolicspeedforthememory(1..4):1isthefastest,4theslowest.Thelinkerusestherelative speedofthememoriesinsuchaway,thatoptimalspeedisachieved.Thedefaultspeedis1. • Themapfieldspecifieshowthismemorymapsontoan(internal)bus.Mappingsaredescribedinsection8.5.4,Mappings. • Theoptionalfillfieldcontainsabitpatternthatthelinkerwritestoallmemoryaddressesthatremainunoccupiedduring thelocateprocess.Theresultoftheexpression,orlistofexpressions,isusedasvaluestowritetomemory,eachinMAU. memorymem_name { type=rom; mau=8; fill=0xaa; size=64k; speed=2; map(map_description); }

Withthebuskeywordyoudefineabusinaderivativedefinition.Busesaredescribedinsection8.5.2,DefiningInternalBuses.

8−21 NiosIIEmbeddedToolsReference

8.7 SemanticsoftheBoardSpecification

Keywordsintheboardspecification processor derivative bus mau width map memory typereservedromramnvram mau size speed fill map map destbusspace dest_dbits dest_offset size src_dbits src_offset

8.7.1 DefiningaProcessor

Ifyouhaveatargetboardwithmultipleprocessorsthathavethesamederivative,youneedtoinstantiateeachindividual processorinaprocessordefinition.Thisinformationtellsthelinkerwhichprocessorhaswhichderivativeandenablesthelinker todistinguishbetweenthepresentprocessors.

Ifyouuseprocessorsthatallhaveauniquederivative,youmayomittheprocessordefinitions.Inthiscasethelinker assumesthatforeachderivativedefinitionintheLSLfilethereisoneprocessor.Thelinkerusesthederivativenamealso fortheprocessor. Withthekeywordprocessoryoudefineaprocessor.Youcanfreelychoosetheprocessorname.Thenameisusedtoreferto itatotherplacesintheLSLfile: processorproc_name { processordefinition }

8.7.2 InstantiatingDerivatives

Withthekeywordderivativeyoutellthelinkerthatthegivenprocessorhasacertainderivative.Thederivativenamerefers toanexistingderivativedefinitioninthesameLSLfile. Forexamples,ifyouhavetwoprocessorsonyourtargetboard(calledmyproc_1andmyproc_2)thathavethesamederivative (calledmyderiv),youmustinstantiatebothprocessorsasfollows: processormyproc_1 { derivative=myderiv; } processormyproc_2 { derivative=myderiv; }

8−22 LinkerScriptLanguage

Ifthederivativedefinitionhasparametersyoumustspecifytheargumentsthatcorrespondwiththeparameters.Forexample myderiv1expectstwoparameterswhichareusedinthederivativedefinition: processormyproc { derivative=myderiv1(2,4); }

8.7.3 DefiningExternalMemoryandBuses

Itiscommontodefineexternalmemory(off−chip)andexternalbusesattheglobalscope(outsideanyenclosingdefinition). Internalmemory(on−chipmemory)isusuallydefinedinthescopeofaderivativedefinition. Withthekeywordmemoryyoudefinephysicalmemorythatispresentonthetargetboard.Thememorynameisusedtoidentify thememoryanddoesnotconflictwithotheridentifiers.IfyoudefinememorypartsintheLSLfile,onlythememorydefinedin thesepartsisusedforplacingsections. IfnoexternalmemoryisdefinedintheLSLfileandifthelinkeroptiontoallocatememoryondemandissetthenthelinkerwill assumethatallvirtualaddressesaremappedonphysicalmemory.Youcanoverridethisbehaviorbyspecifyingoneormore memorydefinitions. memorymem_name { type=rom; mau=8; fill=0xaa; size=64k; speed=2; map(map_description); }

Foradescriptionofthekeywords,seesection8.6.3,DefiningInternalMemoryandBuses. Withthekeywordbusyoudefineabus(thecombinationofdataandcorrespondingaddressbus).Thebusnameisusedto identifyabusanddoesnotconflictwithotheridentifiers.Busdescriptionsattheglobalscope(outsideanydefinition)define externalbuses.Thesearebusesthatarepresentonthetargetboard. busbus_name { mau=8; width=8; map(map_description); }

Foradescriptionofthekeywords,seesection8.5.2,DefiningInternalBuses. Youcanconnectoff−chipmemorytoanyderivative:youneedtomaptheoff−chipmemorytoabusandmapthatbusonthe internalbusofthederivativeyouwanttoconnectitto.

8−23 NiosIIEmbeddedToolsReference

8.8 SemanticsoftheSectionSetupDefinition

Keywordsinthesectionsetupdefinition section_setup stack min_size growslow_to_highhigh_to_low align fixed id heap min_size growslow_to_highhigh_to_low align fixed id vector_table vector_size size id_symbol_prefix run_addr template template_symbol vector_prefix fill no_inline copy vector id fillloop reserved

8.8.1 SettingupaSection

Withthekeywordsection_setupyoucandefinestacks,heaps,vectortables,and/orreservedaddressrangesoutsidetheir addressspacedefinition. section_setup::my_space { vectortablestatements reservedaddressrange stackdefinition heapdefinition }

SeethesubsectionsStacksandheaps,VectortableandReservedaddressrangesinsection8.5.3,DefiningAddress Spaces,fordetailsonthekeywordsstack,heap,vector_tableandreserved.

8−24 LinkerScriptLanguage

8.9 SemanticsoftheSectionLayoutDefinition

Keywordsinthesectionlayoutdefinition section_layout directionlow_to_highhigh_to_low group align attributes+−rwxbis copy nocopy fill ordered contiguous clustered overlay allow_cross_references load_addr mem run_addr mem page page_size priority select stack size heap size reserved size attributesrwx fill alloc_allowedabsoluteranged copytable section size blocksize attributesrwx fill overflow if else

8.9.1 DefiningaSectionLayout

Withthekeywordsection_layoutyoudefineasectionlayoutforexactlyoneaddressspace.Inthesectionlayoutyoucan specifyhowinputsectionsareplacedintheaddressspace,relativetoeachother,andwhattheabsoluterunandload addressesofeachsectionwillbe. Youcandefineoneormoresectiondefinitions.Eachsectiondefinitionarrangesthesectionsinoneaddressspace.Youcan precedetheaddressspacenamewithaprocessornameand/orcorename,separatedbycolons.Youcanomittheprocessor nameand/orthecorenameifonlyoneprocessorisdefinedand/oronlyonecoreispresentintheprocessor.Areferencetoa spaceintheonlycoreoftheonlyprocessorinthesystemwouldlooklike"::my_space".Areferencetoaspaceoftheonly coreonaspecificprocessorinthesystemcouldbe"my_chip::my_space".Thenextexampleshowsasectiondefinitionfor sectionsinthemy_spaceaddressspaceoftheprocessorcalledmy_chip:

8−25 NiosIIEmbeddedToolsReference

section_layoutmy_chip::my_space(locate_direction) { sectionstatements }

Withtheoptionalkeyworddirectionyouspecifywhetherthelinkerstartslocatingsectionsfromlow_to_high(default)or fromhigh_to_low.Inthesecondcasethelinkerstartslocatingsectionsatthehighestaddressesintheaddressspacebut preservestheorderofsectionswhennecessary(oneprocessorandcoreinthisexample). section_layout::my_space(direction=high_to_low) { sectionstatements }

Ifyoudonotexplicitlytellthelinkerhowtolocateasection,thelinkerdecidesonthebasisofthesectionattributesinthe objectfileandtheinformationinthearchitecturedefinitionandmemorypartswheretolocatethesection.

8.9.2 CreatingandLocatingGroupsofSections

Sectionsarelocatedpergroup.Agroupcancontainoneormore(setsof)inputsectionsaswellasothergroups.Pergroupyou canassignamutualordertothesetsofsectionsandlocatethemintoaspecificmemorypart. group(group_specifications) { section_statements }

Withthesection_statementsyougenerallyselectsetsofsectionstoformthegroup.ThisisdescribedinsubsectionSelecting sectionsforagroup. Insteadofselectingsections,youcanalsomodifyspecialsectionslikestackandheaporcreateareservedsection.Thisis describedinsection8.9.3,CreatingorModifyingSpecialSections. Withthegroup_specificationsyouactuallylocatethesectionsinthegroup.ThisisdescribedinsubsectionLocatingagroup.

Selectingsectionsforagroup Withtheselectkeywordyoucanselectoneormoresectionsforthegroup.Youcanselectasectionbynameorbyattributes. Ifyouselectasectionbyname,youcanuseawildcardpattern: "*" matcheswithallsectionnames "?" matcheswithasinglecharacterinthesectionname "\" takesthenextcharacterliterally "[abc]" matcheswithasingle’a’,’b’or’c’character "[a−z]" matcheswithanysinglecharacterintherange’a’to’z’ group(...) { select"mysection"; select"*"; }

Thefirstselectstatementselectsthesectionwiththename"mysection".Thesecondselectstatementselectsallsections thatwerenotselectedyet. Asectionisselectedbythefirstselectstatementthatmatches,intheunionofallsectionlayoutsfortheaddressspace. GlobalsectionlayoutsareprocessedintheorderinwhichtheyappearintheLSLfile.Internalcorearchitecturesectionlayouts alwaystakeprecedenceoverglobalsectionlayouts. • Theattributesfieldselectsallsectionsthatcarry(ordonotcarry)thegivenattribute.With+attributeyouselectsections thathavethespecifiedattributeset.With−attributeyouselectsectionsthatdonothavethespecifiedattributeset.Youcan specifyoneormoreofthefollowingattributes: − r readablesections − w writablesections

8−26 LinkerScriptLanguage

− x executablesections − i initializedsections − b sectionsthatshouldbeclearedatprogramstartup − s scratchsections(notclearedandnotinitialized) Toselectallread−onlysections: group(...) { select(attributes=+r−w); }

Keepinmindthatallsectionselectionsarerestrictedtotheaddressspaceofthesectionlayoutinwhichthisgroup definitionoccurs.

• Withtheref_treefieldyoucanselectagroupofrelatedsections.Therelationbetweensectionsisoftenexpressedby meansofreferences.Byselectingjustthe’root’oftree,thecompletetreeisselected.Thisisforexampleusefultolocatea groupofrelatedsectionsinspecialmemory(e.g.fastmemory).The(referenced)sectionsmustmeetthefollowing conditionsinordertobeselected: 1. Thesectionsarewithinthesectionlayout’saddressspace 2. Thesectionsmatchthespecifiedattributes 3. Thesectionshavenoabsoluterestriction(asisthecaseforallwildcardselections) Forexample,toselectthecodesectionsreferencedfromfoo1: grouprefgrp(ordered,contiguous,run_addr=mem:ext_c) { selectref_tree"foo1"(attributes=+x); }

Ifsectionfoo1referencesfoo2andfoo2referencesfoo3,thenallthesesectionsareselectedbytheselectionshown above.

Locatingagroup groupgroup_name(group_specifications) { section_statements }

Withthegroup_specificationsyouactuallydefinehowthelinkermustlocatethegroup.Youcanroughlydefinethreethings:1) assignpropertiestothegrouplikealignmentandread/writeattributes,2)definethemutualorderintheaddressspacefor sectionsinthegroupand3)restrictthepossibleaddressesforthesectionsinagroup. Thelinkercreateslabelsthatallowyoutorefertothebeginandendaddressofagroupfromwithintheapplicationsoftware. Labels_lc_gb_group_nameand_lc_ge_group_namemarkthebeginandendofthegrouprespectively,wherethebeginis thelowestaddressusedwithinthisgroupandtheendisthehighestaddressused.Noticethatagroupnotnecessarilyoccupies allmemorybetweenbeginandendaddress.Thegivenlabelreferstowherethesectionislocatedatrun−time(versus load−time). 1. Assignpropertiestothegrouplikealignmentandread/writeattributes. Thesepropertiesareassignedtoallsectionsinthegroup(andsubgroups)andoverridetheattributesoftheinputsections. • Thealignfieldtellsthelinkertoalignallsectionsinthegroupandthegroupasawholeaccordingtothealignvalue.By defaultthelinkerusesthelargestalignmentconstraintofeithertheinputsectionsorthealignmentoftheaddressspace. • Theattributesfieldtellsthelinkertoassignoneormoreattributestoallsectionsinthegroup.Thisoverrulesthe defaultattributes.Bydefaultthelinkerusestheattributesoftheinputsections.Youcansetther,worrwattributesand youcanswitchbetweenthebandsattributes. • Thecopyfieldtellsthelinkertolocatearead−onlysectioninRAMandgenerateaROMcopyandacopyactioninthe copytable.ThispropertymakesthesectionsinthegroupwritablewhichcausesthelinkertogenerateROMcopiesfor thesections.

8−27 NiosIIEmbeddedToolsReference

• Theeffectofthenocopyfieldistheoppositeofthecopyfield.ItpreventsthelinkerfromgeneratingROMcopiesofthe selectedsections. 2. Definethemutualorderofthesectionsinthegroup. Bydefault,agroupisunrestrictedwhichmeansthatthelinkerhastotalfreedomtoplacethesectionsofthegroupinthe addressspace. • Theorderedkeywordtellsthelinkertolocatethesectionsinthesameorderintheaddressspaceastheyappearinthe group(butnotnecessarilyadjacent). Supposeyouhaveanorderedgroupthatcontainsthesections’A’,’B’and’C’.Bydefaultthelinkerplacesthesections intheaddressspacelike’A’−’B’−’C’,wheresection’A’getsthelowestpossibleaddress.With direction=high_to_lowinthesection_layoutspaceproperties,thelinkerplacesthesectionsintheaddress spacelike’C’−’B’−’A’,wheresection’A’getsthehighestpossibleaddress. • Thecontiguouskeywordtellsthelinkertolocatethesectionsinthegroupinasingleaddressrange.Withina contiguousgrouptheinputsectionsarelocatedinarbitraryorder,howeverthegroupoccupiesonecontigousrangeof memory.Duetoalignmentofsectionstherecanbe’alignmentgaps’betweenthesections. Whenyoudefineagroupthatisbothorderedandcontiguous,thisiscalledasequentialgroup.Inasequentialgroup thelinkerplacessectionsinthesameorderintheaddressspaceastheyappearinthegroupanditoccupiesa contiguousrangeofmemory. • Theclusteredkeywordtellsthelinkertolocatethesectionsinthegroupinanumberofcontiguousblocks.Ittriesto keepthenumberoftheseblockstoaminimum.Ifenoughmemoryisavailable,thegroupwillbelocatedasifitwas specifiedascontiguous.Otherwise,itgetssplitintotwoormoreblocks. Ifacontiguousorclusteredgroupcontainsalignmentgaps,thelinkercanlocatesectionsthatarenotpartofthegroupin thesegaps.Topreventthis,youcanusethefillkeyword.IfthegroupislocatedinRAM,thegapsaretreatedas reserved(scratch)space.IfthegroupislocatedinROM,thealignmentgapsarefilledwithzerosbydefault.Youcan howeverchangethefillpatternbyspecifyingabitpattern.Theresultoftheexpression,orlistofexpressions,isusedas valuestowritetomemory,eachinMAU. • Theoverlaykeywordtellsthelinkertooverlaythesectionsinthegroup.Thelinkerplacesallsectionsintheaddress spaceusingacontiguousrangeofaddresses.(Thusanoverlaygroupisautomaticallyalsoacontiguousgroup.)To overlaythesections,allsectionsintheoverlaygroupsharethesamerun−timeaddress. Foreachinputsectionwithintheoverlaythelinkerautomaticallydefinestwosymbols.Thesymbol _lc_cb_section_nameisdefinedastheload−timestartaddressofthesection.Thesymbol_lc_ce_section_name isdefinedastheload−timeendaddressofthesection.C(orassembly)codemaybeusedtocopytheoverlaidsections. Ifsectionsintheoverlaygroupcontainreferencesbetweengroups,thelinkerreportsanerror.Thekeyword allow_cross_referencestellsthelinkertoacceptcross−references.Normally,itdoesnotmakesensetohave referencesbetweensectionsthatareoverlaid. groupovl(overlay) { groupa { select"my_ovl_p1"; select"my_ovl_p2"; } groupb { select"my_ovl_q1"; } }

Itmaybepossiblethatoneofthesectionsintheoverlaygroupalreadyhasbeendefinedinanothergroupwhereit receivedaload−timeaddress.Inthiscasethelinkerdoesnotoverrulethisload−timeaddressandexcludesthesection fromtheoverlaygroup.

8−28 LinkerScriptLanguage

3. Restrictthepossibleaddressesforthesectionsinagroup. Theload−timeaddressspecifieswherethegroup’selementsareloadedinmemoryatdownloadtime.Therun−timeaddress specifieswheresectionsarelocatedatrun−time,thatiswhentheprogramisexecuting.Ifyoudonotexplicitlyrestrictthe addressintheLSLfile,thelinkerassignsaddressestothesectionsbasedontherestrictionsrelativetoothersectionsinthe LSLfileandsectionalignments.Theprogramisresponsibleforcopyingoverlaysectionsatappropriatemomentfromits load−timelocationtoitsrun−timelocation(thisistypicallydonebythestartupcode). • Therun_addrkeyworddefinestherun−timeaddress.Iftherun−timelocationofagroupissetexplicitly,thegivenorder betweengroupsspecifywhethertherun−timeaddresspropagatestotheparentgroupornot.Thelocationofthesections agroupcanberestrictedeithertoasingleabsoluteaddress,ortoanumberofaddressranges(notincludingtheend address).Withanexpressionyoucanspecifythatthegroupshouldbelocatedattheabsoluteaddressspecifiedbythe expression: group(run_addr=0xa00f0000)

Youcanusethe’[offset]’varianttolocatethegroupatthegivenabsoluteoffsetinmemory: group(run_addr=mem:A[0x1000])

Arangecanbeanabsolutespaceaddressrange,writtenas[expr..expr],acompletememorydevice,written asmem:mem_name,oramemoryaddressrange, mem:mem_name[expr..expr] group(run_addr=mem:my_dram)

Youcanusethe’|’tospecifyanaddressrangeofmorethanonephysicalmemorydevice: group(run_addr=mem:A|mem:B) • Theload_addrkeywordchangesthemeaningofthesectionselectioninthegroup:thelinkerselectstheload−time ROMcopyofthenamedsection(s)insteadoftheregularsections.Justlikerun_addryoucanspecifyanabsolute addressoranaddressrange. Theload_addrkeyworditself(withoutanassignment)specifiesthatthegroup’spositionintheLSLfiledefinesits load−timeaddress. group(load_addr) select"mydata";//selectROMcopyofmydata:"[mydata]"

Theload−timeandrun−timeaddressesofagroupcannotbesetatthesametime.Iftheload−timepropertyissetfora group,thegroup(only)restrictsthepositioningatload−timeofthegroup’ssections.Itisnotpossibletosettheaddressofa groupthathasanot−unrestrictedparentgroup. Thepropertiesoftheload−timeandrun−timestartaddressare: • Atrun−time,beforeusinganelementinanoverlaygroup,theapplicationcopiesthesectionsfromtheirloadlocationto theirrun−timelocation,butonlyifthesetwoaddressesaredifferent.Fornon−overlaysectionsthishappensatprogram start−up. • Thestartaddressescannotbesettoabsolutevaluesforunrestrictedgroups. • Fornon−overlaygroupsthatdonothaveanoverlayparent,theload−timestartaddressequalstherun−timestart address. • Foranygroup,iftherun−timestartaddressisnotset,thelinkerselectsanappropriateaddress. • Ifanorderedgrouporsequentialgrouphasanabsoluteaddressandcontainssectionsthathaveseparatepage restrictions(notdefinedinLSL),allthosesectionsarelocatedinasinglepage.Inothercases,forexamplewhenan unrestrictedgrouphasanaddressrangeassignedtoit,thepagedsectionsmaybelocatedindifferentpages. Foroverlays,thelinkerreservesmemoryattherun−timestartaddressaslargeasthelargestelementintheoverlaygroup. • Thepagekeywordtellsthelinkertoplacethegroupinonepage.Insteadofspecifyingarun−timeaddress,youcan specifyapageandoptionalapagenumber.Pagenumbersstartfromzero.Ifyouomitthepagenumber,thelinker choosesapage. Thepagekeywordreferstopagesintheaddressspaceasdefinedinthearchitecturedefinition. • Withthepage_sizekeywordyoucanoverridethepagealignmentandsizesetontheaddressspace.Whenyousetthe pagesizetozero,thelinkerremovessimple(autogenerated)pagerestrictionsfromtheselectedsections.Seealsothe page_sizekeywordinsection8.5.3,DefiningAddressSpaces.

8−29 NiosIIEmbeddedToolsReference

group(page,...) group(page=3,...) • Withtheprioritykeywordyoucanchangetheorderinwhichsectionsarelocated.Thisisusefulwhensomesections areconsideredimportantforgoodperformanceoftheapplicationandasmallamountoffastmemoryisavailable.The valueisanumberforwhichthedefaultis1,sohigherprioritiesstartat2.Sectionswithahigherpriorityarelocated beforesectionswithalowerpriority,unlesstheirrelativelocatepriorityisalreadydeterminedbyotherrestrictionslike run_addrandpage. group(priority=2) { select"importantcode1"; select"importantcode2"; }

8.9.3 CreatingorModifyingSpecialSections

Insteadofselectingsections,youcanalsocreateareservedsectionoranoutputsectionormodifyspecialsectionslikeastack oraheap.Becauseyoucannotdefinethesesectionsintheinputfiles,youmustusethelinkertocreatethem.

Stack • Thekeywordstacktellsthelinkertoreservememoryforthestack.Thenameforthestacksectionreferstothestackas definedinthearchitecturedefinition.Ifnonamewasspecifiedinthearchitecturedefinition,thedefaultnameisstack. Withthekeywordsizeyoucanspecifythesizeforthestack.Ifthesizeisnotspecified,thelinkerusesthesizegivenby themin_sizeargumentasdefinedforthestackinthearchitecturedefinition.Normallythelinkerautomaticallytriesto maximizethesize,unlessyouspecifiedthekeywordfixed. group(...) { stack"mystack"(size=2k); }

Thelinkercreatestwolabelstomarkthebeginandendofthestack,_lc_ub_stack_nameforthebeginofthestackand _lc_ue_stack_namefortheendofthestack.Thelinkerallocatesspaceforthestackwhenthereisareferencetoeitherof thelabels. Seealsothestackkeywordinsection8.5.3,DefiningAddressSpaces.

Heap • Thekeywordheaptellsthelinkertoreserveadynamicmemoryrangeforthemalloc()function.Optionallyyoucanassign anametotheheapsection.Withthekeywordsizeyoucanchangethesizefortheheap.Ifthesizeisnotspecified,the linkerusesthesizegivenbythemin_sizeargumentasdefinedfortheheapinthearchitecturedefinition.Normallythe linkerautomaticallytriestomaximizethesize,unlessyouspecifiedthekeywordfixed. group(...) { heap"myheap"(size=2k); }

Thelinkercreatestwolabelstomarkthebeginandendoftheheap,_lc_ub_heap_nameforthebeginoftheheapand _lc_ue_heap_namefortheendoftheheap.Thelinkerallocatesspacefortheheapwhenareferencetoeitherofthe sectionlabelsexistsinoneoftheinputobjectfiles.

Reservedsection • Thekeywordreservedtellsthelinkertocreateanareaorsectionofagivensize.Thelinkerwillnotlocateanyother sectionsinthememoryoccupiedbyareservedsection,withsomeexceptions.Optionallyyoucanassignanametoa reservedsection.Withthekeywordsizeyoucanspecifyasizeforagivenreservedareaorsection. group(...) { reserved"myreserved"(size=2k); }

8−30 LinkerScriptLanguage

Theoptionalfillfieldcontainsabitpatternthatthelinkerwritestoallmemoryaddressesthatremainunoccupiedduring thelocateprocess.Theresultoftheexpression,orlistofexpressions,isusedasvaluestowritetomemory,eachinMAU. ThefirstMAUofthefillpatternisalwaysthefirstMAUinthesection. Bydefault,nosectionscanoverlapwithareservedsection.Withalloc_allowed=absolutesectionsthatarelocatedat anabsoluteaddressduetoanabsolutegrouprestrictioncanoverlapareservedsection.Thesameappliesforreserved sectionswithalloc_allowed=rangedset.Sectionsrestrictedtoafixedaddressrangecanalsooverlapareserved section. Withtheattributesfieldyoucansettheaccesstypeofthereservedsection.Thelinkerlocatesthereservedsectioninits spacewiththerestrictionsthatfollowfromtheusedattributes,r,worxoravalidcombinationofthem.Theallowed attributesareshowninthefollowingtable.Avaluebetween<and>inthetablemeansthisvalueissetautomaticallybythe linker.

PropertiessetinLSL Resultingsectionproperties attributes filled access memory content x yes executable r yes r data r no r scratch rx yes r executable rw yes rw data rw no rw scratch rwx yes rw executable

group(...) { reserved"myreserved"(size=2k, attributes=rw,fill=0xaa); }

Ifyoudonotspecifyanyattributes,thelinkerwillreservethegivennumberofmaus,nomatterwhattypeofmemorylies beneath.Ifyoudonotspecifyafillpattern,nosectionisgenerated. Thelinkercreatestwolabelstomarkthebeginandendofthesection,_lc_ub_nameforthestart,and_lc_ue_namefor theendofthereservedsection.

Outputsections • Thekeywordsectiontellsthelinkertoaccumulatesectionsobtainedfromobjectfiles("inputsections")intoanoutput sectionofafixedsizeinthelocatephase.Youcanselecttheinputsectionswithselectstatements.Youcanusegroups insideoutputsections,butyoucanonlysetthealign,attributesandload_addrattributes. Thefillfieldcontainsabitpatternthatthelinkerwritestoallunusedspaceintheoutputsection.Whenallinputsections haveanimage(code/data)youmustspecifyafillpattern.Ifyoudonotspecifyafillpattern,allinputsectionsmustbe scratchsections.Thefillpatternisalignedatthestartoftheoutputsection. Aswithareservedsectionyoucanusetheattributesfieldtosettheaccesstypeoftheoutputsection. group(...) { section"myoutput"(size=4k,attributes=rw,fill=0xaa) { select"myinput1"; select"myinput2"; } }

8−31 NiosIIEmbeddedToolsReference

Theavailableroomforinputsectionsisdeterminedbythesize,blocksizeandoverflowfields.Withthekeywordsize youspecifythefixedsizeoftheoutputsection.Inputsectionsareplacedfromoutputsectionstarttowardshigheraddresses (offsets).Whentheendoftheoutputsectionisreachedandoneormoreinputsectionsarenotyetplaced,anerroris emitted.Ifhowever,theoverflowfieldissettoanotheroutputsection,remainingsectionsarelocatedasiftheywere selectedfortheoverflowoutputsection. group(...) { section"tsk1_data"(size=4k,attributes=rw,fill=0, overflow="overflow_data") { select".data.tsk1.*" } section"tsk2_data"(size=4k,attributes=rw,fill=0, overflow="overflow_data") { select".data.tsk2.*" } section"overflow_data"(size=4k,attributes=rx, fill=0) { } }

Withthekeywordblocksize,thesizeoftheoutputsectionwilladapttothesizeofitscontent.Forexample: groupflash_area(run_addr=0x10000) { section"flash_code"(blocksize=4k,attributes=rx, fill=0) { select"*.flash"; } }

Ifthecontentofthesectionis1mau,thesizewillbe4k,ifthecontentis11k,thesectionwillbe12k,etc.Ifyouusesizein combinationwithblocksize,thesizevalueisusedasdefault(minimal)sizeforthissection.Ifitisomitted,thedefault sizewillbeofblocksize.Itisnotallowedtoomitbothsizeandblocksizefromthesectiondefinition. Thelinkercreatestwolabelstomarkthebeginandendofthesection,_lc_ub_nameforthestart,and_lc_ue_namefor theendoftheoutputsection.

Copytable • Thekeywordcopytabletellsthelinkertoselectasectionthatisusedascopytable.Thecontentofthecopytableis createdbythelinker.Itcontainsthestartaddressandlengthofallsectionsthatshouldbeinitializedbythestartupcode. Thelinkercreatestwolabelstomarkthebeginandendofthesection,_lc_ub_tableforthestart,and_lc_ue_table fortheendofthecopytable.Thelinkergeneratesacopytablewhenareferencetoeitherofthesectionlabelsexistsinone oftheinputobjectfiles.

8.9.4 CreatingSymbols

Youcantellthelinkertocreatesymbolsbeforelocatingbyputtingassignmentsinthesectionlayoutdefinition.Symbolnames arerepresentedbydouble−quotedstrings.Anystringisallowed,butobjectfilesmaynotsupportallcharactersforsymbol names.Youcanusetwodifferentassignmentoperators.Withthesimpleassignmentoperator’=’,thesymboliscreated unconditionally.Withthe’:=’operator,thesymbolisonlycreatedifitalreadyexistsasanundefinedreferenceinanobjectfile. Theexpressionthatrepresentsthevaluetoassigntothesymbolmaycontainreferencestoothersymbols.Ifsuchareferred symbolisaspecialsectionsymbol,creationofthesymbolinthelefthandsideoftheassignmentwillcausecreationofthe specialsection.

8−32 LinkerScriptLanguage

section_layout { "_lc_bs":="_lc_ub_stack"; //whenthesymbol_lc_bsoccursasanundefinedreference //inanobjectfile,thelinkerallocatesspaceforthestack }

8.9.5 ConditionalGroupStatements

Withinagroup,youcanconditionallyselectsectionsorcreatespecialsections. • Withtheifkeywordyoucanspecifyacondition.Thesucceedingsectionstatementisexecutediftheconditionevaluatesto TRUE(1). • Theoptionalelsekeywordisfollowedbyasectionstatementwhichisexecutedincasetheif−conditionevaluatestoFALSE (0). group(...) { if(exists("mysection")) select"mysection"; else reserved"myreserved"(size=2k); }

8−33 NiosIIEmbeddedToolsReference

8−34 9 CERTCSecureCodingStandard

Summary ThischaptercontainsanoverviewoftheCERTCSecureCodingStandard recommendationsandrulesthataresupportedbytheTASKINGVX−toolset.

TheCERTCSecureCodingStandardprovidesrulesandrecommendationsforsecurecodingintheCprogramminglanguage. Thegoaloftheserulesandrecommendationsistoeliminateinsecurecodingpracticesandundefinedbehaviorsthatcanleadto exploitablevulnerabilities.Theapplicationofthesecurecodingstandardwillleadtohigher−qualitysystemsthatarerobustand moreresistanttoattack.

FordetailsseetheCERTCSecureCodingStandardwebsite.ForgeneralinformationaboutCERTsecurecoding,see www.cert.org/secure−coding.

Identifiers Eachruleandrecommendationisgivenauniqueidentifier.Theseidentifiersconsistofthreeparts: • athree−lettermnemonicrepresentingthesectionofthestandard • atwo−digitnumericvalueintherangeof00−99 • theletter"C"indicatesthatthisisaClanguageguideline Thethree−lettermnemonicisusedtogroupsimilarcodingpracticesandtoindicatetowhichcategoryacodingpracticebelongs. Thenumericvalueisusedtogiveeachcodingpracticeauniqueidentifier.Numericvaluesintherangeof00−29arereserved forrecommendations,whilevaluesintherangeof30−99arereservedforrules.

Ccompilerinvocation WiththeCcompileroption−−certyoucanenableoneormorechecksfortheCERTCSecureCodingStandard recommendations/rules.With−−diag=certyoucanseealistoftheavailablechecks,oryoucanuseathree−lettermnemonicto listonlythechecksinaparticularcategory.Forexample,−−diag=prelistsallsupportedchecksinthepreprocessorcategory.

9.1 Preprocessor(PRE)

PRE01−C Useparentheseswithinmacrosaroundparameternames Parenthesizeallparameternamesinmacrodefinitionstoavoidprecedenceproblems. PRE02−C Macroreplacementlistsshouldbeparenthesized Macroreplacementlistsshouldbeparenthesizedtoprotectanylower−precedenceoperatorsfromthe surroundingexpression.Theexamplebelowissyntacticallycorrect,althoughthe!=operatorwas omitted.Enclosingtheconstant−1inparenthesiswillpreventtheincorrectinterpretationandforcea compilererror: #defineEOF−1//shouldbe(−1) intgetchar(void); voidf(void) { if(getchar()EOF)//!=operatoromitted { /*...*/ } }

9−1 NiosIIEmbeddedToolsReference

PRE10−C Wrapmulti−statementmacrosinado−whileloop Whenmultiplestatementsareusedinamacro,enclosetheminado−whilestatement,sothemacro canappearsafelyinsideifclausesorotherplacesthatexpectasinglestatementorastatementblock. Bracesalonewillnotworkinallsituations,asthemacroexpansionistypicallyfollowedbyasemicolon. PRE11−C Donotconcludeasinglestatementmacrodefinitionwithasemicolon Macrodefinitionsconsistingofasinglestatementshouldnotconcludewithasemicolon.Ifrequired,the semicolonshouldbeincludedfollowingthemacroexpansion.Inadvertentlyinsertingasemicoloncan changethecontrolflowoftheprogram.

9.2 DeclarationsandInitialization(DCL)

DCL30−C Declareobjectswithappropriatestoragedurations Thelifetimeofanautomaticobjectendswhenthefunctionreturns,whichmeansthatapointertothe objectbecomesinvalid. DCL31−C Declareidentifiersbeforeusingthem TheISOC90standardallowsimplicittypingofvariablesandfunctions.Becauseimplicitdeclarations leadtolessstringenttypechecking,theycanoftenintroduceunexpectedanderroneousbehavioror evensecurityvulnerabilities.TheISOC99standardrequirestypeidentifiersandforbidsimplicitfunction declarations.Forbackwardscompatibilityreasons,theVX−toolsetCcompilerassumesanimplicit declarationandcontinuestranslationafterissuingawarningmessage(W505orW535). DCL32−C Guaranteethatmutuallyvisibleidentifiersareunique Thecompilerencounteredtwoormoreidentifiersthatareidenticalinthefirst31characters.TheISO C99standardallowsacompilertoignorecharacterspastthefirst31inanidentifier.Twodistinct identifiersthatareidenticalinthefirst31charactersmayleadtoproblemswhenthecodeisportedtoa differentcompiler. DCL35−C Donotinvokeafunctionusingatypethatdoesnotmatchthefunctiondefinition Thiswarningisgeneratedwhenafunctionpointerissettorefertoafunctionofanincompatibletype. Callingthisfunctionthroughthefunctionpointerwillresultinundefinedbehavior.Example: voidmy_function(inta); intmain(void) { int(*new_function)(inta)=my_function; return(*new_function)(10);/*thebehaviorisundefined*/ }

9.3 Expressions(EXP)

EXP01−C Donottakethesizeofapointertodeterminethesizeofthepointed−totype Thesizeoftheobject(s)allocatedbymalloc(),calloc()orrealloc()shouldbeamultipleofthesizeofthe basetypeoftheresultpointer.Therefore,thesizeofexpressionshouldbeappliedtothisbasetype,and nottothepointertype. EXP12−C Donotignorevaluesreturnedbyfunctions Thecompilergivesthiswarningwhentheresultofafunctioncallisignoredatsomeplace,althoughitis notignoredforothercallstothisfunction.Thiswarningwillnotbeissuedwhenthefunctionresultis ignoredforallcalls,orwhentheresultisexplicitlyignoredwitha(void)cast. EXP30−C Donotdependonorderofevaluationbetweensequencepoints Betweentwosequencepoints,anobjectshouldonlybemodifiedonce.Otherwisethebehavioris undefined. EXP32−C Donotaccessavolatileobjectthroughanon−volatilereference Ifanattemptismadetorefertoanobjectdefinedwithavolatile−qualifiedtypethroughuseofanlvalue withnon−volatile−qualifiedtype,thebehaviorisundefined. EXP33−C Donotreferenceuninitializedmemory Uninitializedautomaticvariablesdefaulttowhichevervalueiscurrentlystoredonthestackorinthe registerallocatedforthevariable.Consequently,uninitializedmemorycancauseaprogramtobehavein anunpredictableorunplannedmannerandmayprovideanavenueforattack.

9−2 CERTCSecureCodingStandard

EXP34−C Ensureanullpointerisnotdereferenced Attemptingtodereferenceanullpointerresultsinundefinedbehavior,typicallyabnormalprogram termination. EXP37−C CallfunctionswiththeargumentsintendedbytheAPI Whenafunctionisproperlydeclaredwithfunctionprototypeinformation,anincorrectcallwillbeflagged bythecompiler.Whenthereisnoprototypeinformationavailableatthecall,thecompilercannotcheck thenumberofargumentsandthetypesofthearguments.Thismessageisissuedtowarnaboutthis situation. EXP38−C Donotcalloffsetof()onbit−fieldmembersorinvalidtypes Thebehavioroftheoffsetof()macroisundefinedwhenthememberdesignatorparameterdesignatesa bit−field.

9.4 Integers(INT)

INT30−C Ensurethatunsignedintegeroperationsdonotwrap Aconstantwithanunsignedintegertypeistruncated,resultinginawrap−around. INT34−C Donotshiftanegativenumberofbitsormorebitsthanexistintheoperand Theshiftcountoftheshiftoperationmaybenegativeorgreaterthanorequaltothesizeoftheleft operand.AccordingtotheCstandard,thebehaviorofsuchashiftoperationisundefined.Makesurethe shiftcountisinrangebyaddingappropriaterangechecks. INT35−C Evaluateintegerexpressionsinalargersizebeforecomparingorassigningtothatsize Ifanintegerexpressioniscomparedto,orassignedtoalargerintegersize,thatintegerexpression shouldbeevaluatedinthatlargersizebyexplicitlycastingoneoftheoperands.

9.5 FloatingPoint(FLP)

FLP30−C Donotusefloatingpointvariablesasloopcounters Toavoidproblemswithlimitedprecisionandrounding,floatingpointvariablesshouldnotbeusedas loopcounters. FLP35−C Takegranularityintoaccountwhencomparingfloatingpointvalues FloatingpointarithmeticinCisinexact,sofloatingpointvaluesshouldnotbetestedforexactequalityor inequality. FLP36−C Bewareofprecisionlosswhenconvertingintegraltypestofloatingpoint Conversionfromintegraltypestofloatingpointtypeswithoutsufficientprecisioncanleadtolossof precision.

9.6 Arrays(ARR)

ARR01−C Donotapplythesizeofoperatortoapointerwhentakingthesizeofanarray Afunctionparameterdeclaredasanarray,isconvertedtoapointerbythecompiler.Therefore,the sizeofoperatorappliedtothisparameteryieldsthesizeofapointer,andnotthesizeofanarray. ARR34−C Ensurethatarraytypesinexpressionsarecompatible Usingtwoormoreincompatiblearraysinanexpressionresultsinundefinedbehavior. ARR35−C Donotallowloopstoiteratebeyondtheendofanarray Readingorwritingofdataoutsidetheboundsofanarraymayleadtoincorrectprogrambehavioror executionofarbitrarycode.

9−3 NiosIIEmbeddedToolsReference

9.7 CharactersandStrings(STR)

STR30−C Donotattempttomodifystringliterals Writingtoastringliteralhasundefinedbehavior,asidenticalstringsmaybesharedand/orallocatedin read−onlymemory. STR33−C Sizewidecharacterstringscorrectly Widecharacterstringsmaybeimproperlysizedwhentheyaremistakenfornarrowstringsorfor multi−bytecharacterstrings. STR34−C Castcharacterstounsignedtypesbeforeconvertingtolargerintegersizes Asignedcharacterissign−extendedtoalargersignedintegervalue.Useanexplicitcast,orcastthe valuetoanunsignedtypefirst,toavoidunexpectedsign−extension. STR36−C Donotspecifytheboundofacharacterarrayinitializedwithastringliteral Thecompilerissuesthiswarningwhenthecharacterbufferinitializedbyastringliteraldoesnotprovide enoughroomfortheterminatingnullcharacter.

9.8 MemoryManagement(MEM)

MEM00−C Allocateandfreememoryinthesamemodule,atthesamelevelofabstraction Thecompilerissuesthiswarningwhentheresultofthecalltomalloc(),calloc()orrealloc()isdiscarded, andthereforenotfree()d,resultinginamemoryleak. MEM08−C Userealloc()onlytoresizedynamicallyallocatedarrays Onlyuserealloc()toresizeanarray.Donotuseittotransformanobjecttoanobjectofadifferenttype. MEM30−C Donotaccessfreedmemory Whenmemoryisfreed,itscontentsmayremainintactandaccessiblebecauseitisatthememory manager’sdiscretionwhentoreallocateorrecyclethefreedchunk.Thedataatthefreedlocationmay appearvalid.However,thiscanchangeunexpectedly,leadingtounintendedprogrambehavior.Asa result,itisnecessarytoguaranteethatmemoryisnotwrittentoorreadfromonceitisfreed. MEM31−C Freedynamicallyallocatedmemoryexactlyonce Freeingmemorymultipletimeshassimilarconsequencestoaccessingmemoryafteritisfreed.The underlyingdatastructuresthatmanagetheheapcanbecomecorrupted.Toeliminatedouble−free vulnerabilities,itisnecessarytoguaranteethatdynamicmemoryisfreedexactlyonce. MEM32−C Detectandhandlememoryallocationerrors Theresultofrealloc()isassignedtotheoriginalpointer,withoutcheckingforfailure.Asaresult,the originalblockofmemoryislostwhenrealloc()fails. MEM33−C Usethecorrectsyntaxforflexiblearraymembers UsetheISOC99syntaxforflexiblearraymembersinsteadofanarraymemberofsize1. MEM34−C Onlyfreememoryallocateddynamically Freeingmemorythatisnotallocateddynamicallycanleadtocorruptionoftheheapdatastructures. MEM35−C Allocatesufficientmemoryforanobject Thecompilerissuesthiswarningwhenthesizeoftheobject(s)allocatedbymalloc(),calloc()orrealloc() issmallerthanthesizeofanobjectpointedtobytheresultpointer.Thismaybecausedbyasizeof expressionwiththewrongtypeorwithapointertypeinsteadoftheobjecttype.

9.9 Environment(ENV)

ENV32−C Allatexithandlersmustreturnnormally Thecompilerissuesthiswarningwhenanatexit()handleriscallingafunctionthatdoesnotreturn.No atexit()registeredhandlershouldterminateinanywayotherthanbyreturning.

9−4 CERTCSecureCodingStandard

9.10 Signals(SIG)

SIG30−C Callonlyasynchronous−safefunctionswithinsignalhandlers SIG32−C Donotcalllongjmp()frominsideasignalhandler Invokingthelongjmp()functionfromwithinasignalhandlercanleadtoundefinedbehaviorifitresultsin theinvocationofanynon−asynchronous−safefunctions,likelycompromisingtheintegrityofthe program.

9.11 Miscellaneous(MSC)

MSC32−C Ensureyourrandomnumbergeneratorisproperlyseeded Ensurethattherandomnumbergeneratorisproperlyseededbycallingsrand().

9−5 NiosIIEmbeddedToolsReference

9−6 10 MISRA−CRules

Summary ThischaptercontainsanoverviewofthesupportedandunsupportedMISRA−C rules.

10.1 MISRA−C:1998

ThissectionlistsallsupportedandunsupportedMISRA−C:1998rules.

Seealsosection2.7.2,CCodeChecking:MISRA−C,inChapterUsingtheCompileroftheUser’sManual.

AnumberofMISRA−Crulesleaveroomforinterpretation.Otherrulescanonlybecheckedinalimitedway.Insuch casestheimplementationdecisionsandpossiblerestrictionsfortheserulesarelisted. xmeansthattheruleisnotsupportedbytheTASKINGCcompiler. (R)isarequiredrule,(A)isanadvisoryrule.

1. (R) ThecodeshallconformtostandardC,withoutlanguageextensions x 2. (A) Otherlanguagesshouldonlybeusedwithaninterfacestandard 3. (A) InlineassemblyisonlyallowedindedicatedCfunctions x 4. (A) Provisionshouldbemadeforappropriaterun−timechecking 5. (R) OnlyusecharactersandescapesequencesdefinedbyISOC x 6. (R) CharactervaluesshallberestrictedtoasubsetofISO106460−1 7. (R) Trigraphsshallnotbeused 8. (R) Multibytecharactersandwidestringliteralsshallnotbeused 9. (R) Commentsshallnotbenested 10. (A) Sectionsofcodeshouldnotbe"commentedout" Ingeneral,itisnotpossibletodecidewhetherapieceofcommentisCcodethatiscommentedout,orjust somepseudocode.Instead,thefollowingheuristicsareusedtodetectpossibleCcodeinsideacomment: −alineendswith’;’,or −alinestartswith’}’,possiblyprecededbywhitespace 11. (R) Identifiersshallnotrelyonsignificanceofmorethan31characters 12. (A) Thesameidentifiershallnotbeusedinmultiplenamespaces 13. (A) Specific−lengthtypedefsshouldbeusedinsteadofthebasictypes 14. (R) Use’unsignedchar’or’signedchar’insteadofplain’char’ x 15. (A) Floating−pointimplementationsshouldcomplywithastandard 16. (R) Thebitrepresentationoffloating−pointnumbersshallnotbeused Aviolationisreportedwhenapointertoafloating−pointtypeisconvertedtoapointertoanintegertype. 17. (R) "typedef"namesshallnotbereused 18. (A) Numericconstantsshouldbesuffixedtoindicatetype Aviolationisreportedwhenthevalueoftheconstantisoutsidetherangeindicatedbythesuffixes,ifany. 19. (R) Octalconstants(otherthanzero)shallnotbeused 20. (R) Allobjectandfunctionidentifiersshallbedeclaredbeforeuse 21. (R) Identifiersshallnothideidentifiersinanouterscope 22. (A) Declarationsshouldbeatfunctionscopewherepossible

10−1 NiosIIEmbeddedToolsReference

x 23. (A) Alldeclarationsatfilescopeshouldbestaticwherepossible 24. (R) Identifiersshallnothavebothinternalandexternallinkage x 25. (R) Identifierswithexternallinkageshallhaveexactlyonedefinition 26. (R) Multipledeclarationsforobjectsorfunctionsshallbecompatible x 27. (A) Externalobjectsshouldnotbedeclaredinmorethanonefile 28. (A) The"register"storageclassspecifiershouldnotbeused 29. (R) Theuseofatagshallagreewithitsdeclaration 30. (R) Allautomaticsshallbeinitializedbeforebeingused Thisruleischeckedusingworst−caseassumptions.Thismeansthatviolationsarereportednotonlyfor variablesthatareguaranteedtobeuninitialized,butalsoforvariablesthatareuninitializedonsome executionpaths. 31. (R) Bracesshallbeusedintheinitializationofarraysandstructures 32. (R) Onlythefirst,orallenumerationconstantsmaybeinitialized 33. (R) Therighthandoperandof&&or||shallnotcontainsideeffects 34. (R) Theoperandsofalogical&&or||shallbeprimaryexpressions 35. (R) AssignmentoperatorsshallnotbeusedinBooleanexpressions 36. (A) Logicaloperatorsshouldnotbeconfusedwithbitwiseoperators 37. (R) Bitwiseoperationsshallnotbeperformedonsignedintegers 38. (R) Ashiftcountshallbebetween0andtheoperandwidthminus1 Thisviolationwillonlybecheckedwhentheshiftcountevaluatestoaconstantvalueatcompiletime. 39. (R) Theunaryminusshallnotbeappliedtoanunsignedexpression 40. (A) "sizeof"shouldnotbeusedonexpressionswithsideeffects x 41. (A) Theimplementationofintegerdivisionshouldbedocumented 42. (R) Thecommaoperatorshallonlybeusedina"for"condition 43. (R) Don’tuseimplicitconversionswhichmayresultininformationloss 44. (A) Redundantexplicitcastsshouldnotbeused 45. (R) Typecastingfromanytypetoorfrompointersshallnotbeused 46. (R) Thevalueofanexpressionshallbeevaluationorderindependent Thisruleischeckedusingworst−caseassumptions.Thismeansthataviolationwillbereportedwhena possiblealiasmaycausetheresultofanexpressiontobeevaluationorderdependent. 47. (A) Nodependenceshouldbeplacedonoperatorprecedencerules 48. (A) Mixedarithmeticshoulduseexplicitcasting 49. (A) Testsofa(non−Boolean)valueagainst0shouldbemadeexplicit 50. (R) F.P.variablesshallnotbetestedforexactequalityorinequality 51. (A) Constantunsignedintegerexpressionsshouldnotwrap−around 52. (R) Thereshallbenounreachablecode 53. (R) Allnon−nullstatementsshallhaveaside−effect 54. (R) Anullstatementshallonlyoccuronalinebyitself 55. (A) Labelsshouldnotbeused 56. (R) The"goto"statementshallnotbeused 57. (R) The"continue"statementshallnotbeused 58. (R) The"break"statementshallnotbeused(exceptina"switch") 59. (R) An"if"orloopbodyshallalwaysbeenclosedinbraces 60. (A) All"if","elseif"constructsshouldcontainafinal"else" 61. (R) Everynon−empty"case"clauseshallbeterminatedwitha"break" 62. (R) All"switch"statementsshouldcontainafinal"default"case

10−2 MISRA−CRules

63. (A) A"switch"expressionshouldnotrepresentaBooleancase 64. (R) Every"switch"shallhaveatleastone"case" 65. (R) Floating−pointvariablesshallnotbeusedasloopcounters 66. (A) A"for"shouldonlycontainexpressionsconcerningloopcontrol Aviolationisreportedwhentheloopinitializationorloopupdateexpressionmodifiesanobjectthatisnot referencedinthelooptest. 67. (A) Iteratorvariablesshouldnotbemodifiedina"for"loop 68. (R) Functionsshallalwaysbedeclaredatfilescope 69. (R) Functionswithvariablenumberofargumentsshallnotbeused 70. (R) Functionsshallnotcallthemselves,eitherdirectlyorindirectly Aviolationwillbereportedfordirectorindirectrecursivefunctioncallsinthesourcefilebeingchecked. Recursionviafunctionsinothersourcefiles,orrecursionviafunctionpointersisnotdetected. 71. (R) Functionprototypesshallbevisibleatthedefinitionandcall 72. (R) Thefunctionprototypeofthedeclarationshallmatchthedefinition 73. (R) Identifiersshallbegivenforallprototypeparametersorfornone 74. (R) Parameteridentifiersshallbeidenticalfordeclaration/definition 75. (R) Everyfunctionshallhaveanexplicitreturntype 76. (R) Functionswithnoparametersshallhavea"void"parameterlist 77. (R) Anactualparametertypeshallbecompatiblewiththeprototype 78. (R) Thenumberofactualparametersshallmatchtheprototype 79. (R) Thevaluesreturnedby"void"functionsshallnotbeused 80. (R) Voidexpressionsshallnotbepassedasfunctionparameters 81. (A) "const"shouldbeusedforreferenceparametersnotmodified 82. (A) Afunctionshouldhaveasinglepointofexit 83. (R) Everyexitpointshallhavea"return"ofthedeclaredreturntype 84. (R) For"void"functions,"return"shallnothaveanexpression 85. (A) Functioncallswithnoparametersshouldhaveemptyparentheses 86. (A) Ifafunctionreturnserrorinformation,itshouldbetested Aviolationisreportedwhenthereturnvalueofafunctionisignored. 87. (R) #includeshallonlybeprecededbyotherdirectivesorcomments 88. (R) Non−standardcharactersshallnotoccurin#includedirectives 89. (R) #includeshallbefollowedbyeitheror"filename" 90. (R) Plainmacrosshallonlybeusedforconstants/qualifiers/specifiers 91. (R) Macrosshallnotbe#define’dand#undef’dwithinablock 92. (A) #undefshouldnotbeused 93. (A) Afunctionshouldbeusedinpreferencetoafunction−likemacro 94. (R) Afunction−likemacroshallnotbeusedwithoutallarguments 95. (R) Macroargumentsshallnotcontainpre−preprocessingdirectives Aviolationisreportedwhenthefirsttokenofanactualmacroargumentis’#’. 96. (R) Macrodefinitions/parametersshouldbeenclosedinparentheses 97. (A) Don’tuseundefinedidentifiersinpre−processingdirectives 98. (R) Amacrodefinitionshallcontainatmostone#or##operator 99. (R) Allusesofthe#pragmadirectiveshallbedocumented Thisruleisreallyadocumentationissue.Thecompilerwillflagall#pragmadirectivesasviolations. 100. (R) "defined"shallonlybeusedinoneofthetwostandardforms 101. (A) Pointerarithmeticshouldnotbeused

10−3 NiosIIEmbeddedToolsReference

102. (A) Nomorethan2levelsofpointerindirectionshouldbeused Aviolationisreportedwhenapointerwiththreeormorelevelsofindirectionisdeclared. 103. (R) Norelationaloperatorsbetweenpointerstodifferentobjects Ingeneral,checkingwhethertwopointerspointtothesameobjectisimpossible.Thecompilerwillonly reportaviolationforarelationaloperationwithincompatiblepointertypes. 104. (R) Non−constantpointerstofunctionsshallnotbeused 105. (R) Functionsassignedtothesamepointershallbeofidenticaltype 106. (R) Automaticaddressmaynotbeassignedtoalongerlivedobject 107. (R) Thenullpointershallnotbede−referenced AviolationisreportedforeverypointerdereferencethatisnotguardedbyaNULLpointertest. 108. (R) Allstruct/unionmembersshallbefullyspecified 109. (R) Overlappingvariablestorageshallnotbeused Aviolationisreportedforevery’union’declaration. 110. (R) Unionsshallnotbeusedtoaccessthesub−partsoflargertypes Aviolationisreportedfora’union’containinga’struct’member. 111. (R) bit−fieldsshallhavetype"unsignedint"or"signedint" 112. (R) bit−fieldsoftype"signedint"shallbeatleast2bitslong 113. (R) Allstruct/unionmembersshallbenamed 114. (R) Reservedandstandardlibrarynamesshallnotberedefined 115. (R) Standardlibraryfunctionnamesshallnotbereused x 116. (R) ProductionlibrariesshallcomplywiththeMISRA−Crestrictions x 117. (R) Thevalidityoflibraryfunctionparametersshallbechecked 118. (R) Dynamicheapmemoryallocationshallnotbeused 119. (R) Theerrorindicator"errno"shallnotbeused 120. (R) Themacro"offsetof"shallnotbeused 121. (R) andthe"setlocale"functionshallnotbeused 122. (R) The"setjmp"and"longjmp"functionsshallnotbeused 123. (R) Thesignalhandlingfacilitiesofshallnotbeused 124. (R) Thelibraryshallnotbeusedinproductioncode 125. (R) Thefunctionsatof/atoi/atolshallnotbeused 126. (R) Thefunctionsabort/exit/getenv/systemshallnotbeused 127. (R) Thetimehandlingfunctionsoflibraryshallnotbeused

Seealsosection2.7.2,CCodeChecking:MISRA−C,inChapterUsingtheCompileroftheUser’smanual.

10−4 MISRA−CRules

10.2 MISRA−C:2004

ThissectionlistsallsupportedandunsupportedMISRA−C:2004rules.

Seealsosection2.7.2,CCodeChecking:MISRA−C,inChapterUsingtheCompileroftheUser’sManual.

AnumberofMISRA−Crulesleaveroomforinterpretation.Otherrulescanonlybecheckedinalimitedway.Insuch casestheimplementationdecisionsandpossiblerestrictionsfortheserulesarelisted. xmeansthattheruleisnotsupportedbytheTASKINGCcompiler. (R)isarequiredrule,(A)isanadvisoryrule.

Environment

1.1 (R) AllcodeshallconformtoISO9899:1990"Programminglanguages−C",amendedandcorrectedby ISO/IEC9899/COR1:1995,ISO/IEC9899/AMD1:1995,andISO/IEC9899/COR2:1996. 1.2 (R) Norelianceshallbeplacedonundefinedorunspecifiedbehavior. x 1.3 (R) Multiplecompilersand/orlanguagesshallonlybeusedifthereisacommondefinedinterfacestandard forobjectcodetowhichthelanguages/compilers/assemblersconform. x 1.4 (R) Thecompiler/linkershallbecheckedtoensurethat31charactersignificanceandcasesensitivityare supportedforexternalidentifiers. x 1.5 (A) Floating−pointimplementationsshouldcomplywithadefinedfloating−pointstandard.

Languageextensions

2.1 (R) Assemblylanguageshallbeencapsulatedandisolated. 2.2 (R) Sourcecodeshallonlyuse/*...*/stylecomments. 2.3 (R) Thecharactersequence/*shallnotbeusedwithinacomment. 2.4 (A) Sectionsofcodeshouldnotbe"commentedout". Ingeneral,itisnotpossibletodecidewhetherapieceofcommentisCcodethatiscommentedout,or justsomepseudocode.Instead,thefollowingheuristicsareusedtodetectpossibleCcodeinsidea comment: −alineendswith’;’,or −alinestartswith’}’,possiblyprecededbywhitespace

Documentation

x 3.1 (R) Allusageofimplementation−definedbehaviorshallbedocumented. x 3.2 (R) Thecharactersetandthecorrespondingencodingshallbedocumented. x 3.3 (A) Theimplementationofintegerdivisioninthechosencompilershouldbedetermined,documentedand takenintoaccount. 3.4 (R) Allusesofthe#pragmadirectiveshallbedocumentedandexplained. Thisruleisreallyadocumentationissue.Thecompilerwillflagall#pragma directivesasviolations. 3.5 (R) Theimplementation−definedbehaviorandpackingofbit−fieldsshallbedocumentedifbeingreliedupon. x 3.6 (R) Alllibrariesusedinproductioncodeshallbewrittentocomplywiththeprovisionsofthisdocument,and shallhavebeensubjecttoappropriatevalidation.

Charactersets

4.1 (R) OnlythoseescapesequencesthataredefinedintheISOCstandardshallbeused. 4.2 (R) Trigraphsshallnotbeused.

10−5 NiosIIEmbeddedToolsReference

Identifiers

5.1 (R) Identifiers(internalandexternal)shallnotrelyonthesignificanceofmorethan31characters. 5.2 (R) Identifiersinaninnerscopeshallnotusethesamenameasanidentifierinanouterscope,andtherefore hidethatidentifier. 5.3 (R) Atypedefnameshallbeauniqueidentifier. 5.4 (R) Atagnameshallbeauniqueidentifier. x 5.5 (A) Noobjectorfunctionidentifierwithstaticstoragedurationshouldbereused. 5.6 (A) Noidentifierinonenamespaceshouldhavethesamespellingasanidentifierinanothernamespace, withtheexceptionofstructureandunionmembernames. x 5.7 (A) Noidentifiernameshouldbereused.

Types

6.1 (R) Theplainchartypeshallbeusedonlyforstorageanduseofcharactervalues. x 6.2 (R) signedandunsignedchartypeshallbeusedonlyforthestorageanduseofnumericvalues. 6.3 (A) typedefsthatindicatesizeandsignednessshouldbeusedinplaceofthebasictypes. 6.4 (R) bit−fieldsshallonlybedefinedtobeoftypeunsignedintorsignedint. 6.5 (R) bit−fieldsoftypesignedintshallbeatleast2bitslong.

Constants

7.1 (R) Octalconstants(otherthanzero)andoctalescapesequencesshallnotbeused.

Declarationsanddefinitions

8.1 (R) Functionsshallhaveprototypedeclarationsandtheprototypeshallbevisibleatboththefunction definitionandcall. 8.2 (R) Wheneveranobjectorfunctionisdeclaredordefined,itstypeshallbeexplicitlystated. 8.3 (R) Foreachfunctionparameterthetypegiveninthedeclarationanddefinitionshallbeidentical,andthe returntypesshallalsobeidentical. 8.4 (R) Ifobjectsorfunctionsaredeclaredmorethanoncetheirtypesshallbecompatible. 8.5 (R) Thereshallbenodefinitionsofobjectsorfunctionsinaheaderfile. 8.6 (R) Functionsshallbedeclaredatfilescope. 8.7 (R) Objectsshallbedefinedatblockscopeiftheyareonlyaccessedfromwithinasinglefunction. x 8.8 (R) Anexternalobjectorfunctionshallbedeclaredinoneandonlyonefile. x 8.9 (R) Anidentifierwithexternallinkageshallhaveexactlyoneexternaldefinition. x 8.10 (R) Alldeclarationsanddefinitionsofobjectsorfunctionsatfilescopeshallhaveinternallinkageunless externallinkageisrequired. 8.11 (R) Thestaticstorageclassspecifiershallbeusedindefinitionsanddeclarationsofobjectsandfunctions thathaveinternallinkage. 8.12 (R) Whenanarrayisdeclaredwithexternallinkage,itssizeshallbestatedexplicitlyordefinedimplicitlyby initialization.

10−6 MISRA−CRules

Initialization

9.1 (R) Allautomaticvariablesshallhavebeenassignedavaluebeforebeingused. Thisruleischeckedusingworst−caseassumptions.Thismeansthatviolationsarereportednotonlyfor variablesthatareguaranteedtobeuninitialized,butalsoforvariablesthatareuninitializedonsome executionpaths. 9.2 (R) Bracesshallbeusedtoindicateandmatchthestructureinthenon−zeroinitializationofarraysand structures. 9.3 (R) Inanenumeratorlist,the"="constructshallnotbeusedtoexplicitlyinitializemembersotherthanthe first,unlessallitemsareexplicitlyinitialized.

Arithmetictypeconversions

10.1 (R) Thevalueofanexpressionofintegertypeshallnotbeimplicitlyconvertedtoadifferentunderlyingtypeif: a)itisnotaconversiontoawiderintegertypeofthesamesignedness,or b)theexpressioniscomplex,or c)theexpressionisnotconstantandisafunctionargument,or d)theexpressionisnotconstantandisareturnexpression. 10.2 (R) Thevalueofanexpressionoffloatingtypeshallnotbeimplicitlyconvertedtoadifferenttypeif: a)itisnotaconversiontoawiderfloatingtype,or b)theexpressioniscomplex,or c)theexpressionisafunctionargument,or d)theexpressionisareturnexpression. 10.3 (R) Thevalueofacomplexexpressionofintegertypemayonlybecasttoatypethatisnarrowerandofthe samesignednessastheunderlyingtypeoftheexpression. 10.4 (R) Thevalueofacomplexexpressionoffloatingtypemayonlybecasttoanarrowerfloatingtype. 10.5 (R) Ifthebitwiseoperators~and<<areappliedtoanoperandofunderlyingtypeunsignedcharor unsignedshort,theresultshallbeimmediatelycasttotheunderlyingtypeoftheoperand. 10.6 (R) A"U"suffixshallbeappliedtoallconstantsofunsignedtype.

Pointertypeconversions

11.1 (R) Conversionsshallnotbeperformedbetweenapointertoafunctionandanytypeotherthananintegral type. 11.2 (R) Conversionsshallnotbeperformedbetweenapointertoobjectandanytypeotherthananintegraltype, anotherpointertoobjecttypeorapointertovoid. 11.3 (A) Acastshouldnotbeperformedbetweenapointertypeandanintegraltype. 11.4 (A) Acastshouldnotbeperformedbetweenapointertoobjecttypeandadifferentpointertoobjecttype. 11.5 (R) Acastshallnotbeperformedthatremovesanyconstorvolatilequalificationfromthetype addressedbyapointer.

Expressions

12.1 (A) LimiteddependenceshouldbeplacedonC’soperatorprecedencerulesinexpressions. 12.2 (R) Thevalueofanexpressionshallbethesameunderanyorderofevaluationthatthestandardpermits. Thisruleischeckedusingworst−caseassumptions.Thismeansthataviolationwillbereportedwhena possiblealiasmaycausetheresultofanexpressiontobeevaluationorderdependent. 12.3 (R) Thesizeofoperatorshallnotbeusedonexpressionsthatcontainsideeffects. 12.4 (R) Theright−handoperandofalogical&&or||operatorshallnotcontainsideeffects. 12.5 (R) Theoperandsofalogical&&or||shallbeprimary−expressions. 12.6 (A) Theoperandsoflogicaloperators(&&,||and!)shouldbeeffectivelyBoolean.Expressionsthatare effectivelyBooleanshouldnotbeusedasoperandstooperatorsotherthan(&&,||and!). 12.7 (R) Bitwiseoperatorsshallnotbeappliedtooperandswhoseunderlyingtypeissigned.

10−7 NiosIIEmbeddedToolsReference

12.8 (R) Theright−handoperandofashiftoperatorshallliebetweenzeroandonelessthanthewidthinbitsof theunderlyingtypeoftheleft−handoperand. Thisviolationwillonlybecheckedwhentheshiftcountevaluatestoaconstantvalueatcompile time. 12.9 (R) Theunaryminusoperatorshallnotbeappliedtoanexpressionwhoseunderlyingtypeisunsigned. 12.10 (R) Thecommaoperatorshallnotbeused. 12.11 (A) Evaluationofconstantunsignedintegerexpressionsshouldnotleadtowrap−around. 12.12 (R) Theunderlyingbitrepresentationsoffloating−pointvaluesshallnotbeused. Aviolationisreportedwhenapointertoafloating−pointtypeisconvertedtoapointertoanintegertype. 12.13 (A) Theincrement(++)anddecrement(−−)operatorsshouldnotbemixedwithotheroperatorsinan expression.

Controlstatementexpressions

13.1 (R) AssignmentoperatorsshallnotbeusedinexpressionsthatyieldaBooleanvalue. 13.2 (A) Testsofavalueagainstzeroshouldbemadeexplicit,unlesstheoperandiseffectivelyBoolean. 13.3 (R) Floating−pointexpressionsshallnotbetestedforequalityorinequality. 13.4 (R) Thecontrollingexpressionofaforstatementshallnotcontainanyobjectsoffloatingtype. 13.5 (R) Thethreeexpressionsofaforstatementshallbeconcernedonlywithloopcontrol. Aviolationisreportedwhentheloopinitializationorloopupdateexpressionmodifiesanobjectthatisnot referencedinthelooptest. 13.6 (R) Numericvariablesbeingusedwithinaforloopforiterationcountingshallnotbemodifiedinthebodyof theloop. 13.7 (R) Booleanoperationswhoseresultsareinvariantshallnotbepermitted.

Controlflow

14.1 (R) Thereshallbenounreachablecode. 14.2 (R) Allnon−nullstatementsshalleither: a)haveatleastonesideeffecthoweverexecuted,or b)causecontrolflowtochange. 14.3 (R) Beforepreprocessing,anullstatementshallonlyoccuronalinebyitself;itmaybefollowedbya commentprovidedthatthefirstcharacterfollowingthenullstatementisawhite−spacecharacter. 14.4 (R) Thegotostatementshallnotbeused. 14.5 (R) Thecontinuestatementshallnotbeused. 14.6 (R) Foranyiterationstatementthereshallbeatmostonebreakstatementusedforlooptermination. 14.7 (R) Afunctionshallhaveasinglepointofexitattheendofthefunction. 14.8 (R) Thestatementformingthebodyofaswitch,while,do...whileorforstatementbeacompound statement. 14.9 (R) Anif(expression)constructshallbefollowedbyacompoundstatement.Theelsekeywordshall befollowedbyeitheracompoundstatement,oranotherifstatement. 14.10 (R) Allif...elseifconstructsshallbeterminatedwithanelseclause.

Switchstatements

15.1 (R) Aswitchlabelshallonlybeusedwhenthemostclosely−enclosingcompoundstatementisthebodyofa switchstatement. 15.2 (R) Anunconditionalbreakstatementshallterminateeverynon−emptyswitchclause. 15.3 (R) Thefinalclauseofaswitchstatementshallbethedefaultclause. 15.4 (R) AswitchexpressionshallnotrepresentavaluethatiseffectivelyBoolean. 15.5 (R) Everyswitchstatementshallhaveatleastonecaseclause.

10−8 MISRA−CRules

Functions

16.1 (R) Functionsshallnotbedefinedwithvariablenumbersofarguments. 16.2 (R) Functionsshallnotcallthemselves,eitherdirectlyorindirectly. Aviolationwillbereportedfordirectorindirectrecursivefunctioncallsinthesourcefilebeingchecked. Recursionviafunctionsinothersourcefiles,orrecursionviafunctionpointersisnotdetected. 16.3 (R) Identifiersshallbegivenforalloftheparametersinafunctionprototypedeclaration. 16.4 (R) Theidentifiersusedinthedeclarationanddefinitionofafunctionshallbeidentical. 16.5 (R) Functionswithnoparametersshallbedeclaredwithparametertypevoid. 16.6 (R) Thenumberofargumentspassedtoafunctionshallmatchthenumberofparameters. 16.7 (A) Apointerparameterinafunctionprototypeshouldbedeclaredaspointertoconstifthepointerisnot usedtomodifytheaddressedobject. 16.8 (R) Allexitpathsfromafunctionwithnon−voidreturntypeshallhaveanexplicitreturnstatementwithan expression. 16.9 (R) Afunctionidentifiershallonlybeusedwitheitherapreceding&,orwithaparenthesizedparameterlist, whichmaybeempty. 16.10 (R) Ifafunctionreturnserrorinformation,thenthaterrorinformationshallbetested. Aviolationisreportedwhenthereturnvalueofafunctionisignored.

Pointersandarrays

x 17.1 (R) Pointerarithmeticshallonlybeappliedtopointersthataddressanarrayorarrayelement. x 17.2 (R) Pointersubtractionshallonlybeappliedtopointersthataddresselementsofthesamearray. 17.3 (R) >,>=,<,<=shallnotbeappliedtopointertypesexceptwheretheypointtothesamearray. Ingeneral,checkingwhethertwopointerspointtothesameobjectisimpossible.Thecompilerwillonly reportaviolationforarelationaloperationwithincompatiblepointertypes. 17.4 (R) Arrayindexingshallbetheonlyallowedformofpointerarithmetic. 17.5 (A) Thedeclarationofobjectsshouldcontainnomorethan2levelsofpointerindirection. Aviolationisreportedwhenapointerwiththreeormorelevelsofindirectionisdeclared. 17.6 (R) Theaddressofanobjectwithautomaticstorageshallnotbeassignedtoanotherobjectthatmaypersist afterthefirstobjecthasceasedtoexist.

Structuresandunions

18.1 (R) Allstructureoruniontypesshallbecompleteattheendofatranslationunit. 18.2 (R) Anobjectshallnotbeassignedtoanoverlappingobject. x 18.3 (R) Anareaofmemoryshallnotbereusedforunrelatedpurposes. 18.4 (R) Unionsshallnotbeused.

Preprocessingdirectives

19.1 (A) #includestatementsinafileshouldonlybeprecededbyotherpreprocessordirectivesorcomments. 19.2 (A) Non−standardcharactersshouldnotoccurinheaderfilenamesin#includedirectives. x 19.3 (R) The#includedirectiveshallbefollowedbyeitheraor"filename"sequence. 19.4 (R) Cmacrosshallonlyexpandtoabracedinitializer,aconstant,aparenthesizedexpression,atype qualifier,astorageclassspecifier,orado−while−zeroconstruct. 19.5 (R) Macrosshallnotbe#define’dor#undef’dwithinablock. 19.6 (R) #undefshallnotbeused. 19.7 (A) Afunctionshouldbeusedinpreferencetoafunction−likemacro. 19.8 (R) Afunction−likemacroshallnotbeinvokedwithoutallofitsarguments.

10−9 NiosIIEmbeddedToolsReference

19.9 (R) Argumentstoafunction−likemacroshallnotcontaintokensthatlooklikepreprocessingdirectives. Aviolationisreportedwhenthefirsttokenofanactualmacroargumentis’#’. 19.10 (R) Inthedefinitionofafunction−likemacroeachinstanceofaparametershallbeenclosedinparentheses unlessitisusedastheoperandof#or##. 19.11 (R) Allmacroidentifiersinpreprocessordirectivesshallbedefinedbeforeuse,exceptin#ifdefand #ifndefpreprocessordirectivesandthedefined()operator. 19.12 (R) Thereshallbeatmostoneoccurrenceofthe#or##preprocessoroperatorsinasinglemacrodefinition. 19.13 (A) The#and##preprocessoroperatorsshouldnotbeused. 19.14 (R) Thedefinedpreprocessoroperatorshallonlybeusedinoneofthetwostandardforms. 19.15 (R) Precautionsshallbetakeninordertopreventthecontentsofaheaderfilebeingincludedtwice. 19.16 (R) Preprocessingdirectivesshallbesyntacticallymeaningfulevenwhenexcludedbythepreprocessor. 19.17 (R) All#else,#elifand#endifpreprocessordirectivesshallresideinthesamefileasthe#ifor #ifdefdirectivetowhichtheyarerelated.

Standardlibraries

20.1 (R) Reservedidentifiers,macrosandfunctionsinthestandardlibrary,shallnotbedefined,redefinedor undefined. 20.2 (R) Thenamesofstandardlibrarymacros,objectsandfunctionsshallnotbereused. x 20.3 (R) Thevalidityofvaluespassedtolibraryfunctionsshallbechecked. 20.4 (R) Dynamicheapmemoryallocationshallnotbeused. 20.5 (R) Theerrorindicatorerrnoshallnotbeused. 20.6 (R) Themacrooffsetof,inlibrary,shallnotbeused. 20.7 (R) Thesetjmpmacroandthelongjmpfunctionshallnotbeused. 20.8 (R) Thesignalhandlingfacilitiesofshallnotbeused. 20.9 (R) Theinput/outputlibraryshallnotbeusedinproductioncode. 20.10 (R) Thelibraryfunctionsatof,atoiandatolfromlibraryshallnotbeused. 20.11 (R) Thelibraryfunctionsabort,exit,getenvandsystemfromlibraryshallnotbeused. 20.12 (R) Thetimehandlingfunctionsoflibraryshallnotbeused.

Run−timefailures

x 21.1 (R) Minimizationofrun−timefailuresshallbeensuredbytheuseofatleastoneof: a)staticanalysistools/techniques; b)dynamicanalysistools/techniques; c)explicitcodingofcheckstohandlerun−timefaults.

10−10 Index

Index Symbols __SIZE_MAX,2−23 #define,5−69 __SIZE_MIN,2−23 #include,systemincludedirectory,5−148 __STDC__,2−23 #undef,5−154 __STDC_VERSION__,2−23 __ABI_CHANGES_FOR_ARRAY_NEW_AND_DELETE, __TASKING__,1−11,2−23,4−3 2−22 __TIME__,2−23 __ABI_CHANGES_FOR_PLACEMENT_DELETE,2−22 __TYPE_TRAITS_ENABLED,2−23 __ABI_CHANGES_FOR_RTTI,2−22 __unaligned,1−2 __ABI_COMPATIBILITY_VERSION,2−22 __VAR_HANDLE_TYPE,2−23 __align(),1−2 __VERSION__,1−11,2−23,4−3 __ARRAY_OPERATORS,2−22 __VIRTUAL_FUNCTION_INDEX_TYPE,2−23 __asm,syntax,1−4 __VIRTUAL_FUNCTION_TYPE,2−23 __ASNIOS__,4−3 __WCHAR_MAX,2−23 __at(),1−4 __WCHAR_MIN,2−23 __BASE_FILE__,2−22 _BOOL,2−22 __BIG_ENDIAN__,1−11,2−22 _close,3−6 __BUILD__,1−11,2−22,4−3 _Exit,3−18 __CHAR_MAX,2−22 _fss_break,3−5 __CHAR_MIN,2−22 _fss_init,3−5 __CHAR_UNSIGNED__,1−11 _IOFBF,3−13 __CNIOS__,1−11 _IOLBF,3−13 __cplusplus,2−22 _IONBF,3−13 __CPNIOS__,2−22 _lseek,3−6 __CPU__,1−11,2−22 _open,3−6 __DATE__,2−22 _read,3−6 __DELTA_TYPE,2−22 _STLP_NO_IOSTREAMS,2−23 __DOUBLE_FP__,1−11,2−22 _tolower,3−3 __embedded_cplusplus,2−22 _unlink,3−6 __EXCEPTIONS,2−22 _WCHAR_T,2−23 __FILE__,2−22 _write,3−6 __func__,2−22 __HW_DIVIDE__,1−11 A __HW_MULTIPLY__,1−11 abort,3−18 __HW_MULX__,1−11 abs,3−19 __IMPLICIT_USING_STD,2−22 AbsoluteAddress,1−4 __interrupt,1−15 access,3−22 __JMP_BUF_ELEMENT_TYPE,2−22 acosfunctions,3−8 __JMP_BUF_NUM_ELEMENTS,2−22 acoshfunctions,3−8 __LINE__,2−22 Addressspaces,8−15 __LITTLE_ENDIAN__,1−11,2−23 alias,1−7 __NAMESPACES,2−23 align,4−11 __NIOS2__,1−11 Alignment,1−2 __NO_LONG_LONG,2−23 compositetypes,5−3 __noinline,1−13 Alignmentgaps,8−28 __NULL_EH_REGION_NUMBER,2−23 AlternativeC++tokens,5−60 __packed__,1−2 Anachronism,2−4 __PLACEMENT_DELETE,2−23 Anachronisms,5−61,5−118 __PRETTY_FUNCTION__,2−23 Architecturedefinition,8−1,8−14 __PTRDIFF_MAX,2−23 arg,4−6 __PTRDIFF_MIN,2−23 arraynewanddelete,5−103 __REGION_NUMBER_TYPE,2−23 asctime,3−21 __REVISION__,1−11,2−23,4−3 asinfunctions,3−7 __RTTI,2−23 asinhfunctions,3−8 __RUNTIME_USES_NAMESPACES,2−23 Assemblerdirectives __SIGNED_CHARS__,2−23 .align,4−11 __SINGLE_FP__,1−11,2−23 .break,4−12

Index−1 NiosIIEmbeddedToolsReference

.bs,4−13 −−error−file,5−171 .bsb,4−13 −−error−limit,5−172 .bsd,4−13 −−gp−relative,5−173 .bsh,4−13 −−help,5−174 .bsw,4−13 −−include−directory,5−175 .calls,4−14 −−include−file,5−176 .db,4−15 −−list−file,5−178 .dd,4−16 −−list−format,5−179 .define,4−17 −−nested−sections,5−180 .dh,4−18 −−no−warnings,5−181 .ds,4−19 −−optimize,5−182 .dsb,4−19 −−option−file,5−183 .dsd,4−19 −−output,5−184 .dsh,4−19 −−page−length,5−185 .dsw,4−19 −−page−width,5−186 .dw,4−20 −−preprocess,5−187 .end,4−21 −−preprocessor−type,5−188 .equ,4−22 −−section−info,5−189 .extern,4−23 −−symbol−scope,5−190 .for/.endfor,4−24 −−use−hardware,5−191 .global,4−25 −−verbose,5−193 .if/.elif/.else/.endif,4−26 −−version,5−192 .include,4−27 −−warnings−as−errors,5−194 .list/.nolist,4−28 −B(−−big−endian),5−170 .macro/.endm,4−29 −C,5−165 .message,4−31 −c,5−163 .offset,4−32 −D,5−167 .page,4−33 −E,5−187 .repeat/.endrep,4−34 −f,5−183 .resume,4−35 −g,5−166 .section,4−36 −H,5−176 .set,4−37 −I,5−175 .size,4−38 −i,5−190 .source,4−39 −k,5−177 .title,4−40 −k(−−keep−output−files),5−177 .type,4−41 −L,5−179 .undef,4−42 −l,5−178 assemblycontrol(overview),4−9 −m,5−188 conditionalassembly(overview),4−10 −N,5−180 datadefinition(overview),4−10 −O,5−182 detaileddescription,4−11 −o,5−184 HLL(overview),4−11 −t,5−189 listingcontrol(overview),4−10 −V,5−192 macros(overview),4−10 −v,5−193 overview,4−9 −w,5−181 storageallocation(overview),4−10 debuginformation,5−166,5−169 symboldefinitions(overview),4−10 diagnostics,5−172,5−181,5−194 weak,4−43 listfile,5−178,5−179,5−189 Assembleroptions,5−162 optimization,5−182 −?,5−174 preprocessing,5−167,5−176,5−187,5−188 −−case−insensitive,5−163 Assemblersignificantcharacters,4−2 −−check,5−164 Assembly,ProgramminginC,1−4 −−cpu,5−165 Assemblyexpressions,4−3 −−debug−info,5−166 Assemblyfunctions,4−5 −−define,5−167 @arg,4−6 −−diag,5−168 @bigendian,4−6 −−emit−locals,5−169 @cnt,4−6 −−endianness,5−170 @cpu,4−7

Index−2 Index

@defined,4−7 −−dep−file,5−13 @gprel,4−7 −−diag,5−14 @hi,4−7 −−endianness,5−15 @hiadj,4−7 −−errorfile,5−16 @lo,4−7 −−extern−sdata,5−17 @lsb,4−8 −−global−type−checking,5−18 @lsh,4−8 −−help,5−19 @lsw,4−8 −−include−directory,5−20 @msb,4−8 −−include−file,5−21 @msh,4−8 −−inline,5−22 @msw,4−8 −−inline−max−incr,5−23 @strcat,4−8 −−inline−max−size,5−23 @strcmp,4−8 −−iso,5−24 @strlen,4−8 −−keep−output−files,5−25 @strpos,4−8 −−language,5−26 detaileddescription,4−6 −−make−target,5−28 overview,4−6 −−mil,5−29 Assemblysyntax,4−1 −−mil−split,5−29 atanfunctions,3−8 −−misrac,5−30 atan2functions,3−8 −−misrac−advisory−warnings,5−31 atanhfunctions,3−8 −−misrac−required−warnings,5−31 atexit,3−18 −−no−double,5−34 atof,3−18 −−no−jmpi,5−35 atoi,3−18 −−no−stdinc,5−36 atol,3−18 −−no−warnings,5−37 atoll,3−18 −−nocache−volatile,5−33 −−optimize,5−38 B −−option−file,5−40 bigendian,4−6 −−output,5−41 Boardspecification,8−2,8−22 −−preprocess,5−42 boolkeyword,5−105 −−profile,5−43 break,4−12 −−rename−sections,5−45 bs,4−13 −−runtime,5−46 bsb,4−13 −−sdata,5−47 bsd,4−13 −−signed−bitfields,5−48 bsearch,3−19 −−source,5−49 bsh,4−13 −−static,5−50 bsw,4−13 −−stdout,5−51 btowc,3−23 −−tradeoff,5−52 BUFSIZ,3−12 −−uchar,5−53 Buildoptions,5−214 −−undefine,5−54 includefilespath,5−20,5−36,5−88,5−175,5−210 −−unroll−max−size,5−55 Busdefinition,8−2 −−use−hardware,5−56 Buses,8−15 −−version,5−57 −−warnings−as−errors,5−58 C −A,5−26 −B,5−15 Ccompileroptions,5−1 −C,5−8 −?,5−19 −c,5−24 −−align−composites,5−3 −D,5−11 −−big−endian,5−15 −E,5−42 −−bypass−cache,5−4 −F,5−34 −−call,5−5 −f,5−40 −−cert,5−6 −g,5−10 −−check,5−7 −H,5−21 −−cpu,5−8 −I,5−20 −−custom−instruction,5−9 −k,5−25 −−debug−info,5−10 −m,5−5 −−define,5−11

Index−3 NiosIIEmbeddedToolsReference

−n,5−51 −−long−lifetime−temps,5−97 −O,5−38 −−long−long,5−98 −o,5−41 −−make−target,5−99 −p,5−43 −−multibyte−chars,5−100 −R,5−45 −−namespaces,5−101 −r,5−46 −−no−arg−dep−lookup,5−102 −s,5−49 −−no−array−new−and−delete,5−103 −t,5−52 −−no−auto−instantiation,5−104 −U,5−54 −−no−bool,5−105 −u,5−53 −−no−class−name−injection,5−106 −V,5−57 −−no−const−string−literals,5−107 −w,5−37 −−no−dep−name,5−108 debuginformation,5−10 −−no−distinct−template−signatures,5−109 diagnostics,5−37,5−58 −−no−double,5−110 language,5−24,5−26,5−48,5−53 −−no−enum−overloading,5−111 MISRA−C,5−30 −−no−explicit,5−112 optimization,5−38,5−52 −−no−export,5−113 preprocessing,5−11,5−21,5−42,5−54 −−no−extern−inline,5−114 C++,languageextensions,2−1 −−no−for−init−diff−warning,5−115 C++compileroptions,5−59 −−no−implicit−typename,5−116 −?,5−84 −−no−inlining,5−117 −−alternative−tokens,5−60 −−no−nonconst−ref−anachronism,5−118 −−anachronisms,5−61 −−no−parse−templates,5−121 −−base−assign−op−is−default,5−62 −−no−pch−messages,5−122 −−big−endian,5−73 −−no−preprocessing−only,5−123 −−building−runtime,5−63 −−no−stdinc,5−124 −−c++0x,5−64 −−no−stdstlinc,5−124 −−check,5−65 −−no−type−traits−helpers,5−152 −−context−limit,5−66 −−no−typename,5−125 −−cpu,5−67 −−no−use−before−set−warnings,5−126 −−create−pch,5−68 −−no−warnings,5−127 −−define,5−69 −−nonconst−ref−anachronism,5−118 −−dep−file,5−70 −−nonstd−qualifier−deduction,5−119 −−dollar,5−71 −−nonstd−using−decl,5−120 −−embedded−c++,5−72 −−old−for−init,5−128 −−endianness,5−73 −−old−line−commands,5−129 −−error−file,5−74 −−old−specializations,5−130 −−error−limit,5−75 −−option−file,5−131 −−exceptions,5−76 −−output,5−133 −−exported−template−file,5−77 −−pch,5−134 −−extended−variadic−macros,5−78 −−pch−dir,5−135 −−force−vtbl,5−79 −−pch−verbose,5−136 −−friend−injection,5−80 −−pending−instantiations,5−137 −−g++,5−81 −−preprocess,5−138 −−gnu−version,5−82 −−remarks,5−139 −−guiding−decls,5−83 −−remove−unneeded−entities,5−140 −−help,5−84 −−rtti,5−141 −−implicit−extern−c−type−conversion,5−85 −−schar,5−142 −−implicit−include,5−86 −−signed−bitfields,5−143 −−incl−suffixes,5−87 −−special−subscript−cost,5−144 −−include−directory,5−88 −−strict,5−145 −−include−file,5−89 −−strict−warnings,5−146 −−include−macros−file,5−90 −−suppress−vtbl,5−147 −−init−priority,5−91 −−sys−include,5−148 −−instantiate,5−92 −−template−directory,5−149 −−io−streams,5−93 −−timing,5−150 −−late−tiebreaker,5−94 −−trace−includes,5−151 −−list−file,5−95 −−type−traits−helpers,5−152

Index−4 Index

−−uchar,5−153 clock_t,3−21 −−undefine,5−154 CLOCKS_PER_SEC,3−21 −−use−pch,5−155 close,3−22 −−using−std,5−156 cnt,4−6 −−variadic−macros,5−157 Codechecking,CERTC,9−1 −−version,5−158 Codecompaction,5−22 −−warnings−as−errors,5−159 Commandfile,5−299 −−wchar_t−keyword,5−160 Comment,4−1 −−xref−file,5−161 Comments,8−3 −A,5−145 compileroptions,−−misrac−version,5−32 −a,5−146 Conditionalassembly,4−47 −B,5−73 Conditionalmakerules,5−286 −C,5−67 const,stringliterals,5−107 −D,5−69 Contextlimit,5−66 −E,5−138 Controlprogram,passingoptions,5−275 −e,5−75 Controlprogramoptions,5−236 −F,5−110 −?,5−254 −f,5−131 −−adress−size,5−237 −H,5−89 −−check,5−238 −I,5−88 −−cpu,5−239 −j,5−126 −−create,5−240 −L,5−95 −−debug−info,5−241 −o,5−133 −−define,5−242 −r,5−139 −−dep−file,5−243 −s,5−142 −−diag,5−244 −t,5−92 −−dry−run,5−245 −U,5−154 −−endianness,5−246 −u,5−153,5−158 −−errorfile,5−247 −V,5−158 −−exceptions,5−248 −w,5−127 −−force−c,5−249 −X,5−161 −−force−c++,5−250 −x,5−76 −−force−munch,5−251 diagnostics,5−159 −−format,5−252 preprocessing,5−69,5−89,5−138 −−global−type−checking,5−253 C++dialect,2−1 −−help,5−254 accepted,2−1 −−ignore−default−library−path,5−262 anachronismsaccepted,2−4 −−include−directory,5−255 C++0xlanguagefeaturesaccepted,2−3 −−instantiate,5−256 normalC++modeextensions,2−4 −−io−streams,5−257 standardlanguagefeaturesaccepted,2−1 −−iso,5−258 C++languagefeatures −−keep−output−files,5−259 accepted,2−1 −−keep−temporary−files,5−260 C++0x,2−3 −−library,5−261 C++stylecomments,5−26 −−library−directory,5−262 C++workingpaper,5−64 −−lsl−file,5−264 call,1−8 −−make−target,5−265 Callgraph,4−14 −−mil−link,5−266 calloc,3−7,3−18 −−mil−split,5−266 calls,4−14 −−no−auto−instantiation,5−267 cbrtfunctions,3−9 −−no−default−libraries,5−268 ceilfunctions,3−9 −−no−double,5−269 CERTC,9−1 −−no−map−file,5−270 CERTCsecurecoding,5−6 −−no−preprocessing−only,5−271 chdir,3−22 −−no−warnings,5−272 Checksourcecode,5−7,5−65,5−164,5−238 −−optionfile,5−273 Classnameinjection,5−106 −−output,5−274 clearerr,3−17 −−pass,5−275 clock,3−21 −−preprocess,5−276

Index−5 NiosIIEmbeddedToolsReference

−−profile,5−277 ds,4−19 −−show−c++−warnings,5−279 dsb,4−19 −−static,5−280 dsd,4−19 −−undefine,5−281 dsh,4−19 −−verbose,5−282 dsw,4−19 −−version,5−283 dw,4−20 −−warnings−as−errors,5−284 −B(−−big−endian),5−246 E −C,5−239 ELF/DWARFobjectformat,7−1 −c,5−240 EmbeddedC++,5−72 −D,5−242 end,4−21 −d,5−264 end_unroll_max_size,1−10 −E,5−276 endextern_sdata,1−8 −F,5−269 Endianness,5−15,5−73,5−170,5−200,5−246 −f,5−273 endprofile,1−9 −g,5−241 endprotect,1−9 −I,5−255 Entities,removeunneeded,5−140 −k,5−259 enumoverloading,5−111 −L,5−262 EOF,3−12 −l,5−261 equ,4−22 −l(−−library),5−263 erffunctions,3−10 −n,5−245 erfcfunctions,3−10 −o,5−274 errno,3−4 −p,5−277 Errorlimit,5−75 −t,5−260 Erroroutputfile,5−74 −U,5−281 Exceptionhandling,5−76 −V,5−283 exit,3−18 −v,5−282 EXIT_FAILURE,3−17 −W,5−275 EXIT_SUCCES,3−17 −w,5−272 expfunctions,3−8 preprocessing,5−242 exp2functions,3−8 Copyassignmentoperator,5−62 explicitspecifier,5−112 Copytable,8−16,8−32 expm1functions,3−8 copysignfunctions,3−9 exportkeyword,2−18,5−113 cosfunctions,3−7 Exportedtemplates,2−18 coshfunctions,3−8 Expressions,4−3 cpu,4−7 absolute,4−4 Cross−referencefile,5−161 relative,4−4 ctime,3−21 relocatable,4−4 ExtensionstoC++,2−1 D extern,1−8,4−23 Datatypes,1−2 externC,5−85 db,4−15 externC++,5−85 dd,4−16 externinline,5−114 Debuginfo,5−241 Externinlinefunctions,2−20 Debuginformation,5−169 extern_sdata,1−8 define,4−17 defined,4−7 F Definingamacro,4−44 fabsfunctions,3−9 Dependentnameprocessing,5−108 fclose,3−13 Derivativedefinition,8−1,8−20 fdimfunctions,3−10 dh,4−18 FE_ALL_EXCEPT,3−5 difftime,3−21 FE_DIVBYZERO,3−5 Digraph,5−60 FE_INEXACT,3−5 Directives,4−1 FE_INVALID,3−5 div,3−19 FE_OVERFLOW,3−5 Dollarsigns,5−71 FE_UNDERFLOW,3−5 Doubleasfloat,5−269 feclearexcept,3−5

Index−6 Index fegetenv,3−5 getwc,3−16 fegetexceptflag,3−5 getwchar,3−16 feholdexept,3−5 global,4−25 feof,3−17 Globaltypechecking,5−18,5−205 feraiseexcept,3−5 gmtime,3−21 ferror,3−17 GNUextensions,2−5,5−81 fesetenv,3−5 compilerversion,5−82 fesetexceptflag,3−5 gprel,4−7 fetestexcept,3−5 Guidingdeclarations,5−83 feupdateenv,3−5 fflush,3−13 H fgetc,3−16 Headerfiles,3−3 fgetpos,3−17 alert.h,3−3 fgets,3−16 complex.h,3−3 fgetwc,3−16 ctype.h,3−3 fgetws,3−16 errno.h,3−4 FILENAME_MAX,3−12 fcntl.h,3−4 Floating−point,singleprecision,5−110 fenv.h,3−5 floorfunctions,3−9 float.h,3−5 fmafunctions,3−9 fss.h,3−5 fmaxfunctions,3−10 inttypes.h,3−6 fminfunctions,3−10 io.h,3−6 fmodfunctions,3−9 iso646.h,3−6 fopen,3−13 limits.h,3−7 FOPEN_MAX,3−12 locale.h,3−7 for−initstatement,5−115,5−128 malloc.h,3−7 for/endfor,4−24 math.h,3−7 fpclassify,3−10 setjmp.h,3−11 fprintf,3−15 signal.h,3−11 fputc,3−16 stdarg.h,3−11 fputs,3−16 stdbool.h,3−11 fputwc,3−16 stddef.h,3−12 fputws,3−16 stdint.h,3−6 fread,3−16 stdio.h,3−12 free,3−7,3−18 stdlib.h,3−17 freopen,3−13 string.h,3−19 frexpfunctions,3−8 tgmath.h,3−7 Friendinjection,5−80 time.h,3−21 fscanf,3−15 unistd.h,3−22 fseek,3−16 wchar.h,3−12,3−19,3−21,3−23 fsetpos,3−17 wctype.h,3−3,3−24 fstat,3−23 Headerstop,2−24,2−26 ftell,3−17 Heap,8−16 Function,syntax,4−5 hi,4−7 Functioninlining,1−13 hiadj,4−7 Functionnames,unqualified,5−102 hypotfunctions,3−9 Functionqualifiers,__interrupt,1−15 fwprintf,3−15 I fwrite,3−16 I/Ostreams,5−93 fwscanf,3−15 if/elif/else/endif,4−26 ilogbfunctions,3−8 G imaxabs,3−6 Genericinstructions,4−1,4−49 imaxdiv,3−6 getc,3−16 Implicitinclusion,2−17 getchar,3−16 include,4−27 getcwd,3−22 Includedirectory,5−20,5−36,5−88,5−175,5−210,5−255 getenv,3−19 Includefile,5−21,5−89,5−176 gets,3−16 macros,5−90

Index−7 NiosIIEmbeddedToolsReference

Includefiles,suffix,5−87 isxdigit,3−3 Inlineassembly,__asm,1−4 Inlinefunction,5−114 K Inlinefunctions,1−13 Keyword inline/noinline/smartinline,1−8 bool,5−105 Inlining,5−22,5−117 explicit,5−112 InliningfunctionsinC++,2−20 export,2−18,5−113 Inputspecification,4−1 typename,5−125 Instantiation,2−14 wchar_t,5−160 pending,5−137 template,5−92 L Instantiationmode,2−15 L_tmpnam,3−12 Instantiationpragmas,2−16 Label,4−2 Instructions,4−1 Labels,4−1 generic,4−1,4−49 labs,3−19 Intelhex,recordtype,7−5 ldexpfunctions,3−8 IntelHexrecordformat,7−5 ldiv,3−19 Interruptfunctions,1−15 lgammafunctions,3−10 __interrupt,1−15 Librarianoptions Interruptserviceroutine,1−15 −?,5−312 defining,1−15 −d,5−313 Intrinsicfunctions,1−14 −f,5−314 isalnum,3−3 −m,5−315 isalpha,3−3 −p,5−316 isblank,3−3 −r,5−317 iscntrl,3−3 −t,5−319 isdigit,3−3 −V,5−320 isfinite,3−10 −w,5−321 isgraph,3−3 −x,5−322 isgreater,3−10 addmodule,5−317 isgreaterequal,3−10 createlibrary,5−317 isinf,3−10 deletemodule,5−313 isless,3−10 extractmodule,5−322 islessequal,3−10 movemodule,5−315 islessgreater,3−10 printlistofobjects,5−319 islower,3−3 printlistofsymbols,5−319 isnan,3−10 printmodule,5−316 isnormal,3−10 replacemodule,5−317 ISOCstandard,selecting,5−24,5−258 warninglevel,5−321 isprint,3−3 Libraries,linking,5−204,5−224 ispunct,3−3 Library,specifying,5−213,5−214,5−261,5−262,5−263 isspace,3−3 Lifetime,5−97 isunordered,3−10 Linkermacro,5−198 isupper,3−3 Linkeroptions,5−195 iswalnum,3−3,3−24 −?,5−206 iswalpha,3−3,3−24 −−case−insensitive,5−196 iswblank,3−3 −−chip−output,5−197 iswcntrl,3−3,3−24 −−define,5−198 iswctype,3−24 −−diag,5−199 iswdigit,3−3,3−24 −−endianness,5−200 iswgraph,3−3,3−24 −−error−file,5−201 iswlower,3−3,3−24 −−error−limit,5−202 iswprint,3−3,3−24 −−extern,5−203 iswpunct,3−3,3−24 −−extra−verbose,5−233 iswspace,3−3,3−24 −−first−library−first,5−204 iswupper,3−3,3−24 −−global−type−checking,5−205 iswxdigit,3−3 −−help,5−206 iswxditig,3−24

Index−8 Index

−−hex−format,5−207 outputformat,5−197 −−hex−record−size,5−208 Linkerscriptfile,5−216,5−217 −−ignore−default−library−path,5−214 architecturedefinition,8−1 −−import−object,5−209 boardspecification,8−2 −−include−directory,5−210 busdefinition,8−2 −−incremental,5−211 derivativedefinition,8−1 −−keep−output−files,5−212 memorydefinition,8−2 −−library,5−213 preprocessing,8−3 −−library−directory,5−214 processordefinition,8−2 −−link−only,5−215 sectionlayoutdefinition,8−2 −−lsl−check,5−216 specifying,5−218,5−264 −−lsl−dump,5−217 structure,8−1 −−lsl−file,5−218 Listfile,5−178,5−179 −−map−file,5−219 C++,5−95 −−map−file−format,5−220 list/nolist,4−28 −−misra−c−report,5−221 llabs,3−19 −−munch,5−222 lldiv,3−19 −−no−rescan,5−224 llrintfunctions,3−9 −−no−rom−copy,5−225 llroundfunctions,3−9 −−no−warnings,5−226 lo,4−7 −−non−romable,5−223 Locallabeloverrideoperator,4−47 −−optimize,5−227 localeconv,3−7 −−option−file,5−228 localtime,3−21 −−output,5−229 logfunctions,3−8 −−print−mangled−symbols,5−230 log10functions,3−8 −−strip−debug,5−231 log1pfunctions,3−8 −−user−provided−initialization−code,5−232 log2functions,3−8 −−verbose,5−233 logbfunctions,3−8 −−version,5−234 longjmp,3−11 −−warnings−as−errors,5−235 Lookupofnamesusedintemplates,5−108 −B(−−big−endian),5−200 Lookupofunqualifiedfunctionnames,5−102 −c,5−197 lrintfunctions,3−9 −D,5−198 lroundfunctions,3−9 −d,5−218 lsb,4−8 −e,5−203 lseek,3−23 −f,5−228 lsh,4−8 −I,5−210 LSLexpressionevaluation,8−13 −i,5−232 LSLfunctions −k,5−212 absolute(),8−5 −L,5−214 addressof(),8−5 −l,5−213 exists(),8−5 −M,5−219 max(),8−5 −m,5−220 min(),8−6 −N,5−225 sizeof(),8−6 −O,5−227 LSLkeywords −o,5−229 align,8−16,8−27 −P,5−230 alloc_allowed,8−31 −r,5−211 allow_cross_references,8−28 −S,5−231 architecture,8−15,8−20 −V,5−234 attributes,8−26,8−27 −v,5−233 blocksize,8−32 −vv,5−233 bus,8−15,8−18,8−23 −w,5−226 clustered,8−28 diagnostics,5−226,5−235 contiguous,8−28 libraries,5−213,5−224 copy,8−17,8−27 MapFile,5−219 copy_unit,8−16 miscellaneous,5−196,5−198,5−203,5−209,5−217,5−218 copytable,8−16,8−32 optimization,5−227 core,8−20

Index−9 NiosIIEmbeddedToolsReference

derivative,8−20,8−22 LSLsyntax,8−3 dest,8−16,8−18 architecturedefinition,8−7 dest_dbits,8−18 boardspecification,8−10 dest_offset,8−18 busdefinition,8−6 direction,8−26,8−28 derivativedefinition,8−9 else,8−33 memorydefinition,8−6 extends,8−15,8−20 processordefinition,8−10 fill,8−17,8−21,8−28,8−31 sectionlayoutdefinition,8−10 fixed,8−16,8−30 lstat,3−23 group,8−26,8−27 lsw,4−8 grows,8−16 heap,8−16,8−30 M high_to_low,8−16,8−26 macro/nomacro,1−9 id,8−15,8−16 Macroargumentstring,4−46 id_symbol_prefix,8−17 Macrocall,4−1 if,8−33 Macrodefinition,5−11,5−69,5−167,5−242 load_addr,8−29 Macrooperations,4−44 low_to_high,8−16,8−26 macro/endm,4−29 map,8−15,8−16,8−18,8−21 Macros,4−44 mau,8−15,8−16,8−21,8−23 .fordirective,4−47 mem,8−29 .repeatdirective,4−47 memory,8−21,8−23 argumentconcatenation,4−45 min_size,8−16,8−30 argumentoperator,4−45 no_inline,8−17 argumentstring,4−46 nocopy,8−28 calling,4−44 nvram,8−21 conditionalassembly,4−47 ordered,8−28 defining,4−44 overflow,8−32 locallabeloverride,4−47 overlay,8−28 makeutility,5−286 page,8−16,8−29 predefined,2−22 page_size,8−16,8−29 returndecimalvalueoperator,4−46 priority,8−30 returnhexvalueoperator,4−46 processor,8−22 variableargumentslist,5−78,5−157 ram,8−21 Macros(preprocessor),1−11,4−3 ref_tree,8−27 Makeutilityoptions reserved,8−18,8−21,8−30 −?,5−287 rom,8−21 −a,5−288 run_addr,8−17,8−18,8−29 −c,5−289 section,8−31 −D,5−290 section_layout,8−25 −d,5−291 section_setup,8−24 −DD,5−290 select,8−26 −dd,5−291 size,8−17,8−18,8−21,8−23,8−30,8−32 −e,5−292 space,8−15,8−18 −err,5−293 speed,8−21,8−23 −f,5−294 src_dbits,8−18 −G,5−295 src_offset,8−18 −i,5−296 stack,8−16,8−30 −K,5−297 start_address,8−18 −k,5−298 symbol,8−18 −m,5−299,5−304 template,8−17 −n,5−300 template_symbol,8−17 −p,5−301 type,8−21,8−23 −q,5−302 vector,8−17 −r,5−303 vector_prefix,8−17 −s,5−305 vector_size,8−17 −t,5−306 vector_table,8−17 −time,5−307 width,8−15 −V,5−308

Index−10 Index

−W,5−309 Optimization,5−38,5−182,5−227 −x,5−310 codecompaction,5−22 definingamacro,5−286 inlining,5−23 malloc,3−7,3−18 optimizeforspeed/size,5−52 Mapfilegeneration,5−219 optimize/endoptimize,1−9 Mappings,8−18 Optionfile,5−40,5−131,5−228,5−273,5−299 MB_CUR_MAX,3−17,3−23 Options,saving/restoring,5−40,5−131,5−228 MB_LEN_MAX,3−23 Outputfile,5−133 mblen,3−19 mbrlen,3−23 P mbrtowc,3−23 page,4−33 mbsinit,3−23 Parameterpassing,1−12 mbsrtowcs,3−23 Passingoptions,5−275 mbstate_t,3−23 PCHmode mbstowcs,3−19 automatic,2−24,5−134 mbtowc,3−19 manual,2−26,5−68,5−155 memchr,3−20 perror,3−17 memcmp,3−20 powfunctions,3−9 memcpy,3−19 Pragma memmove,3−19 can_instantiate,2−16 Memorydefinition,8−2 do_not_instantiate,2−16 Memoryqualifiers,1−3 hdrstop,2−24,2−26 memset,3−20 instantiate,2−16 Mergingsourcecode,5−49 no_pch,2−26 message,1−9,4−31 Pragmas,1−7 MISRA−C,5−30,5−31 inC++,2−21 MISRA−Creport,5−221 Precompiledheader,2−24 supportedrules1998,10−1 automatic,2−24,5−134 supportedrules2004,10−5 create,2−26,5−68 version,5−32 directory,2−26,5−135 mktime,3−21 filecannotbeused,5−136 modffunctions,3−8 manual,2−26 MotorolaS−recordformat,7−2 messages,5−122 msb,4−8 performance,2−26 msh,4−8 pragmas,2−26 msw,4−8 prefix,2−25 Multibytecharacters,5−100 use,2−26,5−155 Predefinedmacros,2−22 N Predefinedpreprocessormacros,1−11,4−3 Namespace,2−13,5−101 Predefinedpreprocessorsymbols,4−3 std,5−156 Preprocessing,5−167,5−187,5−271,5−276,8−3 nanfunctions,3−9 storingoutput,5−42,5−138 nearbyintfunctions,3−9 printf,3−13,3−15 nextafterfunctions,3−9 conversioncharacters,3−14 nexttowardfunctions,3−9 printfversions,1−15 no_pch,2−26 Priorityforglobalinitializationfunctions,5−91 Functions,1−12 Processordefinition,8−2,8−22 intrinsic,1−14 Processoroptions,processordefinition,5−8,5−67,5−165 parameterpassing,1−12 Processortype returntypes,1−12 assemblingfor,5−165 NULL,3−12 compilingfor,5−8,5−67,5−239 selecting,5−8,5−67,5−165,5−239 O profile,1−9 offset,4−32 Profiling,5−43,5−277 offsetof,3−12 profiling,1−9 open,3−4 protect,1−9 Operands,4−2 ptrdiff_t,3−12 Operatorkeywords,5−60 putc,3−16

Index−11 NiosIIEmbeddedToolsReference putchar,3−16 SEEK_CUR,3−12,3−16 puts,3−16 SEEK_END,3−12,3−16 putwc,3−16 SEEK_SET,3−12,3−16 putwchar,3−16 Servicerequest,1−15 set,4−37 Q setbuf,3−13 qsort,3−19 setjmp,3−11 Qualifierdeduction,5−119 setlocale,3−7 setvbuf,3−13 R SIGABRT,3−11 SIGFPE,3−11 raise,3−11 SIGILL,3−11 rand,3−18 SIGINT,3−11 RAND_MAX,3−17 signal,3−11 read,3−23 signbit,3−10 realloc,3−7,3−18 SIGSEGV,3−11 Registerusage,1−12 SIGTERM,3−11 remainderfunctions,3−9 sinfunctions,3−7 Remarks,5−139 sinhfunctions,3−8 remove,3−17 size,4−38 remquofunctions,3−9 size_t,3−12 rename,3−17 smartinline,1−8 Renamingsections,5−45 snprintf,3−15 repeat/endrep,4−34 source,4−39 Reservedaddressranges,8−18 source/nosource,1−10 Resetvector,8−18 sprintf,3−15 resume,4−35 sqrtfunctions,3−9 Returndecimalvalueoperator,4−46 srand,3−18 Returnhexvalueoperator,4−46 sscanf,3−15 rewind,3−17 Stack,2−14,8−16 rintfunctions,3−9 Startaddress,8−18 roundfunctions,3−9 stat,3−23 Run−timeC++library,5−63 Statement,4−1 Run−timechecks,5−46 stderr,3−12 Run−timetypeinformation,5−141 stdin,3−12 runtime,1−9 stdinc,1−10 stdout,3−12 S strcat,3−20,4−8 scalblnfunctions,3−8 strchr,3−20 scalbnfunctions,3−8 strcmp,3−20,4−8 scanf,3−14,3−15 strcoll,3−20 conversioncharacters,3−15 strcpy,3−19 scanfversions,1−15 strcspn,3−20 sdata,1−9 strerror,3−20 Secondarytranslationunit,2−19 strftime,3−21 Section,4−36 Stringliterals,const,5−107 section/endsection,1−9 Strings,substring,4−4 Sectionattributes,4−36 strlen,4−8 Sectioninformation,5−189 strncat,3−20 Sectionlayoutdefinition,8−2,8−25 strncmp,3−20 Sectionrenaming,5−45 strncpy,3−19 Sectionsetupdefinition,8−24 strpbrk,3−20 section_code_init,1−10 strpos,4−8 section_const_init,1−10 strrchr,3−20 section_no_code_init,1−10 strspn,3−20 section_no_const_init,1−10 strstr,3−20 Sections,4−36 strtod,3−18 grouping,8−26 strtof,3−18 nested,5−180

Index−12 Index strtoimax,3−6 U strtok,3−20 undef,4−42 strtol,3−18 ungetc,3−16 strtold,3−18 ungetwc,3−16 strtoll,3−18 unlink,3−23 strtoul,3−18 unroll_max_size,1−10 strtoull,3−18 UsingassemblyinCsource,1−4 strtoumax,3−6 usingdeclaration,allowunqualifiedname,5−120 strxfrm,3−20 Substring,4−4 V swprintf,3−15 va_arg,3−11 swscanf,3−15 va_copy,3−11 Symbolnames,4−2 va_end,3−11 Syntaxerrorchecking,5−7,5−65,5−164,5−238 va_start,3−11 Syntaxofanexpression,4−4 Vectortable,8−17 system,3−19 Versioninformation,5−308,5−320 Systemincludedirectory,5−148 vfprintf,3−15 vfscanf,3−15 T vfwprintf,3−15 tanfunctions,3−7 vfwscanf,3−15 tanhfunctions,3−8 Virtualfunctiontable Template,2−14 force,5−79 distinctsignatures,5−109 suppress,5−147 guidingdeclarations,5−83 vprintf,3−15 specialization,5−130 vscanf,3−15 Templatedirectory,5−149 vsprintf,3−15 Templateinstantiation,2−14 vsscanf,3−15 #pragmadirectives,2−16 vswprintf,3−15 automatic,2−14,5−104 vswscanf,3−15 exportedtemplates,2−18 vwprintf,3−15 implicitinclusion,2−17,5−86 vwscanf,3−15 instantiationmodes,2−15,5−92 pending,5−137 W Templates,5−121 warning,1−10 tgammafunctions,3−10 Warnings Tie−breakers,5−94 suppressing,5−37,5−181,5−226,5−272 time,3−21 treataserrors,5−194 time_t,3−21 wchar_t,3−12 Timinginformation,5−150 wchar_tkeyword,5−160 title,4−40 wcrtomb,3−23 tm(struct),3−21 wcscat,3−20 TMP_MAX,3−12 wcschr,3−20 tmpfile,3−17 wcscmp,3−20 tmpnam,3−17 wcscoll,3−20 tolower,3−3 wcscpy,3−19 toupper,3−3 wcscspn,3−20 towctrans,3−24 wcsncat,3−20 towlower,3−3,3−24 wcsncmp,3−20 towupper,3−3,3−24 wcsncpy,3−19 tradeoff,1−10 wcspbrk,3−20 Transferringparametersbetweenfunctions,1−12 wcsrchr,3−20 truncfunctions,3−9 wcsrtombs,3−23 type,4−41 wcsspn,3−20 Typechecking,5−18,5−205 wcsstr,3−20 Typequalifier,__unaligned,1−2 wcstod,3−18 Typetraitshelpers,5−152 wcstof,3−18 typenamekeyword,5−125

Index−13 NiosIIEmbeddedToolsReference wcstoimax,3−6 wctype,3−24 wcstok,3−20 weak,1−10,4−43 wcstol,3−18 WEOF,3−12 wcstold,3−18 wmemchr,3−20 wcstoll,3−18 wmemcmp,3−20 wcstombs,3−19 wmemcpy,3−19 wcstoul,3−18 wmemmove,3−19 wcstoull,3−18 wmemset,3−20 wcstoumax,3−6 wprintf,3−15 wcsxfrm,3−20 write,3−23 wctob,3−23 wscanf,3−15 wctomb,3−19 wstrftime,3−21 wctrans,3−24

Index−14