This page describes how to cross-use C, C++, and Fortran 77 in an Unix environment. The information provided here is known to work on the following architectures:

  • Digital Alpha
  • HP Unix Workstations
  • Ultrix
  • x86, running Linux

The basic rules for calling Fortran functions from C and C++:

  • Most (almost all) Fortran compilers add, during compilation, an
    underscore (_) at the end of the Fortran routine names. Our experience
    is that the f77 compiler in HP Unix environments does not do
    this.

    • We noticed that if a fortran subroutine has an underscore anywhere in
      its name, the GNU g77 compiler adds two (2) underscores at the end of
      the name.
  • In the compiled Fortran code all arguments to functions are passed by
    their address.
  • If a Fortran function takes a character string as an argument, the
    string length must be passed as the last argument (i.e. after the
    “ordinary” argument list).

We provide a few examples of the above rules.

Additional rules for manipulating Fortran common blocks and variables within C and C++:

  • Variables that is to be shared between Fortran and C/C++ must be global.
  • Most (almost all) Fortran compilers add, during compilation, an underscore (_) at the end of the Fortran common block names. (This is probably true for all Fortran variables but we have not tested this since we always did use common blocks to transfer information between Fortran and C/C++ code.)
  • C and C++ vectors (arrays) always start with index 0. In multidimensional arrays the order of the indices are reversed as compared to Fortran 77.

Further examples that can help solve problems you might encounter:

  • Transferring large chunks of information between Fortran and C/C++ is
    fairly straight forward using common blocks
    and structures.
  • When linking you must also include the different run-time libraries
    needed for the different compilers (examples).
  • There are a few complications when you want to access C/C++ functions
    using Fortran 77. You should keep the rules above in mind, and do the
    following:

    • Add a special interface
      function (a wrapper written in C/C++) which is callable from
      Fortran.
    • Never use fortran code as your main program/function, and always link
      your programs using C++ as the native language at linkage. (This
      should make sure that a number of global objects, i.e. cout, cin, …,
      are correctly constructed and initialized before your main function is
      invoked. Corresponding things should happen after main returns.)
    • It is easy to overcome the restriction in the last bullet by creating
      a very small C++ main function which only calls your ordinary fortran
      main program. See the special interface
      function section for an example of this.