Modules allow you to specify the visibility of variables and procedures defined in them. All entities in a module can be either public or private:
- Public –A public variable or procedure is accessible from within the module and can be accessed from any other program unit. You can declare a variable or procedure public by using the
publicattribute. This is the default behavior if not specified. - Private –A private variable or procedure is accessible only from within the module; it can’t be accessed from any other program unit. It’s automatically accessible from any procedure defined inside that module. You can declare a variable or procedure private by using the
privateattribute.
For example, let’s take a look at a module that defines a function to calculate the area of a circle, given an input radius. The following listing shows how that’s done.
Listing 4.6 Accessing a private variable from within the module procedure
module mod_circle
implicit none
private :: pi ❶
real, parameter :: pi = 3.14159256 ❶
contains
real pure elemental function circle_area(r) result(a)
real, intent(in) :: r
a = r**2 * pi ❷
end function circle_area
end module mod_circle
❶ Defines pi as a private parameter
❷ Function circle_area can access pi because it’s defined in the module scope.
This module defines a parameter pi and a function circle_area. The pi constant is only meant to be used by circle_area, and is thus marked as private. This removes the possibility of pi being imported from outside of the module. You can also just use the private or public words as a statement on their own, which will declare all entities in the module as private or public, respectively. If neither is present, then all entities are assumed public, unless explicitly declared private. For example, if we declare the module for calculating the area of a circle with the private and public statements in the following listing, we’ll ensure that only the procedure we want to give to the user can be accessed.
Listing 4.7 Declaring all entities private, except for one
module mod_circle
...
private ❶
public :: circle_area ❷
...
end module mod_circle
❶ Declares everything as private
❷ Only this function will be public.
You can use the private attribute to hide variables and procedures that are internal to the library and that the user shouldn’t access. In general, it’s good programming practice to declare everything as private and explicitly declare the public variables and procedures as such.
Tip Declare all entities as private, and explicitly list those that are meant to be public.