Fortran logical boolean C_BOOL
Fortran compilers typically use 4 bytes for
logical
while C compilers usually use
1 byte for bool.
This becomes of vital importantance when using iso_c_binding to interface between Fortran and C/C++.
Specifically, the Fortran type declaration must use logical(kind=C_BOOL) to ensure the correct size and values are used for interoperability.
If this is not done, there will likely be randomly occuring bugs that pop up across compiler versions, operating systems, etc. due to the non-standard C values used for .true. and .false. in Fortran.
use, intrinsic :: iso_c_binding
logical(C_BOOL) :: L1Intel oneAPI flag
-fpscomp logicals
ensures integer values 0,1 corresponding to .false., .true. are used.
Otherwise by default unexpected values may cause programs to fail at runtime with impossible boolean values like 255.
In CMake this flag is applied like:
if(CMAKE_Fortran_COMPILER_ID MATCHES "^Intel")
add_compile_options("$<$<COMPILE_LANGUAGE:Fortran>:-fpscomp;logicals>")
elseif(CMAKE_Fortran_COMPILER_ID STREQUAL "NVHPC")
add_compile_options("$<$<COMPILE_LANGUAGE:Fortran>:-Munixlogical>")
endif()For C interoperability, Fortran can use:
use, intrinsic :: iso_c_binding
logical(kind=C_BOOL) :: L
logical :: Q
c_sizeof(L) == 1
c_sizeof(Q) == 4
! typicallywhile C uses:
#if __STDC_VERSION__ < 202311L
#include <stdbool.h>
#endif
#include <stdio.h>
#include <stdlib.h>
int main(void) {
bool L;
printf("%zu\n", sizeof(L));
return EXIT_SUCCESS;
}and likewise C++ bool is typically 1 byte:
#include <iostream>
#Include <cstdlib>
int main(){
bool L;
std::cout << sizeof(L) << "\n";
return EXIT_SUCCESS;
}Always use iso_c_binding when using C or C++ with Fortran modules to produce cross-platform compatible projects.
See “bool” examples for interfacing between C, C++ and Fortran.
Do not use
The Intel oneAPI compiler
-standard-semantics
flag to use C_BOOL
values
correctly between C, C++ and Fortran has a BIG DOWNSIDE in that it breaks linking with system libraries–including Intel MPI!
All projects and libraries linking to a Fortran library that used oneAPI -standard-semantics must also use -standard-semantics.