Tải bản đầy đủ (.pdf) (1,118 trang)

C++ cookbook (2005)

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (3.25 MB, 1,118 trang )

C++Cookbook
ByJeffCogswell,ChristopherDiggins,RyanStephens,
JonathanTurkanis
...............................................
Publisher:O'Reilly
PubDate:November2005
ISBN:0-596-00761-2
Pages:592

TableofContents|Index

Despiteitshighlyadaptableandflexiblenature,C++isalsooneofthemorecomplex
programminglanguagestolearn.Oncemastered,however,itcanhelpyouorganizeand
processinformationwithamazingefficiencyandquickness.
TheC++Cookbookwillmakeyourpathtomasterymuchshorter.Thispractical,problemsolvingguideisidealifyou'reanengineer,programmer,orresearcherwritingan
applicationforoneofthelegionsofplatformsonwhichC++runs.Thealgorithmsprovided
inC++Cookbookwilljump-startyourdevelopmentbygivingyousomebasicbuilding
blocksthatyoudon'thavetodeveloponyourown.
Lessatutorialthanaproblem-solver,thebookaddressesmanyofthemostcommon
problemsyou'relikelyencounter--whetheryou'vebeenprogramminginC++foryearsor
you'rerelativelynewtothelanguage.Herearejustsomeofthetime-consumingtasksthis
bookcontainspracticalsolutionsfor:
Readingthecontentsofadirectory
Creatingasingletonclass
Dateandtimeparsing/arithmetic
Stringandtextmanipulation
Workingwithfiles
ParsingXML
Usingthestandardcontainers
TypicalofO'Reilly's"Cookbook"series,C++Cookbookiswritteninastraightforward
format,featuringrecipesthatcontainproblemstatementsandcodesolutions,andapply


nottohypotheticalsituations,butthosethatyou'relikelytoencounter.Adetailed
explanationthenfollowseachrecipeinordertoshowyouhowandwhythesolutionworks.


Thisquestion-solution-discussionformatisaproventeachingmethod,asanyfanofthe
"Cookbook"seriescanattestto.Thisbookwillmovequicklytothetopofyourlistof
essentialC++references.


C++Cookbook
ByJeffCogswell,ChristopherDiggins,RyanStephens,
JonathanTurkanis
...............................................
Publisher:O'Reilly
PubDate:November2005
ISBN:0-596-00761-2
Pages:592

TableofContents|Index


















































Copyright
Preface
AbouttheExamples
ConventionsUsedinThisBook
UsingCodeExamples
CommentsandQuestions
SafariEnabled
Acknowledgments
Chapter1.BuildingC++Applications
IntroductiontoBuilding
Recipe1.1.ObtainingandInstallingGCC
Recipe1.2.BuildingaSimple"Hello,World"ApplicationfromtheCommandLine
Recipe1.3.BuildingaStaticLibraryfromtheCommandLine
Recipe1.4.BuildingaDynamicLibraryfromtheCommandLine
Recipe1.5.BuildingaComplexApplicationfromtheCommandLine
Recipe1.6.InstallingBoost.Build
Recipe1.7.BuildingaSimple"Hello,World"ApplicationUsingBoost.Build
Recipe1.8.BuildingaStaticLibraryUsingBoost.Build
Recipe1.9.BuildingaDynamicLibraryUsingBoost.Build
Recipe1.10.BuildingaComplexapplicationUsingBoost.Build
Recipe1.11.BuildingaStaticLibrarywithanIDE
Recipe1.12.BuildingaDynamicLibrarywithanIDE
Recipe1.13.BuildingaComplexApplicationwithanIDE

Recipe1.14.ObtainingGNUmake












































































Recipe1.15.BuildingASimple"Hello,World"ApplicationwithGNUmake
Recipe1.16.BuildingaStaticLibrarywithGNUMake
Recipe1.17.BuildingaDynamicLibrarywithGNUMake
Recipe1.18.BuildingaComplexApplicationwithGNUmake
Recipe1.19.DefiningaMacro
Recipe1.20.SpecifyingaCommand-LineOptionfromYourIDE
Recipe1.21.ProducingaDebugBuild
Recipe1.22.ProducingaReleaseBuild
Recipe1.23.SpecifyingaRuntimeLibraryVariant
Recipe1.24.EnforcingStrictConformancetotheC++Standard
Recipe1.25.CausingaSourceFiletoBeLinkedAutomaticallyAgainsta
SpecifiedLibrary
Recipe1.26.UsingExportedTemplates
Chapter2.CodeOrganization
Introduction

