问题
I am working on MacOS-X Lion with GCC 4.2. This code works, but I get a warning I would like fix:
#include <unistd.h>
main()
{
char *args[] = {"/bin/ls", "-r", "-t", "-l", (char *) 0 };
execv("/bin/ls", args);
}
warning: deprecated conversion from string constant to 'char*'
I do not want the warning to be suppressed, I want not to have it at all. It is C++ code, not C.
Using a char *const (so exactly the type required by execv()) still produces the warning.
Thank you.
回答1:
This seems to be ok:
#include <unistd.h>
main()
{
char const *args[] = {"/bin/ls", "-r", "-t", "-l", NULL };
execv("/bin/ls", const_cast<char**>(args));
}
回答2:
You are converting a string constant to a mutable character pointer, change using an implicit cast, the compiler is warning you that newer versions of the language will not allow this cast.
When defining a string litteral c++ understands it to mean a constant character array you have defined it as a mutable character array, change your code accordingly.
回答3:
Change:
char *args[] = {"/bin/ls", "-r", "-t", "-l", (char *) 0 };
To:
char *const args[] = {"/bin/ls", "-r", "-t", "-l", NULL };
回答4:
The only reason you get the warning is that you're using g++, not gcc. In pure C, you'd get absolutely no warnings. It's actually quite difficult to create warning-free C++ code from this. To be honest, I tried but did not succeed.
These hurdles are one of the reasons for the existence of a certain philosophical school. See more here.
回答5:
I do not know why the accepted answer was selected, it does not remove any warnings when I run this code....
I cannot confirm on your specific platform, but adding casts to each string constant has made the warnings go away for me.
#include <unistd.h>
main()
{
char* const args[] = {(char*)"/bin/ls", (char*)"-r", (char*)"-t", (char*)"-l", (char*) 0 };
execv("/bin/ls", args);
}
OR
#include <unistd.h>
main()
{
char *args[] = {(char*)"/bin/ls", (char*)"-r", (char*)"-t", (char*)"-l", (char*) 0 };
execv("/bin/ls", args);
}
It may be overly verbose and annoying, but the warnings go away.
I'm running this on: g++ (Ubuntu 4.8.4-2ubuntu1~14.04) 4.8.4
回答6:
change
char *args[] = {"/bin/ls", "-r", "-t", "-l", (char *) 0 };
to
char args[] = {(char*)"/bin/ls", (char*)"-r", (char*)"-t", (char*)"-l", 0 };
for usability u may will make a simple convert method.
来源:https://stackoverflow.com/questions/10790719/how-to-use-execv-without-warnings