Linking libhdf5-dev with CMake

CMake links HDF5 into your C, C++, or Fortran program with just a few lines in your CMake file. I have an example CMake for writing network data to HDF5 in C CMakeLists.txt.

We can create an even simpler example below used with a simple HDF5 read/write example:

  1. prereqs
    apt install libhdf5-dev
    
  2. create CMakeLists.txt
    cmake_minimum_required (VERSION 3.1) #yes, CMake 3.1 is required
    project(myproj C)
    
    # https://gist.github.com/scienceopen/9f88bbe4841ea67aa692f7395bb38bfe
    
    add_executable(myprog ../myprog.c)
    
    find_package(HDF5 REQUIRED)
    include_directories(${HDF5_INCLUDE_DIR})
    target_link_libraries(myprog ${HDF5_C_LIBRARIES})
    

HDF5 C example

#include "hdf5.h"
#define FILE "dset.h5"

int main() {

   hid_t       file_id, dataset_id,dataspace_id; /* identifiers */
   herr_t      status;
   int         i, j, dset_data[4][6], read_data[4][6];
  hsize_t     dims[2];

   /* Initialize the dataset. */
   for (i = 0; i < 4; i++)
      for (j = 0; j < 6; j++)
         dset_data[i][j] = i * 6 + j + 1;

   /* Create a new file using default properties. */
   file_id = H5Fcreate(FILE, H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);

   /* Create the data space for the dataset. */
   dims[0] = 4; 
   dims[1] = 6; 
   dataspace_id = H5Screate_simple(2, dims, NULL);

   /* Create the dataset. */
   dataset_id = H5Dcreate2(file_id, "/dset", H5T_STD_I32BE, dataspace_id, 
                          H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);

   /* Write the dataset. */
   status = H5Dwrite(dataset_id, H5T_NATIVE_INT, H5S_ALL, H5S_ALL, H5P_DEFAULT, 
                     dset_data);

   /* End access to the dataset and release resources used by it. */
   status = H5Dclose(dataset_id);

//------------------------------------------------------

   /* Open an existing dataset. */
   dataset_id = H5Dopen2(file_id, "/dset", H5P_DEFAULT);


   status = H5Dread(dataset_id, H5T_NATIVE_INT, H5S_ALL, H5S_ALL, H5P_DEFAULT, 
                    read_data);

   for (i = 0; i < 4; i++)
      for (j = 0; j < 6; j++)
        printf("%d ",read_data[i][j]); // 1-24

   /* Close the dataset. */
   status = H5Dclose(dataset_id);

   /* Close the file. */
   status = H5Fclose(file_id);
}

Tags:

Categories:

Updated:

Leave a Comment