C++ : calling Fortran code

De Wiki de Calcul Québec
Aller à : Navigation, rechercher
Cette page est une traduction de la page C++ : appels Fortran et la traduction est complétée à 100 % et à jour.

Autres langues :anglais 100% • ‎français 100%

Calling Fortran from C/C++

It is often practical to call subroutines or functions written in Fortran from a C/C++ program. The below example shows how to do this. One should be careful with matrices, however. In C++, matrices are ordered by row, but in Fortran they are ordered by column.

Here is a C++ program that calls a function and a subroutine written in Fortran computing the sum of the elements of a vector previously declared in the C++ program:

File : call_fortran.cpp
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
 
using namespace std;
 
extern "C" double function_sum_(long *fsize, double* fvec);
extern "C" void subroutine_sum_(long *fsize, double* fvec, double *fsum);
 
int main(int argc, char ** argv)
{
    long i,size;
    double sum;
    double *vec;
 
    size = 5000;
 
    vec = new double[size];
 
    for(i=0;i<size;i++)
    {
        vec[i]=1.1234532;
    }
 
    // Call a Fortran function
    sum = function_sum_(&size,vec);
 
    cout << "Calling a Fortran function" << endl;
    cout << "============================" << endl;
    cout << "size = " << size << endl;
    cout << "sum = " << sum << endl << endl;
 
 
    // Call a Fortran subroutine
    subroutine_sum_(&size,vec,&sum);
 
    cout << "Calling a Fortran subroutine" << endl;
    cout << "===============================" << endl;
    cout << "size = " << size << endl;
    cout << "sum = " << sum << endl << endl;
 
    delete[] vec;
 
}


And the Fortran code containing the function and the subroutine that are called:

File : sum.f90
real*8 function fonction_sum(fsize,fvec)
 
    integer fsize,i
    real*8 fvec(fsize)
    real*8 sum
 
    function_sum=0.0
 
    do i=1,fsize
      fonction_sum=fonction_sum+fvec(i)  
    end do
 
    return
 
end 
 
subroutine subroutine_sum(fsize,fvec,sum)
 
    integer fsize,i
    real*8 fvec(fsize)
    real*8 sum
 
    sum=0.0
 
    do i=1,fsize
      sum=sum+fvec(i)
    end do
 
end


You can compile and run this code with the commands (using GCC compilers):

 
 [name@server $] gfortran sum.f90 -c -o sum.o
 [name@server $] g++ sum.o call_fortran.cpp -o a.out
 [name@server $] ./a.out
 


Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Ressources de Calcul Québec
Outils
Partager