我觉得这必须是重复的,但我似乎无法在任何地方找到它并且我没有通过快速谷歌搜索得到任何东西。
有没有办法更改模块中的东西名称,以便它不会与本地(或全局)的名称冲突?考虑一下这个例子:
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
答案 0 :(得分: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!
虽然当然最好将模块保密,但如果可能的话,最好避免这种事情
答案 1 :(得分:0)
似乎我应该在谷歌搜索中看起来更难:
use namespace, only: namespace_x => x, namespacefoo => foo
在本地名称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