Calling Routines in Fortran Modules From C
I have a module in fortran and I want to call that module from C. I use gfortran (as Fortran compiler) and gcc (as C compiler). I want to calling routines in fortran modules from C. We can solve this problem by compile our code to object file and use gcc to compile object as binary (main program coded in C). This is my fortran code (save this code as tesmodule.f).
module tesmodule !global variable implicit none integer a, b contains !subroutine subroutine tes1(nth, ni) integer :: nth, ni a = nth*ni end subroutine tes1 end module tesmodule
Compile this code with command :
gfortran -O0 -g -frecord-marker=8 -c tesmodule.f
Use nm command to check module or variable from tesmodule.o object file with command :
[toto@localhost tescfortran]$ nm tesmodule.o 00000000 B __tesmodule__a 00000004 B __tesmodule__b 00000000 T __tesmodule__tes1
From this output, fortran translate module tes1 to function __tesmodule__tes1. So if we want to call this module in C, we must use __tesmodule__tes1. Create C code, save as main.c. Copy this code to this file :
#include <stdlib.h> #include <stdio.h> int main(int argc, char **argv) { int nth, nto; nth = 15; nto = 10; __tesmodule__tes1(&nth, &nto); //call fortran module printf("nth=%i, a=%i\n",nth, __tesmodule__a); //call fortran variable return(1); }
Create object file from main.c with command :
gcc -O0 -g -c main.c
Compile object file with command :
gcc -O0 -g -frecord-marker=8 -o tescfortran main.o tesmodule.o -lgfortran
Output from this program is :
[toto@localhost tescfortran]$ ./tescfortran nth=15, a=150
This is an example how to calling routines in fortran modules from C. So, from this example, we can merge code from C and Fortran together.
Fantastic website. Plenty of useful information here. I am sending it to some buddies ans additionally sharing in delicious. And obviously, thanks in your effort! Koha Ditore