Consider a module that generates the first few primes:
module module_primes
contains
function is_prime(n)
! Function to check if a number is prime.
implicit none
integer :: n, m
logical :: is_prime
is_prime = .true.
do m=2, n-1
if ( mod(n,m) == 0 ) then
is_prime = .false.
end if
end do
end function is_prime
subroutine prime_gen( list )
! Subroutine that takes an array, say of size L, and puts first L primes in it.
implicit none
integer, dimension(:) :: list
integer :: n, counter = 0
logical :: is_prime
do n=3, huge(1)-1
if ( is_prime(n) ) then
counter = counter + 1
list(counter) = n
end if
if (counter == size( list) ) then
exit
end if
end do
end subroutine prime_gen
end module module_primes
I am aware that doing something similar inside a program
is incorrect (internal procedures can not reference each other). Inside a module as with the code above, the exact error message is (Mac OS terminal with GFortran compiler)
% gfortran module_primes.o main_primes.o -o primes.exe
Undefined symbols for architecture x86_64:
"_is_prime_", referenced from:
___module_primes_MOD_prime_gen in module_primes.o
ld: symbol(s) not found for architecture x86_64
collect2: error: ld returned 1 exit status
Presently I am putting is_prime
outside the module (I guess that's what is referred to as 'external procedures') as follows
module module_primes
contains
subroutine prime_gen( list )
...
if ( is_prime(n) ) then
...
end subroutine prime_gen
end module module_primes
function is_prime(n)
...
end function is_prime
And it works as intended. The reason I am not satisfied with that is I want is_prime
to be available to programs that use module_primes
; now it is available only to the procedures that are defined inside this module file.
Is the cause of the error what I mentioned, or something else?