rose devine
rose devine

Reputation: 21

C calling Fortran subroutine

I am new to the site, and this looks like it may be a place to get some tips and help if any.

I am learning about "C calling Fortran subroutine", I have knowledge with C but not too much with Fortran.

Plus side: I've looked at some examples, and was able to compile a few.

Negative side: I am somewhat lost. I have a main program which can be designed using C or Fortran 90, and print_matrix.f and print_matrix.c.

Within the main.c program,
- populate array of 1-9 of a matrix size 3 by 3
- call the c function
- call the fortran subrountine

I already have the populated side(it may not be accurate), but I am stuck on the subrountine. The output of fortran and C has to be the same which will output through the print_matrix.f90 and print_matrix.c using makefile. I need help with the calling subrountine part, I just don't know where to begin with that :(

I just need help, any will be appreciated.

Upvotes: 2

Views: 3981

Answers (1)

bob.sacamento
bob.sacamento

Reputation: 6651

Honestly, it's a little hard to tell exactly what your problem is. But here's an example that works on my linux machine:

callf.c:

  #include<stdio.h>
  int main(int argc, char **argv) {
  int i=0;
  increment_(&i);
  printf("%d\n",i);
  return;
  }

increment.f90:

subroutine increment(n)
integer n
n=n+1
return
end subroutine

Compiled with:

gcc -c callf.c
gfortran -c increment.f90
gcc callf.o increment.o -lgfortran

Result:

> ./a.out
1

The two hard parts are 1) getting the exact name of the function call and 2) knowing what flags are needed to link the two codes. Re: 1) I knew to use "increment_" because, after compiling my FORTRAN code, I ran the "nm" utility on increment.o and found the name of the object was "increment_". On some systems, you might see "INCREMENT", "_increment", or all sorts of other things. Re: 2) Information should be available for whatever compiler you are using. It varies alot.

Upvotes: 4

Related Questions