Windows Intel Fortran编译netCDF-Fortran
步骤
-
下载安装预编译的netCDF-C https://docs.unidata.ucar.edu/netcdf-c/current/winbin.html 假设安装在了
C:\Libs\netCDF-c\4.9.1
-
在netCDF-Fortran的GitHub主页下载最新的Release https://github.com/Unidata/netcdf-fortran/releases/tag/v4.6.0
-
解压源代码到
C:\Libs\netCDF-fortran\source
-
从开始菜单打开
Intel oneAPI command prompt for Intel 64 for Visual Studio 2022
-
使用cmake生成项目。注意cmake参数中路径分隔符不要用反斜杠
\
假设我们要安装到C:/Libs/netCDF-fortran/Debug
目录下cd C:\Libs\netCDF-fortran\ cmake -S source -B build-debug -DnetCDF_LIBRARIES=C:/Libs/netCDF-c/4.9.1/lib/netcdf.lib -DnetCDF_INCLUDE_DIR=C:/Libs/netCDF-c/4.9.1/include -DCMAKE_INSTALL_PREFIX=C:/Libs/netCDF-fortran/Debug
-
编译生成
netcdff
cmake --build build-debug --target netcdff netcdff_c --config Debug
-
手动生成
netcdff.lib
cd build-debug\fortran lib netcdff.dir\Debug\*.obj netcdff_c.dir\Debug\netcdff_c.lib /out:Debug\netcdff.lib
-
编译生成测试。正常情况下,生成失败数应该是0。
cd ..\..\ cmake --build build-debug --target ALL_BUILD --config Debug
-
执行安装命令,会安装到第5步指定的
-DCMAKE_INSTALL_PREFIX=
目录下cmake --build build-debug --target INSTALL --config Debug
总结
-
第五步的指定
netCDF_LIBRARIES
和netCDF_INCLUDE_DIR
很关键,不然cmake找不到netcdf-c,会报错netcdf-c version 4.7.4 or greater is required
-
第7步的手动生成
netcdff.lib
很关键。应该是项目的bug,编译netcdff时不会在Debug目录中生成netcdff.lib
,会导致最终安装的文件没有该链接库文件,并且测试项目也不会通过(因为需要链接这个库文件,会报错fatal error LNK1104: 无法打开文件“..\fortran\Debug\netcdff.lib”
) -
cmake默认编译的是Debug版本,Release版本的编译方法如下(不再详细解释)
cd C:\Libs\netCDF-fortran\ cmake -S source -B build-release -DCMAKE_BUILD_TYPE:STRING=RELEASE -DnetCDF_LIBRARIES=C:/Libs/netCDF-c/4.9.1/lib/netcdf.lib -DnetCDF_INCLUDE_DIR=C:/Libs/netCDF/4.9.1/include -DCMAKE_INSTALL_PREFIX=C:/Libs/netCDF-fortran/Release cmake --build build-release --target netcdff netcdff_c --config Release cd build-release\fortran lib netcdff.dir\Release\*.obj netcdff_c.dir\Release\netcdff_c.lib /out:Release\netcdff.lib cd ..\..\ cmake --build build-release --target ALL_BUILD --config Release cmake --build build-release --target INSTALL --config Release
测试
在Visual Studio 新建一个fortran项目
- 在
项目
->属性
->Fortran
->Additional Include Directories
,添加C:\Libs\netcdf-fortran\Debug\inlude\Debug
- 在
项目
->属性
->Linker
->Additional Library Directories
,添加C:\Libs\netCDF-fortran\Debug\lib
和C:\Libs\netCDF-c\4.9.1\lib
- 在
项目
->属性
->Linker
->Input
->Additional Dependencies
,填写netcdff.lib netcdf.lib
PROGRAM testnc
USE netcdf
IMPLICIT NONE
INTEGER :: ncid, status
CHARACTER(len=*),parameter:: ncfile = "C:\Datasets\OSTIA\202202\20220201120000-UKMO-L4_GHRSST-SSTfnd-OSTIA-GLOB-v02.0-fv02.0.nc"
status = nf90_open(ncfile, nf90_nowrite, ncid)
call list_all_var(ncid)
END PROGRAM
SUBROUTINE list_all_var(fid)
USE netcdf
IMPLICIT NONE
INTEGER, Intent(IN) :: fid
INTEGER :: nVars, res, varid
CHARACTER(len=20)::var_name
res = nf90_inquire(fid, nVariables=nvars)
PRINT *,"所有变量:"
DO varid=1, nVars
res= nf90_inquire_variable(fid,varid,name=var_name)
print *, varid,". ",var_name
END DO
END SUBROUTINE
这个方案时使用intel x64 的终端编译的,使用时一定要注意这里的x64,