Search code examples
ctypedef

Is there a way to typedef a function to modify argument in C?


I have code that needs to call sleep for both windows and linux.

In an attempt to avoid placing ifdefs everywhere there is a Sleep I did the following

typedef Sleep sleep

The issue with this is windows takes Sleep in microseconds and linux takes sleep in seconds. Is there a way to do something like this pseudo-code.

typedef Sleep(x) sleep(x/1000)

Solution

  • No, you cannot use a typedef for this purpose.

    However, you can write the following preprocessor macro:

    #if defined( _WIN32 ) || defined( _WIN64 )
    #define MY_SLEEP_MACRO( x ) Sleep(x)
    #else
    #define MY_SLEEP_MACRO( x ) sleep((x)/1000)
    #endif
    

    Now, in your code, you can simply call MY_SLEEP_MACRO( 5000 ); in order to wait 5 seconds on both platforms.