具有可选依赖项的 class 的 C++ 条件编译

C++ conditional compilation for a class with an optional dependency

我有一个 Rainfall class 其实现取决于 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

main.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++;
    }
}

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

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 中:>properties >C/C++ >Preprocessor >Preprocessor definitions.