6-Compiling Your First Program
6-Compiling Your First Program
6Compilingyourfirstprogram
BYALEX,O NMAY28T H,2007
Beforewecanwriteourfirstprogram(whichwewilldoverysoon),weneedtoknowafewthingsaboutdevelopmentenvironments.
First,althoughourprogramswillbewritteninside.cppfiles,the.cppfilesthemselveswillbeaddedtoaproject.Theprojectstoresthenamesofall
thecodefileswewanttocompile,andalsosavesvariousIDEsettings.Everytimewereopentheproject,itwillrestorethestateoftheIDEtowhere
weleftoff.Whenwechoosetocompileourprogram,theprojecttellsthecompilerandlinkerwhichfilestocompileandlink.Itisworthnotingthat
projectfilesforoneIDEwillnotworkinanotherIDE.Youwillneedtocreateanewprojectforeachprogramyouwrite(oroverwriteanoldone).
Second,therearedifferentkindsofprojects.Whenyoucreateanewproject,youwillhavetopickaprojecttype.Alloftheprojectsthatwewillcreate
inthistutorialwillbeconsoleprojects.Aconsoleprojectmeansthatwearegoingtocreateprogramsthatcanberunfromthedosorlinuxcommand
line.Bydefault,consoleapplicationshavenographicaluserinterface(GUI)andarecompiledintostandaloneexecutablefiles.Thisisperfectfor
learningC++,becauseitkeepsthecomplexitytoaminimum.
Third,whenyoucreateanewprojectforyourprogram,manyIDEswillautomaticallyaddyourprojecttoaworkspaceorasolution.Aworkspaceor
solutionisacontainerthatcanholdoneormorerelatedprojects.Althoughyoucanaddmultipleprojectstoasinglesolution,werecommendcreating
anewworkspaceorsolutionforeachprogram.Itssimplerandthereslesschanceofsomethinggoingwrong.
Traditionally,thefirstprogramprogrammerswriteinanewlanguageistheinfamoushelloworldprogram,andwearentgoingtodepriveyouofthat
experience!Youllthankuslater.Maybe.
Aquicknoteaboutexamplescontainingcode
Startingwiththislesson,youwillseemanyexamplesofC++codepresented.Mostoftheseexampleswilllooksomethinglikethis:
1
2
3
4
5
6
7
#include <iostream>
int main()
{
std::cout << "Hello world!" << std::endl;
return 0;
}
Ifyouselectthecodefromtheseexampleswithyourmouseandthencopy/pasteitintoyourIDE,youmayalsogetthelinenumbers(dependingon
howyoumadetheselection).Ifso,youllneedtoremovethesemanually.
IfyoureusingtheVisualStudioIDE
AlthoughthefollowingsectionwaswrittenusingVisualStudio2005,itessentiallyworksthesameforallversionsofVisualStudio.
TocreateanewprojectinVisualStudio,gototheFilemenu,andselectNew>Project.Adialogboxwillpopupthatlookslikethis:
First,makesureVisualC++isselectedontheleftside.
Second,underneathVisualC++,selecttheWin32projecttype,andWin32ConsoleApplicationwillautomaticallybeselectedforyou.IntheName
field,youwillenterthenameofyourprogram.TypeinHelloWorld.IntheLocationfield,pickadirectorythatyouwouldlikeyourprojecttobe
placedinto.WerecommendyouplacetheminasubdirectoryoffofyourCdrive,suchasC:VC2005Projects.ClickOK,andthenFinish.
Ontheleftside,intheSolutionExplorer,VisualStudiohascreatedanumberoffilesforyou,includingstdafx.h,HelloWorld.cpp,andstdafx.cpp.
Inthetexteditor,youwillseethatVC2005hasalreadycreatedsomecodeforyou.Selectanddeleteallofthecode,andtype/copythefollowinginto
yourcompiler:
1
2
3
4
5
6
7
8
#include "stdafx.h"
#include <iostream>
int main()
{
std::cout << "Hello world!" << std::endl;
return 0;
}
Whatyouendupwithshouldlooklikethis:
Tocompileyourprogram,eitherpressF7orgototheBuildmenuandchooseBuildSolution.Ifallgoeswell,youshouldseethefollowingappearin
theOutputwindow:
Thismeansyourcompilewassuccessful!
Torunyourcompiledprogram,pressctrlF5,orgotheDebugmenuandchooseStartWithoutDebugging.Youwillseethefollowing:
Thatistheresultofyourprogram!
ImportantnotetoVisualStudiousers:VisualstudioprogramsshouldALWAYSbeginwiththefollowingline:
1
#include "stdafx.h"
Otherwiseyouwillreceiveacompilerwarning,suchasc:testtest.cpp(21):fatalerrorC1010:unexpectedendoffilewhile
lookingforprecompiledheaderdirective
Alternately,youcanturnoffprecompiledheaders.However,usingprecompiledheaderswillmakeyourprogramcompilemuchfaster,sowe
recommendleavingthemonunlessyouaredevelopingacrossplatformprogram.
Theexampleprogramsweshowyouthroughoutthetutorialwillnotincludethisline,becauseitisspecifictoyourcompiler.
IfyoureusingtheCode::BlocksIDE
Tocreateanewproject,gototheFilemenu,andselectNewProject.Adialogboxwillpopupthatlookslikethis:
SelectConsoleApplicationandpresstheCreatebutton.
Youwillbeaskedtosaveyourproject.Youcansaveitwhereveryouwish,thoughwerecommendyousaveitinasubdirectoryoffoftheCdrive,
suchasC:CBProjects.NametheprojectHelloWorld.
YouwillseeConsoleApplicationunderthedefaultworkspace:
OpenthetreeunderConsoleApplication,openSources,anddoubleclickonmain.cpp.Youwillseethatthehelloworldprogramhasalreadybeen
writtenforyou!
Tobuildyourproject,pressctrlF9,orgototheBuildmenuandchooseBuild.Ifallgoeswell,youshouldseethefollowingappearintheBuildlog
window:
Thismeansyourcompilewassuccessful!
Torunyourcompiledprogram,pressctrlF10,orgotheBuildmenuandchooseRun.Youwillseesomethingsimilartothefollowing:
Thatistheresultofyourprogram!
Ifyoureusingacommandlinebasedcompiler
PastethefollowingintoatextfilenamedHelloWorld.cpp:
1
2
3
4
5
6
7
#include <iostream>
int main()
{
std::cout << "Hello world!" << std::endl;
return 0;
}
Fromthecommandline,type:
g++oHelloWorldHelloWorld.cpp
ThiswillcompileandlinkHelloWorld.cpp.Torunit,type:
HelloWorld(orpossibly./HelloWorldor),andyouwillseetheoutputofyourprogram.
IfyoureusingotherIDEs
Youwillhavetofigureouthowtodothefollowingonyourown:
1)Createaconsoleproject
2)Adda.cppfiletotheproject(ifnecessary)
3)Pastethefollowingcodeintothefile:
1
2
3
4
5
6
7
#include <iostream>
int main()
{
std::cout << "Hello world!" << std::endl;
return 0;
}
4)Compiletheproject
5)Runtheproject
Ifcompilingfails(aka.Ohgodsomethingwentwrong!)
Itsokay,takeadeepbreath.Wecanprobablyfixit.
First,checktoensurethatyouvetypedthecodeincorrectly,withnotyposormisspellings(also,makesureyourenotincludinglinenumbersinyour
code).Thecompilerserrormessagemaygiveyouaclueastowhereorwhattheproblemis.
Second,checksection0.7AfewcommonC++problems,asmanycommonproblemsareaddressedthere(includingtheCOFFerrorthatmanyof
youareencountering).
Ifthatfails,trysearchingforyourerrormessageonGoogle.Itslikelysomeoneelsehasencounteredthisbeforeandfiguredouthowtofixit.
IfyouareusingamucholderC++compiler,thecompilermaygiveanerroraboutnotunderstandinghowtoincludeiostream.Ifthisisthecase,trythe
followingprograminstead:
1
2
3
4
5
6
7
#include <iostream.h>
int main()
{
cout << "Hello world!" << endl;
return 0;
}
Inthiscase,youshouldupgradeyourcompilertosomethingmorecompliantwithrecentstandards.
Ifyourprogramrunsbutthewindowclosesimmediately
Thisisanissuewithsomecompilers,suchasBloodshedsDevC++.Wepresentasolutiontothisprobleminsection0.7afewcommonC++
problems.
Conclusion
Congratulations,youmadeitthroughthehardestpartofthistutorial(installingtheIDEandcompilingyourfirstprogram)!
DontworryifyoudontunderstandwhatallthedifferentlinesintheHelloWorldprogramdo.Welllookatandexplaineachlineindetailinthe
upcomingsection1.1Structureofaprogram.
0.6aBuildconfigurations
Index
0.5InstallinganIntegratedDevelopmentEnvironment(IDE)