34
Compiling with Multiple Files The Importance of Debugging CS 16: Solving Problems with Computers I Lecture #7 Ziad Matni Dept. of Computer Science, UCSB

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

  • Upload
    others

  • View
    27

  • Download
    0

Embed Size (px)

Citation preview

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

#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

#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

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

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

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

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

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

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

4/25/18 Matni,CS16,Sp18 34