c - 为什么 cmake 在 Windows 上使用 cygwin 为 netcdf 提供 undefined reference ?

标签 c cmake cygwin netcdf clion

我正在尝试使用 clion 2016.3-1 及其捆绑的 cmake 3.6.2 在多个操作系统上设置一些模型代码。 在 Windows 上,我使用 cygwin 环境,但遇到了无法解决的链接问题。这是我的代码的最小示例:

#include <stdlib.h>
#include <stdio.h>
#include <netcdf.h>

#define ERRCODE 2
#define ERR(e) {printf("Error: %s\n", nc_strerror(e)); exit(ERRCODE);}

int main() {
  int ncid, varid, dimid, retval;
  size_t nlat;
  char filepath[] = "minimumExample.nc";
  char dimname[64];
  double *latitudes;

  // open nc file
  if ((retval = nc_open(filepath, NC_NOWRITE, &ncid))) ERR(retval);

  // find variable IDs
  if ((retval = nc_inq_varid(ncid, "latitude", &varid))) ERR(retval);

  // find dimension bounds
  if ((retval = nc_inq_vardimid(ncid, varid, &dimid))) ERR(retval);
  if ((retval = nc_inq_dim(ncid, dimid, dimname, &nlat))) ERR(retval);

  // allocate data array
  latitudes = malloc(sizeof(double) * nlat);

  // get data
  if ((retval = nc_get_var_double(ncid, varid, &latitudes[0]))) ERR(retval);

  // close nc file
  if ((retval = nc_close(ncid))) ERR(retval);

  // free data array
  free(latitudes);

  return(0);
}

这是我的 CMakeLists.txt:

cmake_minimum_required(VERSION 3.3)
project(test_examples)

set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -lnetcdf")

include_directories("/usr/include")
link_directories("/usr/lib")

set(SOURCE_FILES main.c)

add_executable(test_examples ${SOURCE_FILES})

但是我收到很多类似于以下内容的错误消息:

undefined reference to `nc_open'

二进制文件和包含文件都存在于 cygwin 环境中的相应文件夹中。 我错过了什么?

最佳答案

错误表明链接器无法找到该函数的代码:换句话说,无法访问该库。

您应该使用CMake target_link_libraries链接 netcdf lib 的函数。

删除

set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -lnetcdf")

并添加

target_link_libraries (test_examples netcdf) 

关于c - 为什么 cmake 在 Windows 上使用 cygwin 为 netcdf 提供 undefined reference ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41220093/

相关文章:

c - 在适用于 Windows 和 Linux 的 C 中拖放

c - 将字符串填充到结构体指针数组中

c - 为什么我的服务器和客户端同时出现TIME_WAIT?

installation - 从源代码 Cmake 为 Scientific Linux 7.8 构建

c++ - 使用 CMake 编译 Eigen + Intel MKL

CLion、CMSIS 和错误 : "expected identifier or ' (' before ' __asm'"

Android Crypto++ 命令行编译,GNUmakefile

C: array type has incomplete element type 错误的外部数组

linux - gettext 编译在 cygwin 上的 crosstool-ng 构建中失败

android-ndk - 如何使用 Android NDK 解决有关 ffmpeg 的这种情况