Being called from C
A numerical library written in Fortran is usually not the program a user runs: it is a set of subroutines that something else calls. This lesson turns the previous one around. A Fortran subroutine computes a mean and a standard deviation of an array that a C main owns, and the two compilers produce the objects that the linker joins.
The Fortran subroutine
bind(c, name="stats") on the subroutine statement exports the symbol stats with the C convention. The array argument is real(c_double), intent(in) :: x(n) with the length as a dummy, which is how a C pointer plus a count becomes an array inside Fortran: no descriptor, no hidden length, just an address and a bound that the caller promised.
The file stats.f90:
subroutine stats(x, n, mean, sd) bind(c, name="stats")
use, intrinsic :: iso_c_binding
implicit none
integer(c_int), value :: n
real(c_double), intent(in) :: x(n)
real(c_double), intent(out) :: mean, sd
integer :: i
mean = 0.0_c_double
do i = 1, n
mean = mean + x(i)
end do
mean = mean / real(n, c_double)
sd = 0.0_c_double
do i = 1, n
sd = sd + (x(i) - mean) ** 2
end do
sd = sqrt(sd / real(n - 1, c_double))
end subroutine stats
The C main
The C side declares what the Fortran side promises: a pointer to const double, an int, and two pointers to double for the results. The value on n in Fortran matches the int n in C, and the two intent(out) dummies match the two pointers, because a Fortran dummy without value is passed by reference.
The file main.c:
#include <stdio.h>
void stats(const double *x, int n, double *mean, double *sd);
int main(void)
{
double x[5] = {2.0, 4.0, 4.0, 4.0, 9.0};
double mean = 0.0, sd = 0.0;
stats(x, 5, &mean, &sd);
printf("mean = %.4f sd = %.4f\n", mean, sd);
return 0;
}
The array that crosses
A C array is a pointer and nothing else, so the Fortran side cannot ask how long it is. The length travels as a second argument, and the declaration x(n) uses that argument as the bound. That declaration is an explicit-shape dummy, which the compiler turns into a plain address for a bind(c) procedure: no descriptor is passed, and the C pointer the caller has is exactly what the Fortran code reads.
Two consequences follow. The bound is a promise: if C passes five and the array has three, Fortran reads two elements past the end, and no compiler can catch it. And the array is one-based inside Fortran even though C counted from zero, because the dummy declaration says so; a program that wants the C index subtracts one on the way in.
Building it the other way
gcc compiles the main, gfortran compiles the subroutine, and gfortran links the pair because it knows where the Fortran runtime is:
gcc -c -O2 main.c
gfortran -Wall -Wextra -std=f2018 -c stats.f90
gfortran main.o stats.o -o prog
./prog
mean = 4.6000 sd = 2.6077
The five values are 2, 4, 4, 4 and 9, so the mean is 23/5 = 4.6, and the sample standard deviation with four in the divisor is 2.6077. The same numbers computed in lesson 096 with a Fortran driver came out the same way, which is the test: an exported subroutine is only useful if its answer does not depend on who called it.
Linking with gcc instead works too and needs -lgfortran as soon as the Fortran code uses anything from the runtime, a print, an allocation or a module. gfortran as the linker is the shorter route and the one to put in a makefile.
Without BIND(C)
A Fortran subroutine without bind(c) exports a different symbol, and the C linker says so:
gfortran -Wall -Wextra -std=f2018 -c nobind.f90
gcc main.o nobind.o -o prog3
/usr/lib/gcc/x86_64-alpine-linux-musl/15.2.0/../../../../x86_64-alpine-linux-musl/bin/ld: main.o: in function
`main':
main.c:(.text.startup+0x62): undefined reference to `stats'
collect2: error: ld returned 1 exit status
The Fortran object contains stats_ with an underscore, and possibly a second symbol for the module if the procedure were in one. The message names the C side of the call, which is the useful half: the program that has to change is the Fortran declaration, and one attribute fixes it.
A caller can also meet the same error in the other direction, a C function that a Fortran program declares without bind(c): the linker then looks for name_ and the C file has name. The two errors are the same mistake seen from either end.
Rules for the exporting side
Put bind(c, name=...) on every procedure a C program will call, and keep the name short and lowercase. Give every array an explicit length argument, or pass a descriptor if the caller can build one. Use iso_c_binding kinds throughout and value only where C passes a value. And write down the sequence of the arguments in one header file that the C side includes, because the C compiler checks nothing about a Fortran object.
A C header is the other half of the contract, and a project that exports Fortran keeps one: void stats(const double *x, int n, double *mean, double *sd); is the whole of it, and it is the only place a C programmer has to look. The next lesson takes the same subroutine and calls it from Python, with no header at all.
Exercises
- Add a third output argument, the maximum, and change both files. Which declaration changes in C, and which in Fortran?
- Pass a sub-array from C, &x[1] with a length of three. What does Fortran compute, and which elements are used?
- Move the subroutine into a module and keep the bind(c). Does the C main still link, and why?
- Build the C main with gcc main.o stats.o -o prog -lgfortran and run it. What changes, and when would the flag be necessary?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does
bind(c)on a subroutine do?Answer
Exports it with the C calling convention and the C external name
Without it the symbol has the Fortran form.
-
How does an array reach a
bind(c)subroutine?Answer
As an address, with its length passed separately
A C array is a pointer and carries no length.
-
Why does
nneed VALUE in the Fortran declaration?Answer
The C side passes an int by value
Without it the int would be read as a pointer.
-
What does this program print?
program p implicit none real :: x(5) real :: m integer :: i x = [2.0, 4.0, 4.0, 4.0, 9.0] m = 0.0 do i = 1, 5 m = m + x(i) end do print *, m / 5.0 end program pAnswer
4.59999990
The sum is twenty-three and the mean 4.6.
-
What happens if C passes a length larger than the array?
Answer
Fortran reads past the end; no compiler can catch it
The bound is a promise the caller makes.
-
What does gfortran as the linker save you?
Answer
It knows the Fortran runtime library
With gcc you add -lgfortran when the code needs it.
-
What symbol does a Fortran subroutine without BIND(C) export?
Answer
The lowercased name with an underscore
That is why the C link fails with the plain name.
-
Where should the C declaration of an exported Fortran procedure live?
Answer
In a header the C side includes
The C compiler checks nothing about a Fortran object.
-
Why compare the mean with the Fortran driver of lesson 096?
Answer
An exported subroutine must give the same answer whoever calls it
The interface must not change the arithmetic.
-
What does a Fortran dummy without VALUE mean to C?
Answer
A pointer
Fortran passes by reference by default.
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