How to use VC++ intrinsic functions w/o run-time library

后端 未结 6 496
夕颜
夕颜 2020-12-13 02:44

I\'m involved in one of those challenges where you try to produce the smallest possible binary, so I\'m building my program without the C or C++ run-time libraries

6条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-13 03:10

    I think I finally found a solution:

    First, in a header file, declare memset() with a pragma, like so:

    extern "C" void * __cdecl memset(void *, int, size_t);
    #pragma intrinsic(memset)
    

    That allows your code to call memset(). In most cases, the compiler will inline the intrinsic version.

    Second, in a separate implementation file, provide an implementation. The trick to preventing the compiler from complaining about re-defining an intrinsic function is to use another pragma first. Like this:

    #pragma function(memset)
    void * __cdecl memset(void *pTarget, int value, size_t cbTarget) {
        unsigned char *p = static_cast(pTarget);
        while (cbTarget-- > 0) {
            *p++ = static_cast(value);
        }
        return pTarget;
    }
    

    This provides an implementation for those cases where the optimizer decides not to use the intrinsic version.

    The outstanding drawback is that you have to disable whole-program optimization (/GL and /LTCG). I'm not sure why. If someone finds a way to do this without disabling global optimization, please chime in.

提交回复
热议问题