ld:找不到-lnetcdf的库

问题描述

我是CMake的新手。我无法解决当前的错误。有人可以帮我吗?

------------错误--------------

ld: library not found for -lnetcdf
collect2: error: ld returned 1 exit status
make[3]: *** [NUP] Error 1
make[2]: *** [CMakeFiles/NUP.dir/all] Error 2
make[1]: *** [CMakeFiles/NUP.dir/rule] Error 2
make: *** [NUP] Error 2

------------------- CMake文件------------------

cmake_minimum_required(VERSION 3.10.0)
project(NUP Fortran)
enable_language(Fortran)

set(INCLUDE_FILE /usr/local/Cellar/netcdf/4.7.4/include)
set(lib_FILE /usr/local/Cellar/netcdf/4.7.4/lib)
find_package(netcdf  required)
if(netcdf_FOUND)
include_directories(${INCLUDE_FILE})

set(
        SOURCE_FILES
        ${PROJECT_BINARY_DIR} unpack.f90
)

add_executable(NUP ${SOURCE_FILES} )
target_link_libraries(NUP netcdf)
endif()

-------------- unpack.f90 -------------------

PROGRAM unpack_array

  IMPLICIT NONE
  INCLUDE 'netcdf.inc'

  INTEGER,ParaMETER :: dp = SELECTED_REAL_KIND(12,307)
......

我正在使用MACOS Catalina。 Apple clang版本11.0.3(clang-1103.0.32.59) 目标:x86_64-apple-darwin19.4.0

解决方法

如果使用find_package()在计算机上查找NetCDF,则无需手动指定路径。让find_package为您做到这一点。

注意:CMake不附带NetCDF的Find Module,因此您必须从Internet下载一个(如this one)。然后,您需要告诉CMake使用FindNetCDF.cmake在系统上将这个CMAKE_MODULE_PATH文件放在哪里。最后,您可以使用NetCDF::NetCDF imported 目标将NetCDF链接到项目的目标。

cmake_minimum_required(VERSION 3.10.0)
project(NUP Fortran)
# Don't need this,you already enabled Fortran above in the 'project' call.
enable_language(Fortran)

set(INCLUDE_FILE /usr/local/Cellar/netcdf/4.7.4/include)
set(lib_FILE /usr/local/Cellar/netcdf/4.7.4/lib)

# Add the location of the 'FindNetCDF.cmake' file to your module path.
list(APPEND CMAKE_MODULE_PATH "/path/to/downloaded/find/module")
# Then,call find package for NetCDF. 
find_package(NetCDF REQUIRED)

if(${NetCDF_FOUND})
    # Don't need this if you use the imported target below.
    include_directories(${INCLUDE_FILE})

    # Don't provide directories with source file list.
    set(SOURCE_FILES
        ${PROJECT_BINARY_DIR} 
        unpack.f90
    )

    add_executable(NUP ${SOURCE_FILES})

    # Use the imported target to link netcdf instead.
    target_link_libraries(NUP PRIVATE NetCDF::NetCDF)
endif()

如前所述,还有其他方法可以将NetCDF添加到CMake项目中。如果使用不同查找模块,则提供的NetCDF CMake变量和导入的目标的语法可能会略有不同。您必须检查查找模块文件本身。

此外,您可以使用从互联网下载的CMake 软件包配置文件(例如netCDFConfig.cmake)将NetCDF添加到您的项目中。在这种情况下,您仍将使用find_package(),但是将使用CMAKE_PREFIX_PATH而不是CMAKE_MODULE_PATH指定配置文件的位置。

您可以在CMake find_package()文档中找到每种方法的详细描述。我强烈建议您花一些时间阅读它。