Tải bản đầy đủ - 0 (trang)
Chapter 1.  Building C++ Applications

Chapter 1.  Building C++ Applications

Tải bản đầy đủ - 0trang

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



necessaryconfigurationinformation,arepassedtothecompiler,

linker,andarchiverastextonthecommandline.Invoking

thesetoolsbyhandistedious,however.Evenforsmallprojects,

itcanbehardtorememberthecommand-lineoptionsforeach

toolandtheorderinwhichtheproject'ssourceandbinaryfiles

mustbecompiledandlinked.Whenasourcefileismodified,

youmustdeterminewhichobjectfilesneedtoberecompiled,

whichstaticlibrariesneedtobeupdated,andwhich

executablesanddynamiclibrariesneedtoberelinked.Ifyou

rebuildmorefilesthannecessary,you'vewastedyourtime;if

youdon'trebuildenough,youmayendupwithafailedbuildor

abuggyapplication.WithlargeC++projectswhichcaninvolve

thousandsofseparatefiles,includingsourcefiles,objectfiles,

libraries,andexecutablesbuildingfromthecommandlineis

simplyimpossible.

TherearetwobasicapproachestobuildinglargeC++

applications:

AnIDEprovidesagraphicalinterfacefororganizinga

collectionofsourcefilesanddescribingthebinaryfilesthat

shouldbegeneratedfromthem.Onceyouspecifythis

information,youcangeneratethebinaryfilessimplyby

selectinganappropriatecommandfromamenuortoolbar.

TheIDEisresponsiblefordeterminingtheorderinwhich

thebinaryfilesshouldbegenerated,thetoolsneededto

generatethem,andthecommand-lineoptionsthatmustbe

passedtothetools.Wheneveryoumodifyoneormoreof

yoursourcefiles,youcaninstructtheIDEtoregenerate

onlythosebinaryfilesthatareoutofdate.

IDEsorganizesourcefilesintocollectionscalledprojects.An

IDEprojectisusuallyassociatedwithasinglebinaryfile,or

withseveralvariantsofabinaryfile,suchasthedebugand

releasebuildsofanapplication.MostIDEsallowusersto

organizeprojectsintogroupscalledprojectgroups,or

solutions,andtospecifythedependenciesbetweenprojects



inagroup.

Abuildsystemprovidesatextfileformatfordescribinga

collectionofsourcefilesandthebinaryfilesthatshouldbe

generatedfromthem,togetherwithabuildtoolthatreads

thesetextfilesandgeneratesthebinaryfilesbyinvoking

theappropriatecommand-linetools.Typically,thesetext

filesarecreatedandeditedusingatexteditor,andthe

buildtoolisinvokedfromthecommandline.Somebuild

systems,however,provideagraphicalinterfaceforediting

thetextfilesandinvokingthebuildtool.

WhileIDEsorganizefilesintoprojects,buildsystems

organizefilesintotargets.Mosttargetscorrespondto

binaryfilesthatmustbegenerated;othertargets

correspondtoactionsthebuildtoolmustperform,suchas

installinganapplication.

Themostcommonbuildtoolisthemakeutility;thetextfilesit

reliesonarecalledmakefiles.Whiletherearemanyversionsof

make,inthischapterIwilldiscussGNUmake,themost

powerfulandportablemakeincarnation.GNUmakeisan

extremelyflexibletoolthatcanbeusedformuchmorethan

buildingC++applications.Italsohastheadvantageofbeing

widelyusedandwell-understoodbydevelopers.Unfortunately,

gettingGNUmaketodoexactlywhatyouwantittodocanbea

challenge,especiallywithcomplexprojectsinvolvingmultiple

toolsets.Forthatreason,IwillalsodiscussBoost.Build,a

powerfulandextensiblebuildsystemdesignedfromtheground

upforbuildingC++applications.



ForathoroughtreatmentofGNUmake,seeManagingProjectswith

