Jump to content

Entry point: Difference between revisions

From Wikipedia, the free encyclopedia
Content deleted Content added
See also: Added one more link
Cleanups
(5 intermediate revisions by the same user not shown)
Line 2: Line 2:
{{More references|date=February 2014}}
{{More references|date=February 2014}}


In [[computer programming]], an '''entry point''' is where control enters a program or piece of code.
In [[computer programming]], an '''entry point''' is where control enters a program or piece of code. In many [[programming language]]s, the '''main function''' is where a program starts its execution.


== Usage ==
== Usage ==
Line 15: Line 15:


The [[Apple I]] computer also used this to some degree. For example, an alternative entry point in Apple I's [[BASIC]] would keep the BASIC program useful when the reset button was accidentally pushed.{{Clarify|date=July 2010}}<!-- in memory? difficult to know without a reference -->
The [[Apple I]] computer also used this to some degree. For example, an alternative entry point in Apple I's [[BASIC]] would keep the BASIC program useful when the reset button was accidentally pushed.{{Clarify|date=July 2010}}<!-- in memory? difficult to know without a reference -->

==Variants==
In many programming languages, the ''main function'' is where a program starts its execution. It is responsible for the high-level organization of the program's functionality, and typically has access to the [[command-line argument|command arguments]] given to the program when it was executed.

The main function is generally the first programmer-written [[subroutine|function]] that runs when a program starts, and is invoked directly from the system-specific initialization contained in [[crt0]] or equivalent. However, some languages can execute user-written functions before main runs, such as the constructors of [[C++]] global objects.

===C and C++===
In [[C (programming language)|C]] and [[C++]], the [[function prototype]] of the main function looks like one of the following:

<source lang="c">
int main(void);
int main();

int main(int argc, char **argv);
int main(int argc, char *argv[]);
</source>