Recipe2.1.MakingSureaHeaderFileGetsIncludedOnlyOnce
Recipe2.2.EnsuringYouHaveOnlyOneInstanceofaVariableAcrossMultiple
SourceFiles
Recipe2.3.Reducing#includeswithForwardClassDeclarations
Recipe2.4.PreventingNameCollisionswithNamespaces
Recipe2.5.IncludinganInlineFile
Chapter3.Numbers
Introduction
Recipe3.1.ConvertingaStringtoaNumericType
Recipe3.2.ConvertingNumberstoStrings
Recipe3.3.TestingWhetheraStringContainsaValidNumber
Recipe3.4.ComparingFloating-PointNumberswithBoundedAccuracy
Recipe3.5.ParsingaStringContainingaNumberinScientificNotation
Recipe3.6.ConvertingBetweenNumericTypes
Recipe3.7.GettingtheMinimumandMaximumValuesforaNumericType
Chapter4.StringsandText
Introduction
Recipe4.1.PaddingaString
Recipe4.2.TrimmingaString
Recipe4.3.StoringStringsinaSequence
Recipe4.4.GettingtheLengthofaString
Recipe4.5.ReversingaString
Recipe4.6.SplittingaString
Recipe4.7.TokenizingaString
















































































Recipe4.8.JoiningaSequenceofStrings
Recipe4.9.FindingThingsinStrings
Recipe4.10.FindingthenthInstanceofaSubstring
Recipe4.11.RemovingaSubstringfromaString
Recipe4.12.ConvertingaStringtoLower-orUppercase
Recipe4.13.DoingaCase-InsensitiveStringComparison
Recipe4.14.DoingaCase-InsensitiveStringSearch
Recipe4.15.ConvertingBetweenTabsandSpacesinaTextFile
Recipe4.16.WrappingLinesinaTextFile
Recipe4.17.CountingtheNumberofCharacters,Words,andLinesinaTextFile
Recipe4.18.CountingInstancesofEachWordinaTextFile
Recipe4.19.AddMarginstoaTextFile
Recipe4.20.JustifyaTextFile
Recipe4.21.SqueezeWhitespacetoSingleSpacesinaTextFile
Recipe4.22.AutocorrectTextasaBufferChanges
Recipe4.23.ReadingaComma-SeparatedTextFile
Recipe4.24.UsingRegularExpressionstoSplitaString
Chapter5.DatesandTimes
Introduction

Recipe5.1.ObtainingtheCurrentDateandTime
Recipe5.2.FormattingaDate/TimeasaString
Recipe5.3.PerformingDateandTimeArithmetic
Recipe5.4.ConvertingBetweenTimeZones
Recipe5.5.DeterminingaDay'sNumberWithinaGivenYear
Recipe5.6.DefiningConstrainedValueTypes
Chapter6.ManagingDatawithContainers
Introduction
Recipe6.1.UsingvectorsInsteadofArrays
Recipe6.2.UsingvectorsEfficiently
Recipe6.3.Copyingavector
Recipe6.4.StoringPointersinavector
Recipe6.5.StoringObjectsinalist
Recipe6.6.MappingstringstoOtherThings
Recipe6.7.UsingHashedContainers
Recipe6.8.StoringObjectsinSortedOrder
Recipe6.9.StoringContainersinContainers
Chapter7.Algorithms
Introduction















































































