CMake Cookbook
上QQ阅读APP看书,第一时间看更新

How to do it

How can we select a specific compiler? For example, what if we want to use the Intel or Portland Group compilers? CMake stores compilers for each language in the CMAKE_<LANG>_COMPILER variable, where <LANG> is any of the supported languages, for our purposes CXX, C, or Fortran. The user can set this variable in one of two ways:

  1. By using the -D option in the CLI, for example:
$ cmake -D CMAKE_CXX_COMPILER=clang++ ..
  1. By exporting the environment variables CXX for the C++ compiler, CC for the C compiler, and FC for the Fortran compiler. For example, use this command to use clang++ as the C++ compiler:
$ env CXX=clang++ cmake ..

Any of the recipes discussed so far can be configured for use with any other compiler by passing the appropriate option.

CMake is aware of the environment and many options can either be set  via  the  -D  switch of its CLI or via an environment variable. The former mechanism overrides the latter, but we suggest to always set options explicitly with  -D Explicit is better than implicit , since environment variables might be set to values that are not suitable for the project at hand.

We have here assumed that the additional compilers are available in the standard paths where CMake does its lookups. If that is not the case, the user will need to pass the full path to the compiler executable or wrapper.

We recommend to set the compilers using the  -D CMAKE_<LANG>_COMPILER CLI options instead of exporting CXX , CC , and FC . This is the only way that is guaranteed to be cross-platform and compatible with non-POSIX shells. It also avoids polluting your environment with variables, which may affect the environment for external libraries built together with your project.