Search code examples
fortran

Why Fortran does not create explicit interfaces for stand-alone subroutines/functions?


To use a subroutine and allow the compiler to check argument mismatch, one needs to place the defintion of that subroutine in a module, for which case, fortan creates an explicit interface for the calling unit to check argumetn mismatch etc.

For stand-alone subroutines that are not contained in a module, we say they have only "implicit interfaces" and no "explicit interfaces", so that the compiler can not check argument mismatch. Why does not the compiler also create "explicit interfaces" for the stand-alone subroutines? What difficulties prevent the compiler from doing this?


Solution

  • When we are considering interfaces, we are not talking about some mythical object which may be implicit or explicit.

    Consider the two main programs:

    program main1
      implicit none (external)
    
      external sub
    
      call sub
    end program main1
    

    and

    program main2
      implicit none (external)
    
      interface
        subroutine sub()
        end subroutine sub
      end interface
    
      call sub
    end program main2
    

    These two main programs are (perhaps) concerned about the same external subroutine sub. main1 has an implicit interface for sub and main2 has an explicit interface for sub.

    Whichever main program we are wondering about, the subroutine sub always has an explicit interface for itself:

    subroutine sub()
      implicit none (external)
    
      call sub
    end subroutine sub
    

    I've just defined a (pretty terrible) subroutine called sub. I imagine that's going to be a popular name: next time you want to use that name (don't forget: external procedures are global entities) for an external procedure are you going to use the one I've just defined? If you aren't, how are you going to tell the compiler which sub you are talking about?

    Resolution of which external subroutine sub is going to be used is often a problem for the linker, not the compiler. The compiler may never see a particular external procedure so cannot automatically generate for a program unit an explicit interface for an external procedure.1

    That said, there are cases where a compiler will do some work for you:

    program main3
      implicit none (external)
    
      external sub
      
      call sub
    end program main3
    
    subroutine sub(x)
      implicit none (external)
      real x
    end subroutine sub
    

    (as a single file, or separate files, perhaps with specific compiling options) may well prompt your compiler to complain, just as though sub had an explicit interface inside main3.


    1 An external procedure can also be defined by means other than Fortran. In such a case, the Fortran compiler doesn't need to even understand it, let alone worry about having to generate an explicit interface for it.