Calling C from Fortran
A C library is the largest body of code a Fortran program is likely to call, and the mechanism is one block: an interface with bind(c) on each function, the kinds of iso_c_binding in the declarations, and a value attribute where C passes by value. This lesson writes a two-function C file, declares it in Fortran, builds the two objects and runs them together.
The C file
Two functions, both of them double in and double out, so that the interface is as simple as an interface gets: no pointers, no strings, no structs. The second one calls sqrt from the C maths library, which is the ordinary C way and needs nothing from the Fortran side.
The file c_helpers.c:
#include <math.h>
double scale_by(double x, double factor)
{
return x * factor;
}
double hyp(double a, double b)
{
return sqrt(a * a + b * b);
}
The interface block
Each function is declared inside an interface block with its result, its arguments and the bind(c) attribute. import :: c_double brings the kind into the interface body, which does not inherit the names around it, exactly as in lesson 077.
The file callc.f90:
program callc
use, intrinsic :: iso_c_binding
implicit none
interface
function scale_by(x, factor) bind(c, name="scale_by") result(y)
import :: c_double
real(c_double), value :: x, factor
real(c_double) :: y
end function scale_by
function hyp(a, b) bind(c, name="hyp") result(y)
import :: c_double
real(c_double), value :: a, b
real(c_double) :: y
end function hyp
end interface
print '(a,f10.3)', 'scale_by(3.0, 2.5) = ', scale_by(3.0_c_double, 2.5_c_double)
print '(a,f10.3)', 'hyp(3.0, 4.0) = ', hyp(3.0_c_double, 4.0_c_double)
end program callc
The VALUE attribute
Fortran passes every argument by reference and C passes numbers by value, so the declaration has to say which one the C function expects. value makes the dummy an ordinary value: the compiler passes a copy and the C function reads it from a register or the stack, which is what double scale_by(double x, double factor) does.
Leave value out and the C function receives a pointer where it expects a number. Nothing refuses to compile, because the two sides never see each other's declarations: the program links, runs, and prints a number computed from the bit pattern of an address. That is the first interop bug to look for when a call returns something absurd.
The NAME in BIND(C)
bind(c, name="scale_by") tells the compiler that the symbol in the object file is scale_by, with no underscore and no case folding. Without the name= part the symbol would be the Fortran name lowercased and suffixed, which is what the linker error of the last section shows for a C name that has no Fortran declaration at all.
bind(c) on its own is enough when the two names are the same, and it is what a page usually writes. The explicit name= is for a C function with a name that Fortran cannot use, a leading underscore, or a name that collides with a Fortran intrinsic: scale is an intrinsic, and calling a C function of that name triggers -Wintrinsic-shadow in this build, which is why the example calls its function scale_by.
Building the two files
gcc compiles the C file to an object, gfortran compiles the Fortran file and links both. The C compiler needs no flag to match the Fortran one: the two objects follow the platform's calling convention, and bind(c) is what makes the Fortran side use it.
gcc -c -O2 c_helpers.c
gfortran -Wall -Wextra -std=f2018 callc.f90 c_helpers.o -o callc
./callc
scale_by(3.0, 2.5) = 7.500
hyp(3.0, 4.0) = 5.000
Two calls, both by value, both returning a double: three times two and a half is seven and a half, and the hypotenuse of three and four is five. That is the whole of the mechanism for a numeric function, and everything else in this part is a variation on the argument list.
Forgetting the object
A Fortran program with a C interface block compiles on its own and fails to link, and the message names the C symbol rather than the Fortran name:
gfortran -Wall -Wextra -std=f2018 callc.f90 -o callc_nolink
/usr/lib/gcc/x86_64-alpine-linux-musl/15.2.0/../../../../x86_64-alpine-linux-musl/bin/ld: /tmp/ccJiDEPI.o: in
function `MAIN__':
callc.f90:(.text+0xa5): undefined reference to `scale_by'
/usr/lib/gcc/x86_64-alpine-linux-musl/15.2.0/../../../../x86_64-alpine-linux-musl/bin/ld:
callc.f90:(.text+0x16d): undefined reference to `hyp'
collect2: error: ld returned 1 exit status
The two names in the error are exactly the strings of the name= attributes, which is a useful check: if the message names scale_by_ with an underscore, the bind(c) is missing, and if it names something else entirely the C file is compiled with a different name.
Rules for a C function
Declare the whole interface in one module, not once per caller, so that a change to the C signature breaks the build in one place. Use value exactly where C passes by value, and a pointer or an array where C takes an address. Match the kinds with iso_c_binding and never with a default kind. And test the return value against a value computed in Fortran, because a silently wrong convention gives a number that looks like a result.
The next lesson is the same mechanism in the other direction: a Fortran subroutine with bind(c) called from a C main, which is how a numerical library written in Fortran ends up inside a program written in anything else.
Exercises
- Add a C function that takes an int and returns it squared, and declare it with integer(c_int), value. Which kind would be wrong?
- Remove value from scale_by and run the program. What is printed, and why does it not crash?
- Change the C function name to scale and build without the name= attribute. What does gfortran warn about?
- Pass an array to a C function that takes a pointer, with real(c_double) :: x(*). Which attribute does the Fortran dummy need?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does
bind(c, name="hyp")do?Answer
Tells the compiler the symbol in the object file is hyp, with the C convention
It fixes the external name and the calling convention.
-
Why does a Fortran dummy need
valuefor a C parameter passed by value?Answer
Fortran passes by reference unless the dummy says otherwise
Without it C receives a pointer where it expects a number.
-
How is a C parameter of type
double *declared in the Fortran interface?Answer
As a dummy without VALUE, which passes by reference
C pointers are Fortran's default passing mode for a dummy.
-
What does the linker error name when the C object is missing?
Answer
The string of the name= attribute
That is how a missing bind(c) is diagnosed.
-
Why does leaving out
valuenot fail to compile?Answer
The two sides never see each other's declarations; the bug is at run time
The call reads an address as a number and prints nonsense.
-
How are the two files built?
Answer
gcc -c for the C file, then gfortran for the Fortran file and the link
Each compiler produces an object, one link line joins them.
-
Where should the interface block live?
Answer
In one module, so a change breaks the build in one place
One declaration of an interface is the point of a module.
-
What warning does a C function named
scalecause?Answer
It shadows the Fortran intrinsic SCALE
That is why the example uses scale_by.
-
What does the C function do with the array a Fortran program passes?
Answer
It receives a pointer and must be told the length separately
A C array parameter is a pointer.
-
How is a wrong calling convention found?
Answer
By comparing the result with one computed in Fortran
A wrong convention gives a plausible wrong number.
The programs on this page were built with GNU Fortran (Alpine 15.2.0) 15.2.0 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev