Incomputer programming, anentry point is the place in a program where the execution of a program begins, and where the program has access tocommand line arguments.[failed verification][1]

Main()
might look inC# source code. Different parts are labeled for reference.To start a program'sexecution, theloader oroperating system passes control to its entry point. (Duringbooting, the operating systemitself is the program). This marks the transition fromload time (and dynamiclink time, if present) torun time.
For some operating systems andprogramming languages, the entry point is in aruntime library, a set of support functions for the language. The library code initializes the program and then passes control to the program proper. In other cases, the program may initialize the runtime library itself.[2]
In simple systems, execution begins at the first statement, which is common ininterpreted languages, simpleexecutable formats, andboot loaders. In other cases, the entry point is at some other knownmemory address which can be anabsolute address or relative address (offset).
Alternatively, execution of a program can begin at a named point, either with a conventional name defined by the programming language or operating system or at a caller-specified name. In manyC-family languages, this is a function calledmain
; as a result, the entry point is often known as themain function.[3]
InJVM languages, such asJava, the entry point is a static method calledmain
; inCLI languages such as C# the entry point is a static method namedMain
.[4]
Usage
editEntry points apply both to source code and toexecutable files. However, in day-to-daysoftware development, programmers specify the entry points only in source code, which makes them much better known. Entry points in executable files depend on theapplication binary interface (ABI) of the actual operating system, and are generated by the compiler or linker (if not fixed by the ABI). Other linkedobject files may also have entry points, which are used later by the linker when generating entry points of an executable file.
Entry points are capable of passing on command arguments, variables, or other information as a local variable used by theMain()
method. This way, specific options may be set upon execution of the program, and then interpreted by the program. Many programs use this as an alternative way to configure different settings, or perform a set variety of actions using a single program.
Contemporary
editIn most of today's popular programming languages and operating systems, acomputer program usually only has a singleentry point.
InC,C++,D,Zig,Rust andKotlin programs this is afunction namedmain
; inJava it is astatic method namedmain
(although the class must be specified at the invocation time), and inC# it is a static method namedMain
.[5][6]
In many major operating systems, the standard executable format has a single entry point. In theExecutable and Linkable Format (ELF), used inUnix andUnix-like systems such asLinux, the entry point is specified in thee_entry
field of the ELF header. In theGNU Compiler Collection (gcc), the entry point used by the linker is the_start
symbol. Similarly, in thePortable Executable format, used inMicrosoft Windows, the entry point is specified by theAddressOfEntryPoint
field, which is inherited fromCOFF. InCOM files, the entry point is at the fixedoffset of 0100h.
One exception to the single-entry-point paradigm isAndroid. Android applications do not have a single entry point – there is no specialmain
function. Instead, they haveessential components (activities and services) which the system can load and run as needed.[7]
An occasionally used technique is thefat binary, which consists of several executables for different targets packaged in a single file. Most commonly, this is implemented by a single overall entry point, which is compatible with all targets and branches to the target-specific entry point. Alternative techniques include storing separate executables in separateforks, each with its own entry point, which is then selected by the operating system.
Historical
editHistorically, and in some contemporarylegacy systems, such asVMS andOS/400, computer programs have a multitude ofentry points, each corresponding to the different functionalities of the program. The usual way to denote entry points, as used system-wide in VMS and inPL/I andMACRO programs, is to append them at the end of the name of theexecutable image, delimited by adollar sign ($), e.g.directory.exe$make
.
TheApple I computer also used this to some degree. For example, an alternative entry point in Apple I'sBASIC would keep the BASIC program useful when the reset button was accidentally pushed.[clarification needed]
Exit point
editIn general, programs can exit at any time by returning to the operating system orcrashing. Programs in interpreted languages return control to the interpreter, but programs in compiled languages must return to the operating system, otherwise the processor will simply continue executing beyond the end of the program, resulting inundefined behavior.
Usually, there is not a single exit point specified in a program. However, in other cases runtimes ensure that programs always terminate in a structured way via a single exit point, which is guaranteed unless the runtime itself crashes; this allows cleanup code to be run, such asatexit
handlers. This can be done by either requiring that programs terminate by returning from the main function, by calling a specific exit function, or by the runtime catching exceptions or operating system signals.
Programming languages
editIn many programming languages, themain
function is where a program starts its execution. It enables high-level organization of the program's functionality, and typically has access to thecommand arguments given to the program when it was executed.
The main function is generally the first programmer-writtenfunction that runs when a program starts, and is invoked directly from the system-specific initialization contained in theruntime environment (crt0 or equivalent). However, some languages can execute user-written functions before main runs, such as the constructors ofC++ global objects.
In other languages, notably manyinterpreted languages, execution begins at the first statement in the program.
A non-exhaustive list of programming languages follows, describing their way of defining the main entry point:
APL
editInAPL, when a workspace is loaded, the contents of "quad LX" (latent expression) variable is interpreted as an APL expression and executed.
C and C++
editInC andC++, thefunction prototype of the main function must be equivalent to one of the following:
intmain();intmain(void);intmain(intargc,char**argv);
The main function is the entry point for application programs written in ISO-standard C or C++. Low-level system programming (such as for abare-metalembedded system) might specify a different entry point (for example via a resetinterrupt vector) using functionality not defined by the language standard.
Theparametersargc
,argument count, andargv
,argument vector,[citation needed] respectively give the number and values of the program'scommand-line arguments. The names ofargc
andargv
may be any valid identifier, but it is common convention to use these names. Other platform-dependent formats are also allowed by the C and C++ standards, except that in C++ the return type must always beint
;[8] for example,Unix (though notPOSIX.1) andWindows have a third argument giving the program'senvironment, otherwise accessible throughgetenv
instdlib.h
:
intmain(intargc,char**argv,char**envp);
Darwin-based operating systems, such asmacOS, have a fourth parameter containing arbitrary OS-supplied information, such as the path to the executing binary:[9]
intmain(intargc,char**argv,char**envp,char**apple);
The value returned from the main function becomes theexit status of the process, though the C standard only ascribes specific meaning to two values:EXIT_SUCCESS
(traditionally 0) andEXIT_FAILURE
. The meaning of other possible return values is implementation-defined. In case a return value is not defined by the programmer, an implicitreturn 0;
at the end of themain()
function is inserted by the compiler; this behavior is required by the C++ standard.
It is guaranteed thatargc
is non-negative and thatargv[argc]
is anull pointer. By convention, the command-line arguments specified byargc
andargv
include the name of the program as the first element ifargc
is greater than 0; if a user types a command of "rm file
", theshell will initialise therm
process withargc = 2
andargv = {"rm", "file", NULL}
. Asargv[0]
is the name that processes appear under inps
,top
etc., some programs, such asdaemons or those running within aninterpreter orvirtual machine (whereargv[0]
would be the name of the host executable), may choose to alter their argv to give a more descriptiveargv[0]
, usually by means of theexec
system call.
Themain()
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 declaredstatic
orinline
.
In C++,main()
must be in the globalnamespace (i.e.::main
), cannot be overloaded, and cannot be amember 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 calledrecursively and cannot have its address taken.
C#
editWhen executing a program written inC#, theCLR searches for a static method marked with the.entrypoint
IL directive, which takes either no arguments, or a single argument of typestring[]
, and has a return type ofvoid
orint
, and executes it.[10]
staticvoidMain();staticvoidMain(string[]args);staticintMain();staticintMain(string[]args);
Command-line arguments are passed inargs
, similar to how it is done in Java. For versions ofMain()
returning an integer, similar to both C and C++, it is passed back to the environment as the exit status of the process.
Since C#7.1 there are four more possiblesignatures of the entry point, which allow asynchronous execution in theMain()
Method.[11]
staticasyncTaskMain()staticasyncTask<int>Main()staticasyncTaskMain(string[])staticasyncTask<int>Main(string[])
TheTask
andTask<int>
types are the asynchronous equivalents ofvoid
andint
.async
is required to allow the use of asynchrony (theawait
keyword) inside the method.
Clean
editClean is a functional programming language based on graph rewriting. The initial node is namedStart
and is of type*World -> *World
if itchanges the world or some fixed type if the program only prints the result afterreducingStart
.
Start::*World->*WorldStartworld=startIO...
Or even simpler
Start::StringStart="Hello, world!"
One tells the compiler which option to use to generate the executable file.
Common Lisp
editANSI Common Lisp does not define a main function; instead, the code is read and evaluated from top to bottom in a source file. However, the following code willemulate a main function.
(defunhello-main()(formatt"Hello World!~%"))(hello-main)
D
editInD, thefunction prototype of the main function looks like one of the following:
voidmain();voidmain(string[]args);intmain();intmain(string[]args);
Command-line arguments are passed inargs
, similar to how it is done in C# or Java. For versions ofmain()
returning an integer, similar to both C and C++, it is passed back to the environment as the exit status of the process.
Dart
editDart is ageneral-purpose programming language that is often used for building web and mobile applications. Like many other programming languages, Dart has an entry point that serves as the starting point for a Dart program. The entry point is the first function that is executed when a program runs. In Dart, the entry point is typically a function namedmain
. When a Dart program is run, the Dart runtime looks for a function namedmain
and executes it. Any Dart code that is intended to be executed when the program starts should be included in themain
function. Here is an example of a simplemain
function in Dart:
voidmain(){print("Hello, world!");}
In this example, themain
function simply prints the textHello, world!
to the console when the program is run. This code will be executed automatically when the Dart program is run.
It is important to note that while themain
function is the default entry point for a Dart program, it is possible to specify a different entry point if needed. This can be done using the@pragma("vm:entry-point")
annotation in Dart. However, in most cases, themain
function is the entry point that should be used for Dart programs.
FORTRAN
editFORTRAN does not have a main subroutine or function. Instead aPROGRAM
statement as the first line can be used to specify that a program unit is a main program, as shown below. ThePROGRAM
statement cannot be used for recursive calls.[12]
PROGRAMHELLOPRINT*,"Cint!"END PROGRAMHELLO
Some versions of Fortran, such as those on theIBM System/360 and successor mainframes, do not support the PROGRAM statement. Many compilers from other software manufacturers will allow a fortran program to be compiled without a PROGRAM statement. In these cases, whatever module that has any non-comment statement where no SUBROUTINE, FUNCTION or BLOCK DATA statement occurs, is considered to be the Main program.
GNAT
editUsingGNAT, the programmer is not required to write a function namedmain
; a source file containing a single subprogram can be compiled to an executable. The binder will however create a packageada_main
, which will contain and export a C-style main function.
Go
editInGo programming language, program execution starts with themain
function of thepackage main
packagemainimport"fmt"funcmain(){fmt.Println("Hello, World!")}
There is no way to access arguments or a return code outside of the standard library in Go. These can be accessed viaos.Args
andos.Exit
respectively, both of which are included in the"os"
package.
Haskell
editAHaskell program must contain a namemain
bound to a value of typeIO t
, for some typet
;[13] which is usuallyIO ()
.IO
is amonad, which organizesside-effects in terms ofpurely functional code.[14] Themain
value represents the side-effects-ful computation done by the program. The result of the computation represented bymain
is discarded; that is whymain
usually has typeIO ()
, which indicates that the type of the result of the computation is()
, theunit type, which contains no information.
main::IO()main=putStrLn"Hello, World!"
Command line arguments are not given tomain
; they must be fetched using another IO action, such asSystem.Environment.getArgs
.
Java
editJava programs start executing at the mainmethod of a class,[15][16][17][18] which has one of the followingmethod headings:
publicstaticvoidmain(String[]args)publicstaticvoidmain(String...args)publicstaticvoidmain(Stringargs[])voidmain()
Command-line arguments are passed inargs
. 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 theSystem.exit()
method.
Unlike C, the name of the program is not included inargs
, because it is the name of the class that contains the main method, so it is already known. Also unlike C, the number of arguments need not be included, since arrays in Java have a field that keeps track of how many elements there are.
The main function must be included within a class. This is because in Java everything has to be contained within a class. For instance, ahello world program in Java may look like:
publicclassHelloWorld{publicstaticvoidmain(String[]args){System.out.println("Hello, world!");}}
To run this program, one must calljava HelloWorld
in the directory where the compiledclass fileHelloWorld.class
) exists. Alternatively, executableJAR files use amanifest file to specify the entry point in a manner that is filesystem-independent from the user's perspective.
LOGO
editInFMSLogo, 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]
The variablestartup
is used for the startup list of actions, but the convention is that this calls a procedure that runs the actions. That procedure may be of any name.
OCaml
editOCaml has nomain
function. Programs are evaluated from top to bottom.
Command-line arguments are available in an array namedSys.argv
and the exit status is 0 by default.
Example:
print_endline"Hello World"
Pascal
editInPascal, the main procedure is the only unnamedblock in the program. Because Pascal programs define procedures and functions in a more rigorous bottom-up order than C, C++ or Java programs, the main procedure is usually the last block in the program. Pascal does not have a special meaning for the name "main
" or any similar name.
programHello(Output);beginwriteln('Hello, world!');end.
Command-line arguments are counted inParamCount
and accessible as strings byParamStr(n)
, with n between 0 andParamCount
.
Versions of Pascal that support units or modules may also contain an unnamed block in each, which is used to initialize the module. These blocks are executed before the main program entry point is called.
Perl
editInPerl, there is no main function. Statements are executed from top to bottom, although statements in aBEGIN
block are executed before normal statements.
Command-line arguments are available in the special array@ARGV
. Unlike C,@ARGV
does not contain the name of the program, which is$0
.
PHP
editPHP does not have a "main" function. Starting from the first line of a PHP script, any code not encapsulated by a function header is executed as soon as it is seen.
Pike
editInPike syntax is similar to that of C and C++. The execution begins atmain
. The "argc
" variable keeps the number ofarguments passed to the program. The "argv
" variable holds the value associated with the arguments passed to the program.
Example:
intmain(intargc,array(string)argv)
Python
editPython programs are evaluated top-to-bottom, as is usual in scripting languages: the entry point is the start of the source code. Since definitions must precede use, programs are typically structured with definitions at the top and the code to execute at the bottom (unindented), similar to code for aone-pass compiler, such as in Pascal.
Alternatively, a program can be structured with an explicitmain
function containing the code to be executed when a program is executed directly, but which can also be invoked by importing the program as a module and calling the function. This can be done by the following idiom, which relies on the internal variable__name__
being set to__main__
when a program is executed, but not when it is imported as a module (in which case it is instead set to the module name); there are many variants of this structure:[19][20][21]
importsysdefmain(argv):n=int(argv[1])print(n+1)if__name__=='__main__':sys.exit(main(sys.argv))
In this idiom, the call to the named entry pointmain
is explicit, and the interaction with the operating system (receiving the arguments, calling system exit) are done explicitly by library calls, which are ultimately handled by the Python runtime. This contrasts with C, where these are doneimplicitly by the runtime, based on convention.
QB64
editTheQB64 language has no main function, the code that is not within a function, or subroutine is executed first, from top to bottom:
print"Hello World! a =";a=getInteger(1.8d):printa
functiongetInteger(nasdouble)getInteger=int(n)endfunction
Command line arguments (if any) can be read using theCOMMAND$ function:
dimsharedcommandlineasstringcommandline=COMMAND$
'Several space-separated command line arguments can be read using COMMAND$(n)commandline1=COMMAND$(2)
Ruby
editInRuby, there is no distinct main function. Instead, code written outside of anyclass .. end
ormodule .. end
scope is executed in the context of a special "main
" object. This object can be accessed usingself
:
irb(main):001:0>self=> main
It has the following properties:
irb(main):002:0>self.class=> Objectirb(main):003:0>self.class.ancestors=> [Object, Kernel, BasicObject]
Methods defined outside of aclass
ormodule
scope are defined as private methods of the "main
" object. Since the class of "main
" isObject
, such methods become private methods of almost every object:
irb(main):004:0>deffooirb(main):005:1>42irb(main):006:1>end=> nilirb(main):007:0>foo=> 42irb(main):008:0>[].fooNoMethodError: private method `foo' called for []:Arrayfrom (irb):8from /usr/bin/irb:12:in `<main>'irb(main):009:0>false.fooNoMethodError: private method `foo' called for false:FalseClassfrom (irb):9from /usr/bin/irb:12:in `<main>'
The number and values of command-line arguments can be determined using theARGV
constant array:
$irb/dev/ttyfoobartty(main):001:0> ARGVARGV=> ["foo", "bar"]tty(main):002:0> ARGV.sizeARGV.size=> 2
The first element ofARGV
,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
.[22]
Similar to Python, one could use:
if__FILE__==$PROGRAM_NAME# Put "main" code hereend
to execute some code only if its file was specified in theruby
invocation.
Rust
editIn Rust, the entry point of a program is a function namedmain
. Typically, this function is situated in a file calledmain.rs
orlib.rs
.
// In `main.rs`fnmain(){println!("Hello, World!");}
Additionally, as of Rust 1.26.0, the main function may return aResult
:[23]
fnmain()->Result<(),std::io::Error>{println!("Hello, World!");Ok(())// Return a type `Result` of value `Ok` with the content `()`, i.e. an empty tuple.}
Swift
editWhen run in anXcode Playground,[24]Swift behaves like a scripting language, executing statements from top to bottom; top-level code is allowed.
// HelloWorld.playgroundlethello="hello"letworld="world"lethelloWorld=hello+" "+worldprint(helloWorld)// hello world
Cocoa- andCocoa Touch-based applications written in Swift are usually initialized with the@NSApplicationMain
and@UIApplicationMain
attributes, respectively. Those attributes are equivalent in their purpose to themain.m
file inObjective-C projects: they implicitly declare themain
function that callsUIApplicationMain(_:_:_:_:)
[25] which creates an instance ofUIApplication
.[26]The following code is the default way to initialize a Cocoa Touch-basediOS app and declare its application delegate.
// AppDelegate.swiftimportUIKit@UIApplicationMainclassAppDelegate:UIResponder,UIApplicationDelegate{varwindow:UIWindow?funcapplication(_application:UIApplication,didFinishLaunchingWithOptionslaunchOptions:[UIApplication.LaunchOptionsKey:Any]?)->Bool{returntrue}}
Visual Basic
editInVisual Basic, when a project contains no forms, the startup object may be theMain()
procedure. TheCommand$
function can be optionally used to access the argument portion of the command line used to launch the program:
SubMain()Debug.Print"Hello World!"MsgBox"Arguments if any are: "&Command$EndSub
Xojo
editInXojo, there are two different project types, each with a different main entry point. Desktop (GUI) applications start with theApp.Open
event of the project'sApplication
object. Console applications start with theApp.Run
event of the project'sConsoleApplication
object. In both instances, the main function is automatically generated, and cannot be removed from the project.
See also
edit- crt0, a set of execution startup routines linked into a C program
- Runtime system
References
edit- ^"In Computing, what is an Entry Point? (with picture)".wiseGEEK.Archived from the original on 2020-08-05. Retrieved2020-01-22.
- ^Decker, Karsten M.; Rehmann, René M. (1994).Programming Environments for Massively Parallel Distributed Systems: Working Conference of the Ifip Wg 10.3, April 25-29, 1994. Springer Science & Business Media.ISBN 978-3-7643-5090-1.
- ^"Main Method in C#".GeeksforGeeks. 2018-11-30.Archived from the original on 2020-07-31. Retrieved2020-01-22.
- ^Wagner, Bill (2017-08-01)."Main() / Entry Points (C# Programming Guide) - Microsoft Developer Network".docs.microsoft.com.Archived from the original on 2020-11-11. Retrieved2018-12-03.
- ^"The main() function".ibm.com.IBM.Archived from the original on 2017-09-10. Retrieved2014-05-08.
- ^"Main() and Command-Line Arguments (C# Programming Guide)". Msdn.microsoft.com.Archived from the original on 2014-06-09. Retrieved2014-05-08.
- ^"Application Fundamentals".Android Development. linuxtopia.org.Archived from the original on 2013-12-31. Retrieved2014-02-19.
- ^Section 3.6.1.2, Standard C++ 2011 edition.
- ^"The
char *apple
Argument Vector". Archived fromthe original on 2015-12-22. Retrieved2014-05-12. - ^"Console Applications in .NET, or Teaching a New Dog Old Tricks". Msdn.microsoft.com. 2003-06-12. Archived fromthe original on 2008-02-04. Retrieved2013-08-19.
- ^"The official repo for the design of the C# programming language: Dotnet/Csharplang".GitHub. 2019-08-26.
- ^XL FORTRAN forAIX. Language Reference. Third Edition, 1994.IBM
- ^"The Haskell 98 Report: Modules". Haskell.org.Archived from the original on 2013-08-19. Retrieved2013-08-19.
- ^Some Haskell Misconceptions: Idiomatic Code, Purity, Laziness, and IOArchived 2010-07-27 at theWayback Machine — on Haskell's monadic IO>
- ^"The Java Language Environment".Oracle.Archived from the original on 2019-04-20. Retrieved2020-03-14.
Within the HelloWorld class, we declare a single method called main() which in turn contains a single method invocation to display the string "Hello world!" on the standard output. The statement that prints "Hello world!" does so by invoking the println method of the out object. The out object is a class variable in the System class that performs output operations on files.
- ^Schildt, Herbert (2019).Java : a beginner's guide. New York: McGraw-Hill Education. p. 46.ISBN 978-1-260-44022-5.OCLC 1061561931.
A JAVA program begins with a call to main ().
- ^"Hello, World! - Free Interactive Java Tutorial".Learn Java. Retrieved2020-03-14.
In Java, every line of code that can actually run needs to be inside a class. "public class Main {}" declares a class named Main, which is public, that means that any other class can access it.
- ^"Hello, World! - Free Interactive Java Tutorial".Learn Java. Retrieved2020-03-14.
"public static void main(String[] args) {} " is the entry point of our Java program. the main method has to have this exact signature in order to be able to run our program.
- ^Guido van Rossum (May 15, 2003)."Python main() functions".Archived from the original on July 11, 2015. RetrievedJune 29, 2015,comments
- ^Code Like a Pythonista: Idiomatic PythonArchived 2014-05-27 at theWayback Machine—on Python scripts used as modules
- ^Ned Batchelder (6 June 2003)."Python main() functions".Archived from the original on 20 September 2015. Retrieved29 June 2015.
- ^Programming Ruby: The Pragmatic Programmer's Guide, Ruby and Its WorldArchived 2013-08-31 at theWayback Machine — on Ruby
ARGV
- ^"Releases.md". GitHub Rust.Archived from the original on 2015-05-15. Retrieved15 February 2019.
- ^Not to be confused withSwift PlaygroundsArchived 2022-07-08 at theWayback Machine, an Apple-developed iPad app for learning the Swift programming language.
- ^"UIApplicationMain(_:_:_:_:) — UIKit".Apple Developer Documentation.Archived from the original on 2019-01-12. Retrieved2019-01-12.
- ^"UIApplication — UIKit".Apple Developer Documentation.Archived from the original on 2019-01-13. Retrieved2019-01-12.
External links
edit- Hello from a libc-free world! (Part 1)Archived 2016-11-17 at theWayback Machine, March 16, 2010
- How main method works in Java