Argc
   HOME

TheInfoList



OR:

In
computer programming Computer programming or coding is the composition of sequences of instructions, called computer program, programs, that computers can follow to perform tasks. It involves designing and implementing algorithms, step-by-step specifications of proc ...
, an entry point is the place in a program where the execution of a program begins, and where the program has access to
command line A command-line interface (CLI) is a means of interacting with software via command (computing), commands each formatted as a line of text. Command-line interfaces emerged in the mid-1960s, on computer terminals, as an interactive and more user ...
arguments. To start a program's
execution Capital punishment, also known as the death penalty and formerly called judicial homicide, is the state-sanctioned killing of a person as punishment for actual or supposed misconduct. The sentence ordering that an offender be punished in ...
, the loader or
operating system An operating system (OS) is system software that manages computer hardware and software resources, and provides common daemon (computing), services for computer programs. Time-sharing operating systems scheduler (computing), schedule tasks for ...
passes control to its entry point. (During
booting In computing, booting is the process of starting a computer as initiated via Computer hardware, hardware such as a physical button on the computer or by a software command. After it is switched on, a computer's central processing unit (CPU) h ...
, the operating system ''itself'' is the program). This marks the transition from load time (and dynamic
link time In computer science, link time refers to the period of time, during the creation of a computer program, in which a linker is being applied to that program. Link time occurs after compile time and before runtime (when a program is executed). It ...
, if present) to run time. For some operating systems and
programming language A programming language is a system of notation for writing computer programs. Programming languages are described in terms of their Syntax (programming languages), syntax (form) and semantics (computer science), semantics (meaning), usually def ...
s, the entry point is in a
runtime library A runtime library is a library that provides access to the runtime environment that is available to a computer program tailored to the host platform. A runtime environment implements the execution model as required for a development environme ...
, 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. In simple systems, execution begins at the first statement, which is common in
interpreted language In computer science, an interpreter is a computer program that directly executes instructions written in a programming or scripting language, without requiring them previously to have been compiled into a machine language program. An inter ...
s, simple
executable In computer science, executable code, an executable file, or an executable program, sometimes simply referred to as an executable or binary, causes a computer "to perform indicated tasks according to encoded instruction (computer science), in ...
formats, and
boot loader A bootloader, also spelled as boot loader or called bootstrap loader, is a computer program that is responsible for booting a computer and booting an operating system. If it also provides an interactive menu with multiple boot choices then it's o ...
s. In other cases, the entry point is at some other known
memory address In computing, a memory address is a reference to a specific memory location in memory used by both software and hardware. These addresses are fixed-length sequences of digits, typically displayed and handled as unsigned integers. This numeric ...
which can be an
absolute address In computing, a memory address is a reference to a specific memory location in memory used by both software and hardware. These addresses are fixed-length sequences of digits, typically displayed and handled as unsigned integers. This numeric ...
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 many C-family languages, this is a function called main; as a result, the entry point is often known as the main function. In JVM languages, such as
Java Java is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea (a part of Pacific Ocean) to the north. With a population of 156.9 million people (including Madura) in mid 2024, proje ...
, the entry point is a static method called main; in
CLI languages CLI languages are computer programming languages that are used to produce libraries and programs that conform to the Common Language Infrastructure (CLI) specifications. With some notable exceptions, most CLI languages compile entirely to the Com ...
such as C# the entry point is a static method named Main.


Usage

