我正在尝试使用 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/