mercredi 1 mars 2017

X legacy code with g++: ISO C++ forbids converting a string constant to 'char*'

The attached code creates problems when compiled with g++ as indicated. 1) Why does const char* (and char const*) work while const String does not, where String is typdef'd to char*? 2) In the second code snippet, how to avoid the warning? I cannot change the struct XrmOptionDescRec. It is defined at X11/Xresource.h from lib1-dev.

#include <unistd.h>
#include <stdio.h>

//From: libxt-dev: /usr/include/X11/Intrinsic.h
typedef char* String;
typedef char *XPointer;

typedef enum {
  XrmoptionSepArg
} XrmOptionKind;

// From: libx11-dev: /usr/include/X11/Xresource.h
typedef struct {
  char *option;
  char *specifier;
  XrmOptionKind argKind;
  XPointer value;
} XrmOptionDescRec;

typedef struct {
  const char *option;
  const char *specifier;
  XrmOptionKind argKind;
  XPointer value;
} const_XrmOptionDescRec;

int main(void)
{
/*
Causes compiler warnings:
ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]
static const String fallbackResources[] = {
*/

/* Works fine */
  static const char* fallbackResources[] = {
  "*.zoomComboBox*fontList: -*-helvetica-medium-r-normal--12-*-*-*-*-*-iso8859-1",
  "*XmTextField.fontList: -*-courier-medium-r-normal--12-*-*-*-*-*-iso8859-1",
  NULL
};
  printf ("fallbackResources[1]=%s\n",fallbackResources[1]); 

/*
Causes compiler warnings:
ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]
static XrmOptionDescRec xOpts[] = {
*/
/* Works fine */
  static const_XrmOptionDescRec xOpts[] = {
  {"-display",       ".display",         XrmoptionSepArg,  NULL},
  {"-foreground",    "*Foreground",      XrmoptionSepArg,  NULL}
};
   printf ("xOpts[1]=%s, %s, %d, %p\n", xOpts[1].option, xOpts[1].specifier, xOpts[1].argKind, xOpts[1].value);

Aucun commentaire:

Enregistrer un commentaire