您的位置:首页 > 其它

Makefile新手入门:How to write Makefile

2013-05-07 14:42 330 查看
I'vealwaysthoughtthiswaseasiertolearnwithadetailedexample,sohere'showIthinkofmakefiles.Foreachsectionyouhaveonelinethat'snotindentedanditshowsthenameofthesectionfollowedbydependencies.Thedependenciescanbeeitherothersections(whichwillberunbeforethecurrentsection)orfiles(whichifupdateswillcausethecurrentsectiontoberunagain).

Here'saquickexample(keepinmindthatI'musing4spaceswhereIshouldbeusingatab,SOwon'tletmeusetabs):

all:a3driver.o g++-oa3drivera3driver.o a3driver.o:a3driver.cpp g++-ca3driver.cpp

Whenyoutype
make
,itwillchoosethefirstsection(all).alldependsona3driver.o,soitwillgotothatsection.a3driver.odependsona3driver.cpp,soitwillonlyrunifa3driver.cpphaschangedsinceitwaslastrun.Assumingithas(orhasneverbeenrun),itwillcompilea3driver.cpptoa.ofile,thengobacktoallandcompilethatintothefileexecutable.

Sincethere'sonlyonefile,itcouldevenbereducedto:

a3driver:a3driver.cpp g++-oa3drivera3driver.cpp

ThereasonIshowedthefirstexampleisthatitshowsthepowerofmakefiles.Ifyouneedtocompileanotherfile,youcanjustaddanothersection.Here'sanexamplewithasecondFile.cpp(whichloadsinaheadernamedsecondFile.h):

all:a3driver.osecondFile.o g++-oa3drivera3driver.osecondFile.o a3driver.o:a3driver.cpp g++-ca3driver.cpp secondFile.o:secondFile.cppsecondFile.h g++-csecondFile.cpp 

ThiswayifyouchangesomethinginsecondFile.cpporsecondFile.handrecompile,itwillonlyrecompilesecondFile.cpp(nota3driver.cpp).Oralternately,ifyouchangesomethingina3driver.cpp,itwon'trecompilesecondFile.cpp.

######################################################################################################

Dependencyareatreeofrulesthatlooklikethis:

main_target:source1source2etc commandtobuildmain_targetfromsources source1:dependentsforsource1 commandtobuildsource1  

Theremustbeablanklineafterthecommandsforatarget,andtheremustnotbeablanklinebeforethecommands.Thefirsttargetinthemakefileistheoverallgoal,othertargetsarebuiltonlyifthefirsttargetdependsonthem.

Soyourmakefilewilllooksomethinglikethis.

a3a.exe:a3driver.obj link/out:a3aa3driver.obj a3driver.obj:a3driver.cpp cca3driver.cpp

  

PS:HarvestfromStackflow'target='_blank'>http://stackoverflow.com/questions/2481269/how-to-make-simple-c-makefile[/code]

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: