1

我觉得这必须是重复的,但我似乎无法在任何地方找到它,而且我没有通过非常快速的谷歌搜索得到任何东西。

有没有办法更改模块中的东西的名称,使其不与本地(或全局)的名称冲突?考虑这个例子:

module namespace
   real x  !some data
   contains
   subroutine foo()
     write(0,*) "foo!"
   end subroutine foo
end module
subroutine foo()
   write(0,*) "foo is the new bar :)"
end subroutine

program main
  use namespace
  real x
  call foo() !should print "foo is the new bar"
  call namespacefoo() !somehow call module namespace's version of foo
end program main

上面的代码没有编译,因为x没有定义。当然,如果我不想要一个名为 的局部变量x,那么我可以use namespace, only: foo,但是必须弄乱我的局部变量名称似乎有点麻烦。(作为旁注,我很确定我以前在only声明的一部分中看到过一些魔法......)


为了那些也了解python的人的利益,我正在寻找类似于python的东西:

import namespace as other_namespace

或者我猜因为 Fortran 没有那种级别的命名空间控制:

from namespace import somefunc as otherfunc
from namespace import somedata as otherdata
4

2 回答 2

4

您需要重命名:

[luser@cromer stackoverflow]$ cat ren.f90
module namespace
   real x  !some data
   contains
   subroutine foo()
     write(0,*) "foo!"
   end subroutine foo
end module
subroutine foo()
   write(0,*) "foo is the new bar :)"
end subroutine

program main
  use namespace, local_name => x, namespacefoo => foo  
  real x
  call foo() !should print "foo is the new bar"
  call namespacefoo() !somehow call module namespace's version of foo
end program main
[luser@cromer stackoverflow]$ nagfor ren.f90
NAG Fortran Compiler Release 5.3.1 pre-release(904)
Warning: ren.f90, line 17: X explicitly imported into MAIN (as LOCAL_NAME) but not used
Warning: ren.f90, line 17: Unused local variable X
[NAG Fortran Compiler normal termination, 2 warnings]
[luser@cromer stackoverflow]$ ./a.out
 foo is the new bar :)
 foo!

当然,如果可能的话,最好将模块私有化,以避免这种事情

于 2013-01-11T13:42:32.117 回答
0

似乎我应该在我的谷歌搜索中更加努力:

use namespace, only: namespace_x => x, namespacefoo => foo

“imports”命名空间x在本地名称namespace_x和命名空间的子例程下foo,就像namespacefoo在本地命名空间中一样。

一些代码是为了他人的利益:

module namespace
   real x  !some data
   real y
   contains
   subroutine foo()
     write(0,*) "foo!"
   end subroutine foo
end module

subroutine foo()
   use namespace, only: x,y
   write(0,*) "foo is the new bar :)"
   write(0,*) "by the way, namespace.x is:",x
   write(0,*) "by the way, namespace.y is:",y
end subroutine

program main
  use namespace, only: namespacefoo => foo, y, z => x
  real x
  x = 0.0
  y = 1.0
  z = 2.0
  call foo() !should print "foo is the new bar"
  call namespacefoo() !somehow call module namespace's version of foo
end program main
于 2013-01-11T13:40:03.160 回答