1

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?

asked May 27, 2016 at 8:23
1
  • I would suggest that you decorate these methods as constexpr as they are returning from literals, an a better grouping would be all together in a PlatformConsts class, rather than one class per constant. Then it is really obvious these are platform specific constants. Commented May 27, 2016 at 8:46

1 Answer 1

4

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.

answered May 27, 2016 at 8:59

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.