GNUmake,ThirdEdition,byRobertMecklenburg(O'Reilly).



Boost.BuildwasdevelopedbymembersoftheBoostC++

Librariesproject.Ithasbeenusedbyalargecommunityof

developersforseveralyears,andiscurrentlyunderactive

development.Boost.Buildusesabuildtoolcalledbjamandtext

filescalledJamfiles.Itsgreateststrengthistheeasewithwhich

itallowsyoutomanagecomplexprojectsinvolvingmultiple

platformsandbuildconfigurations.AlthoughBoost.Buildstarted

outasanextensionofPerforce'sJambuildsystem,ithassince

undergoneextensiveredesign.Asthisbookgoestopress,the

Boost.Builddevelopersarepreparingfortheofficialreleaseof

thesecondmajorversionofthebuildsystem,whichisthe

versiondescribedinthischapter.



ToolsetOverview

InthischapterI'lldiscusssevencollectionsofcommand-line

tools:GCC,VisualC++,Intel,Metrowerks,Borland,Comeau,

andDigitalMars.Table1-2showsthenamesofthecommandlinetoolsfromthevarioustoolsets;Table1-3showswherethey

arelocatedonyoursystem,ifyouhavetheminstalled.Tool

namesforWindowsusethe.exesuffixrequiredforWindows

executables;fortoolsetsthatareavailableforbothWindows

andUnix,I'veputthissuffixinbrackets.

Table1-2.Namesofcommand-linetoolsforvarioustoolsets

Toolset



Compiler



Linker



Archiver



GCC



g++[.exe]



g++



ar[.exe]ranlib[.exe]



VisualC++



cl.exe



link.exe



lib.exe



Intel(Windows)



icl.exe



xilink.exe



xilib.exe



Intel(Linux)



Icpc



icpc



arranlib



Metrowerks



mwcc[.exe]



mwld[.exe]



mwld[.exe]



Comeau



como[.exe]



como[.exe]



Toolset-dependent



Borland



bcc32.exe



bcc32.exeilink32.exe



tlib.exe



DigitalMars



dmc.exe



link.exe



lib.exe



Table1-3.Locationofyourcommand-linetools

Toolset



Location



GCC(Unix) Typically/usr/binor/usr/local/bin

GCC

(Cygwin)



ThebinsubdirectoryofyourCygwininstallation



GCC

(MinGW)



ThebinsubdirectoryofyourMinGWinstallation



VisualC++ TheVC/binsubdirectoryofyourVisualStudioinstallation[1]

Intel

(Windows)



TheBinsubdirectoryofyourIntelcompilerinstallation



Intel(Linux) ThebinsubdirectoryofyourIntelcompilerinstallation



Metrowerks



TheOtherMetrowerksTools/CommandLineToolssubdirectoryofyour

CodeWarriorinstallation



Comeau



ThebinsubdirectoryofyourComeauinstallation



Borland



TheBinsubdirectoryofyourC++Builder,C++BuilderXorBorlandcommandlinetoolsinstallation



[1]InpreviousversionsofVisualStudio,theVCdirectorywascalledVC98orVc7.



Don'tletthenumberoftoolsetsscareyouyoudon'tneedto

learnthemall.Inmostcasesyoucansimplyskipthematerial

thatdoesn'trelatetoyourtoolset.Ifyouwanttolearnalittle

aboutothertoolsets,however,besuretoreadthesectionson

VisualC++andGCC,sincethesearethedominanttoolsetson

WindowsandUnix.

Nowlet'slookateachoftheseventoolsets.



TheGNUCompilerCollection(GCC)

GCCisacollectionofcompilersforawideassortmentof

languages,includingCandC++.It'sremarkableforbeingopen

source,availableonalmosteveryimaginableplatform,and

highlyconformanttotheC++languagestandard.It'sthe

dominantcompileronmanyUnixplatforms,andisalsowidely

usedonMicrosoftWindows.EvenifGCCisnotyourprimary

toolset,youcanlearnalotbycompilingyourcodewithGCC.

Also,ifyouthinkyouknowawaytoimprovetheC++

language,youcantestyourideawiththeGCCcodebase.

GCCcomeswithlibstdc++,agoodopensourceimplementation

oftheC++standardlibrary.Itcanalsobeusedwiththeopen

sourceSTLPortC++standardlibraryandwithDinkumware's

standardlibrary.



ToobtainGCC,seeRecipe1.1.



TheGCCexamplesinthischapterweretestedwithGCC3.4.3andGCC



4.0.0onGNU/Linux(FedoraCore3),withGCC4.0.0onMacOSX

(Darwin8.2.0),andwithGCC3.4.2(MinGW)and3.4.4(Cygwin)on

Windows2000Professional.



VisualC++

Microsoft'stoolsetisthedominanttoolsetontheWindows

platform.Whileseveraloldversionsarestillinwideuse,the

mostrecentversionishighlystandardsconforming.Itisalso

capableofproducinghighlyoptimizedcode.Microsoft'stools

aredistributedwiththeVisualC++andVisualStudio

developmentenvironments,discussedinthenextsection.Asof

thiswriting,theyarealsoavailableaspartoftheVisualC++

Toolkit2003,whichcanbedownloadedforfreefrom

www.microsoft.com.

VisualC++comeswithacustomizedversionofthe

DinkumwareC++standardlibraryimplementation.

Dinkumware'sC++standardlibraryisamongthemostefficient

andstandards-conformingcommercialimplementation.It's

availableforawidevarietyofplatforms,includingmanyofthe

othertoolsetscoveredinthischapter.



TheVisualC++examplesinthischapterweretestedwithMicrosoft

VisualStudio.NET2003andMicrosoftVisualStudio2005(Beta2).See

Table1-4.



Table1-4.VersionsofMicrosoftVisualStudio

Productname



IDEversion



Compilerversion



MicrosoftVisualStudio



6.0



1200



MicrosoftVisualStudio.NET



7.0



1300



MicrosoftVisualStudio.NET2003



7.1



1310



MicrosoftVisualStudio2005(Beta2)



8.0



1400



Intel

IntelproducesseveralC++compilersforusewithIntel

processors.Theyarenotableforgeneratingextremelyfast

codeperhapsthefastestavailablefortheIntelarchitecture.

BasedontheC++frontendfromtheEdisonDesignGroup

(EDG),theyarealsohighlystandardsconforming.

TheIntelC++CompilerforWindowsmakesuseofMicrosoft's

VisualC++orVisualStudiodevelopmentenvironments,which

mustbeinstalledfortheIntelcompilertofunctionproperly.The

compilerisdesignedforcompatibilitywithVisualC++:itcanbe

usedasaplug-intotheVisualC++developmentenvironment,

itcangeneratecodethatisbinary-compatiblewithcode

generatedbytheVisualC++compiler,itoffersmanyofthe

samecommand-lineoptionsastheVisualC++compiler,

andunlessyoutellitnottoitevenemulatessomeMicrosoft

bugs.ThecommercialversionoftheIntelC++Compilerfor

Windowsisavailableforpurchaseatwww.intel.com.A

reasonablypricedacademicversionisalsoavailable.

WhereasIntel'scompilerforWindowsisdesignedtobe

compatiblewiththeVisualC++compiler,Intel'scompilerfor

LinuxisdesignedtobecompatiblewithGCC.ItrequiresGCCto

operate,supportsanumberofGCCoptions,andbydefault



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

Chapter 1.  Building C++ Applications

Tải bản đầy đủ ngay(0 tr)

×