Main function (programming)
Encyclopedia
In many programming language
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
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.
and C++
, the function prototype
of the main function looks like one of the following:
The parameter
s
(though not POSIX.1) and Microsoft Windows
have a third argument giving the program's environment
, otherwise accessible through
Mac OS X
and Darwin
have a fourth parameter containing arbitrary OS-supplied information, such as the path to the executing binary:
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:
It is guaranteed that
will initialise the
s or those running within an interpreter
or virtual machine
(where
The
If declared,
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 CC (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:
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, UnixUnix
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
: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:
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 shellShell (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
rmRm (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 psPs (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....
, topTop (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 daemonDaemon (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 execExec (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 namespaceNamespaceIn 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 recursivelyRecursion (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 reducingGraph rewritingGraph 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 CLRCommon Language RuntimeThe 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.
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 DD (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 prototypeFunction prototypeA 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:
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).
FORTRAN
FORTRANFortranFortran 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.
GNAT
Using GNATGNATGNAT 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 GoGo (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
Haskell
A HaskellHaskell (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 monadMonads in functional programmingIn 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-effectsSide 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 functionalPurely functionalPurely 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 typeUnit typeIn 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
JavaJava (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 methodMethod (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:
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 CamlObjective CamlOCaml , 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:
Pascal
In PascalPascal (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.
Command-line arguments are counted in ParamCount
and accessible as strings by ParamStr(n)
, with n between 0 and ParamCount
.
Perl
In PerlPerlPerl 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 argumentsParameter (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 PythonPython (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:
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:
REALbasic
In REALbasicREALbasicRealbasic 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 RubyRuby (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:
and contain the following properties:
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:
Number and values of command-line arguments can be determined using the single ARGV
constant array:
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:
LOGO
In FMSLogoLogo (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