简体   繁体   中英

Function Declaration & Definition in C for main()

I researched & understood that the standard way of creating or writing a function in C is to:

function declaration - declare the function name, arguments, and return value
function definition - define the function with the actual code implementation
function call - call or invoke the function with the name and arguments

The function main() in C is a special function name which indicates where your program is to start, the entry point in your program for the C source code you write. Part of the C Standard Runtime is a need to know the entry point for where the C program that you are writing starts from. This is indicated with the function name main() .

First you must understand that a C compiler converts the C source code text into binary object files. These binary object files are then linked together with other binary object files to produce the actual executable program. One of these types of binary object files is library files which contain the binary code of one or more functions that were previously compiled and combined into a single file.

The C compiler comes with several library files that contains functionality which you will need to complete your executable program. One of these is the C Runtime for the compiler.

When your executable program starts up, it does not start at main() . It instead starts at a special place in the C Runtime which sets up the runtime environment for your executable and then calls the main() function you provide. The main() function is where your source code starts.

As part of the C compiler there are a also include files such as #include <stdio.h> and others. These include files contain declarations for the functions of the C Standard Library such as the printf() function.

So the main() function is declared for you in the C compiler however you have to provide the actual definition of the function.

Since main() is an external label there can only be one function called main() that you define. If you have more than one definition of main() then when the linker tries to link your binary object files together into an executable, it will see the multiple main() functions and issue an error because it will not know which one to use.

One way of thinking of this is: (1) the C compiler provides the declaration for main() , (2) you provide the definition for main() and (3) the C Runtime calls your function main() as part of starting up your program.

See also What is the difference between - 1) Preprocessor,linker, 2)Header file,library? Is my understanding correct?

Function definition for main()

The standard for C indicates two different declarations for main() : int main(int argc, char *argv[]) and int main(void) (see section 5.1.2.2.1 Program startup in draft ISO/IEC 9899:TC3 ). See also What does int argc, char *argv[] mean? . See also the various discussions in What should main() return in C and C++? .

Some C compilers may also provide other alternatives including a wide character interface such as int wmain(int argc, wchar_t *argv[]) (see WINMAIN and main() in C++ (Extended) ). C++ compilers may allow int main(int argc, wchar_t *argv[]) because C++ allows function overloading which C does not. Microsoft C++ compilers have had a variety of main() alternatives depending on whether the target program was a console application or a GUI.

The normal way of using the return value of main() is to return a value of 0 if successful and a non-zero positive number if there was an error. This was the normal and accepted behavior from the original Unix environments where programs were run in a terminal window from a command line (see Wikipedia topic Bourne Shell and Wikipedia topic Bash as well as Returning value from called function in a shell script which contains some examples of scripts) and most programs were used with command shell scripts.

Some programs use the return value to indicate the results of a test of some kind. In those cases, the value returned by main() isn't either success or an error code but instead the return value indicates some condition that a script could test for as part of carrying out its purpose. For example a program that queries an air quality indication from a sensor may return three different values indicating Good, Fair, or Poor which a script then uses to do something such as turn on a ventilation system fan at a particular speed.

Here are a couple of examples of main() definitions:

// usage: mypgm pathname
// Open the specified file and do things with the file's contents.
//
// program expects a single command line argument specifying a file.
// if pathname is not specified then it's an error.
int main(int argc, char *argv[])
{
    // there is always one argument as the first argument is always
    // the program name. Any additional arguments added to the
    // command line begin with the second argument.
    //    argv[0]  -> program or command name
    //    argv[1]  -> expecting a pathname to be specified
    if (argc < 2) {
        printf ("Filename not specified\n");
        return 1;    // return non-zero indicating an error
    }

    // source code to do stuff with the specified file

    return 0;     // return zero indicating no error
}

// usage: mypgm 
//
// program does not expect any command line arguments and if any are
// specified the arguments are ignored.
//
int main (void)
{
    // source code to do stuff 
    return 0;
}

// usage: mypgm 
//
// program does not expect any command line arguments and if any are
// specified the arguments are ignored.
//
// the following definition also compiles.
int main ()
{
    // source code to do stuff 
    return 0;
}

In C you may call main recursively. You shall not declare main without its definition.

"

C language standard n1256

5.1.2.2.1 Program startup

1 The function called at program startup is named main. The implementation declares no prototype for this function. It shall be defined with a return type of int and with no parameters:

 int main(void) { /* ... */ }

or with two parameters (referred to here as argc and argv, though any names may be used, as they are local to the function in which they are declared):

 int main(int argc, char *argv[]) { /* ... */ }

or equivalent;9) or in some other implementation-defined manner.

In C, the compiler has to know a function's return type and parameter list (if any) before it can translate a function call .

A function definition also serves as its declaration ; if you define the function before it is called within the same translation unit, then you do not need to write a separate declaration for it:

void foo ( void ) // definition, also serves as declaration
{
  ...
}

void bar( void )
{
  ...
  foo();   // call
  ...
}

Since we define foo before it's called by bar , the compiler already knows foo 's return type and parameter list, so we don't need another declaration before the call in bar . However, if we were to define foo after bar , or if foo were defined in a separate translation unit (source file), then we would need a separate declaration before the call in bar :

void bar( void )
{
  void foo( void ); // declaration
  ...
  foo( ); // call
}

void foo( void ) // definition
{
  ...
}

main is special in that there's typically no need for a separate declaration of it in your code; you don't normally call main explicitly. It's normally called by the run time environment, which already expects main to return an int and take either zero or two parameters, like so:

int main( void );
int main( int, char ** );

Implementations may provide additional signatures for main , which they must document.

About the only place I've seen anyone call main explicitly was in the IOCCC ; I've never seen a valid use case for it in production code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM