Wrapping functions with macros (without renaming) C

前端 未结 2 1230
日久生厌
日久生厌 2021-01-29 02:29

Im interested to add in some extra logic around existing function calls, by wrapping them without renaming them. (just for a test).

The existin

2条回答
  •  无人共我
    2021-01-29 03:08

    For example, lets say I want to check the types on a function call.

    A simple case, I want to check that sqrt only takes (int or double), not float.

    Here is a method that works OK.

    /* add this to a header or at the top of the source-code */
    #include 
    static typeof(&sqrt) sqrt_wrap = sqrt;
    #define sqrt(f) (_Generic((f), int: sqrt_wrap, double: sqrt_wrap))(f)
    

    This works but has some drawbacks.

    • Must include , or at least define sqrt since we dont know if the static function is called or not.
    • Defines a function all over which may be unused. though __attribute__((__unused__)) works in works in GCC/Clang.
    • All output must have access to the function symbol, even if it ends up not using sqrt.

    Edit!


    This does in fact work, the header just needs to be included first (obviously - in retrospect)

    #include 
    #define sqrt(f) _Generic((f), int: sqrt(f), double: sqrt(f))
    

    Heres a trick to check sqrt isn't called with float and sqrtf isn't called with double

    #include 
    #define sqrt(X)  _Generic((X), float:  NULL, default: sqrt)(X)
    #define sqrtf(X) _Generic((X), double: NULL, default: sqrtf)(X)
    

提交回复
热议问题