Reputation: 9893
I have a Rainfall
class whose implementation depends on NetCDF, but the project should be compilable with or without NetCDF. Can I achieve conditional compilation without sprinkling preprocessor directives all over the code? What's the best practice in this situation?
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++;
}
}
Upvotes: 1
Views: 676
Reputation: 124
If you want a project that can be compiled with or without a specified library, you need to have two implementations
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
And in your project, you must define the USE_NETCDF macro if you want to use this lib. For example in visual studio : >properties >C/C++ >Preprocessor >Preprocessor definitions.
Upvotes: 1