mac上使用brew下载hdf及使用CLion开发时如何添加第三方库

博主 1989 2021-03-08

在mac上安装hdf十分简单,直接命令行敲入:

brew install hdf5

然后等待安装完成,至于如何安装brew请自行使用搜索引擎


我使用Clion进行hdf5的开发,想对着hdf官方文档敲一些例子
如下就是hdf5的helloworld案例,创建一个h5文件

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * Copyright by The HDF Group.                                               *
 * Copyright by the Board of Trustees of the University of Illinois.         *
 * All rights reserved.                                                      *
 *                                                                           *
 * This file is part of HDF5.  The full HDF5 copyright notice, including     *
 * terms governing use, modification, and redistribution, is contained in    *
 * the COPYING file, which can be found at the root of the source code       *
 * distribution tree, or in https://www.hdfgroup.org/licenses.               *
 * If you do not have access to either file, you may request a copy from     *
 * help@hdfgroup.org.                                                        *
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

/*
 *  This example illustrates how to create a dataset that is a 4 x 6
 *  array.  It is used in the HDF5 Tutorial.
 */

#include "hdf5.h"
#define FILE "file.h5"
#include "stdio.h"
int main() {

    hid_t       file_id;   /* file identifier */
    herr_t      status;

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

    /* Terminate access to the file. */
    status = H5Fclose(file_id);
    printf("%d", status);
}

然后编译运行报错
image.png
实际上就是没找到库文件。

解决方法:
打开我们的CMakeLists.txt文件
首先创建两个变量来分别代表头文件路径和库文件路径,homebrew安装的hdf路径在/usr/local/Cellar/hdf5下

#头文件路径
set(INC_DIR source /usr/local/Cellar/hdf5/1.12.0/include)
#库路径
set(LINK_DIR /usr/local/Cellar/hdf5/1.12.0/lib)

然后依次链接头文件路径和库文件路径

include_directories(${INC_DIR})
link_directories(${LINK_DIR})

以上需要放在add_executable之前

在add_executable后面添加

target_link_libraries(hdfLearning hdf5)

完成库的链接操作
hdfLearning 是工程名称 hdf5是库名称

完整Cmake文件如下:

cmake_minimum_required(VERSION 3.17)
project(hdfLearning C)

set(CMAKE_C_STANDARD 99)
#头文件路径
set(INC_DIR source /usr/local/Cellar/hdf5/1.12.0/include)
#库路径
set(LINK_DIR /usr/local/Cellar/hdf5/1.12.0/lib)

include_directories(${INC_DIR})
link_directories(${LINK_DIR})

add_executable(hdfLearning main.c)

target_link_libraries(hdfLearning hdf5)