cmake 3.5:find_package(HDF5) 指定HDF5_ROOT无效问题

本文介绍了一个关于CMake中FindHDF5.cmake模块的问题:即使设置了HDF5_ROOT环境变量,CMake仍可能无法正确找到指定的HDF5安装路径。文中详细解释了问题的原因在于对HDF5_ROOT环境变量的不正确引用,并提供了通过升级CMake版本到3.9来解决该问题的方法。

我们知道cmake提供了FindHDF5.cmake(位置:$cmake_root/Modules)模块用于搜索HDF5组件。
通过查看FindHDF5.cmake的源码可以知道,可以通过定义HDF5_ROOT环境变量,来指定要使用的HDF5位置。
HDF5_ROOT是个很有用的参数,当系统安装了HDF5(/usr下),而自己又编译一个版本(比如在/home下),如果想使用自己编译的版本,就可以通过这个参数来实现,避免在执行find_package(HDF5)时cmake自做聪明的找到系统安装的版本。
原文如下:

To provide the module with a hint about where to find your HDF5
installation, you can set the environment variable HDF5_ROOT. The
Find module will then look in this path when searching for HDF5
executables, paths, and libraries.
@FindHDF5.cmake

然而理想很丰满,现实很骨感,当我使用HDF5_ROOT来指定HDF5安装位置时,cmake在执行find_package(HDF5)却并没有找到我编译的版本,还是找到了/usr下安装的版本,调用代码下如:

export HDF5_ROOT=$hdf5_install_folder
cmake . $CMAKE_VARS_DEFINE -G "Unix Makefiles" 

#问题溯源
最终找到了原因:cmake 3.5(我没有一个个版本去试,至少这个3.1,3.5是有问题的)以前的版本中的FindHDF5.cmake有bug,进一步的原因是对HDF5_ROOT环境变量的用法错误,造成HDF5_ROOT无效,下面这是FindHDF5.cmake其中一段代码:

find_program( HDF5_C_COMPILER_EXECUTABLE
    NAMES h5cc h5pcc
    HINTS ENV HDF5_ROOT
    PATH_SUFFIXES bin Bin
    DOC "HDF5 Wrapper compiler.  Used only to detect HDF5 compile flags." )

上面的代码中,通过ENV HDF5_ROOT这样的写法来引用一个环境变量,这显然是错误的。正确的写法应该是$ENV{HDF5_ROOT}
#解决办法
知道问题原因了,如何解决呢?修改FindHDF5.cmake源码当然是个办法,但太耗费精力了。
所以我尝试下载了cmake最新的3.9版本,通过查看FindHDF5.cmake源码,发现3.9版本已经解决了这个问题。所以最简单的解决办法就是升级cmake到3.9。
而且3.9版本中还做了进一步的改进,即可以在环境变量中定义HDF5_ROOT,也可以将HDF5_ROOT定义成一个cmake变量。所以开始的cmake命令又可以写成如下形式:

cmake . $CMAKE_VARS_DEFINE -G "Unix Makefiles" -DHDF5_ROOT=$hdf5_install_folder

#参考资料

《FindHDF5》