The [[parameter (computer science)|parameter]]s <code>argc</code>, ''argument count'', and <code>argv</code>, ''argument vector'',<ref>argv: the vector term in this variable's name is used in traditional sense to refer to strings.</ref> respectively give the number and values of the program's [[command-line argument]]s. The names of <code>argc</code> and <code>argv</code> 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.<ref>[http://groups.google.com/group/comp.std.c++/browse_thread/thread/a1e5504b499bc58f] - Parameter types and names of main.</ref> Other platform-dependent formats are also allowed by the C and C++ standards, except that in C++ the return type must always be <code>int</code>;<ref>Section 3.6.1.2, Standard C++ 2011 edition.</ref> for example, [[Unix]] (though not [[POSIX.1]]) and [[Microsoft Windows]] have a third argument giving the program's [[environment variable|environment]], otherwise accessible through <code>getenv</code> in <code>[[stdlib.h]]</code>:
<source lang="c">
int main(int argc, char **argv, char **envp);
</source>

[[Mac OS X]] and [[Darwin (operating system)|Darwin]] have a fourth parameter containing arbitrary OS-supplied information, such as the path to the executing binary:<ref>[http://unixjunkie.blogspot.com/2006/02/char-apple-argument-vector.html The <code>char *apple</code> Argument Vector]</ref>

<source lang="c">
int main(int argc, char **argv, char **envp, char **apple);
</source>

The value returned from the main function becomes the [[exit status]] of the process, though the C standard only ascribes specific meaning to two values: <code>EXIT_SUCCESS</code> (traditionally 0) and <code>EXIT_FAILURE</code>. The meaning of other possible return values is implementation-defined. In case a return value is not defined by the programmer, an implicit <code>return 0;</code> at the end of the <code>main()</code> function is inserted by the compiler; this behavior is required by the C++ standard.

It is guaranteed that <code>argc</code> is non-negative and that <code>argv[argc]</code> is a [[null pointer]]. By convention, the command-line arguments specified by <code>argc</code> and <code>argv</code> include the name of the program as the first element if <code>argc</code> is greater than 0; if a user types a command of "<code>rm file</code>", the [[shell (computing)|shell]] will initialise the <code>[[rm (Unix)|rm]]</code> process with <code>argc = 2</code> and <code>argv = ["rm", "file", NULL]</code>. As <code>argv[0]</code> is the name that processes appear under in <code>[[ps (Unix)|ps]]</code>, <code>[[top (Unix)|top]]</code> etc., some programs, such as [[Daemon (computer software)|daemon]]s or those running within an [[interpreter (computing)|interpreter]] or [[virtual machine]] (where <code>argv[0]</code> would be the name of the host executable), may choose to alter their argv to give a more descriptive <code>argv[0]</code>, usually by means of the <code>[[Exec (operating system)|exec]]</code> system call.

The <code>main()</code> function is special; normally every C and C++ program must define it exactly once.

If declared, <code>main()</code> must be declared as if it has external linkage; it cannot be declared <code>static</code> or <code>inline</code>.

In C++, <code>main()</code> must be in the global [[namespace]] (i.e. <code>::main</code>), 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) <code>main()</code> cannot be called [[Recursion (computer science)|recursively]] and cannot have its address taken.

===Clean===
[[Clean (programming language)|Clean]] is a functional programming language based on graph rewriting. The initial node is called <code>Start</code> and is of type <code>*World -> *World</code> if it ''changes'' the world or some fixed type if the program only prints the result after [[graph rewriting|reducing]] <code>Start</code>.

Start :: *World -> *World
Start world = startIO ...

Or even simpler

Start :: String
Start = "Hello, world!"

One tells the compiler which option to use to generate the executable file.

===C#===
When executing a program written in [[C Sharp (programming language)|C#]], the [[Common Language Runtime|CLR]] searches for a static method marked with the <code>.entrypoint</code> IL directive, which takes either no arguments, or a single argument of type <code>string[]</code>, and has a return type of <code>void</code> or <code>int</code>, and executes it.<ref>{{cite web|url=http://msdn.microsoft.com/msdnmag/issues/04/02/NETConsoleApps/ |title=Console Appplications in .NET, or Teaching a New Dog Old Tricks |publisher=Msdn.microsoft.com |date=2003-06-12 |accessdate=2013-08-19}}</ref>

<source lang="csharp">
static void Main();
static void Main(string[] args);
int Main();
static int Main(string[] args);
</source>

Command-line arguments are passed in <code>args</code>, similar to how it is done in Java. For versions of <code>Main()</code> returning an integer, similar to both C and C++, it is passed back to the environment as the exit status of the process.

===D===
In [[D (programming language)|D]], the [[function prototype]] of the main function looks like one of the following:

<source lang="D">
void main();
void main(string[] args);
int main();
int main(string[] args);
</source>

Command-line arguments are passed in <code>args</code>, similar to how it is done in C# or Java. For versions of <code>main()</code> returning an integer, similar to both C and C++, it is passed back to the environment as the exit status of the process.

===Common Lisp===
ANSI Common Lisp does not define a main function. However, the following code will emulate a main function in CMUCL. It is easily adjusted to work in ECL, SBCL, and Clojure (CLISP not at all).

<source lang="lisp">
#!/usr/bin/env lisp -quiet -load

(defun hello-main ()
(format t "Hello World!~%")
(quit))

(if (member (pathname-name *load-truename*)
extensions:*command-line-strings*
:test #'(lambda (x y) (search x y :test #'equalp)))
(hello-main))
</source>

===FORTRAN===
[[FORTRAN]] does not have a main subroutine or function. Instead a <code>PROGRAM</code> statement as the first line can be used to specify that a program unit is a main program, as shown below. The <code>PROGRAM</code> statement cannot be used for recursive calls.<ref>XL FORTRAN for [[AIX]]. Language Reference. Third Edition, 1994. [[IBM]]</ref>

<source lang="fortran">
PROGRAM HELLO
PRINT *, "Cint!"
END PROGRAM HELLO
</source>

===GNAT===
Using [[GNAT]], the programmer is not required to write a function called <code>main</code>; a source file containing a single subprogram can be compiled to an executable. The binder will however create a package <code>ada_main</code>, which will contain and export a C-style main function.

===Go===
In [[Go (programming language)|Go]] programming language, program execution starts with the <code>main</code> function of the <code>package main</code>

<source lang="go">
package main

import "fmt"

func main() {
fmt.Println("Hello, World!")
}
</source>

===Haskell===
A [[Haskell (programming language)|Haskell]] program must contain a name called <code>main</code> bound to a value of type <code>IO t</code>, for some type <code>t</code>;<ref>{{cite web|url=http://www.haskell.org/onlinereport/modules.html |title=The Haskell 98 Report: Modules |publisher=Haskell.org |date= |accessdate=2013-08-19}}</ref> which is usually <code>IO ()</code>. <code>IO</code> is a [[monads in functional programming|monad]], which organizes [[Side effect (computer science)|side-effects]] in terms of [[purely functional]] code.<ref>[http://geekrant.wordpress.com/2008/06/23/misconceptions/ Some Haskell Misconceptions: Idiomatic Code, Purity, Laziness, and IO] — on Haskell's monadic IO></ref> The <code>main</code> value represents the side-effects-ful computation done by the program. The result of the computation represented by <code>main</code> is discarded; that is why <code>main</code> usually has type <code>IO ()</code>, which indicates that the type of the result of the computation is <code>()</code>, the [[unit type]], which contains no information.

<source lang="haskell">
main :: IO()
main =
putStrLn "Hello, World!"
</source>

Command line arguments are not given to <code>main</code>; they must be fetched using another IO action, such as [http://haskell.org/ghc/docs/latest/html/libraries/base/System-Environment.html#v%3AgetArgs <code>System.Environment.getArgs</code>].

===Java===
[[Java (programming language)|Java]] programs start executing at the main [[method (computer science)|method]], which has the following [[method heading]]:

<source lang="java5">
public static void main(String[] args)
public static void main(String... args)
public static void main(String args[])
</source>

Command-line arguments are passed in <code>args</code>. As in C and C++, the name "<code>main()</code>" is special. Java's main methods do not return a value directly, but one can be passed by using the <code>System.exit()</code> method.

Unlike C, the name of the program is not included in <code>args</code>, because the name of the program is exactly the name of the class that contains the main method called, so it is already known. Also unlike C, the number of arguments need not be included, since the array class in Java has an attribute that keeps track of how many elements there are.

===OCaml===
[[OCaml]] has no <code>main</code> function. Programs are evaluated from top to bottom.

Command-line arguments are available in an array named <code>Sys.argv</code> and the exit status is 0 by default.

Example:
<source lang="ocaml">

print_endline "Hello World"

</source>

===Pascal===
In [[Pascal (programming language)|Pascal]], the main procedure is the only unnamed procedure in the program. Because Pascal programs have the procedures and functions in a more rigorous top-down order than C, C++ or Java programs, the main procedure is usually the last procedure in the program. Pascal does not have a special meaning for the name "<code>main</code>" or any similar name.

<source lang="pascal">
program Hello(Output);
begin
writeln('Hello, world!');
end.
</source>

Command-line arguments are counted in <code>ParamCount</code> and accessible as strings by <code>ParamStr(n)</code>, with n between 0 and <code>ParamCount</code>.

Note that "unit" or "module" based versions of Pascal start the main module with the PROGRAM keyword, while other separately compiled modules start with UNIT (UCSD/Borland) or MODULE (ISO). The unnamed function in modules is often module initialization, and run before the main program starts.

===Perl===
In [[Perl]], there is no main function. Statements are executed from top to bottom.

Command-line arguments are available in the special array <code>@ARGV</code>. Unlike C, <code>@ARGV</code> does not contain the name of the program, which is <code>$0</code>.

===Pike===
In [[Pike (programming language)|Pike]] syntax is similar to that of C and C++. The execution begins at <code>main</code>. The "<code>argc</code>" variable keeps the number of [[Parameter (computer science)|arguments]] passed to the program. The "<code>argv</code>" variable holds the value associated with the arguments passed to the program.

Example:
int main(int argc, array(string) argv)

===Python===
In [[Python (programming language)|Python]] a function called <code>main</code> doesn't have any special significance. However, it is common practice to organize a program's main functionality in a function called <code>main</code> and call it with code similar to the following:

<source lang="python">
def main():
# the main code goes here

if __name__ == "__main__":
main()
</source>

When a Python program is executed directly (as opposed to being imported from another program), the special global variable <code>__name__</code> has the value "<code>__main__</code>".<ref>[http://www.artima.com/weblogs/viewpost.jsp?thread=4829 Python <code>main()</code> functions]</ref>

Some programmers use the following, giving a better look to exits, and making it look more like C:

<source lang="python">
import sys

def main(argc, args):
try:
# program's main code here
except:
# error handling code here
return 1 # exit on error
return 0 # exit errorlessly

if __name__ == '__main__':
sys.exit(main(len(sys.argv), sys.argv))
</source>

===REALbasic===
In [[REALbasic]], there are two different project types, each with a different main entry point. Desktop (GUI) applications start with the <code>App.Open</code> event of the project's <code>Application</code> object. Console applications start with the <code>App.Run</code> event of the project's <code>ConsoleApplication</code> object. In both instances, the main function is automatically generated, and cannot be removed from the project.

===Ruby===
In [[Ruby (programming language)|Ruby]], there is no distinct main function. The code written without additional "<code>class .. end</code>", "<code>module .. end</code>" enclosures is executed directly, step by step, in context of special "<code>main</code>" object. This object can be referenced using:

<source lang="ruby">
self # => main
</source>

and contain the following properties:

<source lang="ruby">
self.class # => Object
self.class.ancestors # => [Object, Kernel]
</source>

Methods defined without additional classes/modules are defined as private methods of the "<code>main</code>" object, and, consequentally, as private methods of almost any other object in Ruby:

<source lang="ruby">
def foo
42
end
foo # => 42
[].foo # => private method `foo' called for []:Array (NoMethodError)
false.foo # => private method `foo' called for false:FalseClass (NoMethodError)
</source>

Number and values of command-line arguments can be determined using the single <code>ARGV</code> constant array:

<source lang="ruby">
ARGV # => ["foo", "bar"]
ARGV.size # => 2
</source>

Note that first element of <code>ARGV</code>, <code>ARGV[0]</code>, contains the first command-line argument, not the name of program executed, as in C. The name of program is available using <code>$0</code> or <code>$PROGRAM_NAME</code>.<ref>[http://www.ruby-doc.org/docs/ProgrammingRuby/html/rubyworld.html#UB Programming Ruby: The Pragmatic Programmer's Guide, Ruby and Its World] — on Ruby <code>ARGV</code></ref>

Similar to Python, one could use:

<source lang="ruby">
if __FILE__ == $PROGRAM_NAME
# Put "main" code here
end
</source>

===Visual Basic===
In [[Visual Basic]], when a project contains no forms, the startup object may be the <code>Main()</code> procedure. The <code>Command$</code> function can be optionally used to access the argument portion of the command line used to launch the program:
<source lang="vb">
Sub Main()
Debug.Print "Hello World!"
MsgBox "Arguments if any are: " & Command$
End Sub
</source>

===LOGO===
In [[Logo (programming language)|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 [Welcome])
end

make "startup [procname]

Note that the variable <code>startup</code> 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.

===AHLSL===
In [[AIGE]]'s [[AHLSL]], the main function, by default, is defined as:

[main]


== See also ==
== See also ==
Line 23: Line 301:


== References ==
== References ==
{{Reflist}}
{{Reflist|30em}}


== External links ==
== External links ==
* [https://blogs.oracle.com/ksplice/entry/hello_from_a_libc_free Hello from a libc-free world! (Part 1)], March 16, 2010
* [https://blogs.oracle.com/ksplice/entry/hello_from_a_libc_free Hello from a libc-free world! (Part 1)], March 16, 2010
* [http://www.javaexperience.com/main-method-in-java/ How main method works in Java]


{{DEFAULTSORT:Entry Point}}
{{DEFAULTSORT:Entry Point}}
[[Category:Control flow]]
[[Category:Control flow]]


{{Operating-system-stub}}

Revision as of 18:40, 12 May 2014

In computer programming, an entry point is where control enters a program or piece of code. In many programming languages, the main function is where a program starts its execution.

Usage

Contemporary

In most of today's popular computer systems, such as Microsoft Windows and Unix, a computer program usually only has a single entry point. In C, C++, D and Kotlin programs this is a function named main; in Java it is a static method named main, and in C# it is a static method named Main.[1][2]

One notable modern exception to the single-entry-point paradigm is Android. Unlike applications on most other operating systems, Android applications do not have a single entry point – there is no main function, for example. Instead of a single entry point, they have essential components (which include activities and services) which the system can instantiate and run as needed.[3]

Historical

Historically, and in some contemporary legacy systems, such as VMS and OS/400, 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 and MACRO programs, is to append them at the end of the name of the executable image, delimited by a dollar sign ($), e.g. directory.exe$make.

The Apple I computer also used this to some degree. For example, an alternative entry point in Apple I's BASIC would keep the BASIC program useful when the reset button was accidentally pushed.[clarification needed]

Variants

In many programming languages, the main function is where a program starts its execution. It is responsible for the high-level organization of the program's functionality, and typically has access to the command arguments given to the program when it was executed.

The main function is generally the first programmer-written function that runs when a program starts, and is invoked directly from the system-specific initialization contained in crt0 or equivalent. However, some languages can execute user-written functions before main runs, such as the constructors of C++ global objects.

C and C++

In C and C++, the function prototype of the main function looks like one of the following:

int main(void);
int main();

int main(int argc, char **argv);
int main(int argc, char *argv[]);

The parameters argc, argument count, and argv, argument vector,[4] respectively give the number and values of the program's command-line arguments. The names of argc and argv may be any valid identifier in C, but it is common convention to use these names. In C++, the names are to be taken literally, and the "void" in the parameter list is to be omitted, if strict conformance is desired.[5] Other platform-dependent formats are also allowed by the C and C++ standards, except that in C++ the return type must always be int;[6] for example, Unix (though not POSIX.1) and Microsoft Windows have a third argument giving the program's environment, otherwise accessible through getenv in stdlib.h:

int main(int argc, char **argv, char **envp);

Mac OS X and Darwin have a fourth parameter containing arbitrary OS-supplied information, such as the path to the executing binary:[7]

int main(int argc, char **argv, char **envp, char **apple);

The value returned from the main function becomes the exit status of the process, though the C standard only ascribes specific meaning to two values: EXIT_SUCCESS (traditionally 0) and EXIT_FAILURE. The meaning of other possible return values is implementation-defined. In case a return value is not defined by the programmer, an implicit return 0; at the end of the main() function is inserted by the compiler; this behavior is required by the C++ standard.

It is guaranteed that argc is non-negative and that argv[argc] is a null pointer. By convention, the command-line arguments specified by argc and argv include the name of the program as the first element if argc is greater than 0; if a user types a command of "rm file", the shell will initialise the rm process with argc = 2 and argv = ["rm", "file", NULL]. As argv[0] is the name that processes appear under in ps, top etc., some programs, such as daemons or those running within an interpreter or virtual machine (where argv[0] would be the name of the host executable), may choose to alter their argv to give a more descriptive argv[0], usually by means of the 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 (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.

Clean

Clean is a functional programming language based on graph rewriting. The initial node is called Start and is of type *World -> *World if it changes the world or some fixed type if the program only prints the result after 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.

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.[8]

static void Main();
static void Main(string[] args);
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.

D

In D, the function prototype 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.

Common Lisp

ANSI Common Lisp does not define a main function. However, the following code will emulate a main function in CMUCL. It is easily adjusted to work in ECL, SBCL, and Clojure (CLISP not at all).

#!/usr/bin/env lisp -quiet -load

(defun hello-main ()
  (format t "Hello World!~%")
  (quit))

(if (member (pathname-name *load-truename*)
            extensions:*command-line-strings*
            :test #'(lambda (x y) (search x y :test #'equalp)))
    (hello-main))

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.[9]

      PROGRAM HELLO
      PRINT *, "Cint!"
      END PROGRAM HELLO

GNAT

Using GNAT, the programmer is not required to write a function called main; a source file containing a single subprogram can be compiled to an executable. The binder will however create a package ada_main, which will contain and export a C-style main function.

Go

In Go programming language, program execution starts with the main function of the package main

package main

import "fmt"

func main() {
	fmt.Println("Hello, World!")
}

Haskell

A Haskell program must contain a name called main bound to a value of type IO t, for some type t;[10] which is usually IO (). IO is a monad, which organizes side-effects in terms of purely functional code.[11] 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, 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.

Java

Java programs start executing at the main method, which has the following method heading:

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 the name of the program is exactly the name of the class that contains the main method called, so it is already known. Also unlike C, the number of arguments need not be included, since the array class in Java has an attribute that keeps track of how many elements there are.

OCaml

OCaml 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 procedure in the program. Because Pascal programs have the procedures and functions in a more rigorous top-down order than C, C++ or Java programs, the main procedure is usually the last procedure in the program. Pascal does not have a special meaning for the name "main" or any similar name.

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.

Note that "unit" or "module" based versions of Pascal start the main module with the PROGRAM keyword, while other separately compiled modules start with UNIT (UCSD/Borland) or MODULE (ISO). The unnamed function in modules is often module initialization, and run before the main program starts.

Perl

In Perl, there is no main function. Statements are executed from top to bottom.

Command-line arguments are available in the special array @ARGV. Unlike C, @ARGV does not contain the name of the program, which is $0.

Pike

In Pike syntax is similar to that of C and C++. The execution begins at main. The "argc" variable keeps the number of arguments passed to the program. The "argv" variable holds the value associated with the arguments passed to the program.

Example:

int main(int argc, array(string) argv)

Python

In Python a function called main doesn't have any special significance. However, it is common practice to organize a program's main functionality in a function called main and call it with code similar to the following:

def main():
    # the main code goes here

if __name__ == "__main__":
    main()

When a Python program is executed directly (as opposed to being imported from another program), the special global variable __name__ has the value "__main__".[12]

Some programmers use the following, giving a better look to exits, and making it look more like C:

import sys

def main(argc, args):
    try:
        # program's main code here
    except:
        # error handling code here
        return 1  # exit on error
    return 0  # exit errorlessly

if __name__ == '__main__':
    sys.exit(main(len(sys.argv), sys.argv))

REALbasic

In REALbasic, 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.

Ruby

In Ruby, there is no distinct main function. The code written without additional "class .. end", "module .. end" enclosures is executed directly, step by step, in context of special "main" object. This object can be referenced using:

self                # => main

and contain the following properties:

self.class           # => Object
self.class.ancestors # => [Object, Kernel]

Methods defined without additional classes/modules are defined as private methods of the "main" object, and, consequentally, as private methods of almost any other object in Ruby:

def foo
  42
end
 
foo                  # => 42
[].foo               # => private method `foo' called for []:Array (NoMethodError)
false.foo            # => private method `foo' called for false:FalseClass (NoMethodError)

Number and values of command-line arguments can be determined using the single ARGV constant array:

ARGV                 # => ["foo", "bar"]
ARGV.size            # => 2

Note that first element of ARGV, ARGV[0], contains the first command-line argument, not the name of program executed, as in C. The name of program is available using $0 or $PROGRAM_NAME.[13]

Similar to Python, one could use:

if __FILE__ == $PROGRAM_NAME
  # Put "main" code here
end

Visual Basic

In Visual Basic, 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

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 [Welcome])
end
make "startup [procname]

Note that the variable startup is used for the startup list of actions, but the convention is that this calls another procedure that runs the actions. That procedure may be of any name.

AHLSL

In AIGE's AHLSL, the main function, by default, is defined as:

[main]

See also

References

  1. ^ "The main() function". ibm.com. IBM. Retrieved 2014-05-08.
  2. ^ "Main() and Command-Line Arguments (C# Programming Guide)". Msdn.microsoft.com. Retrieved 2014-05-08.
  3. ^ "Application Fundamentals". Android Development. linuxtopia.org. Retrieved 2014-02-19.
  4. ^ argv: the vector term in this variable's name is used in traditional sense to refer to strings.
  5. ^ [1] - Parameter types and names of main.
  6. ^ Section 3.6.1.2, Standard C++ 2011 edition.
  7. ^ The char *apple Argument Vector
  8. ^ "Console Appplications in .NET, or Teaching a New Dog Old Tricks". Msdn.microsoft.com. 2003-06-12. Retrieved 2013-08-19.
  9. ^ XL FORTRAN for AIX. Language Reference. Third Edition, 1994. IBM
  10. ^ "The Haskell 98 Report: Modules". Haskell.org. Retrieved 2013-08-19.
  11. ^ Some Haskell Misconceptions: Idiomatic Code, Purity, Laziness, and IO — on Haskell's monadic IO>
  12. ^ Python main() functions
  13. ^ Programming Ruby: The Pragmatic Programmer's Guide, Ruby and Its World — on Ruby ARGV