Friday, October 29, 2021

[SOLVED] strange problem in building Fortran shared library with cmake

Issue

I am trying to build a simple example shared library (using cmake) from the following Fortran code (util.f90):

module util
    implicit none
       

    type dummy
        integer             :: n
        real, allocatable   :: buff(:)
    end type


    contains


        subroutine allocate_dummy(x, n)
            implicit none
            type(dummy), intent(out)    :: x
            integer, intent(in)         :: n
            x%n = n
            allocate(x%buff(n))
        end subroutine 


        subroutine print_dummy(x)
            implicit none
            type(dummy)     :: x
            integer         :: i
            if (allocated(x%buff)) then
                write(*, *) x%n, x%buff, 'Sum:', sum(x%buff)
            else
                write(*, *) 'not allocated'
            end if
        end subroutine 
    
end module 

where the example main program (main.f90) is

program main
    use util
    implicit none
    type(dummy) :: x

    call allocate_dummy(x, 3)
    x%buff = 3.14
    call print_dummy(x)

end program 

Thus the library just allocates x and prints it. I use the following CMakeLists.txt for building the library and executable

cmake_minimum_required(VERSION 3.10)

project(DUMMY)
enable_language(Fortran)

add_library(dumlib SHARED util.f90)
target_include_directories(dumlib INTERFACE ${CMAKE_CURRENT_BINARY_DIR})

add_executable(a.out main.f90)
target_link_libraries(a.out dumlib)

But ./a.out prints

           3 Sum:   9.42000008    

where it should print

           3   3.14000010       3.14000010       3.14000010     Sum:   9.42000008    

Direct compilation (without shared lib), or if I build the library by hand (without cmake), behaves correctly. But with cmake shared lib, x%buff is not printed. The code works correctly since Sum: is correctly calculated and printed. I am wondering what could be the issue?

Edit:

The issue is fixed if (in the write statement) I use (x%buff(j), j=1, n) instead of x%buff. But still, I am curious about the cause of this behavior.

Edit 2:

My Fortran compiler is gfortran (gcc version 9.3.0).


Solution

After a little inspection I figured that this happens because of runtime library mismatch. For compiling the code I used my locally installed gfortran but during the run I think ld grabs some libs from the gcc installed to a CONDA environment.



Answered By - Amir Hajibabaei