The GCC Compilers.pdf
(
163 KB
)
Pobierz
SoftwareDesignLectureNotes
TheGCCCompilers
Prof.StewartWeiss
TheGCCCompilers
Preface
IfallyoureallywanttoknowishowtocompileyourCorC++programusingGCC,andyoudon’thave
thetimeorinterestinunderstandingwhatyou’redoingorwhatGCCis,youcanskipmostofthesenotes
andcuttothechasebyjumpingtotheexamplesinSection6.Ithinkyouwillbebettero
ifyoutakethe
timetoreadthewholething,sinceIbelievethatwhenyouunderstandwhatsomethingis,youarebetter
ableto
gureouthowtouseit.
IfyouhaveneverusedGCC,orifyouhaveuseditwithoutreallyknowingwhatyoudid,(becauseyouwere
prettymuchusingitbyrote),thenyoushouldreadthis.IfyouthinkyoudounderstandGCCanddonot
useitbyrote,youmaystillbene
tfromreadingthis;youmightlearnsomethinganyway.BecauseIbelieve
intheimportanceofhistoricalcontext,IbeginwithabriefhistoryofGCC.
1BriefHistory
RichardStallmanstartedtheGNUProjectin1984withthepurposeofcreatingafree,Unix-likeoperating
system.Hismotivationwastopromotefreedomandcooperationamongusersandprogrammers.Since
UnixrequiresaCcompilerandtherewerenofreeCcompilersatthetime,theGNUProjecthadtobuild
aCcompilerfromthegroundup.TheFreeSoftwareFoundationwasanon-pro
torganizationcreatedto
supporttheworkoftheGNUProject.
GCCwas
rstreleasedin1987.Thiswasasigni
cantbreakthrough,beingthe
rstportableANSIC
optimizingcompilerreleasedasfreesoftware.SincethattimeGCChasbecomeoneofthemostimportant
toolsinthedevelopmentoffreesoftware.
In1992,itwasrevisedandreleasedasGCC2.0,withtheaddedfeatureofaC++compiler.Itwasrevised
againin1997,withimprovedoptimizationandC++support.Thesefeaturesbecamewidelyavailableinthe
3.0releaseofGCCin2001.
2LanguagesSupportedbyGCC
GCCstandsfor
GNUCompilerCollection
.GCCisanintegratedcollectionofcompilersforseveralmajor
programminglanguages,whichasofthiswritingareC,C++,Objective-C,Java,FORTRAN,andAda.
TheGNUcompilersallgeneratemachinecode,nothigher-levellanguagecodewhichisthentranslatedvia
anothercompiler.
3LanguageStandardsSupportedbyGCC
Forthemostpart,GCCsupportsthemajorstandardsandprovidestheabilitytoturnthemonoro
.GCC
itselfprovidesfeaturesforlanguageslikeCandC++thatdeviatefromcertainstandards,butturningonthe
appropriatecompileroptionswillmakeitcheckprogramsagainstthestandards.Thesectionbelowentitled
Consultthemanualfordetails.
1
SoftwareDesignLectureNotes
TheGCCCompilers
Prof.StewartWeiss
4ABitAbouttheCompileandLinkProcess
SupposethatyouhavewrittenaverysimpleCprogramsuchasthefollowing
1: #include<stdio.h>
2:
3: intmain()
4: {
5: printf("Helloworld\n");
6: return0;
7: }
andplaceditina
lenamedhelloworld.c.Youmayhavebeentoldthatyouneedthat
rstline,whichis
the#includedirective,#include<stdio.h>,butyoumaynotreallyknowwhyitisthere.Thereasonis
thattheprintf()functionisdeclaredintheheader
lestdio.handinorderforthecompilertocheckthat
youarecallingitcorrectlyinline5,itneedstocomparethedeclarationoftheprintf()functionwithits
use.Thecompilerjustneedstocheckthingssuchasthenumberofparameters,theirtypes,andthereturn
valueofthefunction.
Thewaythisisdoneisbycopyingtheentireheader
leintotheprogrambeforethecompilerruns.The
#includedirectiveliterallycopiestheentire
le,stdio.h,intoyourprogramstartingatline1.Thisisdone
byaprogramcalledtheCpreprocessor.Oncetheheader
leisphysicallypartofyourprogram,thecompiler
willrunandwillbeabletovalidatethecalltoprintf()bycomparingittothedeclarationthatitreadin
anearlierlineinthemodi
ed
le.
Theheader
ledoesnotcontainthede
nitionoftheprintf()function,i.e.,itsimplementation.Thatis
containedintheCStandardI/OLibrary.Thecompilerisnotabletocreatethemachineinstructionsthat
willcausetheprintf()functiontorun,becauseitdoesnotknow
where
theprintf()implementationis;
itcannotcreatea
call
tothisfunction.Instead,thecompilerplacesanotationintheexecutable
lethat
says,moreorless,
thecalltoprintf()mustberesolvedbythelinker.
Thelinkerisaseparateprogramthatrunsafterthecompiler.Itlooksatalloftheunresolvedsymbolsinthe
program,suchasprintf(),andtriestoresolvethembylookinguptheirlocationsinthesoftwarelibraries
thattheprogramneeds.Inthiscase,thelinkerneedstolookupintheCStandardI/OLibrarythelocation
oftheprintf()function,sothatitcanpatchthecodetomakeacalltoit.TheCStandardI/OLibrary
isspecialbecauseitisusedinalmosteveryCprogram,andthereforemanyCimplementationsincludeit
withintheCruntimelibrary.Thismakesitpossibleforthelinkerto
nditeasily.
ThesamediscussionwouldapplyifyouwrotetheaboveprograminC++asin
1: #include<iostream>
2:
3: intmain()
4: {
5: std::cout<<"Helloworld\n";
6: return0;
7: }
onlyinsteadofusingthestdio.hheader
le,itwouldusetheiostreamheader
le,andtheiostreamlibrary
inC++insteadoftheCStandardI/OLibrary.
Insummary,aheader
lecontainsdeclarationsthatthecompilerneeds,butnotimplementations.The
correspondinglibrary
lehasthose.Thecompilerneedstheheader
lesbutnotthelibraries;thelinker
needsthelibraries,nottheheader
les.
2
SoftwareDesignLectureNotes
TheGCCCompilers
Prof.StewartWeiss
5CommandOptionsandControl
Fromthispointforward,lowercasegccwillrefertotheexecutableprogramname,i.e.,whatyoutypetorun
theGCCcompiler.
5.1OptionsandFileExtensionsControllingtheKindofOutput
Whenyourungcc,itusuallyperformspreprocessing,compiling,assemblyandlinking.Thereareoptionsto
controlwhichofthesestepsareperformed.gcccanalsolookatthe
leextensionforguidanceastowhich
compilertouseandwhatkindofoutputtogenerate.Forexample,a
leendingin.cisassumedtobeC
sourcecode,and
lesendingineither.cc,.cpp,.c++,.C,and.cxxaretakentobeC++sourcecode.
(ThereareotherextensionsthatarealsotakentoimplyC++sourcecode.)Youshouldconsultthemanual
forotherextensionsandlanguages.Thefollowingoptionsareeitherveryusefulorenlightening.
-c Compileorassemblethesource
les,butdonotlink.Thelinkingstagesimplyisnotdone.
Theultimateoutputisintheformofanobject
leforeachsource
le.Bydefault,the
object
lenameforasource
leismadebyreplacingthesu
x‘.c’,‘.i’,‘.s’,etc.,with
‘.o’.E.g.,
gcc
cmyprog.c
producesmyprog.o.
-s Stopafterthestageofcompilationproper;donotassemble.Theoutputisintheformof
anassemblercode
leforeachnon-assemblerinput
lespeci
ed.Bydefault,theassembler
lenameforasource
leismadebyreplacingthesu
x‘.c’,‘.i’,etc.,with‘.s’.Itis
unlikelythatyouwillneedtodothis,butitiseducationaltolookattheoutputofthe
compiler,whichisinassemblylanguage.
-E Stopafterthepreprocessingstage;donotrunthecompilerproper.Theoutputisinthe
formofpreprocessedsourcecode,whichissenttothestandardoutput.E.g.,
gcc
Emyprog.c>myprog.i
Thisisalsoaneducationalexercise
youcanseeforyourselfwhatthepreprocessordoes
toyoursourcecode,togetabetterunderstandingofhowtouseit.
-ofile Placeoutputin
lefile.Thisappliesregardlessofwhateversortofoutputisbeing
produced,whetheritisanexecutable
le,anobject
le,anassembler
leorpreprocessed
Ccode.Usuallyyouusethistonameyourexecutable.E.g.,
gcc
omyprogmyprog.c
-v Print(onstandarderroroutput)thecommandsexecutedtorunthestagesofcompilation.
Alsoprinttheversionnumberofthecompilerdriverprogramandofthepreprocessorand
thecompilerproper.
--help Print(onthestandardoutput)adescriptionofthecommandlineoptionsunderstoodby
gcc.
3
SoftwareDesignLectureNotes
TheGCCCompilers
Prof.StewartWeiss
5.2CompilingC++Programs
gcccomeswithacompilernamedg++thatspeci
callycompilesC++programs,regardlessofthe
le
extension.SometimesyouneedtousetheC++compilereventhoughthe
leextensionisnotaC++
extension;inthiscaseyouneedtouseg++.
5.3OptionsthatControltheCDialect
By
dialect
ismeantaspeci
ccollectionoffeaturesofC.Forexample,theANSIstandardknownasISO90
CisadialectofC.ThefullsetoffeaturessupportedbygccismuchlargerthantheANSIstandard,and
thisisalsoadialect.AnotherdialectisobtainedbyaddingGNUextensionstotheANSIISOC90standard.
YoucanselectivelyremovefeaturesfromthefullGNUsetofextensions.Thebasicoptions,however,are:
-ansi InCmode,supportallISOC90programs.InC++mode,removeGNU
extensionsthatcon
ictwithISOC++.Thisturnso
certainfeaturesofgccthat
areincompatiblewithISOC90(whencompilingCcode),orofstandardC++
(whencompilingC++code).
Forexample,thegetline()functionisaGNUextensiontoC.ItisnotinANSIC.
Ifyourprogrammyprog.ccontainsitsowngetline()functionthenifyoucompile
withtheline
gccmyprog.c
youwillgettheerror
temp4.c:4:error:conflictingtypesfor‘getline’
butifyouuse
gcc-ansimyprog.c
theGNUextensionswillbedisabled,andtherewillbenotypecon
ict.
-std= Whenfollowedbyaspeci
cdialectdesignatingstringsuchas‘c90’or‘gnu9x’,it
speci
esthatdialect.
-fno-... Therearemanyoptionsthatbeginwith
fno-andarefollowedbyastringthat
representssomefeaturetodisable.The’no’means’turno
’.Consultthemanual.
5.4OptionsthatControlWarnings
Warningsarediagnosticmessagesaboutconstructionsthatarenoterrors,butareoftenassociatedwith
errors.Forexample,whenavariableisdeclaredbutneverusedinaprogram,itispossiblethatthe
programmeroverlookedsomething,sothecompilercouldissueawarningwhenit
ndssuchaconstruction.
gccallowsyoutosuppresscertainwarningsandrequestothers.Someofthemorecommonoptionsarelisted
below.
4
SoftwareDesignLectureNotes
TheGCCCompilers
Prof.StewartWeiss
-w Inhibitallwarningmessages.
-Wall Enableallwarningmessages(recommendedforalldevelopmentwork).
-Wextra Enablewarningsthatarenotcheckedby-Wall.Forexample,comparingan
unsignedintvariableagainst-1suggeststhatyouforgotthatthevariablewas
unsigned.
5.5OptionsForDebugging
-g Thisproducesdebugginginformationintheoperatingsystem’snativeformat.
GDBcanworkwiththisdebugginginformation.Onmostsystemsthatusestabs
format,‘-g’enablesuseofextradebugginginformationthatonlyGDBcanuse;
thisextrainformationmakesdebuggingworkbetterinGDBbutwillprobably
makeotherdebuggerscrashorrefusetoreadtheprogram.E.g.,
gcc-g-omyprogmyprog.c
Onceyouhavecompiledaprogramwithdebugginginformation,youcanrunitunderthecontrolofthe
debugger.Ofcourseyouhavetolearnhowtousethedebugger,gdb,fromthecommandline,orfromwithin
aGUI-basedSDKthatusesitastheunderlyingdebugger.
5.6OptionsControllingthePreprocessor
Ofcourseyouareawareofthefactthatwhenyourprogramiscompiled,thevery
rststepthatthecompiler
takesistorunthepreprocessor,whichprocessesallofthepreprocessordirectives,thoselinesthatbeginwith
thepoundsign’#’.Thereareoptionsthatcontrolhowthepreprocessorbehaves,andtheseareimportant
toknowandunderstand.Themostimportantare(1)howtode
nesymbolsonthecommandline,and(2)
howtotellthepreprocessorwheretolookforinclude-
les.
-Dname Thisprede
nesnameasamacrosymbol,withthevalue1,ortrueifyouwant
tothinkofitthatway.
-Dname=definition Thecontentsofde
nitionaretokenizedandprocessedasiftheyappeared
duringtranslationphasethreeina‘#define’directive.E.g.,
gcc-Dtestvalue=6-omyprogmyprog.c
isthesameasifyouhadplaced
#definetestvalue6
inmyprog.c
Ifyouareinvokingthepreprocessorfromashellorshell-likeprogramyouneedtousetheshell’squoting
syntaxtoprotectcharacterssuchasspacesthathaveameaningintheshellsyntax.Forexample,
gcc-D’introduction=AArgh$#^*!!’-omyprogmyprog.c
5
Plik z chomika:
michalr1n
Inne pliki z tego folderu:
pixel.7z
(28 KB)
winscp554source.zip
(9845 KB)
os.7z
(80071 KB)
xine.tar(2).gz
(31592 KB)
mpfrontend-code-4-trunk(1).zip
(80 KB)
Inne foldery tego chomika:
Pliki dostępne do 01.06.2025
Pliki dostępne do 19.01.2025
! Crystal Reports
! HTML CSS XHTML
█ STRZELANKI
Zgłoś jeśli
naruszono regulamin