Skip to content

Instantly share code, notes, and snippets.

@paulbuis
Created August 24, 2015 13:09
Show Gist options
  • Save paulbuis/729d5869a11de13fcd05 to your computer and use it in GitHub Desktop.
Save paulbuis/729d5869a11de13fcd05 to your computer and use it in GitHub Desktop.
Calling C from Fortran

main.f contains the function invocation and hello.c contains the function being invoked.

Using GNU's "gfortran" compiler and GNU's C compiler, one needs to add an underscore to the C function name to match the symbol generated by the Fortran compiler. Fortran is "call by reference" so the formal argument is a pointer to the actual argument. The calling function allocates an anonymous variable to store the literal integer 3 in. If the actual argument had been a variable, the called function would be allowed to alter it. Note also, that the caller has no way of knowing the number or types of aguments to hello. Since it is invoked with the call keyword, it is assumed to be a Fortran "procedure" which is essentially a function with no return value.

#include <stdio.h>
#include "hello.h"
void hello(int repeatCount) {
int i;
for (i = 0; i < repeatCount; i++) {
printf("hello from C\n");
}
}
void hello_(int *repeatCount) {
int i;
for (i = 0; i < *repeatCount; i++) {
printf("hello from C\n");
}
}
call hello(3)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment