Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

From where does the value of argc and argv comes in the main function c++

Tags:

c++

I'm new to c++ and I've seen many c++ compilers automatically pass int argc,char* argv as parameters in main function but where are they defined? A little curious to know about.

like image 785
Agent_A Avatar asked Dec 18 '22 11:12

Agent_A


1 Answers

Please read a good C++ programming book, then see this C++ reference and some C++ standard like n3337 or better.

Your compiler (such as GCC) does not add argc and argv parameters to main. With gcc -Wall -Wextra -g it is checking that main has these arguments (but you could define int main(void) or int main(int argc, char**argv, char**environ) on Linux). What is important is the signature of main, not the exact name of the arguments (just their type and number).

Your operating system (e.g. Linux and its kernel) is passing these to your main. On Linux, a program is started by execve(2) and that system call passes argument to main. Technically, the initial layout of the call stack is specified in the ABI. Some crt0 initialization code is calling main (and static constructors). That initialization code is written in assembler. Read a good OS textbook.

Sometimes, C++ is used in a freestanding mode. Then, there is no main and other conventions apply. A typical example is when you code an operating system kernel in C++ (see OSDEV for examples)

Since GCC, the Linux kernel, and GNU libc are free software, you are allowed to download their source code and study it (and later improve it). See also LinuxFromScratch.

Study -for inspiration- the source code of existing C++ open source projects like Qt, FLTK, RefPerSys etc. For RefPerSys contact me by email to [email protected]

like image 107
Basile Starynkevitch Avatar answered May 24 '23 02:05

Basile Starynkevitch