HP Fortran Programmer's Guide (B3908-90031; September 2011)

Calling C routines from HP Fortran
Sharing data
Chapter 8 201
Sharing data
Fortran programmers have traditionally relied on the common block to share large amounts of data among
different program units. The convenience offered by the common block is that it can give storage access to
program units that don’t otherwise communicate with each other, even when they reside in separate files.
1
Although C has no common blocks, it does provide external variables, which can also be used to
share data among different parts of a C program. A variable becomes external when defined outside any
function. To become accessible to a function, the external variable must be declared without being defined
within the function that wants to access it. (In C, a variable is defined when storage is allocated for it, and
declared when its name and type are stated without any storage allocation.) To declare a variable in C
without defining it, you use the extern storage class specifier, which tells the linker to look elsewhere for
the definition.
For example, the following statement (assuming that it is made outside any function) declares and defines
the external variable some_data:
int some_data;
The next statement declares some_data without defining it, making it available to the function in which the
declaration is made:
extern int some_data;
Fortran’s common block and C’s extern statement can work together to enable Fortran program units to
share data with an HP C function. The storage is actually allocated (or in C terminology, defined) in the
Fortran source file. The C source file declares but does not define the name of the common block, using the
extern specifier. The linker resolves the reference at linktime.
Consider the following Fortran statements, which declare an array of integers and place the array in a
common block named globals:
INTEGER, DIMENSION(100) :: global_array
COMMON /globals/global_array
The next statement is the extern statement that references (in C terminology, declares) the common
block, making it available to a function in the C object file:
extern int globals[100];
Note that the extern specifier references the name of the common block, globals, not the name of the
array. From C’s point of view, the common block is treated as though it were the array.
1. However, overreliance on common blocks can make programs difficult to maintain. For a
discussion of the advantages of the Fortran module over the common block, refer to Chapter 3,
“Controlling data storage,” on page 99.