Skip to content

Instantly share code, notes, and snippets.

@KmolYuan
Last active October 13, 2021 08:46
Show Gist options
  • Save KmolYuan/213156482465b5712aba032f75e76050 to your computer and use it in GitHub Desktop.
Save KmolYuan/213156482465b5712aba032f75e76050 to your computer and use it in GitHub Desktop.
Configuration of compiling Fortran with CMake.

用 CMake 編譯 Fortran Project

CMake: https://cmake.org/download/

新增一個 CMakeList.txt 檔案在 project root,test-fortran 替換成 project name。 其中 add_executable function 會列出全部 source code 檔案的名稱,有新的檔案時務必新增到其中。

以下副檔名 (filename extension) 的排列為 Unix / macOS(?) / Windows。

要產生 Executable (* / *.app / *.exe) 使用 add_executable,要產生 Libray 則使用 add_library。 不過 Libray 主要有兩種選項,共享函式庫 (*.so / *.dylib / *.dll) 是用 SHARED 選項; 靜態函式庫 (*.a / *.lib) 是使用 STATIC 選項。

cmake_minimum_required(VERSION 3.10)
project(test-fortran Fortran)
enable_language(Fortran)
add_executable(  # 產生執行檔 (executable file)
    test-fortran
    src/main.f90
    src/test.f90
)
add_library(
    test-fortran
    SHARED  # 產生共享函式庫 (shared library)
    src/test.f90
)
  • 共享函式庫(動態函式庫):分離主執行檔,可提供多個執行檔使用(或是跨程式語言)、載入速度較慢。
  • 靜態函式庫:提供在編譯時加到主執行檔中,速度快、無法分享。

指令

初步配置,檢查編譯器和腳本檔案,預設會挑現有的來用,通常就是 environment variable PATH 可以找到的為準。可額外指定。

設定檔會存入 build 目錄中,也可以取其它名字。

若配置檔有無法修正的錯誤,把 build 清空再執行一次即可。

mkdir build
cd build
cmake ..
cd ..

編譯,編譯 CMakeList.txt 提到的全部目標 (Target),也就是 project 名稱,可以用 --target test-fortran 來指定目標。

其中 -j4 是使用 4 個執行緒來平行編譯,對大 project 可以提昇編譯速度。

cmake --build build -j4

執行,由於 CMake 沒有提供編譯後直接執行的指令,所以使用 && 可以在編譯成功後執行程式。

cmake --build build -j4 && ./build/test-fortran
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment