Main function

Main function

In many programming languages, the main function is where a program starts execution. It is responsible for the high-level organization of the program's functionality, and typically has access to the command arguments given to the program when it was executed.

The main function is generally the first programmer-written function run when a program starts, and is invoked directly from the system-specific initialization contained in crt0 or equivalent. However, some languages can execute user-written functions before main runs, such as the constructors of C++ global objects.

Contents

Variants

C and C++

In C and C++, the function prototype of the main function looks like one of the following:

int main(void)
 
int main(int argc, char **argv)
int main(int argc, char *argv[])
 
int main()

The parameters argc, argument count, and argv, argument vector,[1] respectively give the number and value of the program's command-line arguments. The names of argc and argv may be any valid identifier in C, but it is common convention to use these names. In C++, the names are to be taken literally, and the "void" in the parameter list is to be omitted, if strict conformance is desired.[2] Other platform-dependent formats are also allowed by the C and C++ standards, except that in C++ the return type must stay int; for example, Unix (though not POSIX.1) and Microsoft Windows have a third argument giving the program's environment, otherwise accessible through getenv in stdlib.h:

int main(int argc, char **argv, char **envp)

Mac OS X and Darwin have a fourth parameter containing arbitrary OS-supplied information, such as the path to the executing binary:[3]

int main(int argc, char **argv, char **envp, char **apple)

The value returned from the main function becomes the exit status of the process, though the C standard only ascribes specific meaning to two values: EXIT_SUCCESS (traditionally 0) and EXIT_FAILURE. The meaning of other possible return values is implementation-defined. In case a return value is not defined by the programmer, an implicit return 0; at the end of the main() function is inserted by the compiler; this behavior is required by the C++ standard.

It is guaranteed that argc is non-negative and that argv[argc] is a null pointer. By convention, the command-line arguments specified by argc and argv include the name of the program as the first element if argc is greater than 0; if a user types a command of "rm file", the shell will initialise the rm process with argc = 2 and argv = ["rm", "file", NULL]. As argv[0] is the name that processes appear under in ps, top etc., some programs, such as daemons or those running within an interpreter or virtual machine (where argv[0] would be the name of the host executable), may choose to alter their argv to give a more descriptive argv[0], usually by means of the exec system call.

The main() function is special; normally every C and C++ program must define it exactly once.

If declared, main() must be declared as if it has external linkage; it cannot be declared static or inline.

In C++, main() must be in the global namespace (i.e. ::main), cannot be overloaded, and cannot be a member function, although the name is not otherwise reserved, and may be used for member functions, classes, enumerations, or non-member functions in other namespaces. In C++ (unlike C) main() cannot be called recursively and cannot have its address taken.

Clean

Clean is a functional programming language based on graph rewriting. The initial node is called Start and is of type *World -> *World if it changes the world or some fixed type if the program only prints the result after reducing Start.

 Start :: *World -> *World
 Start world = startIO ...

Or even simpler

 Start :: String
 Start = "Hello, world!"

One tells the compiler which option to use to generate the executable file.

C#

When executing a program written in C#, the CLR searches for a static method marked with the .entrypoint IL directive, which takes either no arguments, or a single argument of type string[], and has a return type of void or int, and executes it.[4]

static void Main();
static void Main(string[] args);
static int Main();
static int Main(string[] args);

Command-line arguments are passed in args, similar to how it is done in Java. For versions of Main() returning an integer, similar to both C and C++, it is passed back to the environment as the exit status of the process.

D

In D, the function prototype of the main function looks like one of the following:

void main();
void main(string[] args);
int main();
int main(string[] args);

Command-line arguments are passed in args, similar to how it is done in C# or Java. For versions of main() returning an integer, similar to both C and C++, it is passed back to the environment as the exit status of the process.

Common Lisp

ANSI Common Lisp does not define a main function. However, the following code will emulate a main function in CMUCL. It is easily adjusted to work in ECL, SBCL, and Clojure (CLISP not at all).

#!/usr/bin/env lisp -quiet -load
 
(defun hello-main ()
  (format t "Hello World!~%")
  (quit))
 
