Search code examples
fortrangfortran

Calling a function or subroutine


I'm quite new to fortran, i'm trying to execute a function/subroutine but i'm getting an error Explicit interface required

This is my code:

function printmat(m)
    integer, dimension(:,:) :: m
    integer :: row,col
    row = size(m,1)
    col = size(m,2)
       do k=1,row
            print *, m(k,1:col)
       enddo
end function printmat

program test
    integer, dimension(5, 5) :: mat
    integer :: i,j
    do i=1,5
    do j=1,5
           mat(j,i) = real(i)/real(j)
    enddo
    enddo
    call printmat(mat)
end program test

But when i execute it i get:

Error: Explicit interface required for 'printmat' at (1): assumed-shape argument

Any idea of what could it be? I tried wrapping it into a module, but when i use "use modulename" in the program it gives me an error (tries to read it from a file with the same name)


Solution

  • Wrap it into a module and make it a subroutine if you want to use it with CALL.

    module printmat_module
    contains
      subroutine printmat(m)
        integer, dimension(:,:) :: m
        integer :: row,col
        row = size(m,1)
        col = size(m,2)
        do k=1,row
           print *, m(k,1:col)
        enddo
      end subroutine printmat
    end module printmat_module
    
    program test
      use printmat_module
      integer, dimension(5, 5) :: mat
      integer :: i,j
      do i=1,5
         do j=1,5
            mat(j,i) = real(i)/real(j)
         enddo
      enddo
      call printmat(mat)
    end program test
    

    Alternatively you can just do what the compiler tells you and add an explicit interface to the program.

    subroutine printmat(m)
      integer, dimension(:,:) :: m
      integer :: row,col
      row = size(m,1)
      col = size(m,2)
      do k=1,row
         print *, m(k,1:col)
      enddo
    end subroutine printmat
    
    program test
      interface
         subroutine printmat(m)
           integer, dimension(:,:) :: m
         end subroutine printmat
      end interface
      integer, dimension(5, 5) :: mat
      integer :: i,j
      do i=1,5
         do j=1,5
            mat(j,i) = real(i)/real(j)
         enddo
      enddo
      call printmat(mat)
    end program test