int main(int argc, char* argv[])
or int main(int argc, char** argv)
1. Overview
argc
: argument countargv
: argument value which is an array of string- In C++ we have
std::string
, equivalent in C we havechar*
- A string “abc” is an array of characters {‘a’, ’b’, ’c’}
- An array is a pointer which points to the 1st character in the array thus
char[]
equalchar*
- As argv is an array of “string”, or we can say is an array of “array of characters”, so it’s a 2 dimensional pointer
// we could use both ways
int main(int argc, char** argv)
int main(int argc, char *argv[])
2. Code
- Create the “test.cpp” file
/*
#include <stdio.h> : is the header file in the C standard library. It is used for input/output printf(), scanf() (in C++, stdio.h became cstdio)
#include <iostream> : is the input output class in C++ and objects (std::cout, std::cin...).
So if you're using C++ just use #include <iostream>
*/
#include <iostream>
int main(int argc, char *argv[])
{
for(int i = 0; i < argc; i++)
{
printf("Argument[%d] : %s\n",i, argv[i]);
}
return 0;
}
- Compile the source
// std::cout, ... is present in the C++ standard library, which would need explicit linking with -lstdc++ when using gcc; g++ links the standard library by default.
gcc test.cpp -lstdc++ -o test
// or we could use g++ which is preferred over gcc
g++ -Wall -Wextra -Werror -c test.cpp -o tes
- Testing
btnguyen@DESKTOP-UAIA29B:/mnt/h/DEVELOPER/Linux/prog$ gcc test.cpp -lstdc++ -o test
btnguyen@DESKTOP-UAIA29B:/mnt/h/DEVELOPER/Linux/prog$ ./test
Argument[0] : ./test
btnguyen@DESKTOP-UAIA29B:/mnt/h/DEVELOPER/Linux/prog$ ./test a b 1 2 hello
Argument[0] : ./test
Argument[1] : a
Argument[2] : b
Argument[3] : 1
Argument[4] : 2
Argument[5] : hello
btnguyen@DESKTOP-UAIA29B:/mnt/h/DEVELOPER/Linux/prog$ echo $?
0
btnguyen@DESKTOP-UAIA29B:/mnt/h/DEVELOPER/Linux/prog$
NOTE
- The first argument value is the path of your program
- In the older C++, we could define a
void main()
, but in the later it requires to define aint main()
which should return a value - The returned value could be any number, but usually 0 which means no error
- The returned value will be read by the OS, we also could see the returned value by
echo $?
btnguyen@DESKTOP-UAIA29B:/mnt/h/DEVELOPER/Linux/prog$ echo $?
0
btnguyen@DESKTOP-UAIA29B:/mnt/h/DEVELOPER/Linux/prog$
3. Bonus
- Instead of opening a terminal then typing the command, we could do it directly in code C.
int system(const char* command)
- The
system()
will fork a child process to execute your command. - The cons of
system()
is slow, and we can’t control the error because the returned value ofsystem()
is not the status of a child process but just means it executed the command.