(if (member (pathname-name *load-truename*)
            extensions:*command-line-strings*
            :test #'(lambda (x y) (search x y :test #'equalp)))
    (hello-main))

FORTRAN

FORTRAN does not have a main subroutine or function. Instead a PROGRAM statement as the first line can be used to specify that a program unit is a main program, as shown below. The PROGRAM statement cannot be used for recursive calls.[5]

      PROGRAM HELLO
      PRINT *, "Hello World!"
      END PROGRAM HELLO

GNAT

Using GNAT, the programmer is not required to write a function called main; a source file containing a single subprogram can be compiled to an executable. The binder will however create a package ada_main, which will contain and export a C-style main function.

Go

In Go programming language, program execution starts with the main function of the package main

package main
 
import "fmt"
 
func main() {
        fmt.Println("Hello, World!")
}

Haskell

A Haskell program must contain a name called main bound to a value of type IO t, for some type t;[6] which is usually IO (). IO is a monad, which organizes side-effects in terms of purely functional code.[7] The main value represents the side-effects-ful computation done by the program. The result of the computation represented by main is discarded; that is why main usually has type IO (), which indicates that the type of the result of the computation is (), the unit type, which contains no information.

Command line arguments are not given to main; they must be fetched using another IO action, such as System.Environment.getArgs.

Java

Java programs start executing at the main method, which has the following method heading:

public static void main(String[] args)
public static void main(String... args)
public static void main(String args[])

Command-line arguments are passed in args. As in C and C++, the name "main()" is special. Java's main methods do not return a value directly, but one can be passed by using the System.exit() method.

Unlike C, the name of the program is not included in args, because the name of the program is exactly the name of the class that contains the main method called, so it is already known. Also unlike C, the number of arguments need not be included, since the array class in Java has an attribute that keeps track of how many elements there are

Objective Caml

Objective Caml has no main function. Programs are evaluated from top to bottom.

Command-line arguments are available in an array named Sys.argv and the exit status is 0 by default.

Example:

let hello_world () =
  print_endline "hello, world"
;;
 
let () = hello_world () ;;

Pascal

In Pascal, the main procedure is the only unnamed procedure in the program. Because Pascal programs have the procedures and functions in a more rigorous top-down order than C, C++ or Java programs, the main procedure is usually the last procedure in the program. Pascal does not have a special meaning for the name "main" or any similar name.

program Hello;
 
  procedure HelloWorld;
  begin
    writeln('Hello, world!');
  end;
 
begin
  HelloWorld;
end.

Command-line arguments are counted in ParamCount and accessible as strings by ParamStr(n), with n between 0 and ParamCount.

Perl

In Perl, there is no main function. Statements are executed from top to bottom.

Command-line arguments are available in the special array @ARGV. Unlike C, @ARGV does not contain the name of the program, which is $0.

Pike

In Pike syntax is similar to that of C and C++. The execution begins at main. The "argc" variable keeps the number of arguments passed to the program. The "argv" variable holds the value associated with the arguments passed to the program.

Example:

int main(int argc, array(string) argv)

Python

In Python a function called main doesn't have any special significance. However, it is common practice to organize a program's main functionality in a function called main and call it with code similar to the following:

def main():
    # the main code goes here
 
if __name__ == "__main__":
    main()

When a Python program is executed directly (as opposed to being imported from another program), the special global variable __name__ has the value "__main__".[8]

Some programmers use the following, giving a better look to exits:

import sys
 
def main(*args):
    try:
        # some code here
    except:
        # handle some exceptions
    else:
        return 0 # exit errorlessly
 
if __name__ == '__main__':
    sys.exit(main(*sys.argv))

REALbasic

In REALbasic, there are two different project types, each with a different main entry point. Desktop (GUI) applications start with the App.Open event of the project's Application object. Console applications start with the App.Run event of the project's ConsoleApplication object. In both instances, the main function is automatically generated, and cannot be removed from the project.printf("% \",i);

Ruby

In Ruby, there is no distinct main function. The code written without additional "class .. end", "module .. end" enclosures is executed directly, step by step, in context of special "main" object. This object can be referenced using:

self                # => main

and contain the following properties:

self.class           # => Object
self.class.ancestors # => [Object, Kernel]

Methods defined without additional classes/modules are defined as private methods of the "main" object, and, consequentally, as private methods of almost any other object in Ruby:

def foo
  42
end
 
foo                  # => 42
[].foo               # => private method `foo' called for []:Array (NoMethodError)
false.foo            # => private method `foo' called for false:FalseClass (NoMethodError)

Number and values of command-line arguments can be determined using the single ARGV constant array:

ARGV                 # => ["foo", "bar"]
ARGV.size            # => 2

Note that first element of ARGV, ARGV[0], contains the first command-line argument, not the name of program executed, as in C. The name of program is available using $0 or $PROGRAM_NAME.[9]

Similar to Python, one could use:

if __FILE__ == $PROGRAM_NAME
  # Put "main" code here
end

In FMSLogo, the procedures when loaded do not execute. To make them execute, it is necessary to use this code:

to procname
 ...                 ; Startup commands (such as print [Welcome])
end
make "startup [procname]

Note that the variable startup is used for the startup list of actions, but the convention is that this calls another procedure that runs the actions. That procedure may be of any name.

AHLSL

In AIGE's AHLSL, the main function, by default, is defined as:

[main]

References

  1. ^ argv: the vector term in this variable's name is used in traditional sense to refer to strings.
  2. ^ [1] - Parameter types and names of main.
  3. ^ The char *apple Argument Vector
  4. ^ http://msdn.microsoft.com/msdnmag/issues/04/02/NETConsoleApps/
  5. ^ XL FORTRAN for AIX. Language Reference. Third Edition, 1994. IBM
  6. ^ http://www.haskell.org/onlinereport/modules.html
  7. ^ Some Haskell Misconceptions: Idiomatic Code, Purity, Laziness, and IO — on Haskell's monadic IO>
  8. ^ Python main() functions
  9. ^ Programming Ruby: The Pragmatic Programmer's Guide, Ruby and Its World — on Ruby ARGV

External links


Wikimedia Foundation. 2010.

Игры ⚽ Нужна курсовая?

Look at other dictionaries:

  • Main function (programming) — In some programming languages, the main function is where a program starts execution. It is generally the first user written function run when a program starts (some system specific software generally runs before the main function), though some… …   Wikipedia

  • Main (disambiguation) — Main may refer to any of the following: * The Main, a river in Germany * The Main, a river in Far Eastern Siberia. * Main River (Newfoundland), a river in Newfoundland, Canada * Spanish Main, a name given to the Caribbean coast * Main Street, a… …   Wikipedia

  • Function object — A function object, also called a functor or functional, is a computer programming construct allowing an object to be invoked or called as if it were an ordinary function, usually with the same syntax.Function objects are unrelated to functors in… …   Wikipedia

  • Main — For the Wikipedia website front page, see Main Page. For the Wikipedia main namespace, see Help:Namespace. Main may refer to: Main (river), a major river and tributary of the Rhine in Germany Main River (Chukotka), a river in Far Eastern Siberia… …   Wikipedia

  • function — ▪ I. function func‧tion 1 [ˈfʌŋkʆn] noun 1. [countable] the purpose for which something is made or used, or the job that someone does; =role: • The main function of a cash machine is to provide people with cash when the bank is shut. • He was… …   Financial and business terms

  • Function (engineering) — In engineering, in psychology, as well as in common parlance, function denotes the property of something which is used/applied for an objective/goal/purpose/scope.In fact, it is possible to realize the same function using different physical… …   Wikipedia

  • function — [[t]fʌ̱ŋkʃ(ə)n[/t]] ♦♦ functions, functioning, functioned 1) N COUNT: with supp The function of something or someone is the useful thing that they do or are intended to do. The main function of the merchant banks is to raise capital for industry …   English dictionary

  • Main Market Square, Kraków — Rynek Główny as seen from the tower of the St. Mary s Basilica. On the left Church of St. Wojciech, on the right Sukiennice with Town Hall Tower behind. The Adam Mickiewicz Monument in the bottom center The Main Market Square in Kraków (Polish:… …   Wikipedia

  • function — 1. noun 1) the main function of the machine Syn: purpose, task, use, role 2) my function was to select and train the recruits Syn: responsibility, duty, role, concern, province, activity, assignment …   Thesaurus of popular words

  • function — 1. noun 1) the main function of the machine Syn: purpose, task, use, role 2) my function was to train the recruits Syn: responsibility, duty, role, province, activity, assignment …   Synonyms and antonyms dictionary

Share the article and excerpts

Direct link
Do a right-click on the link above
and select “Copy Link”