cfortranmixing

undefined reference to `cos' when I use iso_c_binding


I have the Fortran90 function

 function eg_fun(r) bind(c)
  use, intrinsic :: iso_c_binding
  implicit none

  real(c_double), intent(in) :: r
  real(c_double)             :: eg_fun

  real(c_double), parameter :: PI = acos(-1.d0)

  eg_fun = PI * r * r + cos(r)
end function

and my C program

#include <stdio.h>
#include <math.h>

extern double eg_fun(double *r);

int main(int argc, char **argv){
    double r;

    printf("Enter the argument\n");
    scanf("%lf", &r);

    printf("The result is %lf\n", eg_fun(&r));

    return 0;
}

I want to use the Fortran function under the C program using the iso_c_binding tool. But when I try to compile thos with gcc -Wall main.c routine.f90 -o app -lgfortran I receive the error message

/tmp/ccn2Zeac.o: In function `eg_fun':
routine.f90:(.text+0x42): undefined reference to `cos'
collect2: error: ld returned 1 exit status

How I can solve this?


Solution

  • When linking with gcc you have to link the math library explicitly using -lm. You can try linking with gfortran instead.

    The iso_c_binding module has no connection to your error. And bind(C) attribute as well.