Community
cancel
Showing results for 
Search instead for 
Did you mean: 
Highlighted
New Contributor I
18 Views

USE Statement

Hi, every one. I am a little confused about the USE Statement in fortran, assume this:

module mod1
    integer :: a = 1
end module mod1

module mod2
    use mod1
    integer :: b = 2
end module mod2

program test
    use mod1
    use mod2
    write(*,*) a, b
end program test

Since I have reference mod1 from mod2 through USE Statement, When I reference mod1 again in program section, there's no error occur, don't they conflict or multiple defining? Thanks for reply.

0 Kudos
6 Replies
Highlighted
Valued Contributor III
18 Views

It is clear in Test you only need to USE mod2 but there is no conflict as there is no multiple definition because the  "a" from mod2 is exactly the same "a" that is in mod1, "a" is only actually defined once.

If it was not this way it would be a nightmare in large complex projects. Where you do have conflicts extensive use of the ONLY clause or the rename facility of USE is very helpful. 

 

 

 

0 Kudos
Highlighted
New Contributor I
18 Views

Got it Andrew, Thanks times a million.

0 Kudos
Highlighted
18 Views

It's interesting that you ask this as I recently had a discussion with the editor of the standard regarding this very topic While the behavior Andrew describes is what we want to happen, the standard lacks sufficient words to specify it and in at least one place has comments that are contradictory. I have a paper in progress for the next standards meeting to discuss an edit to make the behavior clear.

The idea is that nested USE references the "ultimate" declaration and it's not a redeclaration of the entity. This is complicated by the standard allowing you to tack on VOLATILE or ASYNCHRONOUS to a USE-associated variable (something I wish had not been added.)

0 Kudos
Highlighted
New Contributor I
18 Views

Oh, so we are directing to the standard issues :-) . I think the way Andrew mentioned may be useful to try at present. Wishing some improvement to be made by the meeting. Thanks a lot, Steve.

0 Kudos
Highlighted
18 Views

It would be easy to explain it the way Andrew did if it weren't for the pesky feature of being able to add attributes to a use-associated variable. But for the most part his explanation is fine.

0 Kudos
Highlighted
New Contributor I
18 Views

Indeed, adding attributes to use-associated variables are pesky things anyway. I find out a way of using such as ONLY, PRIVATE and PUBLIC to strict access to the module, that should be fine and seems work.

module test
    use, intrinsic :: iso_fortran_env, only: int32
    implicit none

    private
    public :: a

    integer(int32) :: a = 5

end module test

program main
    use test
    implicit none

    write(*,*) a         ! No. 1
    write(*,*) int32     ! No. 2

end program main

So line No. 2 will generate an error message of variable int32 is not defined yet.

0 Kudos