Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get rid of `deprecated conversion from string constant to ‘char*’` warnings in GCC?

Tags:

c++

string

gcc

I'm working on an exceedingly large codebase, and recently upgraded to GCC 4.3, which now triggers this warning:

warning: deprecated conversion from string constant to ‘char*’

Obviously, the correct way to fix this is to find every declaration like

char *s = "constant string";

or function call like:

void foo(char *s);
foo("constant string");

and make them const char pointers. However, that would mean touching 564 files, minimum, which is not a task I wish to perform at this point in time. The problem right now is that I'm running with -Werror, so I need some way to stifle these warnings. How can I do that?

like image 600
Josh Matthews Avatar asked Sep 12 '08 18:09

Josh Matthews


3 Answers

Any functions into which you pass string literals "I am a string literal" should use char const * as the type instead of char*.

If you're going to fix something, fix it right.

Explanation:

You can not use string literals to initialise strings that will be modified, because they are of type const char*. Casting away the constness to later modify them is undefined behaviour, so you have to copy your const char* strings char by char into dynamically allocated char* strings in order to modify them.

Example:

#include <iostream>

void print(char* ch);

void print(const char* ch) {
    std::cout<<ch;
}

int main() {
    print("Hello");
    return 0;
}
like image 179
John Avatar answered Nov 01 '22 03:11

John


I believe passing -Wno-write-strings to GCC will suppress this warning.

like image 35
DGentry Avatar answered Nov 01 '22 02:11

DGentry


I had a similar problem, and I solved it like this:

#include <string.h>

extern void foo(char* m);
 
int main() {
    // warning: deprecated conversion from string constant to ‘char*’
    //foo("Hello");
   
    // no more warning
    char msg[] = "Hello";
    foo(msg);
}

I did not have access to foo in order to adapt it to accept const char*, which would be a better solution because foo did not change m.

like image 74
BlackShift Avatar answered Nov 01 '22 03:11

BlackShift