Possibly a very silly question involving subroutines


TheIsingGuy
08-11-2009, 05:46 AM
Hi, I have written a piece of code with some subroutine and a module, and I am having problem passing some variables between the main program and the subroutines that I have. I have included below part of my program to which this is concerned.
!-------------------------------------------------------------------
Program MonteCarlo
use vars
..
..
Call Distribute_Velocity
write(10,*)TCP !Failed to output from subroutine
..
End Program

Subroutine Distribute_Velocity
use vars
..
..
..
A loop to modify a real variable TCP
write(20,*)TCP This gives a value out.
..
..
End Subroutine Distribute_Velocity
!-------------------------------------------------------------------------
and the Module call vars, which is included by the subroutine and the main program:

Module vars
..
Real :: TCP
..
..
End Module
!-----------------------------------------------------------------------
As you can see, TCP is global, after calling the subroutine from the main program, its value should be allocated, but apparently there is no output, it doesn't even give me anything, just an empty file.

Sorry if I'm being silly at all, but do I HAVE to put the subroutine inside the main program with a CONTAINS statement for it work?

Thanks

Ising

TheIsingGuy
08-11-2009, 08:21 AM
silly me.. of course it won't write..

davekw7x
08-11-2009, 08:34 AM
...do I HAVE to put the subroutine inside the main program with a CONTAINS statement for it work?

No. Here's a simple complete example (I used GNU gfortran to compile)


!
! Global variables in a module
!
! davekw7x
!
MODULE global_vars
INTEGER :: foo
END MODULE global_vars


SUBROUTINE change_global_foo
USE global_vars
IMPLICIT none
INTEGER :: i
write(*, '("In subroutine change_global_foo.")')
write(*, '(" Enter an integer: ")', advance='no')
read *, i
foo = i*2
write(*, '(" foo = ", I0/)') foo

END SUBROUTINE change_global_foo



PROGRAM test_globals_in_a_module
USE global_vars
IMPLICIT none
INTEGER :: x

write(*, '("In main program.")')
write(*, '(" Enter an integer: ")', advance='no')
read *, x
foo = 2*x
write(*, '(" foo = ",I0/)') foo
call change_global_foo
write(*, '("In main program after returning from subroutine.")')
write(*, '(" foo = ", I0)') foo

END PROGRAM test_globals_in_a_module


Output:

In main program.
Enter an integer: 21
foo = 42

In subroutine change_global_foo.
Enter an integer: 888
foo = 1776

In main program after returning from subroutine.
foo = 1776


Regards,

Dave

TheIsingGuy
08-11-2009, 09:04 AM
No. Here's a simple complete example (I used GNU gfortran to compile)

..

Regards,

Dave

Thanks again Dave, I found the error, I put the open file statement in my subroutine, the main program doesn't know which file to open, which is why nothing is written there in the first place.