C言語の警告: ISO C++ forbids converting a string constant to ‘char*’ [-Wwrite-strings]

# make -f testmain.mk
g++ -c -g3 -O0 -fPIC -Wno-deprecated -m64 -mtune=generic -mcmodel=small ../src/testmain.c -o ../obj/testmain.o
../src/testmain.c: 関数 ‘char* getConst()’ 内:
../src/testmain.c:5:18: 警告: ISO C++ forbids converting a string constant to ‘char*’ [-Wwrite-strings]
 #define CONST_RC "RC_0001"
                  ^~~~~~~~~
../src/testmain.c:8:10: 備考: in expansion of macro ‘CONST_RC’
   return CONST_RC;
          ^~~~~~~~
g++ -m64 ../obj/testmain.o -o ../obj/testmain

文字列リテラル"RC_0001"はconst char*なので、char*へconvertするのに警告となっている。

# cat testmain.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define CONST_RC "RC_0001"

char* getConst() {
  return CONST_RC;
}

int main(int argc, char *argv[]) {
  char* rc = getConst();
  printf("rc=%s\n",rc);
  return 0;
}

↓以下のようにcastすれば警告は解消する。
#define CONST_RC "RC_0001"

char* getConst() {
  return (char*)CONST_RC;
}

# make -f testmain.mk
g++ -c -g3 -O0 -fPIC -Wno-deprecated -m64 -mtune=generic -mcmodel=small ../src/testmain.c -o ../obj/testmain.o
g++ -m64 ../obj/testmain.o -o ../obj/testmain

コメント

人気の投稿