CMake

2021-06-26

  • 1 Basics
    • 1.1 Variables
      • 1.1.1 Use environment variable
  • 2 Advanced
    • 2.1 Tips
      • 2.1.1 Show the commands of make
      • 2.1.2 Check compiler version
      • 2.1.3 list should include double quotes
      • 2.1.4 Add Git commit ID to the compiled program

1 Basics

1.1 Variables

1.1.1 Use environment variable

Use the syntax $ENV{VAR} to read environment variable VAR.

2 Advanced

2.1 Tips

2.1.1 Show the commands of make

  1. Let make do this.
cmake .
make VERBOSE=1
  1. Let CMake do this.
cmake -DCMAKE_RULE_MESSAGES:BOOL=OFF -DCMAKE_VERBOSE_MAKEFILE:BOOL=ON .
make --no-print-directory

2.1.2 Check compiler version

if(CMAKE_CXX_COMPILER_VERSION VERSION_GREATER 9.99.0)
  set(FC_EXTRA_FLAGS "-frealloc-lhs -fallow-argument-mismatch -DGNU")
else()
  set(FC_EXTRA_FLAGS "-frealloc-lhs -DGNU")
endif()

2.1.3 list should include double quotes

Using CMake version 3.15.4, LAPACK version 3.9.0 has a command in its CMakeLists.txt which results in error in the compilation.

list(APPEND CMAKE_Fortran_FLAGS -fp-model strict)

CMake will add ; to separate -fp-model strict to be -fp-model;strict.

The fix is to use double quotes to encapsulate them: "-fp-model strict".

For additional reference, check Semicolon safety instead of whitespace safety.

2.1.4 Add Git commit ID to the compiled program

Use the following snippet to obtain the Git commit ID and set it as a CMake variable. This snippet is run each time make is run. This snippet should be added to the top CMakeLists.txt of the CMake hierarchy.

execute_process(COMMAND
  git describe --always --abbrev=32
  WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}"
  OUTPUT_VARIABLE GIT_SHA1
  ERROR_QUIET OUTPUT_STRIP_TRAILING_WHITESPACE)
add_definitions("-DGIT_SHA1=\'${GIT_SHA1}\'")
execute_process(COMMAND
  git log -1 --format=%ad --date=local
  WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}"
  OUTPUT_VARIABLE GIT_DATE
  ERROR_QUIET OUTPUT_STRIP_TRAILING_WHITESPACE)
add_definitions("-DGIT_DATE=\'${GIT_DATE}\'")

With the above snippet, the Fortran codes have the variable GIT_SHA1, GIT_DATE defined. Use the following procedure to print the Git information.

  subroutine PrintVersionInfo()
    continue
    if (mypnum == glb_root) then
      write (iout, 1) GIT_SHA1
      write (iout, 2) GIT_DATE
    end if
1   format("NFS version: ", A)
2   format("NFS built time: ", A)
  end subroutine PrintVersionInf
.
Created on 2021-06-26 with pandoc