Main function (programming)
Encyclopedia
In many programming language
Programming language
A programming language is an artificial language designed to communicate instructions to a machine, particularly a computer. Programming languages can be used to create programs that control the behavior of a machine and/or to express algorithms precisely....

s, 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
Subroutine
In computer science, a subroutine is a portion of code within a larger program that performs a specific task and is relatively independent of the remaining code....

 run when a program starts, and is invoked directly from the system-specific initialization contained in crt0
Crt0
crt0 is a set of execution startup routines compiled into a program which perform any initialization work required before calling the program's main function. The work performed by crt0 depends on the program's language, compiler, operating system and C standard library implementation."crt" stands...

 or equivalent. However, some languages can execute user-written functions before main runs, such as the constructors of C++
C++
C++ is a statically typed, free-form, multi-paradigm, compiled, general-purpose programming language. It is regarded as an intermediate-level language, as it comprises a combination of both high-level and low-level language features. It was developed by Bjarne Stroustrup starting in 1979 at Bell...

 global objects.

C and C++

In C
C (programming language)
C is a general-purpose computer programming language developed between 1969 and 1973 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system....

 and C++
C++
C++ is a statically typed, free-form, multi-paradigm, compiled, general-purpose programming language. It is regarded as an intermediate-level language, as it comprises a combination of both high-level and low-level language features. It was developed by Bjarne Stroustrup starting in 1979 at Bell...

, the function prototype
Function prototype
A function prototype in C, Perl or C++ is a declaration of a function that omits the function body but does specify the function's return type, name, arity and argument types...

 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 parameter
Parameter (computer science)
In computer programming, a parameter is a special kind of variable, used in a subroutine to refer to one of the pieces of data provided as input to the subroutine. These pieces of data are called arguments...

s argc, argument count, and argv, argument vector, 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. 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
Unix
Unix is a multitasking, multi-user computer operating system originally developed in 1969 by a group of AT&T employees at Bell Labs, including Ken Thompson, Dennis Ritchie, Brian Kernighan, Douglas McIlroy, and Joe Ossanna...

 (though not POSIX.1) and Microsoft Windows
Microsoft Windows
Microsoft Windows is a series of operating systems produced by Microsoft.Microsoft introduced an operating environment named Windows on November 20, 1985 as an add-on to MS-DOS in response to the growing interest in graphical user interfaces . Microsoft Windows came to dominate the world's personal...

 have a third argument giving the program's environment
Environment variable
Environment variables are a set of dynamic named values that can affect the way running processes will behave on a computer.They can be said in some sense to create the operating environment in which a process runs...

, otherwise accessible through getenv in stdlib.h:


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


Mac OS X
Mac OS X
Mac OS X is a series of Unix-based operating systems and graphical user interfaces developed, marketed, and sold by Apple Inc. Since 2002, has been included with all new Macintosh computer systems...

 and Darwin
Darwin (operating system)
Darwin is an open source POSIX-compliant computer operating system released by Apple Inc. in 2000. It is composed of code developed by Apple, as well as code derived from NeXTSTEP, BSD, and other free software projects....

 have a fourth parameter containing arbitrary OS-supplied information, such as the path to the executing binary:

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


The value returned from the main function becomes the exit status
Exit status
The exit status or return code of a process in computer programming is a small number passed from a child process to a parent process when it has finished executing a specific procedure or delegated task...

 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
Shell (computing)
A shell is a piece of software that provides an interface for users of an operating system which provides access to the services of a kernel. However, the term is also applied very loosely to applications and may include any software that is "built around" a particular component, such as web...

 will initialise the rm
Rm (Unix)
rm is a basic UNIX command used to remove objects such as files, directories, device nodes, symbolic links, and so on from the filesystem...

process with argc = 2 and argv = ["rm", "file", NULL]. As argv[0] is the name that processes appear under in ps
Ps (Unix)
In most Unix-like operating systems, the ps program displays the currently-running processes. A related Unix utility named top provides a real-time view of the running processes....

, top
Top (Unix)
top is a program found in many Unix-like operating systems. It produces an ordered list of running processes selected by user-specified criteria, and updates it periodically. Default ordering by CPU usage, and only the top CPU consumers shown top shows how much processing power and memory are...

etc., some programs, such as daemon
Daemon (computer software)
In Unix and other multitasking computer operating systems, a daemon is a computer program that runs as a background process, rather than being under the direct control of an interactive user...

s or those running within an interpreter
Interpreter (computing)
In computer science, an interpreter normally means a computer program that executes, i.e. performs, instructions written in a programming language...

 or virtual machine
