Reputation: 43
I'm trying to write a C wrapper to call a set of functions in a Fortran module. I'm starting with something basic but I'm missing something important.
I've tried appending/prepending different numbers of underscores. I've also tried linking with gcc instead of gfortran. What I show below gives the simplest error(s).
I'm 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
Here is how I'm compiling, 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
$
Upvotes: 4
Views: 2125
Reputation: 16213
You have 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 has to modified as follows:
#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;
}
The you can do:
$ gcc -c main.c
$ gfortran -c intrealstring.f90
$ gfortran main.o intrealstring.o -o cwrapper
Upvotes: 4