main
; as a result, the entry point is often known as the main function.
In main
; in Main
.
Usage
Entry points apply both to source code and toMain()
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
In most of today's popular programming languages and operating systems, amain
; in main
(although the class must be specified at the invocation time), and in C# it is a static method named Main
.
In many major operating systems, the standard executable format has a single entry point. In the e_entry
field of the ELF header. In the _start
symbol. Similarly, in the AddressOfEntryPoint
field, which is inherited from main
function. Instead, they have ''essential components'' (activities and services) which the system can load and run as needed.
An occasionally used technique is the Historical
Historically, and in some contemporarydirectory.exe$make
.
The Exit point
In general, programs can exit at any time by returning to the operating system or crashing. 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 inatexit
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
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 the command arguments given to the program when it was executed.
The main function is generally the first programmer-written APL
In APL, when a workspace is loaded, the contents of "quad LX" (latent expression) variable is interpreted as an APL expression and executed.C and C++
In C andargc
, ''argument count'', and argv
, ''argument vector'', respectively give the number and values of the program's 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 always be int
; for example, getenv
in stdlib.h
:
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 rgc/code> 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 may refer to:
Architecture and design
* Shell (structure), a thin structure
** Concrete shell, a thin shell of concrete, usually with no interior columns or exterior buttresses
** Thin-shell structure
Science Biology
* Seashell, a hard o ...
will initialise the rm
process with argc = 2
and argv =
. As argv /code> is the name that processes appear under in ps
, top
A spinning top, or simply a top, is a toy with a squat body and a sharp point at the bottom, designed to be spun on its vertical axis, balancing on the tip due to the gyroscopic effect.
Once set in motion, a top will usually wobble for a few ...
etc., some programs, such as daemons or those running within an interpreter or virtual machine
In computing, a virtual machine (VM) is the virtualization/emulation of a computer system. Virtual machines are based on computer architectures and provide functionality of a physical computer. Their implementations may involve specialized hardw ...
(where argv /code> would be the name of the host executable), may choose to alter their argv to give a more descriptive argv /code>, usually by means of the exec Exec or EXEC may refer to:
* Executive officer, a person responsible for running an organization
* Executive producer, provides finance and guidance for the making of a commercial entertainment product
* A family of kit helicopters produced by Rot ...
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
In computing, a namespace is a set of signs (''names'') that are used to identify and refer to objects of various kinds. A namespace ensures that all of a given set of objects have unique names so that they can be easily identified.
Namespaces ...
(i.e. ::main
), cannot be overloaded, and cannot be a member function
A method in object-oriented programming (OOP) is a procedure associated with a message and an object. An object consists of ''state data'' and ''behavior''; these compose an ''interface'', which specifies how the object may be utilized by any of ...
, 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 (adjective: ''recursive'') occurs when a thing is defined in terms of itself or of its type. Recursion is used in a variety of disciplines ranging from linguistics to logic. The most common application of recursion is in mathematics ...
and cannot have its address taken.
C#
When executing a program written in C#, the CLR CLR may refer to:
* Calcium Lime Rust, a household cleaning-product
* California Law Review, a publication by the UC Berkeley School of Law
* Tube_bending, Centerline Radius, a term in the tubing industry used to describe the radius of a bend
* Cen ...
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.
Since C#7.1 there are four more possible signatures of the entry point, which allow asynchronous execution in the Main()
Method.
static Task Main()
static Task Main()
static Task Main(string[])
static Task Main(string[])
The Task
and Task<int>
types are the asynchronous equivalents of void
and int
.
Clean
Clean is a functional programming language based on graph rewriting. The initial node is named Start
and is of type *World -> *World
if it ''changes'' the world or some fixed type if the program only prints the result after reducing Start
.
Start :: *World -> *World
Start world = startIO ...
Or even simpler
Start :: String
Start = "Hello, world!"
One tells the compiler which option to use to generate the executable file.
Common Lisp
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 will emulate
Emulate, Inc. (Emulate) is a biotechnology company that commercialized Organs-on-Chips technology—a human cell-based technology that recreates organ-level function to model organs in healthy and diseased states. The technology has applications ...
a main function.
(defun hello-main ()
(format t "Hello World!~%"))
(hello-main)
D
In D, the function prototype
In computer programming, a function prototype or function interface is a declaration of a function that specifies the function’s name and type signature (arity, data types of parameters, and return type), but omits the function body. While a ...
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.
FORTRAN
FORTRAN does not have a main subroutine or function. Instead a PROGRAM
statement as the first line can be used to specify that a program unit is a main program, as shown below. The PROGRAM
statement cannot be used for recursive calls.
PROGRAM HELLO
PRINT *, "Cint!"
END PROGRAM HELLO
Some versions of Fortran, such as those on the IBM System/360
The IBM System/360 (S/360) is a family of mainframe computer systems that was announced by IBM on April 7, 1964, and delivered between 1965 and 1978. It was the first family of computers designed to cover both commercial and scientific applica ...
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
Using GNAT
A gnat () is any of many species of tiny flying insects in the dipterid suborder Nematocera, especially those in the families Mycetophilidae, Anisopodidae and Sciaridae. They can be both biting and non-biting. Most often they fly in large ...
, the programmer is not required to write a function named main
; a source file containing a single subprogram can be compiled to an executable. The binder will however create a package ada_main
, which will contain and export a C-style main function.
Go
In Go programming language, program execution starts with the main
function of the package main
package main
import "fmt"
func main()
There is no way to access arguments or a return code outside of the standard library in Go. These can be accessed via os.Args
and os.Exit
respectively, both of which are included in the "os"
package.
Haskell
A Haskell
Haskell () is a general-purpose, statically-typed, purely functional programming language with type inference and lazy evaluation. Designed for teaching, research and industrial applications, Haskell has pioneered a number of programming lan ...
program must contain a name main
bound to a value of type IO t
, for some type t
; which is usually IO ()
. IO
is a monad
Monad may refer to:
Philosophy
* Monad (philosophy), a term meaning "unit"
**Monism, the concept of "one essence" in the metaphysical and theological theory
** Monad (Gnosticism), the most primal aspect of God in Gnosticism
* ''Great Monad'', a ...
, which organizes side-effects
In medicine, a side effect is an effect, whether therapeutic or adverse, that is secondary to the one intended; although the term is predominantly employed to describe adverse effects, it can also apply to beneficial, but unintended, consequence ...
in terms of purely functional 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
In the area of mathematical logic and computer science known as type theory, a unit type is a type that allows only one value (and thus can hold no information). The carrier (underlying set) associated with a unit type can be any singleton set. ...
, which contains no information.
main :: IO ()
main = putStrLn "Hello, World!"
Command line arguments are not given to main
; they must be fetched using another IO action, such as System.Environment.getArgs
/code>.
Java
Java
Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's List ...
programs start executing at the main method
Method ( grc, μέθοδος, methodos) literally means a pursuit of knowledge, investigation, mode of prosecuting such inquiry, or system. In recent centuries it more often means a prescribed process for completing a task. It may refer to:
*Scien ...
of a class, which has one of the following method headings:
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 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, a hello world
''Hello'' is a salutation or greeting in the English language. It is first attested in writing from 1826. Early uses
''Hello'', with that spelling, was used in publications in the U.S. as early as the 18 October 1826 edition of the '' Norwich ...
program in Java may look like:
public class HelloWorld
To run this program, one must call java HelloWorld
in the directory where the compiled class file
A Java class file is a file (with the filename extension) containing Java bytecode that can be executed on the Java Virtual Machine (JVM). A Java class file is usually produced by a Java compiler from Java programming language source files ( fi ...
HelloWorld.class
) exists. Alternatively, executable JAR
A jar is a rigid, cylindrical or slightly conical container, typically made of glass, ceramic, or plastic, with a wide mouth or opening that can be closed with a lid, screw cap, lug cap, cork stopper, roll-on cap, crimp-on cap, press-on c ...
files use a manifest file A manifest file in computing is a file containing metadata for a group of accompanying files that are part of a set or coherent unit. For example, the files of a computer program may have a manifest describing the name, version number, license and t ...
to specify the entry point in a manner that is filesystem-independent from the user's perspective.
LOGO
In FMSLogo
''FMSLogo'' is a free implementation of a computing environment called Logo, which is an educational interpreter language. GUI and Extensions were developed by George Mills at MIT. Its core is the same as UCBLogo by Brian Harvey. It is free soft ...
, 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 elcome
end
make "startup rocname
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.
OCaml
OCaml
OCaml ( , formerly Objective Caml) is a general-purpose programming language, general-purpose, multi-paradigm programming language which extends the Caml dialect of ML (programming language), ML with object-oriented programming, object-oriented ...
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:
print_endline "Hello World"
Pascal
In Pascal, the main procedure is the only unnamed block
Block or blocked may refer to:
Arts, entertainment and media Broadcasting
* Block programming, the result of a programming strategy in broadcasting
* W242BX, a radio station licensed to Greenville, South Carolina, United States known as ''96.3 ...
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.
program Hello(Output);
begin
writeln('Hello, world!');
end.
Command-line arguments are counted in ParamCount
and accessible as strings by ParamStr(n)
, with n between 0 and ParamCount
.
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
In Perl
Perl is a family of two high-level, general-purpose, interpreted, dynamic programming languages. "Perl" refers to Perl 5, but from 2000 to 2019 it also referred to its redesigned "sister language", Perl 6, before the latter's name was offici ...
, there is no main function. Statements are executed from top to bottom, although statements in a BEGIN
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
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.
Pike
In Pike
Pike, Pikes or The Pike may refer to:
Fish
* Blue pike or blue walleye, an extinct color morph of the yellow walleye ''Sander vitreus''
* Ctenoluciidae, the "pike characins", some species of which are commonly known as pikes
* ''Esox'', genus of ...
syntax is similar to that of C and C++. The execution begins at main
. The "argc
" variable keeps the number of arguments
An argument is a statement or group of statements called premises intended to determine the degree of truth or acceptability of another statement called conclusion. Arguments can be studied from three main perspectives: the logical, the dialectic ...
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
Python
Python may refer to:
Snakes
* Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia
** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia
* Python (mythology), a mythical serpent
Computing
* Python (pro ...
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 a one-pass compiler
In computer programming, a one-pass compiler is a compiler that passes through the parts of each compilation unit only once, immediately translating each part into its final machine code. This is in contrast to a multi-pass compiler which conver ...
, such as in Pascal.
Alternatively, a program can be structured with an explicit main
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:
import sys
def main(argv):
n = int(argv
print(n + 1)
if __name__ '__main__':
sys.exit(main(sys.argv))
In this idiom, the call to the named entry point main
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 contrast with C, where these are done ''implicitly'' by the runtime, based on convention.
QB64
The QB64
QB64 (originally QB32) is a Self-hosting (compilers), self-hosting BASIC compiler for Microsoft Windows, Linux and Mac OS X, designed to be compatible with Microsoft QBasic and QuickBASIC. QB64 is a C++ Code generation (compiler), emitter, which ...
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): print a
function getInteger(n as double)
getInteger = int(n)
end function
Command line arguments (if any) can be read using the COMMAND$ function:
dim shared commandline as string
commandline = COMMAND$
'Several space-separated command line arguments can be read using COMMAND$(n)
commandline1 = COMMAND$(2)
Ruby
In Ruby
A ruby is a pinkish red to blood-red colored gemstone, a variety of the mineral corundum ( aluminium oxide). Ruby is one of the most popular traditional jewelry gems and is very durable. Other varieties of gem-quality corundum are called sa ...
, there is no distinct main function. Instead, code written outside of any class .. end
or module .. end
scope is executed in the context of a special "main
" object. This object can be accessed using self
:
irb(main):001:0> self
=> main
It has the following properties:
irb(main):002:0> self.class
=> Object
irb(main):003:0> self.class.ancestors
=> bject, Kernel, BasicObject
Methods defined outside of a class
or module
scope are defined as private methods of the "main
" object. Since the class of "main
" is Object
, such methods become private methods of almost every object:
irb(main):004:0> def foo
irb(main):005:1> 42
irb(main):006:1> end
=> nil
irb(main):007:0> foo
=> 42
irb(main):008:0> [].foo
NoMethodError: private method `foo' called for []:Array
from (irb):8
from /usr/bin/irb:12:in `'
irb(main):009:0> false.foo
NoMethodError: private method `foo' called for false:FalseClass
from (irb):9
from /usr/bin/irb:12:in `'
The number and values of command-line arguments can be determined using the ARGV
constant array:
$ irb /dev/tty foo bar
tty(main):001:0> ARGV
ARGV
=> foo", "bar"tty(main):002:0> ARGV.size
ARGV.size
=> 2
The first element of ARGV
, ARGV /code>, 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
to execute some code only if its file was specified in the ruby
invocation.
Rust
In Rust, the entry point of a program is a function named main
. Typically, this function is situated in a file called main.rs
or lib.rs
.
// In `main.rs`
fn main()
Additionally, as of Rust 1.26.0, the main function may return a Result
:
fn main() -> Result<(), std::io::Error>
Swift
When run in an Xcode
Xcode is Apple's integrated development environment (IDE) for macOS, used to develop software for macOS, iOS, iPadOS, watchOS, and tvOS. It was initially released in late 2003; the latest stable release is version 14.2, released on December 13, ...
Playground, Swift
Swift or SWIFT most commonly refers to:
* SWIFT, an international organization facilitating transactions between banks
** SWIFT code
* Swift (programming language)
* Swift (bird), a family of birds
It may also refer to:
Organizations
* SWIFT, ...
behaves like a scripting language, executing statements from top to bottom; top-level code is allowed.
// HelloWorld.playground
let hello = "hello"
let world = "world"
let helloWorld = hello + " " + world
print(helloWorld) // hello world
Cocoa
Cocoa may refer to:
Chocolate
* Chocolate
* ''Theobroma cacao'', the cocoa tree
* Cocoa bean, seed of ''Theobroma cacao''
* Chocolate liquor, or cocoa liquor, pure, liquid chocolate extracted from the cocoa bean, including both cocoa butter and ...
- and Cocoa Touch
Cocoa Touch is the application development environment for building software programs to run on iOS for the iPhone and iPod Touch, iPadOS for the iPad, watchOS for the Apple Watch, and tvOS for the Apple TV, from Apple Inc.
Cocoa Touch provide ...
-based applications written in Swift are usually initialized with the @NSApplicationMain
and @UIApplicationMain
attributes, respectively. Those attributes are equivalent in their purpose to the main.m
file in Objective-C
Objective-C is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. Originally developed by Brad Cox and Tom Love in the early 1980s, it was selected by NeXT for its NeXTS ...
projects: they implicitly declare the main
function that calls UIApplicationMain(_:_:_:_:)
which creates an instance of UIApplication
.
The following code is the default way to initialize a Cocoa Touch-based iOS
iOS (formerly iPhone OS) is a mobile operating system created and developed by Apple Inc. exclusively for its hardware. It is the operating system that powers many of the company's mobile devices, including the iPhone; the term also include ...
app and declare its application delegate.
// AppDelegate.swift
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate
Visual Basic
In Visual Basic Visual Basic is a name for a family of programming languages from Microsoft. It may refer to:
* Visual Basic .NET (now simply referred to as "Visual Basic"), the current version of Visual Basic launched in 2002 which runs on .NET
* Visual Basic (cl ...
, when a project contains no forms, the startup object may be the Main()
procedure. The Command$
function can be optionally used to access the argument portion of the command line used to launch the program:
Sub Main()
Debug.Print "Hello World!"
MsgBox "Arguments if any are: " & Command$
End Sub
Xojo
In Xojo
The Xojo programming environment and programming language is developed and commercially marketed by Xojo, Inc. of Austin, Texas for software development targeting macOS, Microsoft Windows, Linux, iOS, the Web and Raspberry Pi. Xojo uses a propri ...
, 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.
See also
* crt0
(also known as ) is a set of execution startup routines linked into a C program that performs any initialization work required before calling the program's main function.
Form and usage
Crt0 generally takes the form of an object file called ...
, a set of execution startup routines linked into a C program
* Runtime system
In computer programming, a runtime system or runtime environment is a sub-system that exists both in the computer where a program is created, as well as in the computers where the program is intended to be run. The name comes from the compile t ...
References
External links
Hello from a libc-free world! (Part 1)
, March 16, 2010
How main method works in Java
{{DEFAULTSORT:Entry Point
Control flow
Computer programming
.NET programming languages
Software