create my own main function

I would like to understand how the main function works with argument argc and argv.
So I try and create my own but it doesn't works.


1
2
3
4
5
6
7
8
int myownmain ( int argc, char*argv[]){

char**argv=new char*[argc];
for(int i=0;i<argc;i++){
argv[i]=new char*;
cin>>argv[i]
}
You can't create your own main function. Don't even try.

https://en.cppreference.com/w/cpp/language/main_function
But his function should 'work' though its a normal function. Nothing special about the variable names.

what does not work is renaming your parameter locally.
and it won't work as a 'main' so there may not be any point in fixing that, but you can't redefine your parameters in the body.


basically, the OS has an entry point to all programs that say 'start here'. You can't hijack that in c++, and doing so on most OS is going to be nothing but trouble if you manage to do it in assembly or something.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <iostream>
#include <iomanip>

int my_own_main( int argc, char* argv[] )
{
    std::cout << "my_own_main:\n-----------\n\nargc == "
              << argc << " (number of arguments)\n\n" ;

    for( int i = 0 ; i < argc ; ++i )
        std::cout << "argv[" << i << "] == " << std::quoted( argv[i] ) << '\n' ;

    if( argv[argc] != nullptr )
        std::cout << "*** error: argv[" << argc << "] should be nullptr\n" ;

    // the main function need not contain an explicit return statement
    // (implicit return 0 if no return statement is encountered)
    // however, my_own_main must contain a return statement
    return 0 ;
}

int main()
{
    char program_name[] = "the_name_of_my_program" ;

    // program arguments
    const int N = 5 ;
    char arg[N][256] = { "one", "two,", "buckle", "my", "shoe." } ;

    // see: https://en.cppreference.com/w/cpp/language/main_function

    // argc: Non-negative value representing the number of arguments passed
    const int argc = N+1 ;

    // argv: array of argc+1 pointers to null-terminated c-strings
    //       the first item in the array ( argv[0] ) is the name of the program
    //       the last item in the array ( argv[argc] ) is a nullptr
    char* argv[argc+1] = { program_name, arg[0], arg[1], arg[2], arg[3], arg[4], nullptr };

    // main can't be called; but there are no such restrictions on my_own_main
    return my_own_main( argc, argv ) ;
}

http://coliru.stacked-crooked.com/a/6d561717c3a4aa4c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
using namespace std;

namespace myspace
{ 
   int main( int argc, char* argv[] )
   {
      cout << "Got here!\n";
      cout << "argc = " << argc << '\n';
      for ( int i = 0; i < argc; i++ ) cout << i << ": " << argv[i] << "    ";
      return 0;
   }
}
      
int main( int argc, char* argv[] )
{
   return myspace::main( argc, argv );     
}
Topic archived. No new replies allowed.