
Main() might look inC# source code. Different parts are labeled for reference.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]
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]
Entry 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.
In 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.
Historically, 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]
In 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.
In 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:
InAPL, when a workspace is loaded, the contents of "quad LX" (latent expression) variable is interpreted as an APL expression and executed.
InC andC++, thefunction prototype of the main function must be equivalent to one of the following:
intmain();intmain(void);intmain(intargc,char*argv[]);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.
If using trailing return types, C++ also supports the following signatures ofmain:
automain()->int;automain(intargc,char*argv[])->int;
Theparametersargc,argument count, andargv,argument vector,[8] 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;[9] 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:[10]
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.
OnGCC andClang, it is possible to callmain() (or potentially even select a different function as the entry point) by passing the compiler flag–nostartfiles and then defining the function_start(). Arguments from command line tomain() can be retrieved using inline assembly.
#include<stdio.h>#include<stdlib.h>void_start(){intexitCode=altMain();exit(exitCode);}intaltMain(){printf("No main() function in this program.");return0;}
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), and cannot be overloaded. In C++ (unlike C)main() cannot be calledrecursively and cannot have its address taken. Ifmain() is not defined in the global namespace (for example if it is only defined as amember function of a class), the compiler will not detect it. The namemain is not otherwise reserved, and may be used for member functions, classes, enumerations, or non-member functions in other namespaces.
importstd;usingstd::string;usingstd::vector;classMain{public:staticvoidmain(constvector<string>&args){std::println("Java-style main() function");}};intmain(intargc,char*argv[]){vector<string>args(argv,argv+argc);Main::main(args);return0;}
When 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.[11]
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.
Like Java, the entry point of a program typically resides in a named class, like so:
namespaceWikipedia.Examples;usingSystem;publicclassHelloWorld{staticvoidMain(string[]args){Console.WriteLine("Hello, world!");}}
Since C#7.1 there are four more possiblesignatures of the entry point, which allow asynchronous execution in theMain() Method.[12]
staticasyncTaskMain()staticasyncTask<int>Main()staticasyncTaskMain(string[]args)staticasyncTask<int>Main(string[]args)
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 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.
ANSI 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)
InD, 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 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 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.[13]
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.
UsingGNAT, 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.
InGo 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.
AHaskell program must contain a namemain bound to a value of typeIO t, for some typet;[14] which is usuallyIO ().IO is amonad, which organizesside-effects in terms ofpurely functional code.[15] 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 programs start executing at the mainmethod of a class,[16][17][18][19] which has one of the followingmethod headings:
// named class-basedpublicstaticvoidmain();publicstaticvoidmain(String[]args);publicstaticvoidmain(String...args);publicstaticvoidmain(Stringargs[]);// unnamed class-basedvoidmain();voidmain(String[]args);voidmain(String...args);voidmain(Stringargs[]);
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:
packageorg.wikipedia.examples;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.
Since Java 25, it is possible to create a "compact source file" which implicitly declares afinal class in the unnamed package. This class extendsjava.lang.Object and does not implement any interfaces, has only a default constructor, and has the fields and methods declared in the compact source file.[20] Furthermore, Java 25 moves the classjava.io.IO to the packagejava.lang (thus implicitly importing it into all source files), based onSystem.out andSystem.in rather thanjava.io.Console. This allows a simplified Hello World program, perhaps more similar to C and C++ wheremain resides in the global namespace:
voidmain(){IO.println("Hello, world!");}
InJulia the entry point (at least for scripts, see below for compiled programs) is the program file you itself you run, i.e. from the very first line so you can simply do (or start with):
println("Hello, world! Called from$PROGRAM_FILE with following arguments:");forxinARGS;println(x);end
Since Julia version 1.11 there's also the possibility of defining amain function that will be called as an entry point, and it can e.g. look like this if using the associated@main macro:
(@main)(ARGS)=println("Hello World! Called from main.")
For compatibility with prior Julia versions, such as Julia 1.10 (LTS), the above line can be made to work with one extra line from the documentation, and using this way can help since the new "feature is intended to aid in the unification of compiled and interactive workflows."[21] Other ways documented elsewhere[22] are no longer needed.
The formerprintln above showing the older way for an entry point without defining amain function is still perfectly fine for scripts (and ARGS is available in both cases, there directly from the a global variable; and PROGRAM_FILE in either case). Note if you do both, scripts will still run the first line as usual, and from there onward so this would also callmain and print twice. But neither is necessarily the first code run unless you invoke Julia with--startup-file=no since the default Julia startup file is run before anything else (it's empty after install, but can easily be forgotten e.g. when benchmarking, if you've added to it).
The exit status is 0 by default (on success, throwing changes that), andexit(my_exit_code) exits the program with a non-default one.
InFMSLogo, 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 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"
InPascal, 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.
InPerl, 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 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.
InPike 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 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:[23][24][25]
importsysdefmain(argv:list[str])->int:argc:int=len(argv)# get length of argvn:int=int(argv[1])print(n+1)return0if__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.
TheQB64 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)
InRuby, 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.[26]
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.
In Rust, the entry point of a program is a function namedmain. By convention, this function is situated in a file calledmain.rs.
// In main.rsfnmain(){println!("Hello, World!");}
Additionally, as of Rust 1.26.0, the main function may return aResult:[27]
usestd::io::Error;fnmain()->Result<(),Error>{println!("Hello, World!");Ok(())// Return a type Result of value Ok with the content (), the unit type.}
Rust does not have parameters in themain() function like C++ and Java or otherC-style languages. Instead, it accesses command-line arguments usingstd::env::args(), which returnsstd::env::Args and can then be converted toVec<String> using.collect().
usestd::env;usestd::env::Args;usestd::io::Error;fnmain()->Result<(),Error>{letargs:Args=env::args();// get the command line argsletargs_vec:Vec<String>=args.collect();// collect args into a Vec<String>forarginargs_vec{println!("{}",arg);}Ok(())}
When run in anXcode Playground,[28]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(_:_:_:_:)[29] which creates an instance ofUIApplication.[30]
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}}
InVisual 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
InXojo, 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.
char *apple Argument Vector". Archived fromthe original on 2015-12-22. Retrieved2014-05-12.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.
A JAVA program begins with a call to main ().
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.
"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.
ARGV