Recipe7.1.IteratingThroughaContainer
Recipe7.2.RemovingObjectsfromaContainer
Recipe7.3.RandomlyShufflingData
Recipe7.4.ComparingRanges
Recipe7.5.MergingData
Recipe7.6.SortingaRange
Recipe7.7.PartitioningaRange
Recipe7.8.PerformingSetOperationsonSequences
Recipe7.9.TransformingElementsinaSequence
Recipe7.10.WritingYourOwnAlgorithm
Recipe7.11.PrintingaRangetoaStream
Chapter8.Classes
Introduction
Recipe8.1.InitializingClassMemberVariables
Recipe8.2.UsingaFunctiontoCreateObjects(a.k.a.FactoryPattern)
Recipe8.3.UsingConstructorsandDestructorstoManageResources(orRAII)
Recipe8.4.AutomaticallyAddingNewClassInstancestoaContainer
Recipe8.5.EnsuringaSingleCopyofaMemberVariable
Recipe8.6.DetermininganObject'sTypeatRuntime
Recipe8.7.DeterminingifOneObject'sClassIsaSubclassofAnother
Recipe8.8.GivingEachInstanceofaClassaUniqueIdentifier
Recipe8.9.CreatingaSingletonClass
Recipe8.10.CreatinganInterfacewithanAbstractBaseClass
Recipe8.11.WritingaClassTemplate
Recipe8.12.WritingaMemberFunctionTemplate

Recipe8.13.OverloadingtheIncrementandDecrementOperators
Recipe8.14.OverloadingArithmeticandAssignmentOperatorsforIntuitiveClass
Behavior
Recipe8.15.CallingaSuperclassVirtualFunction
Chapter9.ExceptionsandSafety
Introduction
Recipe9.1.CreatinganExceptionClass
Recipe9.2.MakingaConstructorException-Safe
Recipe9.3.MakinganInitializerListException-Safe
Recipe9.4.MakingMemberFunctionsException-Safe
Recipe9.5.SafelyCopyinganObject
Chapter10.StreamsandFiles
Introduction
Recipe10.1.LiningUpTextOutput

















































































Recipe10.2.FormattingFloating-PointOutput
Recipe10.3.WritingYourOwnStreamManipulators
Recipe10.4.MakingaClassWritabletoaStream
Recipe10.5.MakingaClassReadablefromaStream
Recipe10.6.GettingInformationAboutaFile
Recipe10.7.CopyingaFile
Recipe10.8.DeletingorRenamingaFile
Recipe10.9.CreatingaTemporaryFilenameandFile
Recipe10.10.CreatingaDirectory
Recipe10.11.RemovingaDirectory
Recipe10.12.ReadingtheContentsofaDirectory
Recipe10.13.ExtractingaFileExtensionfromaString
Recipe10.14.ExtractingaFilenamefromaFullPath
Recipe10.15.ExtractingaPathfromaFullPathandFilename
Recipe10.16.ReplacingaFileExtension
Recipe10.17.CombiningTwoPathsintoaSinglePath
Chapter11.ScienceandMathematics
Introduction
Recipe11.1.ComputingtheNumberofElementsinaContainer
Recipe11.2.FindingtheGreatestorLeastValueinaContainer
Recipe11.3.ComputingtheSumandMeanofElementsinaContainer
Recipe11.4.FilteringValuesOutsideaGivenRange
Recipe11.5.ComputingVariance,StandardDeviation,andOtherStatistical
Functions
Recipe11.6.GeneratingRandomNumbers
Recipe11.7.InitializingaContainerwithRandomNumbers
Recipe11.8.RepresentingaDynamicallySizedNumericalVector
Recipe11.9.RepresentingaFixed-SizeNumericalVector

Recipe11.10.ComputingaDotProduct
Recipe11.11.ComputingtheNormofaVector
Recipe11.12.ComputingtheDistanceBetweenTwoVectors
Recipe11.13.ImplementingaStrideIterator
Recipe11.14.ImplementingaDynamicallySizedMatrix
Recipe11.15.ImplementingaConstant-SizedMatrix
Recipe11.16.MultiplyingMatricies
Recipe11.17.ComputingtheFastFourierTransform
Recipe11.18.WorkingwithPolarCoordinates
Recipe11.19.PerformingArithmeticonBitsets
Recipe11.20.RepresentingLargeFixed-WidthIntegers







































































Recipe11.21.ImplementingFixed-PointNumbers
Chapter12.Multithreading
Introduction
Recipe12.1.CreatingaThread
Recipe12.2.MakingaResourceThread-Safe
Recipe12.3.NotifyingOneThreadfromAnother
Recipe12.4.InitializingSharedResourcesOnce
Recipe12.5.PassinganArgumenttoaThreadFunction
Chapter13.Internationalization
Introduction

