error when calling subroutine from module in fortran [duplicate] - module

I am trying to compile some really old code (1986 and before). This code references an external function. Today's compilers ask for far more code to make this work. And I keep failing.
I now created a small hello world program, which demonstrates the problem.
hello.for
PROGRAM hello
USE func
PRINT *, "Hello World!"
PRINT *, f ()
END PROGRAM hello
func.for
MODULE func
PUBLIC f
CONTAINS
FUNCTION f ()
f='Hello Func'
END FUNCTION
END MODULE
This has not only one, but two problems:
How do I define the return type? Docs tell <type> FUNCTION <function> or FUNCTION <function> () <type>::<something> , but neither works.
How do I make the linker find the function?
gfortran -c func.for works (if I use the default return type real) and creates a mod file but linking does not work
$ gfortran hello.for
/tmp/ccHNzcXA.o: In function `MAIN__':
hello.for:(.text+0xa4): undefined reference to `__func_MOD_f'
collect2: error: ld returned 1 exit status
__func_MOD_f is not contained in the mod file, but in the o file there is func.for__func_MOD_f.
Any idea?
thanks

You have two issues, the delcaration of f and properly linking the module.
First, compiling the module yields the error:
% gfortran -c func.f
func.f:5:8:
f='Hello Func'
1
Error: Can't convert CHARACTER(1) to REAL(4) at (1)
This error is due to implicit typing of f and an incompatible assignment. Fixing this is simple, declare f explicitly as a character instead of an implicit type. Add:
character(len=30) :: f
to the function and now your module compiles. Here is the modified module:
MODULE func
PUBLIC f
CONTAINS
FUNCTION f ()
character(len=30) :: f
f='Hello Func'
END FUNCTION
END MODULE
Your second problem is linking. Your command:
gfortran hello.for
fails because you did not specify the module object. If you already compiled the module you would specify:
gfortran hello.for func.o
if you were compiling them both at the same time you would do:
gfortran -o hworld func.for hello.for
if you are compiling everything individually:
gfortran -c func.for
gfortran -c hello.for
gfortran -o hworld hello.o func.o
Any of these will compile and run:
% ./hworld
Hello World!
Hello Func
If you are modernizing your code, it would also be worth adding implicit none to avoid any implicit typing and declaring explicit variables for everything. e.g.:
module func
implicit none
contains
function f
implicit none
character(len=30) :: f
f='Hello Func'
end function f
end module func
and
program hello
use func
implicit none
print *, "Hello World!"
print *, f ()
end program hello

Related

gfortran, DLL and nothing making sense (or working) at all [duplicate]

This question already has answers here:
Fortran functions returning unexpected types and values
(3 answers)
Closed 2 years ago.
I have the following short piece of code in Fortran, which I named myDLL.f90:
Real(Kind=8) Function mySinCos(x,y)
Real(Kind=8), Intent(In) :: x, y
mySinCos = Sin(x)*Cos(y)
End Function mySinCos
Real(Kind=8) Function myPiSinCos(x,y)
Real(Kind=8), Intent(In) :: x, y
Real(Kind=8), Parameter :: Pi = 4.0d0*Datan(1.0d0)
myPiSinCos = Sin(Pi*x)*Cos(Pi*y)
End Function myPiSinCos
And the following main program TestDLL.f90:
Program TestDLL
Real(Kind=8) :: x, y
Real(Kind=8) :: a, b
x = 2.0d-01
y = 9.0d-01
a = mySinCos(x,y) !Should be 0.12349483641187213
b = myPiSinCos(x,y) !Should be -0.5590169943749475
Write(*,*) a
Write(*,*) b
End Program TestDLL
I compiled and linked the above sources with:
gfortran -shared -fPIC -o myDLL.dll myDLL.f90
gfortran -o a.exe TestDLL.f90 -L. myDLL.dll
No compilation/linkedition errors and a.exe runs without error messages. What it produces is:
6.0000000000000000
6.0000000000000000
Which obviously aren't the expected results as sin(...)*cos(...) must never be > 0.5 (or < -0.5), let alone 6.0000[...].
In a nutshell: compiled well, linked well, executed well and produced garbage.
Changing either x or y doesn't change the results. They're always 6.0000[...].
What went wrong? The example above doesn't differ a lot from other simple examples I've found in the internet.
I'm using GNU Fortran (MinGW.org GCC Build-20200227-1) 9.2.0, Windows 10 64-bit.
It works fine if I turn the two functions into a module:
Module myDLL
Implicit None
Contains
... The two original functions are inserted here ...
End Module myDLL
and import/use the module in the main program:
Program TestDLL
Use myDLL
Implicit None
... Other commands are inserted here ...
End Program TestDLL
Then, and only then, the correct results are spit.

Why syntax error in this very simple print command

