compiling with multiple files the importance of debugging · more loop debugging tips: tracing •...
TRANSCRIPT
![Page 1: Compiling with Multiple Files The Importance of Debugging · More Loop Debugging Tips: Tracing • Be sure that the mistake is really in the loop • Trace the variable to observe](https://reader030.vdocuments.site/reader030/viewer/2022041101/5ed9aafba5d2fa37887930fd/html5/thumbnails/1.jpg)
CompilingwithMultipleFilesTheImportanceofDebugging
CS16:SolvingProblemswithComputersILecture#7
ZiadMatni
Dept.ofComputerScience,UCSB
![Page 2: Compiling with Multiple Files The Importance of Debugging · More Loop Debugging Tips: Tracing • Be sure that the mistake is really in the loop • Trace the variable to observe](https://reader030.vdocuments.site/reader030/viewer/2022041101/5ed9aafba5d2fa37887930fd/html5/thumbnails/2.jpg)
LectureOutline
• ProgramminginMultipleFiles• TheMagicofMakefiles!
• DesignandDebugTips– DesigningandDebuggingLoops– TheMightyTRACE– DesigningandDebuggingFunctions
4/25/18 Matni,CS16,Sp18 2
![Page 3: Compiling with Multiple Files The Importance of Debugging · More Loop Debugging Tips: Tracing • Be sure that the mistake is really in the loop • Trace the variable to observe](https://reader030.vdocuments.site/reader030/viewer/2022041101/5ed9aafba5d2fa37887930fd/html5/thumbnails/3.jpg)
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
![Page 4: Compiling with Multiple Files The Importance of Debugging · More Loop Debugging Tips: Tracing • Be sure that the mistake is really in the loop • Trace the variable to observe](https://reader030.vdocuments.site/reader030/viewer/2022041101/5ed9aafba5d2fa37887930fd/html5/thumbnails/4.jpg)
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
![Page 5: Compiling with Multiple Files The Importance of Debugging · More Loop Debugging Tips: Tracing • Be sure that the mistake is really in the loop • Trace the variable to observe](https://reader030.vdocuments.site/reader030/viewer/2022041101/5ed9aafba5d2fa37887930fd/html5/thumbnails/5.jpg)
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(){...}
![Page 6: Compiling with Multiple Files The Importance of Debugging · More Loop Debugging Tips: Tracing • Be sure that the mistake is really in the loop • Trace the variable to observe](https://reader030.vdocuments.site/reader030/viewer/2022041101/5ed9aafba5d2fa37887930fd/html5/thumbnails/6.jpg)
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
![Page 7: Compiling with Multiple Files The Importance of Debugging · More Loop Debugging Tips: Tracing • Be sure that the mistake is really in the loop • Trace the variable to observe](https://reader030.vdocuments.site/reader030/viewer/2022041101/5ed9aafba5d2fa37887930fd/html5/thumbnails/7.jpg)
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
![Page 8: Compiling with Multiple Files The Importance of Debugging · More Loop Debugging Tips: Tracing • Be sure that the mistake is really in the loop • Trace the variable to observe](https://reader030.vdocuments.site/reader030/viewer/2022041101/5ed9aafba5d2fa37887930fd/html5/thumbnails/8.jpg)
ThereAreSeveralWaysToDoThisPiece-wiseApproach
• See“example1”and“example2”inthedemocodeforthislecture(demo_lecture07)
• example1:similartotheonewejustwentthrough
• example2:byre-arrangingheaders,wecanmakeonecompilecommand(simpler,butalsomorelimiting)
4/25/18 Matni,CS16,Sp18 8
![Page 9: Compiling with Multiple Files The Importance of Debugging · More Loop Debugging Tips: Tracing • Be sure that the mistake is really in the loop • Trace the variable to observe](https://reader030.vdocuments.site/reader030/viewer/2022041101/5ed9aafba5d2fa37887930fd/html5/thumbnails/9.jpg)
Make
• “Make”isabuildautomationtool– Automaticallybuildsexecutableprogramsandlibraries
fromsourcecode– TheinstructionsformakeisinafilecalledMakefile.
• MakefileiscodewritteninOS-friendlycode– LinuxOS,tobeprecise…
4/25/18 Matni,CS16,Sp18 9
![Page 10: Compiling with Multiple Files The Importance of Debugging · More Loop Debugging Tips: Tracing • Be sure that the mistake is really in the loop • Trace the variable to observe](https://reader030.vdocuments.site/reader030/viewer/2022041101/5ed9aafba5d2fa37887930fd/html5/thumbnails/10.jpg)
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
![Page 11: Compiling with Multiple Files The Importance of Debugging · More Loop Debugging Tips: Tracing • Be sure that the mistake is really in the loop • Trace the variable to observe](https://reader030.vdocuments.site/reader030/viewer/2022041101/5ed9aafba5d2fa37887930fd/html5/thumbnails/11.jpg)
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
![Page 12: Compiling with Multiple Files The Importance of Debugging · More Loop Debugging Tips: Tracing • Be sure that the mistake is really in the loop • Trace the variable to observe](https://reader030.vdocuments.site/reader030/viewer/2022041101/5ed9aafba5d2fa37887930fd/html5/thumbnails/12.jpg)
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
![Page 13: Compiling with Multiple Files The Importance of Debugging · More Loop Debugging Tips: Tracing • Be sure that the mistake is really in the loop • Trace the variable to observe](https://reader030.vdocuments.site/reader030/viewer/2022041101/5ed9aafba5d2fa37887930fd/html5/thumbnails/13.jpg)
What’sinYourDirectory?
Beforeyourunyourmake(andcompile),yourdirectoryshouldhaveatleastthesefiles
(pertheexamplefromthepreviousslide)
ex1.cppex2.cppmakefile
4/25/18 Matni,CS16,Sp18 13
![Page 14: Compiling with Multiple Files The Importance of Debugging · More Loop Debugging Tips: Tracing • Be sure that the mistake is really in the loop • Trace the variable to observe](https://reader030.vdocuments.site/reader030/viewer/2022041101/5ed9aafba5d2fa37887930fd/html5/thumbnails/14.jpg)
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
![Page 15: Compiling with Multiple Files The Importance of Debugging · More Loop Debugging Tips: Tracing • Be sure that the mistake is really in the loop • Trace the variable to observe](https://reader030.vdocuments.site/reader030/viewer/2022041101/5ed9aafba5d2fa37887930fd/html5/thumbnails/15.jpg)
4/25/18 Matni,CS16,Sp18 15
![Page 16: Compiling with Multiple Files The Importance of Debugging · More Loop Debugging Tips: Tracing • Be sure that the mistake is really in the loop • Trace the variable to observe](https://reader030.vdocuments.site/reader030/viewer/2022041101/5ed9aafba5d2fa37887930fd/html5/thumbnails/16.jpg)
DebuggingLoops
Commonerrorsinvolvingloopsinclude:• Off-by-oneerrorsinwhichtheloopexecutesonetoomanyor
onetoofewtimes
• InfiniteloopsusuallyresultfromamistakeintheBooleanexpressionthatcontrolstheloop
4/25/18 Matni,CS16,Sp18 16
![Page 17: Compiling with Multiple Files The Importance of Debugging · More Loop Debugging Tips: Tracing • Be sure that the mistake is really in the loop • Trace the variable to observe](https://reader030.vdocuments.site/reader030/viewer/2022041101/5ed9aafba5d2fa37887930fd/html5/thumbnails/17.jpg)
FixingOff-By-OneErrors
• Checkyourcomparison:shoulditbe<or<=?– SawafewmistakeslikethisontheexamL
• Checkthatthevar.initializationusesthecorrectvalue
4/25/18 Matni,CS16,Sp18 17
![Page 18: Compiling with Multiple Files The Importance of Debugging · More Loop Debugging Tips: Tracing • Be sure that the mistake is really in the loop • Trace the variable to observe](https://reader030.vdocuments.site/reader030/viewer/2022041101/5ed9aafba5d2fa37887930fd/html5/thumbnails/18.jpg)
FixingInfiniteLoops
• Commonmistake:checkthedirectionofinequalities: shouldIuse<or>?• Leantowardsusing<or>inyourloopconditions• Avoidequality(==)orinequality(!=)
4/25/18 Matni,CS16,Sp18 18
![Page 19: Compiling with Multiple Files The Importance of Debugging · More Loop Debugging Tips: Tracing • Be sure that the mistake is really in the loop • Trace the variable to observe](https://reader030.vdocuments.site/reader030/viewer/2022041101/5ed9aafba5d2fa37887930fd/html5/thumbnails/19.jpg)
MoreLoopDebuggingTips:Tracing
• Besurethatthemistakeisreallyintheloop
• Tracethevariabletoobservehowitchanges– Tracingavariableiswatchingitsvaluechangeduringexecution.– Bestwaytodothisistoinsertcoutstatements
andhavetheprogramshowyouthevariable ateveryiterationoftheloop.
4/25/18 Matni,CS16,Sp18 19
![Page 20: Compiling with Multiple Files The Importance of Debugging · More Loop Debugging Tips: Tracing • Be sure that the mistake is really in the loop • Trace the variable to observe](https://reader030.vdocuments.site/reader030/viewer/2022041101/5ed9aafba5d2fa37887930fd/html5/thumbnails/20.jpg)
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
![Page 21: Compiling with Multiple Files The Importance of Debugging · More Loop Debugging Tips: Tracing • Be sure that the mistake is really in the loop • Trace the variable to observe](https://reader030.vdocuments.site/reader030/viewer/2022041101/5ed9aafba5d2fa37887930fd/html5/thumbnails/21.jpg)
LoopTestingGuidelines
• Everytimeaprogramischanged,itshouldbere-tested– Changingonepartmayrequireachangetoanother
• Everyloopshouldatleastbetestedusinginputtocause:– Zeroiterationsoftheloopbody– Oneiterationoftheloopbody– Onelessthanthemaximumnumberofiterations– Themaximumnumberofiterations
4/25/18 Matni,CS16,Sp18 21
Ifalloftheseareok,youlikelyhaveaveryrobustloop
![Page 22: Compiling with Multiple Files The Importance of Debugging · More Loop Debugging Tips: Tracing • Be sure that the mistake is really in the loop • Trace the variable to observe](https://reader030.vdocuments.site/reader030/viewer/2022041101/5ed9aafba5d2fa37887930fd/html5/thumbnails/22.jpg)
StartingOver
• Sometimesitismoreefficienttothrowoutabuggyprogramandstartover!– Thenewprogramwillbeeasiertoread– Thenewprogramislesslikelytobeasbuggy– Youmaydevelopaworkingprogramfasterthanifyouworkto
repairthebadcode• Thelessonslearnedinthebuggycode
willhelpyoudesignabetterprogramfaster
4/25/18 Matni,CS16,Sp18 22
![Page 23: Compiling with Multiple Files The Importance of Debugging · More Loop Debugging Tips: Tracing • Be sure that the mistake is really in the loop • Trace the variable to observe](https://reader030.vdocuments.site/reader030/viewer/2022041101/5ed9aafba5d2fa37887930fd/html5/thumbnails/23.jpg)
TestingandDebuggingFunctions
• Eachfunctionshouldbetestedasaseparateunit
• Testfunctionsbythemselves:itmakefindingmistakeseasier!
• “Driver”or“Test”Programscanhelp– Yes:createanotherprogramtotestyouroriginalprogram…
• Onceafunctionistested,itcanbeusedinthedriverprogramtotestotherfunctions
4/25/18 Matni,CS16,Sp18 23
![Page 24: Compiling with Multiple Files The Importance of Debugging · More Loop Debugging Tips: Tracing • Be sure that the mistake is really in the loop • Trace the variable to observe](https://reader030.vdocuments.site/reader030/viewer/2022041101/5ed9aafba5d2fa37887930fd/html5/thumbnails/24.jpg)
ExampleofaDriverTestProgram
4/25/18 Matni,CS16,Sp18 24
![Page 25: Compiling with Multiple Files The Importance of Debugging · More Loop Debugging Tips: Tracing • Be sure that the mistake is really in the loop • Trace the variable to observe](https://reader030.vdocuments.site/reader030/viewer/2022041101/5ed9aafba5d2fa37887930fd/html5/thumbnails/25.jpg)
Stubs• Whenafunctionbeingtested
callsotherfunctionsthatarenotyettested,useastub
• Astubisasimplifiedversionofafunction– Aplaceholderfortherealthing…– i.e.they’refakefunctions
• Stubsshouldbesosimple thatyouhavefullconfidencetheywillperformcorrectly
4/25/18 Matni,CS16,Sp18 25
![Page 26: Compiling with Multiple Files The Importance of Debugging · More Loop Debugging Tips: Tracing • Be sure that the mistake is really in the loop • Trace the variable to observe](https://reader030.vdocuments.site/reader030/viewer/2022041101/5ed9aafba5d2fa37887930fd/html5/thumbnails/26.jpg)
#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
![Page 27: Compiling with Multiple Files The Importance of Debugging · More Loop Debugging Tips: Tracing • Be sure that the mistake is really in the loop • Trace the variable to observe](https://reader030.vdocuments.site/reader030/viewer/2022041101/5ed9aafba5d2fa37887930fd/html5/thumbnails/27.jpg)
#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
![Page 28: Compiling with Multiple Files The Importance of Debugging · More Loop Debugging Tips: Tracing • Be sure that the mistake is really in the loop • Trace the variable to observe](https://reader030.vdocuments.site/reader030/viewer/2022041101/5ed9aafba5d2fa37887930fd/html5/thumbnails/28.jpg)
DebuggingYourCode:TheRules
• Keepanopenmind– Don’tassumethebugisinaparticularlocation
• Don’trandomlychangecodewithoutunderstandingwhatyouaredoinguntiltheprogramworks– Thisstrategymayworkforthefirstfewsmallprogramsyouwritebutitisdoomedtofailureforanyprogramsofmoderatecomplexity
• Showtheprogramtosomeoneelse
4/25/18 Matni,CS16,Sp18 28
![Page 29: Compiling with Multiple Files The Importance of Debugging · More Loop Debugging Tips: Tracing • Be sure that the mistake is really in the loop • Trace the variable to observe](https://reader030.vdocuments.site/reader030/viewer/2022041101/5ed9aafba5d2fa37887930fd/html5/thumbnails/29.jpg)
GeneralDebuggingTechniques• Checkforcommonerrors,forexample:– Localvs.ReferenceParameters– =insteadof==– Didyouuse&&whenyoumeant||?– Thesearetypicallyerrorsthatmightnotgetflaggedbyacompiler!!
• Localizetheerror– Narrowdownbugsbyusingtracingandstubtechniques– Onceyourevealthebugandfixit,removetheextracoutstatements
• Yourtextbookhasgreatdebuggingexamples
4/25/18 Matni,CS16,Sp18 29
![Page 30: Compiling with Multiple Files The Importance of Debugging · More Loop Debugging Tips: Tracing • Be sure that the mistake is really in the loop • Trace the variable to observe](https://reader030.vdocuments.site/reader030/viewer/2022041101/5ed9aafba5d2fa37887930fd/html5/thumbnails/30.jpg)
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
![Page 31: Compiling with Multiple Files The Importance of Debugging · More Loop Debugging Tips: Tracing • Be sure that the mistake is really in the loop • Trace the variable to observe](https://reader030.vdocuments.site/reader030/viewer/2022041101/5ed9aafba5d2fa37887930fd/html5/thumbnails/31.jpg)
WhyusePre-andPost-conditions?
• Pre-conditionsandpost-conditionsshouldbethefirststepindesigningafunction
• SpecifywhatafunctionshoulddoBEFOREdesigningit– Thisminimizesdesignerrorsandtimewastedwritingcodethatdoesn’t
matchthetaskathand
4/25/18 Matni,CS16,Sp18 31
![Page 32: Compiling with Multiple Files The Importance of Debugging · More Loop Debugging Tips: Tracing • Be sure that the mistake is really in the loop • Trace the variable to observe](https://reader030.vdocuments.site/reader030/viewer/2022041101/5ed9aafba5d2fa37887930fd/html5/thumbnails/32.jpg)
Example
voidwrite_sqrt(doublex)//Precondition: x>=0.//Postcondition:Thesquarerootofxhas//beenwrittentothestandardoutput{cout<<sqrt(x)<<endl;
}
4/26/18 Matni,CS16,Sp18 32
![Page 33: Compiling with Multiple Files The Importance of Debugging · More Loop Debugging Tips: Tracing • Be sure that the mistake is really in the loop • Trace the variable to observe](https://reader030.vdocuments.site/reader030/viewer/2022041101/5ed9aafba5d2fa37887930fd/html5/thumbnails/33.jpg)
YOURTO-DOs
q FinishLab3bynextMondayq PrepareLab4fornextWednesdayq DoHW7bynextTuesday
q VisitProf’sandTAs‘officehoursifyouneedhelp!
q Hugatree!(oralovedonewilldo)
4/25/18 Matni,CS16,Sp18 33
![Page 34: Compiling with Multiple Files The Importance of Debugging · More Loop Debugging Tips: Tracing • Be sure that the mistake is really in the loop • Trace the variable to observe](https://reader030.vdocuments.site/reader030/viewer/2022041101/5ed9aafba5d2fa37887930fd/html5/thumbnails/34.jpg)
4/25/18 Matni,CS16,Sp18 34