Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Derived type is being used before it is defined" in interface block [duplicate]

Using cygwin64 on Windows this program won't compile:

program test
  implicit none

  !define my type
  type myType
    real::foo
    integer::bar
  end type myType

  !define an operator for this type
  interface operator (>)
      logical function compare(a,b)
        type(myType),intent(in) :: a,b
        compare = a%foo>b%foo
      end function compare
  end interface operator (>)

  !simple example of operator usage
  type(myType) :: tfoo, tbar
  tfoo = card(1.,2); tbar = card(3.,4)
  print*, tfoo>tbar
end program test

gfortran (only argument is "std=f2008") tells me:

type(myType),intent(in) :: a,b
                    1
Error: Derived type ‘mytype’ at (1) is being used before it is defined

which is confusing to me, since the type is defined right before the operator. I'm relatively new to Fortran, so this example code might have some more errors.

The same problem occurred here, but encapsulating myType in a separate module did not resolve the issue.

like image 570
Obay Avatar asked Feb 07 '23 15:02

Obay


1 Answers

There are several issues with your code, but this particular error is because myType is in the host scope, but not in the interface block. The solution is to either place the derived type in a separate module as suggested in the linked thread, or import the derived type from the host scoping unit:

  interface operator (>)
      logical function compare(a,b)
        import myType
        type(myType),intent(in) :: a,b
      end function compare
  end interface operator (>)

This is described in the Fortran 2008 Standard, Cl. 12.4.3.3 "IMPORT statement":

1 The IMPORT statement specifies that the named entities from the host scoping unit are accessible in the interface body by host association. An entity that is imported in this manner and is defined in the host scoping unit shall be explicitly declared prior to the interface body.


An interface block may not have executable statements included - so the assignment you have there is not valid. Furthermore, card is not defined in your code.

like image 184
Alexander Vogt Avatar answered Apr 27 '23 23:04

Alexander Vogt