Recipe13.1.HardcodingaUnicodeString
Recipe13.2.WritingandReadingNumbers
Recipe13.3.WritingandReadingDatesandTimes
Recipe13.4.WritingandReadingCurrency
Recipe13.5.SortingLocalizedStrings
Chapter14.XML
Introduction
Recipe14.1.ParsingaSimpleXMLDocument
Recipe14.2.WorkingwithXercesStrings
Recipe14.3.ParsingaComplexXMLDocument
Recipe14.4.ManipulatinganXMLDocument
Recipe14.5.ValidatinganXMLDocumentwithaDTD
Recipe14.6.ValidatinganXMLDocumentwithaSchema
Recipe14.7.TransforminganXMLDocumentwithXSLT
Recipe14.8.EvaluatinganXPathExpression
Recipe14.9.UsingXMLtoSaveandRestoreaCollectionofObjects
Chapter15.Miscellaneous
Introduction
Recipe15.1.UsingFunctionPointersforCallbacks
Recipe15.2.UsingPointerstoClassMembers
Recipe15.3.EnsuringThataFunctionDoesn'tModifyanArgument
Recipe15.4.EnsuringThataMemberFunctionDoesn'tModifyItsObject
Recipe15.5.WritinganOperatorThatIsn'taMemberFunction
Recipe15.6.InitializingaSequencewithComma-SeparatedValues
Colophon
Index


Copyright©2006O'ReillyMedia,Inc.Allrightsreserved.
PrintedintheUnitedStatesofAmerica.

PublishedbyO'ReillyMedia,Inc.,1005GravensteinHighway
North,Sebastopol,CA95472.
O'Reillybooksmaybepurchasedforeducational,business,or
salespromotionaluse.Onlineeditionsarealsoavailablefor
mosttitles().Formoreinformation,
contactourcorporate/institutionalsalesdepartment:(800)
998-9938or
NutshellHandbook,theNutshellHandbooklogo,andthe
O'ReillylogoareregisteredtrademarksofO'ReillyMedia,Inc.
TheCookbookseriesdesignations,C++Cookbook,theimageof
acollie,andrelatedtradedressaretrademarksofO'Reilly
Media,Inc.
Manyofthedesignationsusedbymanufacturersandsellersto
distinguishtheirproductsareclaimedastrademarks.Where
thosedesignationsappearinthisbook,andO'ReillyMedia,Inc.
wasawareofatrademarkclaim,thedesignationshavebeen
printedincapsorinitialcaps.
Whileeveryprecautionhasbeentakeninthepreparationofthis
book,thepublisherandauthorsassumenoresponsibilityfor
errorsoromissions,orfordamagesresultingfromtheuseof
theinformationcontainedherein.


Preface
C++runsonvirtuallyeveryplatformandinaninfinitenumber
ofapplications.Ifyouboughtormightbuythisbook,youare
probablyanengineerorresearcherwritingoneofthese
applications.Butregardlessofwhatyouarewritingandwhat
platformyouaretargeting,oddsarethatyouwillbere-solving
manyofthesameproblemsthatotherC++programmershave

beensolvingforyears.Whatwehavedoneinthisbookissolve
manyofthesecommonproblemsandexplaineachofthe
solutions.
WhetheryouhavebeenprogramminginC++foryearsorare
relativelynewtothelanguage,youareprobablyfamiliarwith
thethingsyouhaverewriteoneachnewproject:Dateandtime
parsing/arithmetic,manipulatingstringandtext,workingwith
files,parsingXML,usingthestandardcontainers,andsoon.
Thesearethekindsofproblemsthisbookcontainssolutionsfor.
Insomecases(e.g.,dateandtimearithmetic),thestandard
librarycontainsverylittlesupport.Inothers(e.g.,string
manipulation)thestandardlibrarycontainsfunctionallyrich
classes,butitcan'tdoeverythingandsomeverycommontasks
arecumbersome.
Theformatisstraightforward.Eachrecipehasaproblem
statementandacodesolution,andmosthaveadiscussionthat
follows.Wehavetriedtobepragmaticandsolvetheproblems
athandwithoutdigressingtoofar,butinmanycasesthereare
relatedtopicsthataresouseful(orjustcool)thatwehaveto
provideapageortwoofexplanation.
ThisisabookaboutsolvingcommonproblemswithC++,but
notabookaboutlearningC++.Weassumethatyouhaveat
leastabasicknowledgeofC++andobject-oriented
programming.Inparticular,itwillbehelpfulifyouhaveatleast
somefamiliaritywith:


C++inheritanceandvirtualfunctions
Thestandardlibrary
ComponentsoftheStandardTemplateLibrary(containers,

iterators,andalgorithms)
Templates
Thesearenotstrictprerequisitesforreadingthisbook,but
havingatleastabasicknowledgeofthemwillhelp.


AbouttheExamples
Incraftingourcodeexamples,westroveforsimplicity,
portability,andperformance.Thedesignforeachsolution
followedasimilarpath:usestandardC++(languageorlibrary)
ifpossible;ifnot,useadefactostandardasthereplacement.
Forexample,manyoftherecipesthatdealwithstringsusethe
standardstringclass,andmostofthemathematicaland
scientificrecipesusestandardnumerictypes,containers,and
templates.Thestandardlibraryhasstrongsupportforthese
areas,sostandardfacilitiesareaperfectfit.Bycomparison,
however,C++haslittleornostandardizedsupportfor
multithreadingorXMLparsing.Thus,weusedthe
multithreadingsupportprovidedintheBoostThreadslibrary
andtheXMLparsingfunctionalityprovidedbytheXerces
parser.
Often,therearemanywaystodothesamethinginC++,which
givesdevelopersflexibility,butalsoinvitessomecontroversy.
Mostoftheexamplesillustratethebestgeneralsolutionwe
couldcomeupwith,butthatdoesn'tmeanthatit'sthebest
solutionever.Iftherearealternativesolutionsthatarebetterin
somewaysandnotasgoodinothers(maybethesolutionthat
usesthestandardlibraryisawkwardorunintuitive;inthiscase,
wemayprovideanalternativethatusesBoost),wepresentthe
alternativeanywaytogiveyousomeinsightintothevarious

solutionsthatareavailable.
Lotsoftheexamplesusetemplates.Ifyoudon'thavemuch
experiencewritingtemplates,youshouldgetsomesoon.There
isverylittleintroductorymaterialontemplatesinthisbook,
exceptfortworecipesinChapter8:Recipe8.11andRecipe
8.12.MostoftheinterestingdevelopmentsinC++areinthe
areasoftemplatemetaprogrammingandpolicy-baseddesign.
Atthetimeofthiswriting,thereisalotofmovementinthe


C++community.Thefirsttechnicalreport(calledTR1)ismore
orlessstable.Itisastandardizedlistoffeaturesthatwillbe
eventuallyaddedtothenextversionoftheC++standard.Itis
notrequiredthatstandardlibraryimplementationssupportit,
butmanyvendorshavealreadybegunimplementingTR1and
youcanexpecttoseeitappearinginshippedcompilerssoon.
ManyofthelibrariesinTR1firstappearedintheBoostproject.
WeuselibrariesfromBoostalot.Boostisasetofopensource,
peer-reviewed,portablelibrariesthatfillinmanyofthegapsin
thestandardlibrary.Thecurrentversionasofthiswritingis
1.32,and1.33shouldbeoutanytimenow.Weprovidemany
pointerstospecificBoostlibrariesintheexamples.Formore
informationonBoostingeneral,checkouttheprojectwebsite
atwww.boost.org.




ConventionsUsedinThisBook
Thefollowingtypographicalconventionsareusedinthisbook:


Italic
Indicatesnewterms,URLs,emailaddresses,filenames,file
extensions,pathnames,directories,Unixutilities,
commands,andcommand-lineparameters.

<...>
Angle-bracketssurroundelementsthatyouneedtospecify
incommandsandcommand-lineparameterswhenthose
elementsappearinline,initalics.

Constantwidth
Indicatescodeorfragmentsthereof.Forexample,class
names,methodnames,andthelikearerenderedin
constantwidthwhenevertheyappearinthetext.

