'using #if to run a function

I'm trying to run the expression _setmode only if I'm using Windows, and setlocale only if I'm using Linux, but I can't manage to make them work with a simple if-else inside a function due to Linux having errors with the Windows libraries, and vice versa.

#if defined(_WIN32) || defined(_WIN64) || (defined(__CYGWIN__) && !defined(_WIN32))
#define PLATFORM_NAME 0
#include <io.h>
#include <fcntl.h>
#elif defined(__linux__)
#define PLATFORM_NAME 1
#include <locale>
#elif defined(__APPLE__) && defined(__MACH__)
#include <TargetConditionals.h>
#if TARGET_OS_MAC == 1
#define PLATFORM_NAME 2
#endif
#else
#define PLATFORM_NAME NULL
#endif

#if PLATFORM_NAME == 0
    _setmode(_fileno(stdout), _O_U8TEXT);
#endif
#if PLATFORM_NAME == 1
    setlocale(LC_CTYPE, "");
#endif


Solution 1:[1]

If you write OS-dependent* code (as in this case), you can manage it at compile-time**. To do this, we need two parts:

  1. Define OS-dependent constants (optional, if condition simple, this part can be omitted):
    #if defined(_WIN32)
    #define PLATFORM_NAME 0
    #include <fcntl.h>
    #include <io.h>
    #elif defined(__linux__)
    #define PLATFORM_NAME 1
    #include <locale>
    #endif
  1. In needed place call OS-dependent code with preprocessor conditions:
    #if PLATFORM_NAME == 0
        //Windows code here
    #endif

You can write more complex conditions:

    #if PLATFORM_NAME == 0
        //Windows code here
    #elif PLATFORM_NAME != 0
        //Non-Windows code here
        #if PLATFORM_NAME == 1 || PLATFORM_NAME == 2
        //Linux or unknown OS code here
        #endif
    #endif

See restrictions of conditions here

Tip: If your code have entrypoint (main function as example), you can call most of OS-dependent code at main if this help to reduce code. In library you can place OS-dependent code to dedicated source-file functions like there. Usage preprocessor-time code is good method for writing zero-cost runtime code because of preprocessor just remove all sources,if they're not met conditions.

* - or whatever-dependent ?

** - more precisely, preprocessor-time

Source: GNU, Microsoft docs.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Avatar Mod