Unable to call FORTRAN subroutine from C

FORTRAN Code

MODULE my_fortran_func

   USE iso_c_binding
   IMPLICIT NONE

CONTAINS


   INTEGER(c_int) FUNCTION fortran_add(A,B) BIND(c, name="fortranAdd")
      INTEGER (c_int), INTENT(IN) :: A, B
      
      fortran_add = A + B
   END FUNCTION fortran_add


   SUBROUTINE hello_world_from_fortran() BIND(c)
      PRINT *, 'HELLO WORLD FROM FORTRAN!'
   END SUBROUTINE


END MODULE my_fortran_func

C Code

#include <stdio.h>

int fortranAdd(int *a, int *b);
void hello_world_from_fortran();

int fortran_add_wrapper(int a, int b)
{
	return fortranAdd(&a, &b);
}


int main()
{
	printf("Hello Word from C\n");
	hello_world_from_fortran();

	int sum = fortran_add_wrapper(12, 1);
	printf("The sum is %d\n", sum);

	return 0;
}

The following commands using nvfortran will result in the error

gcc -c C/mycwrapper.c -o mycwrapper.o
nvfortran -c FORTRAN/myfortranfunc.f90 -o myfortranfunc.o
nvfortran mycwrapper.o myfortranfunc.o -o MAIN.O
/usr/bin/ld: mycwrapper.o: in function `main':
mycwrapper.c:(.text+0x27): multiple definition of `main'; /opt/nvidia/hpc_sdk/Linux_x86_64/22.11/compilers/lib/f90main.o:nvcqRGdbWjhLbGMi.ll:(.text+0x0): first defined here
/usr/bin/ld: /opt/nvidia/hpc_sdk/Linux_x86_64/22.11/compilers/lib/f90main.o: in function `main':
nvcqRGdbWjhLbGMi.ll:(.text+0x2f): undefined reference to `MAIN_'

But if we compile with gfortran it will work.

Hello Word from C
 HELLO WORLD FROM FORTRAN!
The sum is 13

So how do I use nvfortran to get the result.

Thanks in advance
Azad

Hi Azad,

Since Fortran predates C and even most OSs, it doesn’t have a concept of “main” as part of the language. Hence when linking with Fortran, the compiler needs to implicitly add it. But since you’ve defined “main” in your C program, you get multiple definitions.

The solution is to tell nvfortran to not add a “main”, via the “-Mnomain” flag which you’ll want to add to your link line.

% gcc -c mycwrapper.c -o mycwrapper.o
% nvfortran -c myfortranfunc.f90 -o myfortranfunc.o
% nvfortran mycwrapper.o myfortranfunc.o -o MAIN.O -Mnomain
% ./MAIN.O
Hello Word from C
 HELLO WORLD FROM FORTRAN!
The sum is 13

-Mat

Thank you so much Mat. It worked!