# COMMON

To reference C structures from Fortran common blocks and vice versa, you must take into account how common blocks and structures differ in their methods of storing member variables in memory. Fortran places common block variables into memory in order as close together as possible, with the following rules:

- A single BYTE, INTEGER(1), LOGICAL(1), or CHARACTER variable in common block list begins immediately following the previous variable or array in memory.

- All other types of single variables begin at the next even address immediately following the previous variable or array in memory.

- All arrays of variables begin on the next even address immediately following the previous variable or array in memory, except for CHARACTER arrays which always follow immediately after the previous variable or array.

- All common blocks begin on a four-byte aligned address.

Because of these rules, you must consider the alignment of C structure elements with Fortran common block elements. Specifically, you should ensure interoperability either by making all variables exactly equivalent types and kinds in both languages (using only 4-byte and 8-byte data types in both languages simplifies this) or by using the C pack pragmas in the C code around the C structure. This makes C data packing compatible with Fortran data packing.

As an example, suppose your Fortran code has a common block named `Really`, as shown:

Fortran Code Example
      USE, INTRINSIC::ISO_C_BINDING
        REAL (C_float)::x,y,z(6)
        REAL (C_double)::ydbl
        COMMON, BIND(C) / Really /x, y, z(6), ydbl

You can access this data structure from your C code with the following external data structures.

C Code Example
     #pragma pack(2)
     extern struct {
      float x, y, z[6];
      double ydbl;
     } Really;
     #pragma pack()

To restore the original packing, you must add `#pragma pack()` at the end of the C structure.

You can also access C structures from Fortran by creating common blocks that correspond to those structures. This is the reverse case from that shown above. However, the implementation is the same; after common blocks and structures have been defined and given a common address (name), and, assuming the alignment in memory has been accounted for, both languages share the same memory locations for the variables.

Once you have accounted for alignment and padding, you can give C access to an entire common block or set of common blocks. Alternatively, you can pass individual members of a Fortran common block in an argument list, just as you can any other data item.

Parent topic: Global Data