Also it's like C++ header file defining namespace, therefore, other components, who USE it, can access its content.
A form of a module is as follows
MODULE name
specifications
END MODULE name
See example below:
To make use of the module in the main program, we employ the USE statement. We use a special form of the USE statement that specifies that we are only interested in variable radius in the main program, namely, USE Circle, ONLY : radius. Similarly, we make use of only the parameter Pi in the function subprogram Area_Circle by way of the USE statement appearing in that routine.
eg 1:
MODULE Circle REAL, PARAMETER :: Pi = 3.1415927 REAL :: radius END MODULE Circle PROGRAM Area USE Circle, ONLY : radius ! only interested in radius. IMPLICIT NONE INTERFACE ! check function signature FUNCTION Area_Circle (r) REAL, INTENT(IN) :: r END FUNCTION Area_Circle END INTERFACE write(*, '(A)', ADVANCE = "NO") "Enter the radius of the circle: " read(*,*) radius ! radius is NOT defined in main code, included from Module Circle write(*,100) "Area of circle with radius", radius, " is", & Area_Circle(radius) 100 format (A, 2x, F6.2, A, 2x, F11.2) END PROGRAM Area FUNCTION Area_Circle(r) USE Circle, ONLY : Pi ! only interested in constant/parameter Pi. IMPLICIT NONE REAL :: Area_Circle REAL, INTENT(IN) :: r Area_Circle = Pi * r * r ! Pi is NOT defined in function either, included from module. END FUNCTION Area_Circle
eg 2:
MODULE Dyn_Array
INTEGER :: n
REAL, DIMENSION(:), ALLOCATABLE :: A
END MODULE Dyn_Array
PROGRAM Play_with_Array
USE Dyn_Array
IMPLICIT NONE
INTERFACE ! checking subroutine signature
SUBROUTINE Get_Data
END SUBROUTINE Get_Data
END INTERFACE
INTERFACE ! checking subroutine signature
SUBROUTINE Dealloc_Array
END SUBROUTINE Dealloc_Array
END INTERFACE
REAL :: Prod_A, Sum_A
CALL Get_Data ! load data into A
Prod_A = PRODUCT(A) ! use A
write(*,100) "The product of the elements of array A area", &
Prod_A
Sum_A = SUM(A) ! use A
write(*,100) "The sum of the elements of array A are", &
Sum_A
CALL Dealloc_Array ! unload A
100 format (A, 2x, F11.2)
END PROGRAM Play_with_Array
SUBROUTINE Get_Data
USE Dyn_Array ! include everything from module (header file in c)
IMPLICIT NONE
INTEGER :: AllocateStatus
write(*,'(A)', ADVANCE = "NO") "Input the number of elements desired: "
read(*,*) n
ALLOCATE( A(n), STAT = AllocateStatus) ! load A
IF (AllocateStatus /= 0) STOP "*** Not enough memory ***"
write(*, '(A)', ADVANCE = "NO") "Input array values: "
read(*,*) A
END SUBROUTINE Get_Data
SUBROUTINE Dealloc_Array
USE Dyn_Array
IMPLICIT NONE
INTEGER :: DeAllocateStatus
DEALLOCATE( A, STAT = DeAllocateStatus) ! unload A
IF (DeAllocateStatus /= 0) STOP "*** Trouble deallocating ***"
END SUBROUTINE Dealloc_Array
No comments:
Post a Comment