Computational Physics - Department of Physics

(Axel Boer) #1

14 2 Introduction to C++ and Fortran


WRITE(,)'Hello World! SINE of ', r,' =', s
END PROGRAMshw


The first statement must be a program statement; the last statement must have a corre-
sponding end program statement. Integer numerical variables and floating point numerical
variables are distinguished. The names of all variables must be between 1 and 31 alphanu-
meric characters of which the first must be a letter and the last must not be an underscore.
Comments begin with a! and can be included anywhere in the program. Statements are writ-
ten on lines which may contain up to 132 characters. The asterisks (,) following WRITE
represent the default format for output, i.e., the output ise.g., written on the screen. Sim-
ilarly, the READ(,) statement means that the program is expecting a line input. Note also
the IMPLICIT NONE statement which we strongly recommend theuse of. In many Fortran 77
programs one can find statements like IMPLICIT REAL*8(a-h,o-z), meaning that all variables
beginning with any of the above letters are by default floating numbers. However, such a
usage makes it hard to spot eventual errors due to misspelling of variable names. With IM-
PLICIT NONE you have to declare all variables and therefore detect possible errors already
while compiling. I recommend strongly that you declare all variables when using Fortran.
We call the Fortran compiler (using free format) through


f90 -c -free myprogram.f90
f90 -o myprogram.x myprogram.o

Under Linux/Unix it is often convenient to create a so-called makefile, which is a script
which includes possible compiling commands, in order to avoid retyping the above lines every
once and then we have made modifcations to our program. A typical makefile for the above
cccompiling options is listed below


# General makefile for c - choose PROG = name of given program

# Here we define compiler option, libraries and the target
CC= c++ -Wall
PROG= myprogram

# Here we make the executable file
${PROG} : ${PROG}.o
${CC} ${PROG}.o -o ${PROG}

# whereas here we create the object file

${PROG}.o : ${PROG}.cpp
${CC} -c ${PROG}.cpp

If you name your file for ’makefile’, simply type the commandmakeand Linux/Unix ex-
ecutes all of the statements in the above makefile. Note that C++ files have the extension
.cpp
For Fortran, a similar makefile is

Free download pdf