c++ - strings.h 并用宏检查包装这个宏是否

标签 c++ unix macros

我从 Google 搜索结果中推断出 strings.h(来自 here)适用于 UNIX 系统。我想用主机操作系统是否为 Linux/UNIX 的宏观检查来包装以下行。听到有关它的建议将不胜感激。提前致谢。

#include <strings.h>

最佳答案

strings.h 只包含几个函数,其中大部分只是标准库中函数的不同名称(例如 bcmp() <--> memcmp())。如果您的代码使用这些函数,而不是到处乱扔 #ifdef 为什么不编写您自己的集合呢?

然后每个人都可以使用它们并愉快地免费进行条件编译。

这是公共(public)领域中的一组未完全测试的函数,您可以自行承担使用风险:

#include <string.h>
#include <ctype.h>

int bcmp(const void * p1, const void * p2, size_t n)
{
    return memcmp( p1, p2, n);
}

void   bcopy(const void * src, void * dst, size_t n)
{
    memmove( dst, src, n);  /* note different order of args - yuck */
}

void   bzero(void * p, size_t n)
{
    memset( p, 0, n);
}

char   *index(const char * s, int c)
{
    return strchr( s, c);
}

char   *rindex(const char * s, int c)
{
    return strrchr( s, c);
}

int    strcasecmp(const char* s1, const char* s2)
{
    for (;;) {
        int c1 = tolower( *((unsigned char*) s1++));
        int c2 = tolower( *((unsigned char*) s2++));

        if ((c1 != c2) || (c1 == '\0')) {
            return( c1 - c2);
        }
    }
}

int    strncasecmp(const char* s1, const char* s2, size_t n)
{
    for (; n != 0; --n) {
        int c1 = tolower( *((unsigned char*) s1++));
        int c2 = tolower( *((unsigned char*) s2++));

        if ((c1 != c2) || (c1 == '\0')) {
            return( c1 - c2);
        }
    }

    return( 0);
}


int    ffs(int v)
{
    unsigned int x = v;
    int c = 1;

    /* 
     * adapted from from 
     *      http://graphics.stanford.edu/~seander/bithacks.html#ZerosOnRightBinSearch
     *
     * a modified binary search algorithm to count 0 bits from 
     *  the right (lsb).  This algorithm should work regardless 
     *  of the size of ints on the platform.
     *
     */

    /* a couple special cases */
    if (x == 0) return 0;
    if (x & 1)  return 1;   /* probably pretty common */

    c = 1;
    while ((x & 0xffff) == 0) {
        x >>= 16;
        c +=  16;
    }
    if ((x & 0xff) == 0) {
        x >>= 8;
        c +=  8;
    }
    if ((x & 0x0f) == 0) {
        x >>= 4;
        c +=  4;
    }
    if ((x & 0x03) == 0) {
        x >>= 2;
        c +=  2;
    }

    c -= (x & 1);
    c += 1;     /* ffs() requires indexing bits from 1 */
                /*   ie., the lsb is bit 1, not bit 0  */
    return c;
}

关于c++ - strings.h 并用宏检查包装这个宏是否,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1647723/

相关文章:

c++ - 在 Ctor 调用中将 std::initializer_list 与括号括起来的参数分开

c++ - C++ 中的保存形式(对于普通人来说易于阅读和修改)

c++ - boost 日志 - 使用severity_channel_logger进行格式化

c - gcc 宏中的类型检查和类型衰减

c - 在c中,宏__FILE __,__ LINE__和__PRETTY_FUNCTION__是否分配内存?

ms-access - 在 access 中从 VBA 调用嵌入宏

c++ - 删除所有动态内存后出现 valgrind 泄漏错误

unix - 什么是文件描述符,用简单的术语解释一下?

linux - 在另一个文件中查找一个文件的内容

windows - SSH Windows 到 UNIX