I am trying to run following very simple code:
open Str
print (Str.first_chars "testing" 0)
However, it is giving following error:
$ ocaml testing2.ml
File "testing2.ml", line 2, characters 0-5:
Error: Syntax error
There are no further details in the error message.
Same error with print_endline also; or even if no print command is there. Hence, the error is in part: Str.first_chars "testing" 0
Documentation about above function from here is as follows:
val first_chars : string -> int -> string
first_chars s n returns the first n characters of s. This is the same
function as Str.string_before.
Adding ; or ;; at end of second statement does not make any difference.
What is the correct syntax for above code.
Edit:
With following code as suggested by #EvgeniiLepikhin:
open Str
let () =
print_endline (Str.first_chars "testing" 0)
Error is:
File "testing2.ml", line 1:
Error: Reference to undefined global `Str'
And with this code:
open Str;;
print_endline (Str.first_chars "testing" 0)
Error is:
File "testing2.ml", line 1:
Error: Reference to undefined global `Str'
With just print command (instead of print_endline) in above code, the error is:
File "testing2.ml", line 2, characters 0-5:
Error: Unbound value print
Note, my Ocaml version is:
$ ocaml -version
The OCaml toplevel, version 4.02.3
I think Str should be built-in, since opam is not finding it:
$ opam install Str
[ERROR] No package named Str found.
I also tried following code as suggested in comments by #glennsl:
#use "topfind"
#require "str"
print (Str.first_chars "testing" 0)
But this also give same simple syntax error.
An OCaml program is a list of definitions, which are evaluated in order. You can define values, modules, classes, exceptions, as well as types, module types, class types. But let's focus on values so far.
In OCaml, there are no statements, commands, or instructions. It is a functional programming language, where everything is an expression, and when an expression is evaluated it produces a value. The value could be bound to a variable so that it could be referenced later.
The print_endline function takes a value of type string, outputs it to the standard output channel and returns a value of type unit. Type unit has only one value called unit, which could be constructed using the () expression. For example, print_endline "hello, world" is an expression that produces this value. We can't just throw an expression in a file and hope that it will be compiled, as an expression is not a definition. The definition syntax is simple,
let <pattern> = <expr>
where is either a variable or a data constructor, which will match with the structure of the value that is produced by <expr> and possibly bind variable, that are occurring in the pattern, e.g., the following are definitions
let x = 7 * 8
let 4 = 2 * 2
let [x; y; z] = [1; 2; 3]
let (hello, world) = "hello", "world"
let () = print_endline "hello, world"
You may notice, that the result of the print_endline "hello, world" expression is not bound to any variable, but instead is matched with the unit value (), which could be seen (and indeed looks like) an empty tuple. You can write also
let x = print_endline "hello, world"
or even
let _ = print_endline "hello, world"
But it is always better to be explicit on the left-hand side of a definition in what you're expecting.
So, now the well-formed program of ours should look like this
open Str
let () =
print_endline (Str.first_chars "testing" 0)
We will use ocamlbuild to compile and run our program. The str module is not a part of the standard library so we have to tell ocamlbuild that we're going to use it. We need to create a new folder and put our program into a file named example.ml, then we can compile it using the following command
ocamlbuild -pkg str example.native --
The ocamlbuild tool will infer from the suffix native what is your goal (in this case it is to build a native code application). The -- means run the built application as soon as it is compiled. The above program will print nothing, of course, here is an example of a program that will print some greeting message, before printing the first zero characters of the testing string,
open Str
let () =
print_endline "The first 0 chars of 'testing' are:";
print_endline (Str.first_chars "testing" 0)
and here is how it works
$ ocamlbuild -package str example.native --
Finished, 4 targets (4 cached) in 00:00:00.
The first 0 chars of 'testing' are:
Also, instead of compiling your program and running the resulting application, you can interpret your the example.ml file directly, using the ocaml toplevel tool, which provides an interactive interpreter. You still need to load the str library into the toplevel, as it is not a part of the standard library which is pre-linked in it, here is the correct invocation
ocaml str.cma example.ml
You should add ;; after "open Str":
open Str;;
print (Str.first_chars "testing" 0)
Another option is to declare code block:
open Str
let () =
print (Str.first_chars "testing" 0)

Confusion with Fortran submodules and gcc compliation flag -Wuse-without-only

