2016年1月15日星期五

GCC 4.4.6 const char* to char* compiler error

今天在编译一个同事的代码发现一个小问题,就是报编译错误: error: invalid conversion from ‘const char*’ to ‘char*’,报错出在strstr这个函数,但是他原来编译又是ok的。猜测是GCC版本不一致导致的问题,一看果然是,他用的gcc 4.1.2,我用的gcc 4.4.6。但是为啥gcc 4.4.6编译会报错呢,查了一下gcc 手册:

Strict null-terminated sequence utilities

Some of the standard C++ library include files have been edited to use replacement overloads for some common C library functions (if available), with the goal of improving const-correctness: functions passed a const char* return const char*.
The table below shows the functions and files that have been changed.
HeaderFunctions
<cstring>strchrstrpbrkstrrchrstrstrmemchr
<cwchar>wcschr wcspbrkwcsrchrwcsstrwmemchr
An example.
#include <cstring>

const char* str1;
char* str2 = strchr(str1, 'a');
Gives the following compiler error:
error: invalid conversion from ‘const char*’ to ‘char*’
Fixing this is easy, as demonstrated below.
#include <cstring>

const char* str1;
const char* str2 = strchr(str1, 'a');
More information about the C++ standard requirements can be found in chapter 21, section "Null-terminated sequence utilities."

链接:https://gcc.gnu.org/gcc-4.4/porting_to.html
=====

原来是C++的标准库头文件有变化,目标是“improving const-correctness”,其中就有strstr这个函数。好吧,在原来的代码修改了加了强制转化就ok了。