C Wrapper calling Fortran functions

I am trying to write a C wrapper to call a set of functions in a Fortran module. I start with something basic, but I don't have something important.

I've tried adding / adding different numbers of underscore characters. I've also tried linking gcc instead of gfortran. What I show below gives the simplest error (s).

I am working on a Mac running Yosemite 10.10.3, GNU Fortran 5.1.0, and the C compiler that comes with Xcode.

main.c

#include "stdio.h"

int main(void) 
{
    int a;
    float b;
    char c[30];
    extern int _change_integer(int *a);

    printf("Please input an integer: ");
    scanf("%d", &a);

    printf("You new integer is: %d\n", _change_integer(&a));

    return 0;
}

      

intrealstring.f90

module intrealstring
use iso_c_binding
implicit none

contains

integer function change_integer(n)
    implicit none

    integer, intent(in) :: n
    integer, parameter :: power = 2

    change_integer = n ** power
end function change_integer

end module intrealstring

      

This is how I compile along with the error:

$ gcc -c main.c
$ gfortran -c intrealstring.f90
$ gfortran main.o intrealstring.o -o cwrapper
Undefined symbols for architecture x86_64:
  "__change_integer", referenced from:
      _main in main.o
ld: symbol(s) not found for architecture x86_64
collect2: error: ld returned 1 exit status
$ 

      

+3


source to share


1 answer


You need to bind fortran to c:

module intrealstring
use iso_c_binding
implicit none

contains

integer (C_INT) function change_integer(n) bind(c)
    implicit none

    integer (C_INT), intent(in) :: n
    integer (C_INT), parameter :: power = 2

    change_integer = n ** power
end function change_integer

end module intrealstring

      

Your c file should be modified like this:



#include "stdio.h"

int change_integer(int *n);

int main(void) 
{
    int a;
    float b;
    char c[30];

    printf("Please input an integer: ");
    scanf("%d", &a);

    printf("You new integer is: %d\n", change_integer(&a));

    return 0;
}

      

You can do:

$ gcc -c main.c
$ gfortran -c intrealstring.f90
$ gfortran main.o intrealstring.o -o cwrapper

      

+3


source







All Articles