If you are building FORTRAN projects in linux, you can use Cmake as your build system. Let’s build a very simple project consisting a module and a FORTRAN program file.
The module is defined in the file hello_mod.f90 which contains following code:
module hello
contains
subroutine say_hello(name)
implicit none
character(*),optional,intent(in):: name
if (present(name)) then
write (*,10) name
else
write (*,10) "world"
endif
10 format ("Hello",x,a,"!")
end subroutine say_hello
subroutine say_goodbye(name)
implicit none
character(*),optional,intent(in):: name
if (present(name)) then
write (*,10) name
else
write (*,10) "world"
endif
10 format ("Goodbye,",x,a,"!")
end subroutine say_goodbye
end module hello
The file main.f90 contains the program which in turn uses the the hello module to display messages. The content of main.f90 is trivial as you can see.
program main
use hello
call say_hello("Dolly")
call say_goodbye("friends")
end program main
We need to create a CMakeLists.txt file and define FORTRAN as language.
cmake_minimum_required(VERSION 3.0)
project(test_modules LANGUAGES Fortran)
set (CMAKE_Fortran_MODULE_DIRECTORY ${CMAKE_BINARY_DIR}/modules)
add_executable(test
main.f90
hello_mod.f90)
target_include_directories(test PRIVATE
${CMAKE_BINARY_DIR}/modules)
# use this if you need to link to libraries
# ---------------------------------------------------------------
#find_library(target <library>) # use to locate external libraries
#
#target_link_libraries (test PRIVATE
# library_1
# library_2)
Now when we run cmake using this file, it will create an empty directory named modules under our build directory. We then run make and it will place a module file hello.mod in this directory. It will also create the object files hello_mod-f90.o and main.f90.o in the folder CMakeFiles/test.dir and finally will link these two source files into the executable test.