How C++ call Fortran 77's common blocks

593 views Asked by At

I am a fresh in programming and I want to call a Fortran 77 common block in my C++ code. Actually I have read some Q&A similar like mine, but I was not very clear....

This common block is defined by another Fortran 77 subroutine.

Sample code is:

common.inc:

!test common block:
real delta(5,5)
common /test/ delta
!save /test/ delta  ! any differences if I comment this line?

tstfunc.f

subroutine tstfunc()
    implicit none
    include 'common.inc'
    integer i,j
    do i = 1, 5
        do j = 1, 5
            delta(i,j)=2
            if(i.ne.j) delta(i,j)=0
            write (*,*) delta(i,j)
        end do
    end do
end

tst01.cpp

#include <iostream>

extern "C"
{
    void tstfunc_();
};

void printmtrx(float (&a)[5][5]){
    for(int i=0;i<5;i++){
        for(int j=0;j<5;j++){
            std::cout<<a[j][i]<<'\t';
            a[j][i]+=2;
        }
        std::cout<<std::endl;
    }
}

int main()
{
//start...
    tstfunc_();
    printmtrx(delta);//here i want to call delta and manipulate it. 
    return 0;
}

If I want to pass delta (from common.inc) to the C++ function printmtrx(), what should I do?

2

There are 2 answers

0
ewcz On BEST ANSWER

Apart from the row/column-major order issue (the 5x5 matrix would appear transposed in the C-code), perhaps you could proceed as follows (see section on Common blocks in this tutorial):

tstfunc1.f

  subroutine tstfunc()
      implicit none
      real delta(5, 5)
      common /test/ delta
      integer i,j
      do i = 1, 5
          do j = 1, 5
              delta(i,j)=2
              if(i.ne.j) delta(i,j)=0
              write (*,*) delta(i,j)
          end do
      end do
  end

tst01.cc

#include <iostream>

extern "C" {
  void tstfunc_();
  extern struct{
    float data[5][5];
  } test_;
}

void printmtrx(float (&a)[5][5]){
    for(int i=0;i<5;i++){
        for(int j=0;j<5;j++){
          std::cout << a[i][j] << '\t';
          a[i][j] += 2;
        }
        std::cout << std::endl;
    }
 }

int main()
{
  //start...
  tstfunc_();

  printmtrx(test_.data);//here i want to call delta and manipulate it. 
  return 0;
}

Then in order to compile:

gfortran -c -o tstfunc1.o tstfunc1.f    
g++ -o tst tst01.cc tstfunc1.o -lgfortran
0
Paul R On

Note that 2D arrays in C are row-major whereas in FORTRAN they are column-major, so you need to switch your array indices in one language or the other.