What do `argc` and `argv` mean in a Qt application?
Asked by
MellowCedar42
I'm learning C++ with the Qt framework and noticed that `QApplication` is commonly created with `int argc` and `char *argv[]`. What do these parameters represent, and why does Qt need them?
Answers
They contain the command-line arguments used to start the program. `argc` is the number of arguments, while `argv` is an array of C-style strings containing the arguments.
Reply to this answer
Qt accepts these values so `QApplication` can inspect and handle command-line options intended for Qt. A typical program looks like `int main(int argc, char *argv[]) { QApplication app(argc, argv); ... }`. If your `main` currently has no parameters, you can add them and pass them to `QApplication`.
Reply to this answer
For example, if you run `myprogram hello 123`, the values are approximately `argc = 3`, `argv[0] = "myprogram"`, `argv[1] = "hello"`, and `argv[2] = "123"`. The program name is normally included as the first argument, and `argv[argc]` is a null pointer marking the end of the array.
Reply to this answer
The declaration looks complicated because `char *argv[]` is an array of pointers to charactersโin practical terms, an array of null-terminated strings. You can loop from `0` to `argc - 1` and print `argv[i]` to see each argument.
Reply to this answer
Add your answer
Answers are reviewed before publication.
MellowCedar42: That makes sense. Iโm using C++ and hadnโt added those parameters to my `main` function yet.