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