include(FetchContent) include(ExternalProject) cmake_minimum_required(VERSION 3.16.0) project(SWMM5Plus VERSION 1.0.2) enable_language (Fortran) find_package (Python3 COMPONENTS Interpreter) set(testing_available ON) set(CPACK_SET_DESTDIR ON) function(check_python_dependencies module) message(STATUS "Looking for Python module '${module}'") execute_process(COMMAND pip show ${module} OUTPUT_QUIET ERROR_QUIET RESULT_VARIABLE EXIT_CODE_PIPSHOW ) if (NOT ${EXIT_CODE_PIPSHOW} EQUAL 0) set(testing_available OFF PARENT_SCOPE) message(WARNING "\nMissing Python module '${module}'\n**Testing unavailable**\nPlease run python_dependencies.sh\n") else() message(STATUS "'${module}' found") endif() endfunction() if (NOT (CMAKE_Fortran_COMPILER_ID STREQUAL "Intel" OR CMAKE_Fortran_COMPILER_ID STREQUAL "IntelLLVM")) message(FATAL_ERROR "Intel Fortran compiler not found. Found ${CMAKE_Fortran_COMPILER_ID} instead. This project supports Intel Fortran (ifort) and IntelLLVM (ifx).") else() message(STATUS "Detected Intel Fortran compiler: ${CMAKE_Fortran_COMPILER_ID}") endif() function(commentout IN_FILE line_num) file (STRINGS ${IN_FILE} LINES) file(WRITE ${IN_FILE} "") set(line_counter 1) foreach(LINE IN LISTS LINES) if (${line_counter} STREQUAL line_num) string(PREPEND LINE "//") endif() MATH(EXPR line_counter "${line_counter}+1") file(APPEND ${IN_FILE} "${LINE}\n") endforeach() endfunction() get_filename_component(build_configuration ${CMAKE_BINARY_DIR} NAME) if (build_configuration STREQUAL "build") set(default_build_type "Release") message(STATUS "Building inside '${build_configuration}' named folder, setting configuration as '${default_build_type}'") elseif (build_configuration STREQUAL "dwflow") set(default_build_type "Release") message(STATUS "Building inside '${build_configuration}' named folder, setting configuration as '${default_build_type}'") message(WARNING "Lines [249-252] will be commented out from 'interface/src/dwflow.c'") elseif(build_configuration STREQUAL "debug") set(default_build_type "Debug") message(STATUS "Building inside '${build_configuration}' named folder, setting configuration as '${default_build_type}'") set(CMAKE_Fortran_FLAGS "${CMAKE_Fortran_FLAGS} -g -traceback -debug extended") endif() set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fPIC -lm -lpthread -shared -fcommon") #set(CMAKE_Fortran_FLAGS "${CMAKE_Fortran_FLAGS} -coarray=distributed -ldl") set(CMAKE_Fortran_FLAGS "${CMAKE_Fortran_FLAGS} -coarray=shared -fPIC -traceback") set(FETCHCONTENT_QUIET OFF) set(BUILD_COARRAY_NUM_IMAGES 1 CACHE STRING "Set up the number of processors to use for parallel SWMM5+.") set(BUILD_HDF5 "C:/Users/Admin/gw20250625/SWMM5plus-v-1.0.2/build/_deps/hdf5-src") set(hdf5_SOURCE_DIR "C:/Users/Admin/gw20250625/SWMM5plus-v-1.0.2/build/_deps/hdf5-src") set(HDF5_INCLUDE_DIR "C:/Users/Admin/gw20250625/SWMM5plus-v-1.0.2/build/_deps/hdf5-src/include") set(HDF5_LIB_DIR "C:/Users/Admin/gw20250625/SWMM5plus-v-1.0.2/build/_deps/hdf5-src/lib") set(json_fortran_SOURCE_DIR "C:/Users/Admin/gw20250625/SWMM5plus-v-1.0.2/build/json-fortran-src") if (DEFINED ENV{HDF5_DIR}) set(BUILD_HDF5 $ENV{HDF5_DIR}) endif() FetchContent_Declare( epaswmm5 URL https://github.com/USEPA/Stormwater-Management-Model/archive/v5.1.13.tar.gz ) FetchContent_Declare( json_fortran GIT_REPOSITORY https://github.com/jacobwilliams/json-fortran.git GIT_TAG 3ab8f98209871875325c6985dd0e50085d1c82c2 #Release 8.3.0 GIT_PROGRESS ON ) FetchContent_Declare( hdf5 GIT_REPOSITORY https://github.com/HDFGroup/hdf5.git GIT_TAG 3e847e003632bdd5fdc189ccbffe25ad2661e16f #Release 1.12.2 GIT_PROGRESS ON ) Fetchcontent_MakeAvailable(epaswmm5) FetchContent_GetProperties(json_fortran hdf5) if(NOT json_fortran_POPULATED) FetchContent_Populate(json_fortran) endif() FetchContent_Populate(hdf5) ExternalProject_Add(hdf5 SOURCE_DIR "C:/Users/Admin/gw20250625/SWMM5plus-v-1.0.2/build/_deps/hdf5-src" CONFIGURE_COMMAND FC=ifort ${hdf5_SOURCE_DIR}/configure --enable-fortran --without-zlib BINARY_DIR ${hdf5_BINARY_DIR} BUILD_COMMAND ${MAKE} COMMAND make install) set(HDF5_LIB_DIR ${hdf5_BINARY_DIR}/hdf5/lib/) set(HDF5_INCLUDE_DIR ${hdf5_BINARY_DIR}/hdf5/include/) set(HDF5_LIBRARIES ${hdf5_BINARY_DIR}/hdf5/lib/libhdf5hl_fortran.a ${hdf5_BINARY_DIR}/hdf5/lib/libhdf5_hl.a ${hdf5_BINARY_DIR}/hdf5/lib/libhdf5_fortran.a ${hdf5_BINARY_DIR}/hdf5/lib/libhdf5.a) set(BUILD_HDF5 ${hdf5_BINARY_DIR}) set(HDF5_FOUND ON) #Following sh script file(COPY ${epaswmm5_SOURCE_DIR}/src/ DESTINATION ${CMAKE_SOURCE_DIR}/interface/src) file(COPY ${CMAKE_SOURCE_DIR}/interface/api.h DESTINATION ${CMAKE_SOURCE_DIR}/interface/src) file(COPY ${CMAKE_SOURCE_DIR}/interface/api.c DESTINATION ${CMAKE_SOURCE_DIR}/interface/src) file(COPY ${CMAKE_SOURCE_DIR}/interface/api_error.h DESTINATION ${CMAKE_SOURCE_DIR}/interface/src) file(COPY ${CMAKE_SOURCE_DIR}/interface/api_error.c DESTINATION ${CMAKE_SOURCE_DIR}/interface/src) file(READ ${CMAKE_SOURCE_DIR}/interface/add_to_controls.c CONTROLS) file(READ ${CMAKE_SOURCE_DIR}/interface/add_to_funcs.h FUNCS) file(APPEND ${CMAKE_SOURCE_DIR}/interface/src/controls.c "${CONTROLS}") file(APPEND ${CMAKE_SOURCE_DIR}/interface/src/funcs.h "${FUNCS}") message(STATUS "Appended to controls.c and funcs.h") file(READ ${CMAKE_SOURCE_DIR}/interface/add_to_lid.c LIDC) file(READ ${CMAKE_SOURCE_DIR}/interface/add_to_lid.h LIDH) file(APPEND ${CMAKE_SOURCE_DIR}/interface/src/lid.c "${LIDC}") file(APPEND ${CMAKE_SOURCE_DIR}/interface/src/lid.h "${LIDH}") message(STATUS "Appended to lid.c and lid.h") if (build_configuration STREQUAL "dwflow") commentout(${CMAKE_SOURCE_DIR}/interface/src/dwflow.c 248) commentout(${CMAKE_SOURCE_DIR}/interface/src/dwflow.c 249) commentout(${CMAKE_SOURCE_DIR}/interface/src/dwflow.c 250) commentout(${CMAKE_SOURCE_DIR}/interface/src/dwflow.c 251) commentout(${CMAKE_SOURCE_DIR}/interface/src/dwflow.c 252) message(STATUS "Commented out lines [248-252] from 'interface/src/dwflow.c'") endif() file(GLOB SWMM_SOURCES ${CMAKE_SOURCE_DIR}/interface/src/*.c ${CMAKE_SOURCE_DIR}/interface/src/*.h ) file(GLOB SWMM5X_SOURCES ${json_fortran_SOURCE_DIR}/src/json_kinds.F90 ${json_fortran_SOURCE_DIR}/src/json_parameters.F90 ${json_fortran_SOURCE_DIR}/src/json_string_utilities.F90 ${json_fortran_SOURCE_DIR}/src/json_value_module.F90 ${json_fortran_SOURCE_DIR}/src/json_file_module.F90 ${json_fortran_SOURCE_DIR}/src/json_module.F90 ${CMAKE_SOURCE_DIR}/utility/*.f90 ${CMAKE_SOURCE_DIR}/special_elements/*.f90 ${CMAKE_SOURCE_DIR}/definitions/*.f90 ${CMAKE_SOURCE_DIR}/interface/c_library.f90 ${CMAKE_SOURCE_DIR}/interface/interface.f90 ${CMAKE_SOURCE_DIR}/initialization/*.f90 ${CMAKE_SOURCE_DIR}/geometry/*.f90 ${CMAKE_SOURCE_DIR}/timeloop/*.f90 ${CMAKE_SOURCE_DIR}/output/*.f90 ${CMAKE_SOURCE_DIR}/finalization/*.f90 ${CMAKE_SOURCE_DIR}/main/*.f90 ) #Targets #add_library(swmm5 SHARED # ${SWMM_SOURCES} #) set_target_properties(swmm5 PROPERTIES LINKER_LANGUAGE C CXX_STANDARD 14) add_executable(SWMM5p ${SWMM5X_SOURCES} ) target_include_directories(SWMM5p PUBLIC ${HDF5_INCLUDE_DIR} ) target_link_directories(SWMM5p PUBLIC ${HDF5_LIB_DIR} ) target_link_libraries(SWMM5p PUBLIC ${HDF5_LIBRARIES} ) add_dependencies(SWMM5p hdf5) #Testing check_python_dependencies(tornado) check_python_dependencies(tabulate) check_python_dependencies(h5py) check_python_dependencies(swmmtoolbox) # Tests defined in separate file: ctest/CMakeLists.txt if (testing_available) enable_testing() message(STATUS "Making tests available") add_subdirectory(ctest) endif() #INSTALLATION install(TARGETS SWMM5p DESTINATION bin) install(TARGETS swmm5 DESTINATION lib) #cpack set(CPACK_PACKAGE_CONTACT "NCIMM") set(CPACK_DEBIAN_PACKAGE_MAINTAINER "NCIMM") set(CPACK_DEBIAN_PACKAGE_DEPENDS "intel-hpckit") include(CPack) 以上是我配置swmm5+的CMakeLists.txt,这样配置后,HDF5配置不成功,不能生成 HDF5.mod 文件
06-27
************************************************************************ * Build and Install HDF5 Applications with CMake * ************************************************************************ Notes: This short instruction is written for users who want to quickly build HDF5 applications using the CMake tools. Users can adapt these instructions for their own applications. For more information, see the "Minimum C Project Files for CMake" section. More information about using CMake can be found at the KitWare site, www.cmake.org. CMake uses the command line; however, the visual CMake tool is available for the configuration step. The steps are similar for all of the operating systems supported by CMake. NOTES: 1. Using CMake for building and using HDF5 is under active development. While we have attempted to provide error-free files, please understand that development with CMake has not been extensively tested outside of HDF. The CMake specific files may change before the next release. 2. CMake for HDF5 development should be usable on any system where CMake is supported. Please send us any comments on how CMake support can be improved on any system. 3. See the appendix at the bottom of this file for an example of using a ctest script for building and testing. See INSTALL_CMake.txt for more information. 4. See https://cmake.org/cmake/help/latest/command/find_package.html for more information on the CMake "Config Mode Search Procedure". ======================================================================== I. Preconditions ======================================================================== 1. We suggest you obtain the latest CMake for your platform from the Kitware web site. The HDF5 1.12.x product requires a minimum CMake version of 3.12. If you are using VS2019, the minimum version is 3.15. For VS2022, the minimum version is 3.21. 2. You have installed the HDF5 library built with CMake, by executing the HDF Install Utility (the *.msi file in the binary package for Windows or the *.sh on Linux). You can obtain pre-built binaries from The HDF Group&#39;s website at www.hdfgroup.org. 3. Set the HDF5_ROOT CMake variable, -DHDF5_ROOT=<install_path> or environment variable, set(ENV{HDF5_ROOT} "<install_path>") to the installed location of HDF5. On Windows: HDF5_ROOT=C:/Program Files/HDF_Group/HDF5/1.12.x/ On unix: HDF5_ROOT=<install root folder>/HDF_Group/HDF5/1.12.x/ If you are using shared libraries, you may need to add to the path environment variable. Set the path environment variable to the installed location of the library files for HDF5. On Windows (*.dll): PATH=%PATH%;C:/Program Files/HDF_Group/HDF5/1.12.x/bin On unix (*.so): LD_LIBRARY_PATH=$LD_LIBRARY_PATH:<install root folder>/HDF_Group/HDF5/1.12.x/lib If you are using filter plugin libraries, you will need to set the HDF5_PLUGIN_PATH environment variable. On Windows: HDF5_PLUGIN_PATH=C:/Program Files/HDF_Group/HDF5/1.12.x/lib/plugin On unix: HDF5_PLUGIN_PATH=<install root folder>/HDF_Group/HDF5/1.12.x/lib/plugin (Note there are no quote characters used on Windows and all platforms use forward slashes) 4. Created separate source and build directories. (CMake commands are executed in the build directory) 5. Created a CMakeLists.txt file(s) for your source. See Section III below. ======================================================================== II. Building HDF5 Applications with CMake ======================================================================== Go through these steps to build HDF5 applications with CMake. (The application must support building with CMake.) 1. Run CMake 2. Configure the cache settings 3. Build HDF5 Applications 4. Test HDF5 Applications These steps are described in more detail below. 1. Run CMake The visual CMake executable is named "cmake-gui.exe" on Windows and should be available in your Start menu. For Linux, UNIX, and Mac users the executable is named "cmake-gui" and can be found where CMake was installed. Specify the source and build directories. Make the build and source directories different. For example on Windows, if the source is at c:\MyHDFstuff\hdf5, then use c:\MyHDFstuff\hdf5\build or c:\MyHDFstuff\build\hdf5 for the build directory. PREFERRED: Users can perform the configuration step without using the visual cmake-gui program. The following is an example command line configuration step executed within the build directory: cmake -G "<generator>" [-D<options>] <sourcepath> Where <generator> is * MinGW Makefiles * NMake Makefiles * Unix Makefiles * Visual Studio 14 2015 * Visual Studio 14 2015 Win64 * Visual Studio 15 2017 * Visual Studio 15 2017 Win64 * Visual Studio 16 2019 * ... in addition VS2019 will need to set the "-A" option, * ... [Win32, x64, ARM, ARM64] * Visual Studio 17 2022 * ... in addition VS2022 will need to set the "-A" option, * ... [Win32, x64, ARM, ARM64] <options> is: * BUILD_TESTING:BOOL=ON * BUILD_SHARED_LIBS:BOOL=[ON | OFF] 2. Configure the cache settings 2.1 Visual CMake users, click the Configure button. If this is the first time you are running cmake-gui in this directory, you will be prompted for the generator you wish to use (for example on Windows, Visual Studio 14 2015 Win64). CMake will read in the CMakeLists.txt files from the source directory and display options for the HDF5 project. After the first configure you can adjust the cache settings and/or specify locations of other programs. Any conflicts or new values will be highlighted by the configure process in red. Once you are happy with all the settings and there are no more values in red, click the Generate button to produce the appropriate build files. On Windows, if you are using a Visual Studio generator, the solution and project files will be created in the build folder. On linux, if you are using the Unix Makefiles generator, the Makefiles will be created in the build folder. 2.2 Alternative command line example on Windows in c:\MyHDFstuff\hdf5\build directory: cmake -G "Visual Studio 14 2015 Win64" -DBUILD_TESTING:BOOL=ON .. 3. Build HDF5 Applications On Windows, you can build HDF5 applications using either the Visual Studio Environment or the command line. The command line is normally used on linux, Unix, and Mac. To build from the command line, navigate to your build directory and execute the following: cmake --build . --config {Debug | Release} NOTE: "--config {Debug | Release}" may be optional on your platform. We recommend choosing either Debug or Release on Windows. If you are using the pre-built binaries from HDF, use Release. 3.1 If you wish to use the Visual Studio environment, open the solution file in your build directory. Be sure to select either Debug or Release and build the solution. 4. Test HDF5 Applications To test the build, navigate to your build directory and execute: ctest . -C {Debug | Release} NOTE: "-C {Debug | Release}" may be optional on your platform. We recommend choosing either Debug or Release to match the build step on Windows. 5. The files that support building with CMake are all of the files in the config/cmake folder, the CMakeLists.txt files in each source folder, and CTestConfig.cmake. CTestConfig.cmake is specific to the internal testing performed by The HDF Group. It should be altered for the user&#39;s installation and needs. The cacheinit.cmake file settings are used by The HDF Group for daily testing. It should be altered/ignored for the user&#39;s installation and needs. ======================================================================== III. Minimum C Project Files for CMake ======================================================================== Given the preconditions in section I, create a CMakeLists.txt file at the source root. Include the following text in the file: ########################################################## cmake_minimum_required (VERSION 3.12) project (HDF5MyApp C CXX) set (LIB_TYPE STATIC) # or SHARED string(TOLOWER ${LIB_TYPE} SEARCH_TYPE) find_package (HDF5 NAMES hdf5 COMPONENTS C ${SEARCH_TYPE}) # find_package (HDF5) # Find non-cmake built HDF5 set_directory_properties(PROPERTIES INCLUDE_DIRECTORIES "${HDF5_INCLUDE_DIR}") set (LINK_LIBS ${LINK_LIBS} ${HDF5_C_${LIB_TYPE}_LIBRARY}) set (example hdf_example) add_executable (${example} ${PROJECT_SOURCE_DIR}/${example}.c) TARGET_C_PROPERTIES (${example} PRIVATE ${LIB_TYPE}) target_link_libraries (${example} ${LINK_LIBS}) enable_testing () include (CTest) add_test (NAME test_example COMMAND ${example}) ########################################################## ======================================================================== IV. APPENDIX ======================================================================== Below is an example of a ctest script that can be used to build the examples. Adjust the values as necessary. Note that the defaults can be entered on the command line and the build folder is created as a sub-folder. Windows should adjust the forward slash to double backslashes, except for the HDF_DIR environment variable. NOTE: this file is available at the HDF web site: https://portal.hdfgroup.org/display/support/Building+HDF5+with+CMake HDF5_Examples.cmake HDF5_Examples_options.cmake Also available at the HDF web site is a CMake application framework template. You can quickly add files to the framework and execute the script to compile your application with an installed HDF5 binary. ======================================================================== For further assistance, send email to help@hdfgroup.org ========================================================================
06-27
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

10km

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值