Constantwidthbold
Showsuser-inputinmixed,input/outputexamples.

Constantwidthitalic


Indicatesuser-specifieditemsinsyntaxexamples.

Indicatesatip,suggestion,orgeneralnote.

Indicatesawarningorcaution.


UsingCodeExamples

Thisbookisdesignedtohelpyougetyourjobdone.Ingeneral,
youmayusethecodeinthisbookinyourprogramsand
documentation.Youdonotneedtocontactusforpermission
unlessyou'rereproducingasignificantportionofthecode.For
example,writingaprogramthatusesseveralchunksofcode
fromthisbookdoesnotrequirepermission.Sellingor
distributingaCD-ROMofexamplesfromO'Reillybooksdoes
requirepermission.Answeringaquestionbycitingthisbook
andquotingexamplecodedoesnotrequirepermission.
Incorporatingasignificantamountofexamplecodefromthis
bookintoyourproduct'sdocumentationdoesrequire
permission.
Weappreciate,butdonotrequire,attribution.Anattribution
usuallyincludesthetitle,author,publisher,andISBN.For
example:"C++CookbookbyD.RyanStephens,Christopher
Diggins,JonathanTurkanis,andJeffCogswell.Copyright2006
O'ReillyMedia,Inc.,0-596-00761-2."
Ifyoufeelyouruseofcodeexamplesfallsoutsidefairuseor
thepermissiongivenabove,feelfreetocontactusat





CommentsandQuestions
Pleaseaddresscommentsandquestionsconcerningthisbookto
thepublisher:
O'ReillyMedia,Inc.
1005GravensteinHighwayNorth
Sebastopol,CA95472

(800)998-9938(intheUnitedStatesorCanada)
(707)829-0515(internationalorlocal)
(707)829-0104(fax)
Wehaveawebpageforthisbook,wherewelisterrata,
examples,andanyadditionalinformation.Youcanaccessthis
pageat:
/>Tocommentorasktechnicalquestionsaboutthisbook,send
emailto:

Formoreinformationaboutourbooks,conferences,Resource
Centers,andtheO'ReillyNetwork,seeourwebsiteat:





SafariEnabled

WhenyouseeaSafari®Enabledicononthecoverof
yourfavoritetechnologybook,thatmeansthebookisavailable
onlinethroughtheO'ReillyNetworkSafariBookshelf.
Safarioffersasolutionthat'sbetterthane-books.It'savirtual
librarythatletsyoueasilysearchthousandsoftoptechbooks,
cutandpastecodesamples,downloadchapters,andfindquick
answerswhenyouneedthemostaccurate,currentinformation.
Tryitforfreeat.


Acknowledgments
FromD.RyanStephens

ThemostimportantpeopleIhavetothankaremywife,
Daphne,andmychildren,Jesse,Pascal,andChloe.Writinga
bookishardwork,butaboveallitistime-consumingwork,and
myfamilyhasbeensupportiveandhastoleratedmylatenights
intheofficeinthebestpossibleway.
Ialsohavetothankthetechnicalreviewers,whomadethis
bookbetterthanitotherwisewouldhavebeen.Aswithso
manythings,itisalwayshelpfultohaveasecond,third,and
fourthsetofeyeslookoversomethingforclarityand
correctness.ManythankstoDanSaks,UweSchnitker,and
DavidTheese.
Finally,Ihavetothankmyeditor,JonathanGennick,forhis
advice,whichwasmostlygrammatical,frequentlystylistic,
occasionallypsychologicallysupportive,andalwaysgood.

FromChristopherDiggins
IwishtothankKrisUnger,JonathanTurkanis,Jonathan
Gennick,andRyanStephensfortheirhelpfulsuggestionsand
critiques,andmakingmeabetterwriterforit.Averyspecial
thankstomywifeMélanieCharbonneauforbrighteningmylife.

FromJonathanTurkanis
Becausemychapterstouchedonsomanydifferentcommerical


productsandopensourceprojectsandbecauseIhadsomany
questionsabouteachofthemIhaveanunusuallylargenumber
ofpeopletothank.
LetmefirstthankRonLiechty,HowardHinnant,andthe
engineersatMetrowerksforansweringeveryconceivable

