【问题标题】:C++ conditional compilation for a class with an optional dependency具有可选依赖项的类的 C++ 条件编译
【发布时间】:2020-04-07 16:18:18
【问题描述】:

我有一个 Rainfall 类,它的实现依赖于 NetCDF,但无论是否使用 NetCDF,该项目都应该可以编译。我可以在不将预处理器指令洒在整个代码中的情况下实现条件编译吗?在这种情况下,最佳做法是什么?

rainfall.hpp

#pragma once

class Rainfall {
public:
    // several constructors, methods, and destructor
private:
    // several methods and variables
};

rainfall.cpp

#include "rainfall.hpp"
#include <netcdf.h>

// concrete implementation of class members

ma​​in.cpp

#include "rainfall.hpp"
#include <stdio>
#include <cstdlib>

void main_loop();

int main(int argc, char* argv[]) {
    if (user_wants_rainfall) {
#ifndef NETCDF
        std::cerr << "Rainfall not available: project was not compiled with NetCDF\n";
        return EXIT_FAILURE;
#endif
    }

    main_loop();

    return EXIT_SUCCESS;
}

void main_loop() {
    Rainfall rainfall;
    while (t < end_time) {
        if (user_wants_rainfall) rainfall.apply_to_simulation();
        t++;
    }
}

【问题讨论】:

  • 您可以链接到一个虚拟库,该库定义了您用作存根的所有 NetCDF 入口点。
  • Null_object_pattern 你可能会感兴趣。
  • 这将取决于代码、所需的更改和代码的复杂性。我已经完成了维护预处理器以启用/禁用功能的大量代码。我觉得你可以使用预处理器,因为它看起来并不多。
  • @Jarod42 这就是我所采用的模式:makefile 编译雨量.cpp 或雨量存根.cpp,两者都定义了雨量.hpp 的实现。唯一的障碍是记住在添加新班级成员时更新这两个文件。

标签: c++ conditional-compilation


【解决方案1】:

如果你想要一个可以编译或不使用指定库的项目,你需要有两个实现

rainfall_netcdf.cpp

#ifdef USE_NETCDF
#include "rainfall.hpp"
#include <netcdf.h>
//your definitions using your lib
#endif //USE_NETCDF

rainfall.cpp

#ifndef USE_NETCDF
#include "rainfall.hpp"
//your definitions without your lib
#endif //USE_NETCDF

并且在你的项目中,如果你想使用这个库,你必须定义 USE_NETCDF 宏。例如在 Visual Studio 中:>属性 >C/C++ >预处理器 >预处理器定义。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-21
    相关资源
    最近更新 更多