从C代码库中对C ++中的unsigned char *进行strchr的微创改变?

时间:2012-12-16 22:34:11

标签: c++ c unsigned-char strchr

我正在尝试将C代码库编译为C ++,调整一些包含。它在unsigned char指针上使用strchr(),例如:

#include <string.h>
#include <stdio.h>

// Cannot modify this file with any non-C-isms, but let's say an include can
// be changed (although all things being equal I'd rather not)
#include <SomethingICanChange.h>

int main(int argc, char* argv[]) {
    unsigned char b = 'B';
    unsigned char const * str = "ABC";
    unsigned char const * pos = strchr(str, b);
    if (pos) {
        printf("position is %d\n", pos - str);
    }
    return 0;
}

这导致C ++出错(出于其他地方解释的原因)......即使使用-fpermissive

test.c: In function ‘int main(int, char**)’:
test.c:6:33: warning: invalid conversion from ‘const char*’ to ‘const unsigned char*’ [-fpermissive]
test.c:7:46: error: call of overloaded ‘strchr(const unsigned char*&, unsigned char&)’ is ambiguous
test.c:7:46: note: candidates are:
In file included from test.c:1:0:
/usr/include/string.h:215:14: note: char* strchr(char*, int) <near match>
/usr/include/string.h:215:14: note:   no known conversion for argument 1 from ‘const unsigned char*’ to ‘char*’
/usr/include/string.h:217:22: note: const char* strchr(const char*, int) <near match>
/usr/include/string.h:217:22: note:   no known conversion for argument 1 from ‘const unsigned char*’ to ‘const char*’

通常在面对这种事情时,我会去“strchr,yuck,只是完全摆脱它”。但我不想自己修改这些文件,这是C代码,它保持非常便携,而不是旧平台。他们不会很高兴把演员阵容放在呼吁上来安抚C ++ ......虽然如果一个“struchr”存在并且是标准的,他们可能会使用它。

我也可以用这种或那种方式解决它,比如SomethingICanChange.h我可以添加:

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

适用于-fpermissive。但我无法检查C代码库中的重载(好吧,没有#ifdef)。只是想知道是否有人有更好的想法,我会添加struchr,如果这就是这种情况下的人最终会做什么(或者如果有一个共同的名字是常见的。)

1 个答案:

答案 0 :(得分:2)

初步说明:我知道这也是一个非常丑陋的事情,但它可能会帮助你(希望)更好的想法!

如何使用宏:

#define strchr(s, c) ((unsigned char const *)strchr((char const *)s, c))

您可以从Makefile / build脚本中将其包含为编译标志(-D)。我想你有一个C ++项目的自定义Makefile / build脚本,所以你不需要将这个宏添加到C代码库。

为了使稍微更好,您可以使用Makefile / build脚本中包含的其他文件,该文件以(更)结构化的方式将这些宏添加到CPPFLAGS