questionandforprovidingmewithseveralversionsof
CodeWarrior.
I'dalsoliketothanktheBoost.Builddevelopers,especially
VladimirPrus,ReneRivera,andDavidAbrahams,notjustfor
answeringmyquestionsbutalsoforputtingtogethertheBoost
buildsystem,whichwasthesinglemostimportantsourceof
informationforChapter1.
ThanksalsotoWalterBrightatDigitalMars;GregComeauat
ComeauComputing;P.J.PlaugeratDinkumware;ColinLaplace
atBloodshedSoftware;EdMulroyandPavelVozenilekatthe
borland.public.*newsgroups;ArnaudDebaeneandIgor
Tandetnikatmicrosoft.public.vc.languages;EarnieBoyd,Greg
Chicares,AdibTaraben,JohnVandenberg,andLennart
BorgmanattheMinGW/MSYSmailinglist;ChristopherFaylor,
LarryHall,IgorPechtchanski,JoshuaDanielFranklin,andDave
KornattheCygwinlist;MikeStumpandGeoffreyKeatingatthe
GCCdeveloperslist;MarkGoodhandatDecisionSoft;andDavid
N.Bertoniatapache.org.
I'malsoindebtedtoRobertMecklenburg,whosebookManaging
ProjectswithGNUmake,ThirdEdition(O'Reilly)providedthe
foundationformytreatmentofGNUmake.
Inaddition,VladimirPrus,MatthewWilson,RyanStephens,and
ChristopherDigginsprovideddetailedcriticismofearlydraftsof
themanuscript.
Finally,Imustthankmyeditor,JonathanGennick,mywife,
Jennifer,andmyGrandfather,LouisS.Goodman,whotaught
mehowtowrite.


Chapter1.BuildingC++Applications

IntroductiontoBuilding
Recipe1.1.ObtainingandInstallingGCC
Recipe1.2.BuildingaSimple"Hello,World"Application
fromtheCommandLine
Recipe1.3.BuildingaStaticLibraryfromtheCommand
Line
Recipe1.4.BuildingaDynamicLibraryfromtheCommand
Line
Recipe1.5.BuildingaComplexApplicationfromthe
CommandLine
Recipe1.6.InstallingBoost.Build
Recipe1.7.BuildingaSimple"Hello,World"Application
UsingBoost.Build
Recipe1.8.BuildingaStaticLibraryUsingBoost.Build
Recipe1.9.BuildingaDynamicLibraryUsingBoost.Build
Recipe1.10.BuildingaComplexapplicationUsing
Boost.Build
Recipe1.11.BuildingaStaticLibrarywithanIDE
Recipe1.12.BuildingaDynamicLibrarywithanIDE
Recipe1.13.BuildingaComplexApplicationwithanIDE


Recipe1.14.ObtainingGNUmake
Recipe1.15.BuildingASimple"Hello,World"Application
withGNUmake
Recipe1.16.BuildingaStaticLibrarywithGNUMake
Recipe1.17.BuildingaDynamicLibrarywithGNUMake
Recipe1.18.BuildingaComplexApplicationwithGNU
make
Recipe1.19.DefiningaMacro

Recipe1.20.SpecifyingaCommand-LineOptionfromYour
IDE
Recipe1.21.ProducingaDebugBuild
Recipe1.22.ProducingaReleaseBuild
Recipe1.23.SpecifyingaRuntimeLibraryVariant
Recipe1.24.EnforcingStrictConformancetotheC++
Standard
Recipe1.25.CausingaSourceFiletoBeLinked
AutomaticallyAgainstaSpecifiedLibrary
Recipe1.26.UsingExportedTemplates


IntroductiontoBuilding
ThischaptercontainsrecipesfortransformingC++sourcecode
intoexecutableprogramsandlibraries.Byworkingthrough
theserecipes,you'lllearnaboutthebasictoolsusedtobuild
C++applications,thevarioustypesofbinaryfilesinvolvedin
thebuildprocess,andthesystemsthathavebeendevelopedto
makebuildingC++applicationsmanageable.
Ifyoulookatthetitlesoftherecipesinthischapter,youmight
gettheimpressionthatIsolvethesameproblemsoverand
overagain.You'dberight.That'sbecausetherearemanyways
tobuildC++applications,andwhileIcan'tcoverthemall,Itry
tocoversomeofthemostimportantmethods.Inthefirst
dozenorsorecipes,Ishowhowtoaccomplishthree
fundamentaltasksbuildingstaticlibraries,buildingdynamic
libraries,andbuildingexecutablesusingavarietyofmethods.
Therecipesaregroupedbymethod:first,Ilookatbuilding
fromthecommandline,thenwiththeBoostbuildsystem
(Boost.Build),andthenwithanIntegratedDevelopment

Environment(IDE),andfinallywithGNUmake.
Beforeyoustartreadingrecipes,besuretoreadthefollowing
introductorysections.I'llexplainsomebasicterminology,
provideanoverviewofthecommand-linetools,buildsystems
andIDEscoveredinthechapter,andintroducethesourcecode
examples.

Evenifyou'llbeusingabuildsystemorIDE,youshouldstartby
readingtherecipesonbuildingfromthecommandline:theserecipes
introducesomeessentialconceptsthatyou'llneedtounderstandlater
inthischapter.


BasicTerminology
ThethreebasictoolsusedtobuildC++applicationsarethe
compiler,thelinker,andthearchiver(orlibrarian).Acollection
oftheseprogramsandpossiblyothertoolsiscalledatoolset.
ThecompilertakesC++sourcefilesasinputandproduces
objectfiles,whichcontainamixtureofmachine-executable
codeandsymbolicreferencestofunctionsanddata.The
archivertakesacollectionofobjectfilesasinputandproduces
astaticlibrary,orarchive,whichissimplyacollectionofobject
filesgroupedforconvenientuse.Thelinkertakesacollectionof
objectfilesandlibrariesandresolvestheirsymbolicreferences
toproduceeitheranexecutableordynamiclibrary.Roughly
speaking,thelinkeroperatesbymatchingeachuseofasymbol
toitsdefinition.Whenanexecutableordynamiclibraryis
created,itissaidtobelinked;thelibrariesusedtobuildthe
executableordynamiclibraryaresaidtobelinkedagainst.
Anexecutable,orapplication,issimplyanyprogramthatcan

beexecutedbytheoperatingsystem.Adynamiclibrary,also
calledasharedlibrary,islikeanexecutableexceptthatitcan't
berunonitsown;itconsistsofabodyofmachine-executable
codethatisloadedintomemoryafteranapplicationisstarted
andcanbesharedbyoneormoreapplications.OnWindows,
dynamiclibrariesarealsocalleddynamiclinklibraries(DLLs).
Theobjectfilesandstaticlibrariesonwhichanexecutable
dependsareneededonlywhentheexecutableisbuilt.The
dynamiclibrariesonwhichanexecutabledepends,however,
mustbepresentonauser'ssystemwhentheexecutableisrun.
Table1-1showsthefileextensionstypicallyassociatedwith
thesefourbasictypesoffilesonMicrosoftWindowsandUnix.
WhenImentionafilethathasadifferentextensionon
WindowsandUnix,I'llsometimesomittheextensionifit'sclear
fromthecontext.


Table1-1.FileextensionsonWindowsandUnix
Filetype

Windows

MacOSX

OtherUnix

Objectfiles

.obj


.o

.o

Staticlibraries

.lib

.a

.a

Dynamiclibraries

.dll

.dylib

.so

Executables

.exe

Noextension

Noextension

Inthischapter,wheneverIsayUnix,ImeanLinux,too.


Whenyoubuildtheexamplesinthischapter,yourtoolswillgeneratea
numberofauxiliaryfileswithextensionsthatdon'tappearinTable1-1.
UnlessImentionotherwise,youcansafelyignorethesefiles.Ifyou
reallywanttoknowwhattheydo,consultyourtoolset's
documentation.

IDEsandBuildSystems
Thecompiler,linker,andarchiverarecommand-linetools,
whichmeanstheyaredesignedtoberunfromashell,suchas
bashonUnixorcmd.exeonMicrosoftWindows.Thenamesof
theinputfilesandoutputfiles,togetherwithanyother


Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay
×