Virtual machine
A virtual machine is a "completely isolated guest operating system installation within a normal host operating system". Modern virtual machines are implemented with either software emulation or hardware virtualization or both together.-VM Definitions:A virtual machine is a software...

 (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
Exec (operating system)
The exec collection of functions of Unix-like operating systems cause the running process to be completely replaced by the program passed as an argument to the function...

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
Namespace
In general, a namespace is a container that provides context for the identifiers it holds, and allows the disambiguation of homonym identifiers residing in different namespaces....

 (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
Recursion (computer science)
Recursion in computer science is a method where the solution to a problem depends on solutions to smaller instances of the same problem. The approach can be applied to many types of problems, and is one of the central ideas of computer science....

 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
Graph rewriting
Graph transformation, or Graph rewriting, concerns the technique of creating a new graph out of an original graph using some automatic machine. It has numerous applications, ranging from software verification to layout algorithms....

 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
Common Language Runtime
The Common Language Runtime is the virtual machine component of Microsoft's .NET framework and is responsible for managing the execution of .NET programs. In a process known as just-in-time compilation, the CLR compiles the intermediate language code known as CIL into the machine instructions...

 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.


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
D (programming language)
The D programming language is an object-oriented, imperative, multi-paradigm, system programming language created by Walter Bright of Digital Mars. It originated as a re-engineering of C++, but even though it is mainly influenced by that language, it is not a variant of C++...

, the function prototype
Function prototype
A function prototype in C, Perl or C++ is a declaration of a function that omits the function body but does specify the function's return type, name, arity and argument types...

 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).

  1. !/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
Fortran
Fortran is a general-purpose, procedural, imperative programming language that is especially suited to numeric computation and scientific computing...

 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.


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

GNAT

Using GNAT
GNAT
GNAT is a free-software compiler for the Ada programming language which forms part of the GNU Compiler Collection. It supports all versions of the language, i.e. Ada 2005, Ada 95 and Ada 83; it allows already some constructs of Ada 2012...

, 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
Go (programming language)
Go is a compiled, garbage-collected, concurrent programming language developed by Google Inc.The initial design of Go was started in September 2007 by Robert Griesemer, Rob Pike, and Ken Thompson. Go was officially announced in November 2009. In May 2010, Rob Pike publicly stated that Go was being...

 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
Haskell (programming language)
Haskell is a standardized, general-purpose purely functional programming language, with non-strict semantics and strong static typing. It is named after logician Haskell Curry. In Haskell, "a function is a first-class citizen" of the programming language. As a functional programming language, the...

 program must contain a name called main bound to a value of type IO t, for some type t; which is usually IO . IO is a monad
Monads in functional programming
In functional programming, a monad is a programming structure that represents computations. Monads are a kind of abstract data type constructor that encapsulate program logic instead of data in the domain model...

, which organizes side-effects
Side effect (computer science)
In computer science, a function or expression is said to have a side effect if, in addition to returning a value, it also modifies some state or has an observable interaction with calling functions or the outside world...

 in terms of purely functional
Purely functional
Purely functional is a term in computing used to describe algorithms, data structures or programming languages that exclude destructive modifications...

 code. 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
Unit type
In the area of mathematical logic, and computer science known as type theory, a unit type is a type that allows only one value . The carrier associated with a unit type can be any singleton set. There is an isomorphism between any two such sets, so it is customary to talk about the unit type and...

, 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
Java (programming language)
Java is a programming language originally developed by James Gosling at Sun Microsystems and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities...

 programs start executing at the main method
Method (computer science)
In object-oriented programming, a method is a subroutine associated with a class. Methods define the behavior to be exhibited by instances of the associated class at program run time...

, 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
Objective Caml
OCaml , originally known as Objective Caml, is the main implementation of the Caml programming language, created by Xavier Leroy, Jérôme Vouillon, Damien Doligez, Didier Rémy and others in 1996...

 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
Pascal (programming language)
Pascal is an influential imperative and procedural programming language, designed in 1968/9 and published in 1970 by Niklaus Wirth as a small and efficient language intended to encourage good programming practices using structured programming and data structuring.A derivative known as Object 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
Perl
Perl is a high-level, general-purpose, interpreted, dynamic programming language. Perl was originally developed by Larry Wall in 1987 as a general-purpose Unix scripting language to make report processing easier. Since then, it has undergone many changes and revisions and become widely popular...

, 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
Parameter (computer science)
In computer programming, a parameter is a special kind of variable, used in a subroutine to refer to one of the pieces of data provided as input to the subroutine. These pieces of data are called 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
Python (programming language)
Python is a general-purpose, high-level programming language whose design philosophy emphasizes code readability. Python claims to "[combine] remarkable power with very clear syntax", and its standard library is large and comprehensive...

 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__".

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
REALbasic
Realbasic is the object-oriented dialect of the BASIC programming language used in Real Studio, a programming environment, developed and commercially marketed by Real Software, Inc of Austin, Texas for Mac OS X, Microsoft Windows, 32-bit x86 Linux and the web.- Language features :RB is a strongly...

, 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
Ruby (programming language)
Ruby is a dynamic, reflective, general-purpose object-oriented programming language that combines syntax inspired by Perl with Smalltalk-like features. Ruby originated in Japan during the mid-1990s and was first developed and designed by Yukihiro "Matz" Matsumoto...

, 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.

Similar to Python, one could use:


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

LOGO

In FMSLogo
Logo (programming language)
Logo is a multi-paradigm computer programming language used in education. It is an adaptation and dialect of the Lisp language; some have called it Lisp without the parentheses. It was originally conceived and written as functional programming language, and drove a mechanical turtle as an output...

, 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.
External links
The source of this article is wikipedia, the free encyclopedia.  The text of this article is licensed under the GFDL.
 
x
OK