Search code examples
c++argc

c++ main function, argc value is weird if command-line arguments contain *


A very simple piece of C++ code like this:

int main(int argc, char **argv){
    std::cout << "argc: " << argc << std::endl;
}

Compiled with g++ -o hello hello.cpp

  • when run with ./hello u, output is argc: 2;
  • when run with ./hello u +, output is argc: 3;
  • when run with ./hello u *, output is argc: 26, why 26?

Solution

  • Shell expansion. * is expanded by the shell into all files in the current directory, of which there appear to be 24, and passes them as individual arguments to your program.

    Since this looks like a call from a UNIX shell, use

    ./hello u \*
    

    or

    ./hello u '*'