How to use execv() without warnings?

前端 未结 6 1815
半阙折子戏
半阙折子戏 2021-01-03 07:46

I am working on MacOS-X Lion with GCC 4.2. This code works, but I get a warning I would like fix:

#include 
main()
{
    char *args[] = {\"/b         


        
相关标签:
6条回答
  • 2021-01-03 08:11

    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.

    0 讨论(0)
  • 2021-01-03 08:21

    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.

    0 讨论(0)
  • 2021-01-03 08:27

    Change:

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

    To:

    char *const args[] = {"/bin/ls", "-r", "-t", "-l", NULL };
    
    0 讨论(0)
  • 2021-01-03 08:29

    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.

    0 讨论(0)
  • 2021-01-03 08:35

    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));
    }
    
    0 讨论(0)
  • 2021-01-03 08:37

    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

    0 讨论(0)
提交回复
热议问题