Upload
others
View
27
Download
0
Embed Size (px)
Citation preview
CompilingwithMultipleFilesTheImportanceofDebugging
CS16:SolvingProblemswithComputersILecture#7
ZiadMatni
Dept.ofComputerScience,UCSB
LectureOutline
• ProgramminginMultipleFiles• TheMagicofMakefiles!
• DesignandDebugTips– DesigningandDebuggingLoops– TheMightyTRACE– DesigningandDebuggingFunctions
4/25/18 Matni,CS16,Sp18 2
C++ProgramminginMultipleFiles
• NoviceC++Programming:– Allinone.cppsourcecodefile– Allthefunctiondefinitions,plusthemain()program
• ActualC++Programmingseparatesparts– Thereareusuallyoneormoreheaderfileswithfilenamesendingin.hthat
typicallycontainfunctionprototypes
– Thereareoneormorefilesthatcontainfunctiondefinitions,somewithmain()functions,andothersthatdon'tcontainamain()function
4/25/18 Matni,CS16,Sp18 3
Why?• Reusability
– Somepartsoftheprogramaregenericenoughthatwecanusethemoveragain– Reuseisnotnecessarilyjustinoneprogram!
• Modularization– Createstand-alonepiecesofcode– Cancontainsetsoffunctionsorsetsofclasses(orboth)– Alibraryisamodulethatisinanalready-compiledform(i.e.objectcode)
• Independentworkflows– Ifwehavemultiplepeopleworkingonaproject,itisagoodideatobreakitintopiecessothat
everyonecanworkontheirfiles
• Fasterre-compilations&debug– Whenyoumakeachange,youonlyhavetore-compilethepart(s)thathavechanged– Easiertodebugaportionthantheentireprogram!
4
5
#include<etc…>#include<etc…>floatlinearScale(...);floatquadraticScale(...);floatbellCurve(...);floatlinearScale(...){...}floatquadraticScale(...){...}floatbellCurve(...){...}intmain(){...}
//File:MyFunctions.h#include<etc…>floatlinearScale(...);floatquadraticScale(...);floatbellCurve(...);//File:MyFunctions.cpp#include“MyFunctions.h”floatlinearScale(...){...}floatquadraticScale(...){...}floatbellCurve(...){...}//File:main.cpp#include“MyFunctions.cpp”intmain(){...}
CompilingEverything…g++-cMyFunctions.cpp–oMyfunctions.o
(createsMyFunctions.o)g++-cmain.cpp–omain.o (createsmain.o)
The–coptioncreatesobjectcode–thisismachinelanguagecode,butit’snottheentireprogramyet…Thetargetobjectfilehereisalwaysgeneratedasa.otype
g++-oProgXmain.oMyFunctions.o (createsProgX)
The–ooptioncreatesobjectcode–inthiscase,it’sobjectcodecreatedfromotherobjectcode.Theresultistheentireprograminexecutableform.Theobjectfilehereisalwaysgeneratedwiththenamespecifiedafterthe–ooption.
4/25/18 Matni,CS16,Sp18 6
WhatDoYouEndUpWith?MyFunctions.h Headerfilew/functionprototypesMyFunctions.cpp C++filew/functiondefinitionsMyFunctions.o ObjectfileofMyFunctions.cppmain.cpp C++filew/mainfunctionmain.o Objectfileofmain.cppProgX “Final”executablefile
…andthisisasimpleexample!!…Wouldn’titbenicetohavecodethatgenerates/controlsthis?
4/25/18 Matni,CS16,Sp18 7
ThereAreSeveralWaysToDoThisPiece-wiseApproach
• See“example1”and“example2”inthedemocodeforthislecture(demo_lecture07)
• example1:similartotheonewejustwentthrough
• example2:byre-arrangingheaders,wecanmakeonecompilecommand(simpler,butalsomorelimiting)
4/25/18 Matni,CS16,Sp18 8
Make
• “Make”isabuildautomationtool– Automaticallybuildsexecutableprogramsandlibraries
fromsourcecode– TheinstructionsformakeisinafilecalledMakefile.
• MakefileiscodewritteninOS-friendlycode– LinuxOS,tobeprecise…
4/25/18 Matni,CS16,Sp18 9
Makefile
• Thefilemustbecalled“makefile”(or“Makefile”)
• Putalltheinstructionsyou’regoingtouseinthere– Thereisasyntaxtofollowformakefiles– Justtype“make”attheprompt,insteadofalltheg++commands
• MakefilescaneasilybeusedtodootherOS-relatedstuff– Like“cleanup”yourarea,forexample
4/25/18 Matni,CS16,Sp18 10
SyntaxofaMakeall:Exercise1Exercise2#Thisoneforcesthecompiletouseversion11rules#Alsoshowsmeallwarnings(notjusterrors)Exercise1:ex1.cpp g++ex1.cpp–oex1-std=c++11–Wall#Thisnextone’sadoozyExercise2:ex2.cpp g++ex2.cpp–oex2clean: rm*.oex2ex1
4/25/18 Matni,CS16,Sp18 11
SyntaxofaMakeall:Exercise1Exercise2#Thisoneforcesthecompiletouseversion11rules#Alsoshowsmeallwarnings(notjusterrors)Exercise1:ex1.cpp g++ex1.cpp–oex1-std=c++11–Wall#Thisnextone’sadoozyExercise2:ex2.cpp g++ex2.cpp–oex2clean: rm*.oex2ex1
4/25/18 Matni,CS16,Sp18 12
Target“all”programsinthisproject
Dependencies(macros)thataredeclaredbelow
Note:TheseareTABcharactersusedforthe
indents!Don’tusespaces!!
#isforcommenting
Doesn’thavetobecompilinginstructionsonly!
Dependencyfiles
What’sinYourDirectory?
Beforeyourunyourmake(andcompile),yourdirectoryshouldhaveatleastthesefiles
(pertheexamplefromthepreviousslide)
ex1.cppex2.cppmakefile
4/25/18 Matni,CS16,Sp18 13
UsingmakeintheLinuxOSEnvironment• Nowthatyouhaveamakefile,youcanexecuteacompilingprocesssimplybyissuing:$make ßThisiswillcreateALLtheoutputexecutables• Oryoucanexecutemakeforonedependency(i.e.program)inparticular,likethis:$makeExercise1 ßThisiswillcreatetheoutputexecutablefor
Exercise1(i.e.thefileex1inourexample)
• Inourexample,weevenprovidedawayto“cleanup”afterwe’redonebydeletingalltheexecutablesthatwecreated(incasewewantedtorunthecompilingagain,let’ssay)
$makeclean ßThiswilldeletealltheexecutablesthatwecreated(likeex1andex2)4/25/18 Matni,CS16,Sp18 14
4/25/18 Matni,CS16,Sp18 15
DebuggingLoops
Commonerrorsinvolvingloopsinclude:• Off-by-oneerrorsinwhichtheloopexecutesonetoomanyor
onetoofewtimes
• InfiniteloopsusuallyresultfromamistakeintheBooleanexpressionthatcontrolstheloop
4/25/18 Matni,CS16,Sp18 16
FixingOff-By-OneErrors
• Checkyourcomparison:shoulditbe<or<=?– SawafewmistakeslikethisontheexamL
• Checkthatthevar.initializationusesthecorrectvalue
4/25/18 Matni,CS16,Sp18 17
FixingInfiniteLoops
• Commonmistake:checkthedirectionofinequalities: shouldIuse<or>?• Leantowardsusing<or>inyourloopconditions• Avoidequality(==)orinequality(!=)
4/25/18 Matni,CS16,Sp18 18
MoreLoopDebuggingTips:Tracing
• Besurethatthemistakeisreallyintheloop
• Tracethevariabletoobservehowitchanges– Tracingavariableiswatchingitsvaluechangeduringexecution.– Bestwaytodothisistoinsertcoutstatements
andhavetheprogramshowyouthevariable ateveryiterationoftheloop.
4/25/18 Matni,CS16,Sp18 19
DebuggingExample• Thefollowingcodeissupposedtoconcludewiththevariable
“product”equaltotheproductofthenumbers2through5– i.e.2x3x4x5,which,ofcourse,is120.
• Whatcouldgowrong?!J intnext=2,product=1;
while(next<5){ next++; product=product*next;}
Wheremightyouputatrace?
4/25/18 Matni,CS16,Sp18 20
DEMO!Usingvariabletracing
LoopTestingGuidelines
• Everytimeaprogramischanged,itshouldbere-tested– Changingonepartmayrequireachangetoanother
• Everyloopshouldatleastbetestedusinginputtocause:– Zeroiterationsoftheloopbody– Oneiterationoftheloopbody– Onelessthanthemaximumnumberofiterations– Themaximumnumberofiterations
4/25/18 Matni,CS16,Sp18 21
Ifalloftheseareok,youlikelyhaveaveryrobustloop
StartingOver
• Sometimesitismoreefficienttothrowoutabuggyprogramandstartover!– Thenewprogramwillbeeasiertoread– Thenewprogramislesslikelytobeasbuggy– Youmaydevelopaworkingprogramfasterthanifyouworkto
repairthebadcode• Thelessonslearnedinthebuggycode
willhelpyoudesignabetterprogramfaster
4/25/18 Matni,CS16,Sp18 22
TestingandDebuggingFunctions
• Eachfunctionshouldbetestedasaseparateunit
• Testfunctionsbythemselves:itmakefindingmistakeseasier!
• “Driver”or“Test”Programscanhelp– Yes:createanotherprogramtotestyouroriginalprogram…
• Onceafunctionistested,itcanbeusedinthedriverprogramtotestotherfunctions
4/25/18 Matni,CS16,Sp18 23
ExampleofaDriverTestProgram
4/25/18 Matni,CS16,Sp18 24
Stubs• Whenafunctionbeingtested
callsotherfunctionsthatarenotyettested,useastub
• Astubisasimplifiedversionofafunction– Aplaceholderfortherealthing…– i.e.they’refakefunctions
• Stubsshouldbesosimple thatyouhavefullconfidencetheywillperformcorrectly
4/25/18 Matni,CS16,Sp18 25
#include<iostream>#include<cmath>usenamespacestd;doubleWeirdCalc(doublex,doubley);intmain(){
doublen,m,w;cout<<“Enterthe2valuesforweirdcalculation:”;cin>>n>>m;w=WeirdCalc(n,m)/(37–pow(n/m,m/n));cout<<“Theansweris:”<<w<<endl;return0;
}doubleWeirdCalc(doublex,doubley){
return((sqrt(pow(3*x,y%(max(x,y)))–sqrt(5*y/(x-6))+0.5*pow((x+y),-0.3);}
12345678910111213141516171819
StubExample
4/25/18 Matni,CS16,Sp18 26
#include<iostream>#include<cmath>usenamespacestd;doubleWeirdCalc(doublex,doubley);intmain(){
doublen,m,w;cout<<“Enterthe2valuesforweirdcalculation:”;cin>>n>>m;w=WeirdCalc(n,m)/(37–pow(n/m,m/n));cout<<“Theansweris:”<<w<<endl;return0;
}doubleWeirdCalc(doublex,doubley)//MakeWeirdCalcastub–justfortesting!!{
//return((sqrt(pow(3*x,y%(max(x,y)))–sqrt(5*y/(x-6))+0.5*pow((x+y),-0.3);return(7);
}
12345678910111213141516171819
StubExample
4/25/18 Matni,CS16,Sp18 27
DebuggingYourCode:TheRules
• Keepanopenmind– Don’tassumethebugisinaparticularlocation
• Don’trandomlychangecodewithoutunderstandingwhatyouaredoinguntiltheprogramworks– Thisstrategymayworkforthefirstfewsmallprogramsyouwritebutitisdoomedtofailureforanyprogramsofmoderatecomplexity
• Showtheprogramtosomeoneelse
4/25/18 Matni,CS16,Sp18 28
GeneralDebuggingTechniques• Checkforcommonerrors,forexample:– Localvs.ReferenceParameters– =insteadof==– Didyouuse&&whenyoumeant||?– Thesearetypicallyerrorsthatmightnotgetflaggedbyacompiler!!
• Localizetheerror– Narrowdownbugsbyusingtracingandstubtechniques– Onceyourevealthebugandfixit,removetheextracoutstatements
• Yourtextbookhasgreatdebuggingexamples
4/25/18 Matni,CS16,Sp18 29
Pre-andPost-ConditionsConceptsofpre-conditionandpost-conditioninfunctions
WerecommendyouusetheseconceptswhenmakingcommentsPre-condition:Whatmust“be”beforeyoucallafunction• Stateswhatisassumedtobetruewhenthefunctioniscalled• Functionshouldnotbeusedunlessthepreconditionholds
Post-condition:Whatthefunctionwilldoonceitiscalled• Describestheeffectofthefunctioncall• Tellswhatwillbetrueafterthefunctionisexecuted
(whenthepreconditionholds)• Ifthefunctionreturnsavalue,thatvalueisdescribed• Changestocall-by-referenceparametersaredescribed
4/25/18 Matni,CS16,Sp18 30
WhyusePre-andPost-conditions?
• Pre-conditionsandpost-conditionsshouldbethefirststepindesigningafunction
• SpecifywhatafunctionshoulddoBEFOREdesigningit– Thisminimizesdesignerrorsandtimewastedwritingcodethatdoesn’t
matchthetaskathand
4/25/18 Matni,CS16,Sp18 31
Example
voidwrite_sqrt(doublex)//Precondition: x>=0.//Postcondition:Thesquarerootofxhas//beenwrittentothestandardoutput{cout<<sqrt(x)<<endl;
}
4/26/18 Matni,CS16,Sp18 32
YOURTO-DOs
q FinishLab3bynextMondayq PrepareLab4fornextWednesdayq DoHW7bynextTuesday
q VisitProf’sandTAs‘officehoursifyouneedhelp!
q Hugatree!(oralovedonewilldo)
4/25/18 Matni,CS16,Sp18 33
4/25/18 Matni,CS16,Sp18 34