I have some platform specific code, such as a string needs different values at different platforms like it:
test.cpp
#if(PLATFORM==ANDROID)
string url="android";
#elif(PLATFORM==IOS)
string url="ios";
#endif
I am trying to rewrite platform specific code using separate cpp:
test.cpp
string url=URLHelper::getURL();
URLHelper.h
class URLHelper{
public:
static std::string getURL();
};
URLHelper.cpp (in android only path)
#include "URLHelper.h"
std::string URLHelper::getURL(){
return "android";
}
URLHelper.cpp (in iOS only path)
#include "URLHelper.h"
std::string URLHelper::getURL(){
return "ios";
}
I found it requires far more lines of codes than the original one and looks less straight forward. Also, more files are created, makes me feel it is more difficult to maintain. And imagine if I have other variables need different values at different platform, by following this rule, I would need one more method (or even one more cpp file) for each variable.
My question is, when writing platform specific code, should we always use separate .cpp file instead of #ifdef even using #ifdef seems simpler? Is it acceptable to just leave #ifdef sometimes?
1
For trivial examples, any form of additional overhead will appear massive.
The benefit of separating into TUs is that you know that everything in the file is specific for the platform and you can use platform functionality in convenience functions without having to be careful about surgically placing it in the correct preprocessor sections.
This also helps when reading the code, as you don’t need to stare at each preprocessor block to tell if it applies to a platform of interest or not, particularly as the number of branches in a block and their order will rot over time.