Entry points apply both to source code and to
executable In computer science, executable code, an executable file, or an executable program, sometimes simply referred to as an executable or binary, causes a computer "to perform indicated tasks according to encoded instruction (computer science), in ...
files. However, in day-to-day
software development Software development is the process of designing and Implementation, implementing a software solution to Computer user satisfaction, satisfy a User (computing), user. The process is more encompassing than Computer programming, programming, wri ...
, programmers specify the entry points only in source code, which makes them much better known. Entry points in executable files depend on the
application binary interface An application binary interface (ABI) is an interface exposed by software that is defined for in-process machine code access. Often, the exposing software is a library, and the consumer is a program. An ABI is at a relatively low-level of a ...
(ABI) of the actual operating system, and are generated by the compiler or linker (if not fixed by the ABI). Other linked
object file An object file is a file that contains machine code or bytecode, as well as other data and metadata, generated by a compiler or assembler from source code during the compilation or assembly process. The machine code that is generated is kno ...
s 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 the Main() 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, a
computer program A computer program is a sequence or set of instructions in a programming language for a computer to Execution (computing), execute. It is one component of software, which also includes software documentation, documentation and other intangibl ...
usually only has a single ''entry point''. In C, C++, D, Zig,
Rust Rust is an iron oxide, a usually reddish-brown oxide formed by the reaction of iron and oxygen in the catalytic presence of water or air moisture. Rust consists of hydrous iron(III) oxides (Fe2O3·nH2O) and iron(III) oxide-hydroxide (FeO(OH) ...
and Kotlin programs this is a
function Function or functionality may refer to: Computing * Function key, a type of key on computer keyboards * Function model, a structured representation of processes in a system * Function object or functor or functionoid, a concept of object-orie ...
named main; in
Java Java is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea (a part of Pacific Ocean) to the north. With a population of 156.9 million people (including Madura) in mid 2024, proje ...
it is a
static method A method in object-oriented programming (OOP) is a procedure associated with an object, and generally also a message. An object consists of ''state data'' and ''behavior''; these compose an ''interface'', which specifies how the object may be us ...
named 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
Executable and Linkable Format In computing, the Executable and Linkable FormatTool Interface Standard (TIS) Portable Formats SpecificationVersion 1.1'' (October 1993) (ELF, formerly named Extensible Linking Format) is a common standard file format for executable files, obje ...
(ELF), used in
Unix Unix (, ; trademarked as UNIX) is a family of multitasking, multi-user computer operating systems that derive from the original AT&T Unix, whose development started in 1969 at the Bell Labs research center by Ken Thompson, Dennis Ritchie, a ...
and
Unix-like A Unix-like (sometimes referred to as UN*X, *nix or *NIX) operating system is one that behaves in a manner similar to a Unix system, although not necessarily conforming to or being certified to any version of the Single UNIX Specification. A Uni ...
systems such as
Linux Linux ( ) is a family of open source Unix-like operating systems based on the Linux kernel, an kernel (operating system), operating system kernel first released on September 17, 1991, by Linus Torvalds. Linux is typically package manager, pac ...
, the entry point is specified in the e_entry field of the ELF header. In the
GNU Compiler Collection The GNU Compiler Collection (GCC) is a collection of compilers from the GNU Project that support various programming languages, Computer architecture, hardware architectures, and operating systems. The Free Software Foundation (FSF) distributes ...
(gcc), the entry point used by the linker is the _start symbol. Similarly, in the
Portable Executable The Portable Executable (PE) format is a file format for executables, object file, object code, Dynamic-link library, dynamic-link-libraries (DLLs), and binary files used on 32-bit and 64-bit Microsoft Windows, Windows operating systems, as well ...
format, used in
Microsoft Windows Windows is a Product lining, product line of Proprietary software, proprietary graphical user interface, graphical operating systems developed and marketed by Microsoft. It is grouped into families and subfamilies that cater to particular sec ...
, the entry point is specified by the AddressOfEntryPoint field, which is inherited from
COFF The Common Object File Format (COFF) is a format for executable, object code, and shared library computer files used on Unix systems. It was introduced in Unix System V, replaced the previously used a.out format, and formed the basis for ext ...
. In
COM file A COM file is a type of simple executable file. On the Digital Equipment Corporation (DEC) VAX operating systems of the 1970s, .COM was used as a filename extension for text files containing commands to be issued to the operating system (sim ...
s, the entry point is at the fixed offset of 0100h. One exception to the single-entry-point paradigm is Android. Android applications do not have a single entry point there is no special 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
fat binary A fat binary (or multiarchitecture binary) is a computer executable program or library which has been expanded (or "fattened") with code native to multiple instruction sets which can consequently be run on multiple processor types. This results ...
, 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 separate
forks In cutlery or kitchenware, a fork (from 'pitchfork') is a Eating utensil, utensil, now usually made of metal, whose long handle terminates in a head that branches into several narrow and often slightly curved tine (structural), tines with whic ...
, each with its own entry point, which is then selected by the operating system.


Historical

Historically, and in some contemporary
legacy system Legacy or Legacies may refer to: Arts and entertainment Comics * " Batman: Legacy", a 1996 Batman storyline * '' DC Universe: Legacies'', a comic book series from DC Comics * ''Legacy'', a 1999 quarterly series from Antarctic Press * ''Legacy ...
s, such as VMS and
OS/400 IBM i (the ''i'' standing for ''integrated'') is an operating system developed by IBM for IBM Power Systems. It was originally released in 1988 as OS/400, as the sole operating system of the IBM AS/400 line of systems. It was renamed to i5/OS in 2 ...
, computer programs have a multitude of ''entry points'', each corresponding to the different functionalities of the program. The usual way to denote entry points, as used system-wide in VMS and in
PL/I PL/I (Programming Language One, pronounced and sometimes written PL/1) is a procedural, imperative computer programming language initially developed by IBM. It is designed for scientific, engineering, business and system programming. It has b ...
and MACRO programs, is to append them at the end of the name of the executable image, delimited by a
dollar sign The dollar sign, also known as the peso sign, is a currency symbol consisting of a Letter case, capital crossed with one or two vertical strokes ( or depending on typeface), used to indicate the unit of various currency, currencies around ...
($), e.g. directory.exe$make. The
Apple I The Apple Computer 1 (Apple-1), later known predominantly as the Apple I, is an 8-bit personal computer designed by Steve Wozniak and released by the Apple Computer Company (now Apple Inc.) in 1976. The company was initially formed to ...
computer also used this to some degree. For example, an alternative entry point in Apple I's
BASIC Basic or BASIC may refer to: Science and technology * BASIC, a computer programming language * Basic (chemistry), having the properties of a base * Basic access authentication, in HTTP Entertainment * Basic (film), ''Basic'' (film), a 2003 film ...
would keep the BASIC program useful when the reset button was accidentally pushed.


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 in
undefined behavior In computer programming, a program exhibits undefined behavior (UB) when it contains, or is executing code for which its programming language specification does not mandate any specific requirements. This is different from unspecified 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 as atexit 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, the main 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
function Function or functionality may refer to: Computing * Function key, a type of key on computer keyboards * Function model, a structured representation of processes in a system * Function object or functor or functionoid, a concept of object-orie ...
that runs when a program starts, and is invoked directly from the system-specific initialization contained in the
runtime environment In computer programming, a runtime system or runtime environment is a sub-system that exists 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 time ...
(
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. After the main function completes the control returns to crt0, which c ...
or equivalent). However, some languages can execute user-written functions before main runs, such as the constructors of C++ global objects. In other languages, notably many
interpreted language In computer science, an interpreter is a computer program that directly executes instructions written in a programming or scripting language, without requiring them previously to have been compiled into a machine language program. An inter ...
s, 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

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 and C++, the
function prototype In computer programming, a function prototype 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 function definition ...
of the main function must be equivalent to one of the following: int main(); int main(void); int main(int argc, 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 a
bare-metal In information technology, bare machine (or bare-metal computer) is a computer which has no operating system. The software executed by a bare machine, commonly called a "bare metal program" or "bare metal application", is designed to interact dir ...
embedded system An embedded system is a specialized computer system—a combination of a computer processor, computer memory, and input/output peripheral devices—that has a dedicated function within a larger mechanical or electronic system. It is e ...
) might specify a different entry point (for example via a reset
interrupt vector An interrupt vector table (IVT) is a data structure that associates a list of interrupt handlers with a list of interrupt requests in a table of interrupt vectors. Each entry of the interrupt vector table, called an interrupt vector, is the addre ...
) using functionality not defined by the language standard. The
parameters A parameter (), generally, is any characteristic that can help in defining or classifying a particular system (meaning an event, project, object, situation, etc.). That is, a parameter is an element of a system that is useful, or critical, when ...
argc, ''argument count'', and argv, ''argument vector'', respectively give the number and values of the program's
command-line argument A command-line interface (CLI) is a means of interacting with software via command (computing), commands each formatted as a line of text. Command-line interfaces emerged in the mid-1960s, on computer terminals, as an interactive and more user ...
s. The names of argc and argv 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 be int; for example,
Unix Unix (, ; trademarked as UNIX) is a family of multitasking, multi-user computer operating systems that derive from the original AT&T Unix, whose development started in 1969 at the Bell Labs research center by Ken Thompson, Dennis Ritchie, a ...
(though not POSIX.1) and
Windows Windows is a Product lining, product line of Proprietary software, proprietary graphical user interface, graphical operating systems developed and marketed by Microsoft. It is grouped into families and subfamilies that cater to particular sec ...
have a third argument giving the program's environment, otherwise accessible through getenv in stdlib.h: int main(int argc, char **argv, char **envp); Darwin-based operating systems, such as
macOS macOS, previously OS X and originally Mac OS X, is a Unix, Unix-based operating system developed and marketed by Apple Inc., Apple since 2001. It is the current operating system for Apple's Mac (computer), Mac computers. With ...
, have a fourth parameter containing arbitrary OS-supplied information, such as the path to the executing binary: int main(int argc, char **argv, char **envp, char **apple); The value returned from the main function becomes the
exit status In computing, the exit status (also exit code or exit value) of a terminated process is an integer number that is made available to its parent process (or caller). In DOS, this may be referred to as an errorlevel. When computer programs ar ...
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
rgc RGC may refer to: * Radial glial cell * Receiver General for Canada * Retinal ganglion cell * Retro Game Challenge * Revolutionary Guard Corps * RGC 1404, a Welsh rugby union franchise * Rio Grande City, Texas * Robert Gordon's College * The Ro ...
/code> is a
null pointer In computing, a null pointer (sometimes shortened to nullptr or null) or null reference is a value saved for indicating that the Pointer (computer programming), pointer or reference (computer science), reference does not refer to a valid Object (c ...
. 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 Science Biology * Seashell, a hard outer layer of a marine ani ...
will initialise the rm process with argc = 2 and argv = . As argv /code> is the name that processes appear under in ps,
top Top most commonly refers to: * Top, a basic term of orientation, distinguished from bottom, front, back, and sides * Spinning top, a ubiquitous traditional toy * Top (clothing), clothing designed to be worn over the torso * Mountain top, a moun ...
etc., some programs, such as daemons or those running within an
interpreter Interpreting is translation from a spoken or signed language into another language, usually in real time to facilitate live communication. It is distinguished from the translation of a written text, which can be more deliberative and make use o ...
or
virtual machine In computing, a virtual machine (VM) is the virtualization or emulator, emulation of a computer system. Virtual machines are based on computer architectures and provide the functionality of a physical computer. Their implementations may involve ...
(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 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, 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 and cannot have its address taken.


C#

When executing a program written in C#, the CLR 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 async Task Main() static async Task Main() static async Task Main(string[]) static async Task Main(string[]) The Task and Task<int> types are the asynchronous equivalents of void and int. async is required to allow the use of asynchrony (the await keyword) inside the method.


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 a main function. (defun hello-main () (format t "Hello World!~%")) (hello-main)


D

In D, the
function prototype In computer programming, a function prototype 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 function definition ...
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.


Dart

Dart is a
general-purpose programming language In computer software, a general-purpose programming language (GPL) is a programming language for building software in a wide variety of application Domain (software engineering), domains. Conversely, a Domain-specific language, domain-specific pro ...
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 named main . When a Dart program is run, the Dart runtime looks for a function named main and executes it. Any Dart code that is intended to be executed when the program starts should be included in the main function. Here is an example of a simple main function in Dart: void main() In this example, the main function simply prints the text Hello, 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 the main 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, the main function is the entry point that should be used for Dart programs.


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 announced by IBM on April 7, 1964, and delivered between 1965 and 1978. System/360 was the first family of computers designed to cover both commercial and scientific applicati ...
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 GNAT is a free-software compiler for the Ada programming language which forms part of the GNU Compiler Collection (GCC). It supports all versions of the language, i.e. Ada 2012, Ada 2005, Ada 95 and Ada 83. Originally its ...
, 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 pioneered several programming language ...
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'', an ...
, which organizes
side-effects In medicine, a side effect is an effect of the use of a medicinal drug or other treatment, usually adverse but sometimes beneficial, that is unintended. Herbal and traditional medicines also have side effects. A drug or procedure usually used ...
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 is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea (a part of Pacific Ocean) to the north. With a population of 156.9 million people (including Madura) in mid 2024, proje ...
programs start executing at the main
method Method (, methodos, from μετά/meta "in pursuit or quest of" + ὁδός/hodos "a method, system; a way or manner" of doing, saying, etc.), literally means a pursuit of knowledge, investigation, mode of prosecuting such inquiry, or system. In re ...
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[]) void main() 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 World may refer to: * "Hello, World!" program, a computer program that outputs or displays the message "Hello, World!" Music * "Hello World!" (composition), song by the Iamus computer * "Hello World" (Tremeloes song), 1969 * "Hello World" ...
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 HelloWorld.class) exists. Alternatively, executable JAR files use a
manifest file In computer programming, a manifest file is a Data file, 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, Soft ...
to specify the entry point in a manner that is filesystem-independent from the user's perspective.


LOGO

In FMSLogo, 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 a 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, High-level programming language, high-level, Comparison of multi-paradigm programming languages, multi-paradigm programming language which extends the ...
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 high-level, general-purpose, interpreted, dynamic programming language. Though Perl is not officially an acronym, there are various backronyms in use, including "Practical Extraction and Reporting Language". Perl was developed ...
, 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 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 series of sentences, statements, or propositions some of which are called premises and one is the conclusion. The purpose of an argument is to give reasons for one's conclusion via justification, explanation, and/or persua ...
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 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 processes each compilation unit only once, sequentially translating each source statement or declaration into something close to its final machine code. This is in contrast to a mul ...
, 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 contrasts with C, where these are done ''implicitly'' by the runtime, based on convention.


QB64

The
QB64 QB64 (originally QB32) is a self-hosting BASIC compiler for Microsoft Windows, Linux and Mac OS X, designed to be compatible with Microsoft QBasic and QuickBASIC. QB64 is a transpiler to C++, which is integrated with a C++ compiler to provide ...
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 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 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 sapph ...
, 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 a suite of developer tools for building apps on Apple devices. It includes an integrated development environment (IDE) of the same name for macOS, used to develop software for macOS, iOS, iPadOS, watchOS, tvOS, and visionOS. It w ...
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 * SWIF ...
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- and
Cocoa Touch UIKit is an application development environment and graphical user interface toolkit from Apple Inc. used to build apps for the iOS, iPadOS, watchOS, tvOS, and visionOS operating systems. UIKit provides an abstraction layer of iOS, the ...
-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 high-level general-purpose, object-oriented programming language that adds Smalltalk-style message passing (messaging) to the C programming language. Originally developed by Brad Cox and Tom Love in the early 1980s, it was ...
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, Io or Nio (, ; ; locally Nios, Νιός) is a Greek island in the Cyclades group in the Aegean Sea. Ios is a hilly island with cliffs down to the sea on most sides. It is situated halfway between Naxos and Santorini. It is about long an ...
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), the current version of Visual Basic launched in 2002 which runs on .NET * Visual Basic (classic), the original Visual Basic suppo ...
, 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, Android, the Web and Raspberry Pi. Xojo uses ...
, 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. After the main function completes the control returns to crt0, which c ...
, 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 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 time ...


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 Software