How should I compile C and Fortran code together on windows?

Hi,

If I have a .c main file and a .f90 subroutine, e.g.

main.c

void testfunc();

int main(void)
{
    testfunc();
}

testfunc.f90

subroutine testfunc() bind (C, name = "testfunc")
    write(*,*) "Hello World!"
end subroutine

I normally compile these with the GNU compiler like so

gfortran -o my_prog main.c testfunc.f90

However, when I try this with pgfortran, I get the following errors

main.obj : error LNK2005: main already defined in f90main.obj
f90main.obj : error LNK2019: unresolved external symbol MAIN_ referenced in function main

Is there a standard procedure for compiling and linking C and Fortran code together on Windows?

Thanks

Hi jbravo,

If you want to call a fortran function from C, you’ll need to first create the object file (with -c) from the Fortran source. Then, invoke pgcc and pass in the created object file to link to. You’ll also want to add -pgf90libs to link to the runtime libraries.

$ cat Test.c
void testfunc();
int main ()
{
  testfunc();
  return 0;
}

$ cat TestMod.f90
module example
contains
  subroutine testfunc() bind(c, name="testfunc")
    write(*,*) "Hello World!"
  end subroutine testfunc
end module example

$ pgfortran -c TestMod.f90

$ pgcc -o Test Test.c TestMod.obj -pgf90libs
Test.c:

$ ./Test.exe
 Hello World!

Thanks for the reply,

Your solution worked!

Also, I notice that this solution also works:

 pgfortran -o my_prog main.c testfunc.f90 -Mnomain