How to use execv() without warnings?

2019-02-11 00:47发布

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.

6条回答
ら.Afraid
2楼-- · 2019-02-11 01:10

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

查看更多
\"骚年 ilove
3楼-- · 2019-02-11 01:13

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.

查看更多
孤傲高冷的网名
4楼-- · 2019-02-11 01:17

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));
}
查看更多
甜甜的少女心
5楼-- · 2019-02-11 01:22

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.

查看更多
三岁会撩人
6楼-- · 2019-02-11 01:23

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.

查看更多
Melony?
7楼-- · 2019-02-11 01:25

Change:

char *args[] = {"/bin/ls", "-r", "-t", "-l", (char *) 0 };

To:

char *const args[] = {"/bin/ls", "-r", "-t", "-l", NULL };
查看更多
登录 后发表回答