What worked for me on Ubuntu 20.04 (Focal) was:
$ sudo apt-get install mingw-w64
$ sudo apt-get install gfortran-mingw-w64-x86-64
$ sudo apt-get install wine # to run the programs
This required roughly 2 GB of memory.
Next I created the following CMake toolchain file:
# mingw.cmake
# the name of the target operating system
set(CMAKE_SYSTEM_NAME Windows)
# which compilers to use for C and C++
set(CMAKE_C_COMPILER x86_64-w64-mingw32-gcc)
set(CMAKE_CXX_COMPILER x86_64-w64-mingw32-g++)
set(CMAKE_Fortran_COMPILER x86_64-w64-mingw32-gfortran)
# where is the target environment located
set(CMAKE_FIND_ROOT_PATH /usr/x86_64-w64-mingw32)
# adjust the default behavior of the FIND_XXX() commands:
# search programs in the host environment
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
# search headers and libraries in the target environment
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
The toolchain file can be referenced in the build configuration step:
~fortran/win/build$ cmake -DCMAKE_TOOLCHAIN_FILE=../mingw.cmake ..
Otherwise you just use CMake as usual:
cmake_minimum_required(VERSION 3.15.0 FATAL_ERROR)
project(test VERSION 0.1.0 LANGUAGES CXX C Fortran)
if(CMAKE_SYSTEM MATCHES Windows)
message(STATUS "Target system is Windows")
endif()
add_executable(main main.cpp)
add_executable(main-f90 main.f90)
if(CMAKE_CROSSCOMPILING)
target_link_libraries(main-f90 PUBLIC "-static")
endif()
The main Fortran program was:
program main
use iso_fortran_env
print '(4a)', 'This file was compiled by ', &
compiler_version(), ' using the options ', &
compiler_options()
end program
Here is the output:
:~/fortran/win/build$ make main-f90
Scanning dependencies of target main-f90
[ 50%] Building Fortran object CMakeFiles/main-f90.dir/main.f90.o
[100%] Linking Fortran executable main-f90.exe
[100%] Built target main-f90
~/fortran/win/build$ wine ./main-f90.exe
This file was compiled by GCC version 9.3-win32 20200320 using the options -mtune=generic -march=x86-64 -auxbase-strip CMakeFiles/main-f90.dir/main.f90.o
I was quite surprised by how easy cross-compiling was. It’s a great showcase of the work that goes into MinGW, GCC, and CMake.
I wonder if it’s possible to develop QuickWin (Intel) or AppGraphics (Approximatrix, cc @jeff) apps this way?