Issue with booleen when linking Fortran to C++ code

Hi,

I am trying to link some Fortran code to some C++ code which was compiled with gcc. The problem is that when passing the booleen (l1) to the C++ part, true values are associated to 255. This is an issue when evaluating ( ! l1), as it is then 254 which is still true. I have made a small example to illustrate the problem:

Main.f90

PROGRAM test
  USE, INTRINSIC :: iso_c_binding
  REAL*8 :: x(2)
  LOGICAL :: l1,l2
  LOGICAL(KIND=C_BOOL) :: cl1,cl2

  ! external functions
  INTERFACE
     SUBROUTINE cfunc(a,l1,l2) &
          BIND(c, name='cfunc_')
       USE, INTRINSIC :: iso_c_binding
       REAL*8 :: a(:)   
       LOGICAL(KIND=C_BOOL), value :: l1,l2

     END SUBROUTINE cfunc
  END INTERFACE
  
  x(1)=3.0
  x(2)=4.0

  l1=.TRUE.
  l2=.FALSE.

  cl1=l1
  cl2=l2
  call cfunc(x,cl1,cl2)

END PROGRAM test

cfunc.cpp :

#include <iostream>     // std::cout
#include "cfunc.h"

void cfunc_(double* a, bool l1, bool l2)
{
  bool ltest;

  ltest=255;

  std::cout<< "out: " <<  a[0] << " " << a[1]  << " " << l1 << " " << ! l1 << " " << ltest << " " << ! ltest << " "<< std::endl;

  if (! l1) std::cout<< "l1: Error (not True) is (True) !" << std::endl;
  if (! ltest) std::cout<< "ltest: Error (not True) is (True) !" << std::endl;

  
}

cfunc.h :

extern "C" {

  void cfunc_(double* a, bool l1, bool l2);

}

If I compile and run this I get:

+ g++ -c cfunc.cpp
+ pgf90 -lstdc++ cfunc.o -o test Main.f90
Main.f90:
test/C_Fortran> ./test 
out: 3 4 255 254 1 0 
l1: Error (not True) is (True) !

I though that using iso_c_binding would help, but apparenlty it’s not. Do you have any idea/suggestions on how I could preceed ? (Note that if I compile with gfortran I don’t have this issue)

Thanks,

Xavier

PS : I have been using PGI 13.2

The issue here is that in pgf90 we set .TRUE. to 0xff ,
while gfortran sets .TRUE. to 1.

Use the compiler flag pgf90 -Munixlogical to use the unix logical value of .TRUE.

thanks !

Hi,

Thanks Deborah for the answer. Are there any other flags which need to be set in order to ensure PGI/GNU interoperability?

Cheers,
Oli

Hi Oli,

Other than the normal C++/Fortran interoperability issues, I don’t believe that there are further GNU specific issues. Possible, but we’re not aware of them.

Note that we did just add a PGI C++ compiler, pgc++, which is interoperable with g++.

  • Mat