What is the remedy for this gcc Fortran compilation warning?
USE statement at (1) has no ONLY qualifier
The warning occurs when using submodules in gcc 6.0, 6.1, 6.2, and, 7.0.
The full compilation sequence and warning:
$ gfortran -c -Wuse-without-only -o mod_module.o mod_module.f08
$ gfortran -c -Wuse-without-only -o mod_module_sub.o mod_module_sub.f08
mod_module_sub.f08:1:19:
submodule ( mModule ) mSubModule
1
Warning: USE statement at (1) has no ONLY qualifier [-Wuse-without-only]
$ gfortran -c -Wuse-without-only -o demonstration.o demonstration.f08
$ gfortran -o demonstration demonstration.o mod_module.o mod_module_sub.o
$ ./demonstration
this + that = 3.00000000
expected value is 3
Main program (demonstration.f08):
program demonstration
use mModule, only : myType
implicit none
type ( myType ) :: example
example % this = 1.0
example % that = 2.0
call example % adder ( )
write ( *, * ) 'this + that = ', example % other
write ( *, * ) 'expected value is 3'
stop
end program demonstration
Module (mod_module.f08):
module mModule
implicit none
type :: myType
real :: this, that, other
contains
private
procedure, public :: adder => adder_sub
end type myType
private :: adder_sub
interface
module subroutine adder_sub ( me )
class ( myType ), target :: me
end subroutine adder_sub
end interface
end module mModule
Submodule (mod_module_sub.f08):
submodule ( mModule ) mSubModule ! <=== problematic statement
implicit none
contains
module subroutine adder_sub ( me )
class ( myType ), target :: me
me % other = me % this + me % that
end subroutine adder_sub
end submodule mSubModule
That is, what is the proper way to specify submodules? The flag -Wuse-without-only is essential in compilation of longer codes.
Depending on your perspective, it is just a compiler bug. File a bug report and wait for it to get fixed (or fix it yourself).
(An alternative perspective is that because that code gives submodules access to all the entities of their host, whether required or not, the warning is appropriate. But limiting host association requires F2015 support.)
-Wuse-without-only is just a warning to help enforce a particular programming style (one that I don't think is particularly useful). It cannot be "essential" to compile any code, short or long. If the warning bothers you in the meantime, remove that option.

Fortran, Finalization at (1) is not yet implemented

I am trying to implement a simple finalizer, but I can't get even this example to compile:
MODULE m
TYPE :: t1
REAL a,b
END TYPE
TYPE, EXTENDS(t1) :: t2
REAL,POINTER :: c(:),d(:)
CONTAINS
FINAL :: t2f
END TYPE
TYPE, EXTENDS(t2) :: t3
REAL,POINTER :: e
CONTAINS
FINAL :: t3f
END TYPE
CONTAINS
SUBROUTINE t2f(x) ! Finalizer for TYPE(t2)'s extra components
TYPE(t2) :: x
print *, 'entering t2f'
IF (ASSOCIATED(x%c)) then
print *, ' c allocated, cleaning up'
DEALLOCATE(x%c)
end if
IF (ASSOCIATED(x%d)) then
print *, ' d allocated, cleaning up'
DEALLOCATE(x%d)
end if
END SUBROUTINE
SUBROUTINE t3f(y) ! Finalizer for TYPE(t3)'s extra components
TYPE(t3) :: y
print *, 'entering t3f'
IF (ASSOCIATED(y%e)) then
print *, ' e allocated, cleanup up'
DEALLOCATE(y%e)
end if
END SUBROUTINE
END MODULE
using GNU Fortran (GCC) 4.8.2 20131212 (Red Hat 4.8.2-7) gives me this error output:
$ gfortran -c
m_example.f03 m_example.f03:5.26:
TYPE, EXTENDS(t1) :: t2
1 Error: Finalization at (1) is not yet implemented m_example.f03:10.26:
TYPE, EXTENDS(t2) :: t3
1 Error: Finalization at (1) is not yet implemented
Is this a bug, does it mean that finalizers are not yet implemented in gfortran, or am I doing something wrong?
Since gcc 4.9, finalizers are recognized. Furthermore, if you do not implement them yourself, the compiler appears to generate finalization code itself.
Which unfortunately leads to bug 59765. Still available in gcc gfortran 4.10, as I was unfortunate to discover.

Building a FORTRAN DLL

I want to create a dll from following fortran77 code by using g77 compiler in Windows.
sample FORTRAN code
test.f
SUBROUTINE fsub (x)
INTEGER*4 x
x = x + 1
END
INTEGER*2 FUNCTION ffunc (y)
INTEGER*2 y
ffunc = y + 1
END
SUBROUTINE fstring (fstr)
CHARACTER*20 fstr
fstr = 'Jack Be Nimble'
END
I have used the following command
g77 -fno-f2c -shared -s -o test.dll test.f
but it gives an error saying
g77: unrecognized option `-shared'
..\lib\gcc-lib\i386-mingw32\2.95\..\..\..\libg2c.a(main.o)(.text+0x38): undefined
reference to 'MAIN__'
Alternatively I downloaded Mingw and tried to do the same using gfortran.exe
gfortran.exe -fno-f2c -shared -s -o test.dll test.f
Successfully created the test.dll.
My requirement is to create the dll using g77 but i am getting this "unrecognized option `-shared'"
Please help.