Pergunta

I'm trying to use a fortran module subroutine in c and cannot get through, here is a simplified version of my problem:

I have one fortran module that contains a subroutine, and the second subroutine uses the module.

!md.f90
module myadd
implicit none
contains

subroutine add1(a) bind(c)
implicit none
integer a
a=a+1

end subroutine add1
end module myadd


!sb.f90
subroutine sq(a) bind(c)
use myadd
implicit none
integer a
call add1(a)
a=a*a
end subroutine sq

Now I want to call the sb function in c:

//main.cpp
extern "C"{ void sb(int * a); }
int main(){
  int a=2;
  sb(&a);
}

how should I link them together?

I tried something like

ifort -c md.f90 sb.f90
icc sb.o main.cpp

but it gives error

sb.o: In function sq': sb.f90:(.text+0x6): undefined reference to add1' /tmp/icc40D9n7.o: In function main': main.cpp:(.text+0x2e): undefined reference tosb'

Does anyone know how to solve the problem?

Foi útil?

Solução

int main(void){
  int a=2;
  sb(&a);
  return 0;
}

and

module myadd
use iso_c_binding
implicit none
contains

subroutine add1(a) bind(c)
implicit none
integer (c_int),intent (inout) :: a
a=a+1

end subroutine add1
end module myadd


!sb.f90
subroutine sq(a) bind(c, name="sb")
use iso_c_binding
use myadd
implicit none
integer (c_int), intent(inout) :: a
call add1(a)
a=a*a
end subroutine sq

with

gcc -c main.c
gfortran-debug fort_subs.f90 main.o

It is easier to link with the Fortran compiler because it brings in the Fortran libraries.

Outras dicas

The reason for your link error is twofold:

  • you omitted the object file for the source file that holds the module from the final command line (md.o).

  • you've called sq in the fortran sb in the C++ code.

Fix those and you'll be right to go.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top