#include<cstdlib>#include<iostream>#include<string>std::stringsay_hello() {#ifdefIS_INTEL_CXX_COMPILER // only compiled when Intel compiler is selected // such compiler will not compile the other branchesreturn std::string("Hello Intel compiler!");#elif IS_GNU_CXX_COMPILER // only compiled when GNU compiler is selected // such compiler will not compile the other branchesreturn std::string("Hello GNU compiler!");#elif IS_PGI_CXX_COMPILER // etc.return std::string("Hello PGI compiler!");#elif IS_XL_CXX_COMPILERreturn std::string("Hello XL compiler!");#elsereturn std::string("Hello unknown compiler - have we met before?");#endif}intmain() { std::cout <<say_hello() << std::endl; std::cout <<"compiler name is " COMPILER_NAME << std::endl;return EXIT_SUCCESS;}
Fortran示例(hello-world.F90):
program hello
implicit none
#ifdef IS_Intel_FORTRAN_COMPILER
print *, 'Hello Intel compiler!'
#elif IS_GNU_FORTRAN_COMPILER
print *, 'Hello GNU compiler!'
#elif IS_PGI_FORTRAN_COMPILER
print *, 'Hello PGI compiler!'
#elif IS_XL_FORTRAN_COMPILER
print *, 'Hello XL compiler!'
#else
print *, 'Hello unknown compiler - have we met before?'
#endif
end program
具体实施
我们将从C++的例子开始,然后再看Fortran的例子:
CMakeLists.txt文件中,定义了CMake最低版本、项目名称和支持的语言:
cmake_minimum_required(VERSION 3.5 FATAL_ERROR)
project(recipe-03 LANGUAGES CXX)
然后,定义可执行目标及其对应的源文件:
add_executable(hello-world hello-world.cpp)
通过定义以下目标编译定义,让预处理器了解编译器的名称和供应商:
target_compile_definitions(hello-world PUBLIC "COMPILER_NAME=\"${CMAKE_CXX_COMPILER_ID}\"")
if(CMAKE_CXX_COMPILER_ID MATCHES Intel)
target_compile_definitions(hello-world PUBLIC "IS_INTEL_CXX_COMPILER")
endif()
if(CMAKE_CXX_COMPILER_ID MATCHES GNU)
target_compile_definitions(hello-world PUBLIC "IS_GNU_CXX_COMPILER")
endif()
if(CMAKE_CXX_COMPILER_ID MATCHES PGI)
target_compile_definitions(hello-world PUBLIC "IS_PGI_CXX_COMPILER")
endif()
if(CMAKE_CXX_COMPILER_ID MATCHES XL)
target_compile_definitions(hello-world PUBLIC "IS_XL_CXX_COMPILER")
endif()
现在我们已经可以预测结果了:
$ mkdir -p build
$ cd build
$ cmake ..
$ cmake --build .
$ ./hello-world
Hello GNU compiler!