G S Voelker
G S Voelker

Reputation: 3

Why does cmake give undefined references for netcdf with cygwin on windows?

I am trying to set up some model code on multiple operating systems using clion 2016.3-1 and its bundled cmake 3.6.2. On Windows I am using the cygwin environment but I ran into a linking issue I can not resolve. Here is a minimum example of my code:

#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);
}

Here is my 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})

However I get a lot of error messages similar to:

undefined reference to `nc_open'

The binaries and include files are all present in the cygwin environment at the respective folders. What am I missing?

Upvotes: 0

Views: 633

Answers (1)

LPs
LPs

Reputation: 16213

The errors are saying that linker could not find code for that functions: in other words the library is not reachable.

You should use the CMake target_link_libraries function to link netcdf lib.

remove

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

and add

target_link_libraries (test_examples netcdf) 

Upvotes: 1

Related Questions