You are on page 1of 5

6/30/13

Compiling and Running Fortran 90/95 Programs - a basic guide

CompilingandRunningFortranProgramsabasicguide
http://www.fortran.gantep.edu.tr/compilingg95basicguide.html

CONTENTS
1. Introduction
2. Filenameconvention
3. Compilingaprogram
4. CompilerOptions
5. Compilingsubprogramsourcefiles
6. Creatingandlinkingobjectandlibraryfiles
7. KINDtypesforREALsandINTEGERs
8. RunningprogramsunderLinux
1.Introduction
ThisguideisforFortranprogrammersusingcentralLinuxserverssuchasgul3,gul4andgul5,wheretheg95compilerisinstalled.Thisguide
coversatabasicleveltopicsrelatingtothecompilationofprogramsourcesitisnotaguidetotheFortranprogramminglanguage(Ihave
howeverincludedasectiononKINDtypesisgivenattheendofthisguide.
2.FilenameConvention
Filenamesendingin.f90and.f95areassumedtobefreesourceformsuitableforFortran90/95compilation.
Filenamesendingin.fand.forareassumedtobeassumedfixedformsourcecompatiblewitholdFortran77compilation.
3.Compilingaprogram
Theroleofg95FortrancompileristocompileyourFortransourcecodeintoanexecutableprogram.ConsiderthatyouhaveaFortran95source
filecalledmyprog.f90.Thesimplestcommandforcreationofanexecutableisthen:
g95myprog.f90
Thiscreatestheexecutableprogramcalleda.out
Youcangiveamoremeaningfulnametoyourexecutablebyusingtheooption:
g95myprog.f90omyprog
Thiscreatestheexecutableprogramcalledmyprog
ThepathofincludefilescanbegivenwiththeIoption,forexample:
g95myprog.f90omyprogI/home/fred/fortran/inc
or
g95myprog.f90omyprogI$MYINC
wheretheenvironmentvariableMYINCissetwith:
MYINC=/home/fred/fortran/inc/
4.CompilerOptions
AsforanyFortrancompiler,g95providesmanyoptionsthatcontrolitsbehaviour.Thebasicandrecommendedoptionsaregivenhere,amore
detaileddescriptioncanbefoundathttp://www.g95.org/docs.shtml.
Speedoptimisation
TheOleveloptionperformssomeoptimisationoftheexecutableandcanleadtosignificantincreasesinexecutationspeed.Example:
g95myprog.f90omyprogO2
Warningoptions
TheWleveloptionenablesmostwarningmessagesthatcanbeswitchedonbytheprogrammer.Suchmessagesaregeneratedatcompile
timewarningtheprogrammerof,forexample,unusedorunsetvariables.Example:
g95myprog.f90omyprogO2Wall
ItisadvisabletouseOleveloptionassomewarningoptionsrelyonflowanalysisprovidedbythisoption.
Runtimeoptions
Variousruntimeoptionscanbeselected,theseoptionscauseextracodetobeaddedtotheexecutableandsocancausesignificantdecreases
inexecutionspeed.Howevertheseoptionscanbeveryusefulduringprogramdevelopmentanddebugging.Example
g95myprog.f90omyprogO2fboundscheck
Thiscausestheexecutabletocheckfor"arrayindexoutofboundsconditions".
Recommendedoptions
ForteachingstudentsFortranprogramming,andduringprogramdevelopmentintheresearchenvironment,Iadvisesomethinglikethefollowing
optionsastheyhelptheprogrammertoprogramwithsafetyinmind.

www.fortran.gantep.edu.tr/compiling-g95-basic-guide.html

1/5

6/30/13

Compiling and Running Fortran 90/95 Programs - a basic guide

g95myprog.f90omyprogWuninitializedWimplicitnoneWunusedvarsWunsetvarsfboundscheck
ftrace=fullO2
Ifspeedofexecutationisimportantthenthefollowingoptionswillimprovespeed:
g95myprog.f90omyprogWuninitializedWimplicitnoneWunusedvarsWunsetvarsO2
OncentralinteractiveLinuxserversintheuniversity,thefortrancommand(orsimplyf)providestheseoptionsbydefault,example:
fortranmyprog.f90
isequivalentto
g95myprog.f90omyprogWuninitializedWimplicitnoneWunusedvarsWunsetvarsfboundscheck
ftrace=fullO2
Typefortranwithnoargumentstofindtheuptodatelistofdefaultarguments.
5.Compilingsubprogramsourcefiles
Itissometimesusefultoplacesubprogramsintoseparatesourcefilesespeciallyifthesubprogramsarelargeorsharedwithother
programmers.IfaFortran90/95projectcontainsmorethanoneprogramsourcefile,thentocompileallsourcefilestoanexecutableprogramyou
canusethefollowingcommand:
g95main.f90sub1.f90sub2.f90sub3.f90omyprog
Inthisexamplemain.f90isthemainprogramsourceandsub1.f90,sub2.f90,sub3.f90arefilescontainsubprogramsources.
Aworkingexample:
Considerthefollowingmainprogramsourcemain.f90andthreesubprogramsourcessub1.f90,sub2.f90,sub3.f90.
Thesourcesare:
main.f90

real::a
a=2.0
callsub1(a)
callsub2(a)
callsub3(a)
end
sub1.f90sub2.f90sub3.f90

subroutinesub1(x)subroutinesub2(x)subroutinesub3(x)
real::xreal::xreal::x
print*,xprint*,x**2print*,x**3
endendend
Thefoursourcescanbecompiledtogetherwiththecommand:
g95main.f90sub1.f90sub2.f90sub3.f90omyprog
Theprogramisrunbysimplytypingitsname:
myprog
2.
4.
8.
Notethatinthisexamplethesubroutinesareexternal(asinFortran77).
InFortran90/95subroutinescanalsobewritteninamodule.
Inthiscasetheprogramsourcesare:
main2.f90mod.f90

USEmodMODULEmod
real::a
a=2.0CONTAINS
callsub1(a)
callsub2(a)subroutinesub1(x)
callsub3(a)real::x
endprint*,x
endsubroutinesub1
subroutinesub2(x)
real::x
print*,x**2
endsubroutinesub2

www.fortran.gantep.edu.tr/compiling-g95-basic-guide.html

2/5

6/30/13

Compiling and Running Fortran 90/95 Programs - a basic guide

subroutinesub3(x)
real::x
print*,x**3
endsubroutinesub3
ENDMODULEmod
Thetwosourcescanbecompiledtogetherwiththecommand:
g95mod.f90main2.f90omyprog
Notethatinthiscommandthemoduleappearsbeforethemainprogramsothatthefunctionsaredefinedbeforetheyarereferencedinthemain
program.
6.Creatingandlinkingobjectandlibraryfiles
Whenworkingonlargeprojects,especiallyprojectsthataresharedbetweenanumberofprogrammers/users,itisusefultocreateobjectfilesor
librariesofobjectfilesthatcanbesharedbetweenprogrammersandusers.Inpart5thecompilationofmultiplesourcefilesisdescribed.For
example:
g95main.f90sub1.f90sub2.f90sub3.f90omyprog
Ifasubprogramiscompleteitisnotnecessarytorecompileitagainandagainduringthedevelopmentofotherpartsoftheproject.Completed
subprogramscanbecompiledintoobjectfilesthatcanbelinkedduringthecompilationofthewholeprogram,forexample:
g95main.f90sub1.osub2.osub3.oomyprog
Here,sub1.osub2.osub3.oareobjectfilescreatedwith:
g95csub1.f90
g95csub2.f90
g95csub3.f90
Notethatthecoptionislowercase("compiletoobject(.o)only,donotlink").
Ifmanyobjectfilesaretobelinkedthenitisconvenienttoplacetheminalibrary.Librariescanbecreatedusingthearcommand(seemanar
).Objectfilescanbeplacedinalibraryforexampleasfollows:
arrcvflibsubs.asub1.osub2.osub3.o
Thelibrarycreatediscalledlibsubs.a,itcontainsthethreeobjectssub1.osub2.osub3.o.
Notethatthenameofthelibrarymustbeginwithlibandendwith.a.
Moreobjectscanbeaddedtothelibrarywith:
arrcvflibsubs.aanother.o
Thecontentsofalibrarycanbelistedwith:
artvlibsubs.a
Subroutinesandfunctionsinthelibrarycanbelistedwith:
nmlibsubs.a
Objectscanbedeletedfromthelibrarywith:
ardvlibsubs.asub.o
Oncealibraryhasbeencreated,itcanbelinkedinacompilationasfollows:
g95main.f90omyprogL.lsubs
TheL.optionstellsthelinkerthatthelibrarycanbefoundinthecurrentdirectory.
Ifthelibraryisnotinthecurrentdirectorythenyoushouldgivethepath,forexample:
g95main.f90omyprogL/home/fred/fortran/lib/lsubs
or
g95main.f90omyprogL$MYLIBlsubs
wheretheenvironmentvariableMYLIBissetwith:
MYLIB=/home/fred/fortran/lib/
7.KINDtypesforREALsandINTEGERs
Realtypedatacanbedeclaredassingle,double,orquadprecision.Thedefaultissingleprecision(KIND=4)whereeachdataisstoredin4
bytesofmemory.Doubleprecisiondataareallocated8bytesandquadprecisionin16bytes.Doubleprecisionhasabouttwicetheprecisionas
singleprecisionandamuchlargerrangeintheexponent,Quadprecisionhasmorethanfourtimestheprecisionandaverylargerangeinthe
exponent.

www.fortran.gantep.edu.tr/compiling-g95-basic-guide.html

3/5

6/30/13

Compiling and Running Fortran 90/95 Programs - a basic guide

Similarly,integertypedatacanbestoredin1,2,4or8bytes,eachgivingalargerrangeofvaluesthatcanberepresentedbythem.Thedefaultis
4bytes(KIND=4).
KINDtypesavailableintheg95compiler(atthetimeofwritingquadprecisisonisnotyetavailable).
++++++
|Kind|Memory|Precision|Smallestvalue,TINY()|Largestvalue,HUGE()|
++++++
|REAL(KIND=4)*|4bytes|7s.f.(Single)|1.1754944E38|3.4028235E+38|
|REAL(KIND=8)|8bytes|15s.f.(Double)|2.2250738585072014E308|1.7976931348623157E+308|
|REAL(KIND=16)|16bytes|34s.f.(Quad)|||
++++++
++++
|Kind|Memory|Range|
++++
|INTEGER(KIND=1)|1byte|128to127|
|INTEGER(KIND=2)|2bytes|32768to32767|
|INTEGER(KIND=4)*|4bytes|2147483648to2147483647|*meansdefaultkind.
|INTEGER(KIND=8)|8bytes|about+9.2x10^18|s.f.means"significantfigures".
++++
Toassigndoubleandquadprecisioncorrectlyusethe_8and_16notations:
Insingleprecision:A=1.2345678E38or1.2345678E38_4
Indoubleprecision:A=1.234567890123456E308_8
Inquadprecision:A=1.2345678901234567890123456789012345E4931_16
Tospecifythekindtype,theKINDattributeisgiveninthedeclarationofdata.
Examplesdeclarationsofrealtypes:
REAL::A!default(singleprecision)
REAL(KIND=4)::B!singleprecision
REAL(KIND=8)::C!doubleprecision
REAL(KIND=16)::D!quadprecision
Inassignments,constantscanbegiventherequiredprecisionasfollows:
A=1.2345678_4orsimply1.2345678(Single)
A=1.234567890123456_8(Double)
A=1.2345678901234567890123456789012345_16(Quad)
TheEsymbolcanbeusedforexponentiation:
A=1.234568E38
B=1.234568E38_4
C=1.23456789012346E308_8
D=1.234567890123456789012345678901235E4931_16
Doubleandquadprecisiongreatlyreducesroundofferrorsinmanynumericalmethods.
Exampledeclarationsofintegertypes:
INTEGER::E!default(KIND=4)
INTEGER(KIND=1)::F
INTEGER(KIND=2)::G
INTEGER(KIND=4)::H
INTEGER(KIND=8)::I
8.RunningprogramsunderLinux
TherearetwomodesofrunningprogramsunderLinux,thefirstisinteractively,andthesecondinbackground.Runninginteractivelymeansyou
executetheprogramandyourcommandpromptswaitsforittocomplete:
$mybigjob
thecommandpromptwillnotreturnuntilthejobiscomplete:
Alternatively,thejobcanberuninbackgroundinthiscasethecommandpromptisreturnedtoyouandthejobcontinuestorun.Youmaylogoff
thesystem,andthejobwillcontinuetorun.Thisisagreatconvenienceespeciallyforlongrunningprograms.
Aprogramisplacedintobackgroundbyappendingthe&symbolattheendoftheexecutioncommandforexample:
$mybigjob&
Itusualtorequirescreenoutputtoberedirectedtoafilethisisacheivedusingoutputredirection:
$mybigjob>mybigjob.log&
Inthismethoderrormessagesarenotincludedintheoutputfiletherearetwomethodstorecordalsoerrormessagesinafile:

www.fortran.gantep.edu.tr/compiling-g95-basic-guide.html

4/5

6/30/13

Compiling and Running Fortran 90/95 Programs - a basic guide

$mybigjob1>mybigjob.output2>mybigjob.error&
$mybigjob1>mybigjob.log2>&1&
Inthefirstmethodthetwooutputsgotoseparatefiles,inthesecondmethodthetwooutputsgotothesamefile.
Withaninteractivelogin,theprogressofajobcanbeviewedwiththetopcommand.Jobscanbelistedwiththejobscommandandterminated
withthekillcommand.Systemresourcescanbeviewedwiththedfandfreecommands.
system@gantep.edu.tr
19/12/2005
smallupdate04/11/2008

www.fortran.gantep.edu.tr/compiling-g95-basic-guide.html

5/5

You might also like