Using CMake and GCC to build a very basic Fortran project with an iso_c_binding
fails at linking stage. Compiling and linking manually just works fine:
$ gcc6 -c getkey.c
$ gfortran6 -Wl,-rpath=/usr/local/lib/gcc6/ -o key key.f08 getkey.o
The minimal CMakeLists.txt
:
cmake_minimum_required(VERSION 3.9)
project(GetKey)
set(VERSION 1.0)
set(CMAKE_Fortran_COMPILER "gfortran6")
set(GCC_LIB "-Wl,-rpath=/usr/local/lib/gcc6")
set(CMAKE_Fortran_FLAGS "${CMAKE_Fortran_FLAGS} ${GCC_LIB}")
enable_language(Fortran)
add_library(getkey STATIC getkey.c)
add_executable(key key.f08)
set_target_properties(key PROPERTIES LINKER_LANGUAGE Fortran)
target_link_libraries(key getkey)
Building the project leads to the following linker error:
[...]
[100%] Linking Fortran executable key
/usr/lib/crt1.o: In function `_start':
/usr/src/lib/csu/amd64/crt1.c:(.text+0x17b): undefined reference to `main'
collect2: error: ld returned 1 exit status
The linker seems to search for a main()
function, that Fortran does not feature. Trying to force the Fortran linker makes no difference:
set(CMAKE_Fortran_LINKER_PREFERENCE 100)
set(CMAKE_C_LINKER_PREFERENCE_PROPAGATES False)
Help is appreciated.
Example Code
The linker error does not depend on the actual implementation. Anyway, a basic example would be:
key.f08
:
program main
implicit none
interface
function get_key() bind(c, name='get_key')
use iso_c_binding
integer(kind=c_int) :: get_key
end function get_key
end interface
write(*, '(i0)') get_key()
end program main
And the getkey.c
:
int get_key()
{
return 10000;
}
Verbose Make
Running make VERBOSE=1
:
/usr/local/bin/cmake -H"/home/user/fortran" -B"/home/user/fortran" --check-build-system CMakeFiles/Makefile.cmake 0
/usr/local/bin/cmake -E cmake_progress_start "/home/user/fortran/CMakeFiles" "/home/user/fortran/CMakeFiles/progress.marks"
make -f CMakeFiles/Makefile2 all
make -f CMakeFiles/key.dir/build.make CMakeFiles/key.dir/depend
cd "/home/user/fortran" && /usr/local/bin/cmake -E cmake_depends "Unix Makefiles" "/home/user/fortran" "/home/user/fortran" "/home/user/fortran" "/home/user/fortran" "/home/user/fortran/CMakeFiles/key.dir/DependInfo.cmake" --color=
make -f CMakeFiles/key.dir/build.make CMakeFiles/key.dir/build
[ 50%] Linking Fortran executable key
/usr/local/bin/cmake -E cmake_link_script CMakeFiles/key.dir/link.txt --verbose=1
/usr/local/bin/gfortran6 CMakeFiles/key.dir/getkey.c.o -o key
/usr/lib/crt1.o: In function `_start':
/usr/src/lib/csu/amd64/crt1.c:(.text+0x17b): undefined reference to `main'
collect2: error: ld returned 1 exit status
*** Error code 1
Stop.
make[2]: stopped in /usr/home/user/fortran
*** Error code 1
Stop.
make[1]: stopped in /usr/home/user/fortran
*** Error code 1
Stop.
make: stopped in /usr/home/user/fortran