I have some platform specific code, such as a string needs different values at different platforms like it:


    string url="android";
    string url="ios";

I am trying to rewrite platform specific code using separate cpp:


string url=URLHelper::getURL();


class URLHelper{
    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?

  • 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.
    – Caleth
    Commented May 27, 2016 at 8:46

1 Answer 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.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.