Start from a main routine: Difference between revisions

From Rosetta Code
Content added Content deleted
(Added Easylang)
 
(43 intermediate revisions by 24 users not shown)
Line 1: Line 1:
{{task}}
{{task}}

{{omit from|BBC BASIC}}


Some languages (like Gambas and Visual Basic) support two startup modes.   Applications written in these languages start with an open window that waits for events, and it is necessary to do some trickery to cause a main procedure to run instead.   Data driven or event driven languages may also require similar trickery to force a startup procedure to run.
Some languages (like Gambas and Visual Basic) support two startup modes.   Applications written in these languages start with an open window that waits for events, and it is necessary to do some trickery to cause a main procedure to run instead.   Data driven or event driven languages may also require similar trickery to force a startup procedure to run.
Line 10: Line 10:
Languages that always run from main() can be omitted from this task.
Languages that always run from main() can be omitted from this task.
<br><br>
<br><br>
=={{header|6502 Assembly}}==
This depends entirely on the hardware.
* Apple ][: type <code>"BRUN PROG"</code> and press enter
* Commodore 64: type <code>"LOAD"*",8,1</code> and press enter. This is how programs on floppy disks are loaded. Commodore 64 cartridges bypass this step entirely and boot immediately.
* NES/Famicom: Executes <code>JMP ($FFFC)</code> at the start automatically, thus entering the main program.

It should be noted that nothing needs to be called "main" but generally speaking the "main" program is whatever execution flows into at the start.

=={{header|8086 Assembly}}==
Whether a program runs automatically from main or needs to be called depends entirely on the hardware, but in MS-DOS you have to type the name of the program you wish to run.
<code>C:\>prog.exe</code>


=={{header|Ada}}==
=={{header|Ada}}==
Line 15: Line 26:
In Ada, the "Main" procedure doesn't have to follow a special naming scheme. Any parameterless procedure will do.
In Ada, the "Main" procedure doesn't have to follow a special naming scheme. Any parameterless procedure will do.


<lang ada>with Ada.Text_IO;
<syntaxhighlight lang="ada">with Ada.Text_IO;
procedure Foo is
procedure Foo is
begin
begin
Ada.Text_IO.Put_Line("Bar");
Ada.Text_IO.Put_Line("Bar");
end Foo;</lang>
end Foo;</syntaxhighlight>

=={{header|ALGOL 68}}==
An Algol 68 program consists of a sequence of declarations and expressions. The expressions are executed and so form the main program.
<syntaxhighlight lang="algol68">BEGIN
print( ( "Hello, World!", newline ) )
END</syntaxhighlight>

=={{header|Arturo}}==

In Arturo, code is always read and executed from the top to the bottom of the script.

If we need a <code>main</code> function in any case, we can of course create it and call it.

<syntaxhighlight lang="rebol">main: function [][
print "Yes, we are in main!"
]

main</syntaxhighlight>

{{out}}

<pre>Yes, we are in main!</pre>


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
AutoHotkey always starts at the top of the script. A main() function can be called from there, or event hooks set.
AutoHotkey always starts at the top of the script. A main() function can be called from there, or event hooks set.

=={{header|AWK}}==
=={{header|AWK}}==


The awk language is data driven. However, it does support the use of begin blocks, so we could use one of those to provide us with a main startup procedure:
The awk language is data driven. However, it does support the use of begin blocks, so we could use one of those to provide us with a main startup procedure:


<lang awk>BEGIN {
<syntaxhighlight lang="awk">BEGIN {
# This is our main startup procedure
# This is our main startup procedure
print "Hello World!"
print "Hello World!"
}</lang>
}</syntaxhighlight>

=={{header|BASIC}}==
==={{header|GWBASIC}}===
{{works with|GWBASIC}}
As is well known, GWBASIC cannot refer to anything with a name. Also, does not require an executable program to have a main() procedure.
However, as in the other instances, there's nothing to stop you creating a subprocess and then calling it by its line number to start the program:
<syntaxhighlight lang="qbasic">10 'SAVE "MAIN",A
20 GOSUB 100 ' Main
30 END
100 ' Sub Main
110 CLS
120 PRINT "This is the Main sub!"
130 RETURN</syntaxhighlight>

==={{header|QBasic}}===
{{works with|QBasic|1.1}}
{{works with|QuickBasic|4.5}}
QBasic does not require an executable program to have a main() procedure.
However, there's nothing to stop you creating one and then calling it to start the program:
<syntaxhighlight lang="qbasic">SUB main
PRINT "Hello from main!"
END SUB

main</syntaxhighlight>

==={{header|BASIC256}}===
BASIC256 does not require an executable program to have a main() procedure.
However, there's nothing to stop you creating one and then calling it to start the program:
<syntaxhighlight lang="basic256">subroutine main()
print "Hello from main!"
end subroutine
call main()</syntaxhighlight>

==={{header|Run BASIC}}===
Run BASIC does not require an executable program to have a main() procedure.
However, there's nothing to stop you creating one and then calling it to start the program:
<syntaxhighlight lang="lb">sub main
print "Hello from main!"
end sub

call main</syntaxhighlight>

==={{header|True BASIC}}===
{{works with|QBasic}}
True BASIC does not require an executable program to have a main() procedure.
However, there's nothing to stop you creating one and then calling it to start the program:
<syntaxhighlight lang="qbasic">SUB main
PRINT "Hello from main!"
END SUB

CALL main
END</syntaxhighlight>

==={{header|Yabasic}}===
Yabasic does not require an executable program to have a main() procedure.
However, there's nothing to stop you creating one and then calling it to start the program:
<syntaxhighlight lang="yabasic">sub main()
print "Hello from main!"
end sub
main()</syntaxhighlight>


=={{header|C}}==
=={{header|C}}==
Line 36: Line 132:
Code execution in C always starts at main(). Macros make possible programs such as the one below, although it's not the best way to write C code.
Code execution in C always starts at main(). Macros make possible programs such as the one below, although it's not the best way to write C code.


<syntaxhighlight lang="c">
<lang C>
/*Abhishek Ghosh, 7th November 2013, Rotterdam*/
#include<stdio.h>
#include<stdio.h>


Line 47: Line 142:
return 0;
return 0;
}
}
</syntaxhighlight>
</lang>


<pre>
<pre>
Line 58: Line 153:
=={{header|Component Pascal}}==
=={{header|Component Pascal}}==
In BlackBox Componente Builder any exported procedure without paramenter (command) can be invoked through commanders (CTRL-q ModuleName.command)
In BlackBox Componente Builder any exported procedure without paramenter (command) can be invoked through commanders (CTRL-q ModuleName.command)
<lang oberon2>
<syntaxhighlight lang="oberon2">
MODULE MainProcedure;
MODULE MainProcedure;
IMPORT StdLog;
IMPORT StdLog;
Line 73: Line 168:
END MainProcedure.
END MainProcedure.


</syntaxhighlight>
</lang>
Execute:<br/>
Execute:<br/>
^Q MainProcedure.Do<br/>
^Q MainProcedure.Do<br/>
Line 82: Line 177:
From Main
From Main
</pre>
</pre>

=={{header|EasyLang}}==
<syntaxhighlight>
proc main . .
print "Hello from main!"
.
main
</syntaxhighlight>


=={{header|Erlang}}==
=={{header|Erlang}}==
When started Erlang enters a REPL (read-eval-print loop). To call a function called main in the module m you do: erl -run m main argument1 argument 2 ...
When started Erlang enters a REPL (read-eval-print loop). To call a function called main in the module m you do: erl -run m main argument1 argument 2 ...

=={{header|Factor}}==
Use <code>MAIN:</code> to specify the starting point of a runnable vocabulary.
<syntaxhighlight lang="factor">USE: io
IN: example

: hello ( -- ) "Hello, world!" print ;

MAIN: hello</syntaxhighlight>

This is optional for scripts and interactive development, but required to deploy a Factor program as an executable binary.


=={{header|Forth}}==
=={{header|Forth}}==
Forth still runs the interpreter when given a file to include in order to compile the source, but you can avoid the interactive interpreter by invoking an entry point ("main") then calling BYE to exit.
Forth still runs the interpreter when given a file to include in order to compile the source, but you can avoid the interactive interpreter by invoking an entry point ("main") then calling BYE to exit.
<lang forth>include foo.fs
<syntaxhighlight lang="forth">include foo.fs
...
...
: main ... ;
: main ... ;


main bye</lang>
main bye</syntaxhighlight>


This pattern is also used (e.g. GNU Forth) to interpret a Forth snippet from the command line.
This pattern is also used (e.g. GNU Forth) to interpret a Forth snippet from the command line.


<lang forth>$ gforth -e "2 2 + . bye"</lang>
<syntaxhighlight lang="forth">$ gforth -e "2 2 + . bye"</syntaxhighlight>


Furthermore, professional Forth systems like PFE and SwiftForth have a means to make a "turnkey" application which omits the interactive interpreter, suitable for installing on a third-party system. The command would take an entry point and target executable name:
Furthermore, professional Forth systems like PFE and SwiftForth have a means to make a "turnkey" application which omits the interactive interpreter, suitable for installing on a third-party system. The command would take an entry point and target executable name:


<lang forth>' main turnkey app.exe</lang>
<syntaxhighlight lang="forth">' main turnkey app.exe</syntaxhighlight>


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
FreeBASIC does not require an executable program to have a main() procedure. However, there's nothing to stop you creating one and then calling it to start the program:
FreeBASIC does not require an executable program to have a main() procedure. However, there's nothing to stop you creating one and then calling it to start the program:


<lang freebasic>' FB 1.05.0 Win64
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64


Sub main()
Sub main()
Line 112: Line 226:


main
main
Sleep</lang>
Sleep</syntaxhighlight>


{{out}}
{{out}}
Line 127: Line 241:
* In the MMain module, create a public sub called Main as follows:
* In the MMain module, create a public sub called Main as follows:


<lang gambas>PUBLIC SUB Main()
<syntaxhighlight lang="gambas">PUBLIC SUB Main()
' This is the start of the program
' This is the start of the program
END</lang>
END</syntaxhighlight>


* Right click the MMain module, then select Startup class from the context menu
* Right click the MMain module, then select Startup class from the context menu

=={{header|Go}}==
In Go all executable programs must have a main package which includes a function called main() with no parameters nor return value.

However, execution doesn't necessarily begin with main() itself. If there are top-level functions called init() with no parameters nor return value, these are executed first in declaration order and they can call other functions including main() itself.

Here's an example which illustrates this behavior. Note that main() gets called twice, first by the second init() function and then automatically by the runtime.

In practice, init() functions are generally used to initialize top-level variables which cannot (or cannot easily) be initialized in situ rather than to pre-empt the main() function in this way.
<syntaxhighlight lang="go">package main

import "fmt"

var count = 0

func foo() {
fmt.Println("foo called")
}

func init() {
fmt.Println("first init called")
foo()
}

func init() {
fmt.Println("second init called")
main()
}

func main() {
count++
fmt.Println("main called when count is", count)
}</syntaxhighlight>

{{out}}
<pre>
first init called
foo called
second init called
main called when count is 1
main called when count is 2
</pre>


=={{header|J}}==
=={{header|J}}==
Line 142: Line 298:


If you want the script to exit even when it hits an error, you can use an [http://www.jsoftware.com/help/dictionary/dx009.htm#26 immex phrase], which will be the first thing executed by the event loop, before it prompts.
If you want the script to exit even when it hits an error, you can use an [http://www.jsoftware.com/help/dictionary/dx009.htm#26 immex phrase], which will be the first thing executed by the event loop, before it prompts.

=={{header|jq}}==

A jq program consists of a (possibly empty) sequence of directives and function definitions followed by a single (but possibly compound) jq expression that is evaluated in the context of the prior definitions. The jq expression can take many forms, such as a single JSON value, or a pipeline of filters. In particular, it could be the invocation of a previously defined function named main as in this example:
<syntaxhighlight lang="jq">
def main:
"Hello, World!";
main
</syntaxhighlight>

The jq interpreter has two modes of operation: a data-driven mode (the default) and an autonomous mode (corresponding to the `-n` command-line option).
In general, in the data-driven mode, the expression at the end of the jq program is evaluated once for each input, so that in the above example,
the "Hello, World!" string would be emitted once for each input.
By contrast, if the `-n` command-line option is specified, then a single JSON `null` would be presented to the final expression, so that in the above example,
the string would be emitted just once.

=={{header|Julia}}==
If the program, julia, is executed via the command line without a program filename argument, it will enter its REPL (Read–Evaluate-Print-Loop) by default, without executing any user code until that is entered via the REPL command line. If, instead, Julia is started with a Julia program filename as argument, it will execute that program and, after that program terminates, exit without seeking any REPL input.


=={{header|Kotlin}}==
=={{header|Kotlin}}==
Line 157: Line 332:
=={{header|Logtalk}}==
=={{header|Logtalk}}==
Logtalk applications don't run a main procedure at startup by default but there are several ways to accomplish that. One of them is to include an initialization/1 in a source file. The argument of this directive is a goal that will be proved when the source file is compiled and loaded. For example:
Logtalk applications don't run a main procedure at startup by default but there are several ways to accomplish that. One of them is to include an initialization/1 in a source file. The argument of this directive is a goal that will be proved when the source file is compiled and loaded. For example:
<lang logtalk>
<syntaxhighlight lang="logtalk">
:- initialization(main).
:- initialization(main).
</syntaxhighlight>
</lang>
The initialization/1 can also be used within entities (objects and categories) to automatically run entity-specific initializations when the container source file is compiled and loaded. In alternative, it's usually possible to pass a goal as a command-line argument when running the application executable (the details depending on the backend Prolog compiler being used).
The initialization/1 can also be used within entities (objects and categories) to automatically run entity-specific initializations when the container source file is compiled and loaded. In alternative, it's usually possible to pass a goal as a command-line argument when running the application executable (the details depending on the backend Prolog compiler being used).


=={{header|Mathematica}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
Mathematica automatically starts a REPL (read-eval-print loop), which is a kind of event loop. If that is not desired, pass -run on the command line. Note that if Mathematica is called via MathLink from within an external program, then the main loop has to be defined, which will usually differ from the standard one.
Mathematica automatically starts a REPL (read-eval-print loop), which is a kind of event loop. If that is not desired, pass -run on the command line. Note that if Mathematica is called via MathLink from within an external program, then the main loop has to be defined, which will usually differ from the standard one.

=={{header|Nim}}==
Nim does not require a procedure called "main" for program execution, but programmers are free to create a procedure with that name.
<pre>
proc main() =
echo "Hello World!"

main()
</pre>


=={{header|Oforth}}==
=={{header|Oforth}}==
Line 170: Line 354:


For instance if file1.of is :
For instance if file1.of is :
<lang Oforth>: main(n)
<syntaxhighlight lang="oforth">: main(n)
"Sleeping..." println
"Sleeping..." println
n sleep
n sleep
"Awake and leaving." println ;</lang>
"Awake and leaving." println ;</syntaxhighlight>


{{out}}
{{out}}
Line 184: Line 368:


With this file (for instance file2.of) :
With this file (for instance file2.of) :
<lang Oforth>: main(n)
<syntaxhighlight lang="oforth">: main(n)
"Sleeping..." println
"Sleeping..." println
n sleep
n sleep
"Awake and leaving." println ;
"Awake and leaving." println ;


10000 main</lang>
10000 main</syntaxhighlight>


{{out}}
{{out}}
Line 211: Line 395:
=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
GP scripts start from the top of the script. PARI code starts from the main function.
GP scripts start from the top of the script. PARI code starts from the main function.

=={{header|Pascal}}==
Pascal programs are mostly compiled and run a 'main' procedure automatically, this procedure is not explicitly named
main. Units (separate files of code without a main procedure) have initialisation code which also runs automatically.


=={{header|Perl}}==
=={{header|Perl}}==
Same as Perl 6.
Same as Raku.
<lang perl6>BEGIN {...} # as soon as parsed
<syntaxhighlight lang="perl">BEGIN {...} # as soon as parsed
CHECK {...} # end of compile time
CHECK {...} # end of compile time
INIT {...} # beginning of run time
INIT {...} # beginning of run time
END {...} # end of run time</lang>
END {...} # end of run time</syntaxhighlight>

=={{header|Perl 6}}==
When executed with the standard setting, Perl 6 code always runs the mainline code automatically, followed by the <tt>MAIN</tt> function if you have one. However, it's possible to start up with an alternate setting that might want to create its own event loop or <tt>MAIN</tt>. In such cases you can
always capture control at various phases with blocks that we call "phasers":
<lang perl6>BEGIN {...} # as soon as parsed
CHECK {...} # end of compile time
INIT {...} # beginning of run time
END {...} # end of run time</lang>


=={{header|Phix}}==
=={{header|Phix}}==
{{libheader|Phix/basics}}
Any code which is not part of a routine is considered 'main' code. If you want a <code>main()</code> you have to explicitly invoke it.
Any code which is not part of a routine is considered 'main' code. If you want a <code>main()</code> you have to explicitly invoke it.
<!--<syntaxhighlight lang="phix">-->
<lang Phix>procedure main()
<span style="color: #008080;">procedure</span> <span style="color: #000000;">main</span><span style="color: #0000FF;">()</span>
...
<span style="color: #0000FF;">...</span>
end procedure
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
main()</lang>
<span style="color: #000000;">main</span><span style="color: #0000FF;">()</span>
<!--</syntaxhighlight>-->


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
PicoLisp automatically starts a REPL (read-eval-print loop), which is a kind of event loop. If that is not desired, call (wait), or pass -wait on the command line. Per convention, the GUI event loop is started by calling (go), or by passing -go on the command line.
PicoLisp automatically starts a REPL (read-eval-print loop), which is a kind of event loop. If that is not desired, call (wait), or pass -wait on the command line. Per convention, the GUI event loop is started by calling (go), or by passing -go on the command line.

=={{header|Processing}}==
By default, Processing executes the given list of commands with no required main function/method. This is called "immediate mode."

<syntaxhighlight lang="processing">println("hello world");
line(0, 0, width, height);</syntaxhighlight>

Most of the Processing API can be used in immediate mode--however, it has no event loop, so it cannot support animation, interaction (such as keyboard or mouse) or time-based media such as audio or video. Further, this mode cannot define new functions/methods, or classes. For example, this is invalid:

<syntaxhighlight lang="processing">void hello() {
println("hello world");
}
hello();</syntaxhighlight>

In order to define functions or use these language features, setup() and/or draw() must be defined in a Processing sketch. These serve as the equivalent of a main() entrypoint. For example, this is a valid sketch:

<syntaxhighlight lang="processing">void setup() {
hello();
}
void hello() {
println("hello world");
}</syntaxhighlight>

setup() -- or draw() if there is no setup() -- acts as an entrypoint to the sketch, with draw() also serving as an event loop that by default is called at 60fps.


=={{header|PureBasic}}==
=={{header|PureBasic}}==
PureBasic is procedural and any code which is not part of a procedure is considered 'main' code. This code also does not use any explicit syntax (i.e. a 'main' module) to cause it to execute and it always executes first.
PureBasic is procedural and any code which is not part of a procedure is considered 'main' code. This code also does not use any explicit syntax (i.e. a 'main' module) to cause it to execute and it always executes first.

=={{header|Quackery}}==

To run the Quackery shell (i.e. REPL) type <code>quackery</code> in the OS monitor app.

To run a Quackery program from the monitor, type <code>quackery [program-name].qky</code>

To run a Quackery program from the Quackery shell, type <code>$ "[program-name].qky" loadfile</code>.

To run the Quackery shell from a Quackery program, include the word <code>shell</code> in the program.

To run a Quackery program from within a Quackery program, include the phrase <code>$ "[program-name].qky" loadfile</code> in the program.

To run a Quackery program during compilation of a Quackery program, include the phrase <code>[ $ "[program-name].qky" loadfile ] now!</code> in the program.

To run the Quackery shell from within the Quackery shell, type <code>shell</code>.

To run the Quackery shell during compilation within the Quackery shell, type <code>[ shell ] now!</code>.

Other variations are possible. To illustrate this, here is a program which, if typed in in the shell, or included in a <code>.qky</code> file, will temporarily suspend compilation to interact with the user. <code>constant</code> includes the functionality of <code>now!</code> but treats the top item of the stack as if it were part of the program text.

<syntaxhighlight lang="quackery">[ say "Please use the shell to calculate a value" cr
say "and leave it on the stack. Type 'leave' when" cr
say "you have done this." cr
shell ] constant is my-value</syntaxhighlight>

Demonstrating this in the Quackery shell. Text after the duck's head prompt and the continuation ellipses is entered by the user.

<pre> > quackery

Welcome to Quackery.

Enter "leave" to leave the shell.

Building extensions.

/O> [ say "Please use the shell to calculate a value" cr
... say "and leave it on the stack. Type 'leave' when" cr
... say "you have done this." cr
... shell ] constant is my-value
...
Please use the shell to calculate a value
and leave it on the stack. Type 'leave' when
you have done this.

/O> 123 456 +
... leave
...

Be seeing you.


Stack empty.

/O> my-value echo
...
579
Stack empty.

/O> leave
...

Auf wiedersehen.


> </pre>


=={{header|Racket}}==
=={{header|Racket}}==
Line 244: Line 517:
Racket can be configured to run a REPL, run a main function, or just run top-level expressions. A <tt>main</tt> function can be run by executing <tt>racket -tm program.rkt</tt>.
Racket can be configured to run a REPL, run a main function, or just run top-level expressions. A <tt>main</tt> function can be run by executing <tt>racket -tm program.rkt</tt>.


<lang racket>
<syntaxhighlight lang="racket">
#/usr/bin/env racket -tm
#/usr/bin/env racket -tm
#lang racket
#lang racket
(provide main)
(provide main)
(define (main . args) (displayln "Hello World!"))
(define (main . args) (displayln "Hello World!"))
</syntaxhighlight>
</lang>

=={{header|Raku}}==
(formerly Perl 6)
When executed with the standard setting, Raku code always runs the mainline code automatically, followed by the <tt>MAIN</tt> function if you have one. However, it's possible to start up with an alternate setting that might want to create its own event loop or <tt>MAIN</tt>. In such cases you can
always capture control at various phases with blocks that we call "phasers":
<syntaxhighlight lang="raku" line>BEGIN {...} # as soon as parsed
CHECK {...} # end of compile time
INIT {...} # beginning of run time
END {...} # end of run time</syntaxhighlight>


=={{header|REXX}}==
=={{header|REXX}}==
Line 257: Line 539:
<br>XEDIT has native (built-in) support for the REXX language as a macro language.
<br>XEDIT has native (built-in) support for the REXX language as a macro language.
<br>The XEDIT mentioned above runs on the VM/CMS operating system.
<br>The XEDIT mentioned above runs on the VM/CMS operating system.
<lang rexx>/*REXX*/
<syntaxhighlight lang="rexx">/*REXX*/
address 'XEDIT'
address 'XEDIT'
.
.
Line 265: Line 547:
.
.
.
.
.</lang>
.</syntaxhighlight>


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
func Main
func Main
see "Hello World!" + nl
see "Hello World!" + nl
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 280: Line 562:
Every Ruby source file can declare blocks of code to be run as the file is being loaded (the BEGIN blocks) and after the program has finished executing (the END blocks).
Every Ruby source file can declare blocks of code to be run as the file is being loaded (the BEGIN blocks) and after the program has finished executing (the END blocks).
[http://ruby-doc.com/docs/ProgrammingRuby/html/language.html#UA BEGIN and END Blocks]
[http://ruby-doc.com/docs/ProgrammingRuby/html/language.html#UA BEGIN and END Blocks]
<lang ruby>BEGIN {
<syntaxhighlight lang="ruby">BEGIN {
# begin code
# begin code
}
}
Line 286: Line 568:
END {
END {
# end code
# end code
}</lang>
}</syntaxhighlight>
A program may include multiple BEGIN and END blocks. BEGIN blocks are executed in the order they are encountered. END blocks are executed in reverse order.
A program may include multiple BEGIN and END blocks. BEGIN blocks are executed in the order they are encountered. END blocks are executed in reverse order.


Line 293: Line 575:
===No kidding and trickery===
===No kidding and trickery===
In Scala there are two concepts not available in another OO-languages e.g. Java. The concepts are <code>object</code> and <code>trait</code>. Both cannot have parameters. <code>object</code>'s are singletons (one and only one instance of a parameter-less class) and are static. Exactly the same as a <code>main</code>. By use of the <code>trait App</code> a main method is preprogrammed and brought in an <code>object</code> which can be called on the command-line. There are more the one different <code>object</code>'s possible each can be called by his object name on the command-line. In the trait <code>executionStart</code> field is initialized with the starting time. By submitting an <code>-Dscala.time</code> argument on the command-line the execution time can be reported. The field <code>executionStart</code> can also programmatically used.
In Scala there are two concepts not available in another OO-languages e.g. Java. The concepts are <code>object</code> and <code>trait</code>. Both cannot have parameters. <code>object</code>'s are singletons (one and only one instance of a parameter-less class) and are static. Exactly the same as a <code>main</code>. By use of the <code>trait App</code> a main method is preprogrammed and brought in an <code>object</code> which can be called on the command-line. There are more the one different <code>object</code>'s possible each can be called by his object name on the command-line. In the trait <code>executionStart</code> field is initialized with the starting time. By submitting an <code>-Dscala.time</code> argument on the command-line the execution time can be reported. The field <code>executionStart</code> can also programmatically used.
{{out|Example}}<lang scala>object PrimaryMain extends App {
{{out|Example}}<syntaxhighlight lang="scala">object PrimaryMain extends App {
Console.println("Hello World: " + (args mkString ", "))
Console.println("Hello World: " + (args mkString ", "))
}
}
Line 299: Line 581:
object MainTheSecond extends App {
object MainTheSecond extends App {
Console.println("Goodbye, World: " + (args mkString ", "))
Console.println("Goodbye, World: " + (args mkString ", "))
}</lang>
}</syntaxhighlight>


=={{header|sed}}==
=={{header|sed}}==
A <code>sed</code> program repeats itself for each line of input, but your program can begin with commands that address line 1. (This requires that your input has a line 1. If your input is empty file, like <code>/dev/null</code>, then it is impossible to run commands.)<lang sed># This code runs only for line 1.
A <code>sed</code> program repeats itself for each line of input, but your program can begin with commands that address line 1. (This requires that your input has a line 1. If your input is empty file, like <code>/dev/null</code>, then it is impossible to run commands.)<syntaxhighlight lang="sed"># This code runs only for line 1.
1 {
1 {
i\
i\
Line 313: Line 595:


# This code runs for each line of input.
# This code runs for each line of input.
s/\./!!!/g</lang>
s/\./!!!/g</syntaxhighlight>

=={{header|Seed7}}==
Code execution in Seed7 always starts with main. This holds for text programs:

<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";

const proc: main is func
begin
writeln("hello world");
end func;</syntaxhighlight>

And for grahical programs:

<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "draw.s7i";
include "keybd.s7i";

const proc: main is func
begin
screen(200, 200);
KEYBOARD := GRAPH_KEYBOARD;
ignore(getc(KEYBOARD));
end func;</syntaxhighlight>


=={{header|Tcl}}==
=={{header|Tcl}}==
Line 326: Line 631:
* Create a new subroutine in the new module as follows:
* Create a new subroutine in the new module as follows:


<lang vb>SUB Main()
<syntaxhighlight lang="vb">SUB Main()
' This is the start of the program
' This is the start of the program
END</lang>
END</syntaxhighlight>


* From the menu in the application development environment, choose: File, Project Options.
* From the menu in the application development environment, choose: File, Project Options.
Line 337: Line 642:


* Click the OK button.
* Click the OK button.

=={{header|Visual Basic .NET}}==

VB.NET console apps always start in Sub Main, but Windows Forms apps use the application framework by default, meaning the compiler generates a Sub Main that shows a selected startup form. To parse command-line parameters or cancel the application startup, either the appropriate methods in the MyApplication class can be overridden, or the application framework can be disabled, in which case it is allowed to set the startup object to be a method.

===MyApplication===

Comments copied from the metadata of System.Windows.Forms.dll.

OnInitialize can cancel startup by returning false, and the handler for Startup can cancel startup by setting e.Cancel to True.

<syntaxhighlight lang="vbnet">Imports System.Collections.ObjectModel
Imports Microsoft.VisualBasic.ApplicationServices

Namespace My
' The following events are available for MyApplication:
' Startup: Raised when the application starts, before the startup form is created.
' Shutdown: Raised after all application forms are closed. This event is not raised if the application terminates abnormally.
' UnhandledException: Raised if the application encounters an unhandled exception.
' StartupNextInstance: Raised when launching a single-instance application and the application is already active.
' NetworkAvailabilityChanged: Raised when the network connection is connected or disconnected.

Partial Friend Class MyApplication
'''<summary>Sets the visual styles, text display styles, and current principal for the main application thread
'''(if the application uses Windows authentication), and initializes the splash screen, if defined.</summary>
'''<param name="commandLineArgs">A <see cref="ReadOnlyCollection(Of T)" /> of <see langword="String" />,
'''containing the command-line arguments as strings for the current application.</param>
'''<returns>A <see cref="T:System.Boolean" /> indicating if application startup should continue.</returns>
Protected Overrides Function OnInitialize(commandLineArgs As ReadOnlyCollection(Of String)) As Boolean
Console.WriteLine("oninitialize; args: " & String.Join(", ", commandLineArgs))
Return MyBase.OnInitialize(commandLineArgs)
End Function

' WindowsFormsApplicationBase.Startup occurs "when the application starts".
Private Sub MyApplication_Startup(sender As Object, e As StartupEventArgs) Handles Me.Startup
Console.WriteLine("startup; args: " & String.Join(", ", e.CommandLine))
End Sub

'''<summary>Provides the starting point for when the main application is ready to start running, after the
'''initialization is done.</summary>
Protected Overrides Sub OnRun()
Console.WriteLine("onrun")
MyBase.OnRun()
End Sub
End Class
End Namespace</syntaxhighlight>

{{out|input=foo /bar baz "visual basic"}}
<pre>oninitialize; args: foo, /bar, baz, visual basic
startup; args: foo, /bar, baz, visual basic
onrun</pre>

===Sub Main===

'''In Visual Studio:'''

In project properties, create a Sub Main of the appropriate signature, uncheck 'Enable application framework', and set 'Startup object' to 'Sub Main'.

'''By editing vbproj:'''

Change
<pre><MyType>WindowsForms</MyType></pre>
to
<pre><MyType>WindowsFormsWithCustomSubMain</MyType></pre>

and
<pre><StartupObject>[DEFAULT NAMESPACE OF APPLICATION].My.MyApplication</StartupObject></pre>
to
<pre><StartupObject>Sub Main</StartupObject></pre>

Main can choose to not call Application.Run, in which case no form is created.

<syntaxhighlight lang="vbnet">
Module Main
Sub Main(args As String())
Console.WriteLine("main; args:" & String.Join(", ", args))
Application.Run(New Form1())
End Sub
End Module</syntaxhighlight>

{{out|input=foo /bar baz "visual basic"}}
<pre>main; args:foo, /bar, baz, visual basic</pre>

=={{header|V (Vlang)}}==
main() is the usual entry point for a program.
<syntaxhighlight lang="Vlang">

fn main() {
println("hello world")
}
</syntaxhighlight>

However, this can be skipped in one file programs, allowing Vlang to be used like a script.
<syntaxhighlight lang="Vlang">
println("hello world")
</syntaxhighlight>

=={{header|Wren}}==
Wren doesn't have (or need) a ''main'' function. Scripts just run from top to bottom (after a bytecode compilation stage).

However, it's easy enough to create a ''main'' function and call that to start execution of the script.
<syntaxhighlight lang="wren">var main = Fn.new {
System.print("Hello from the main function.")
}

main.call()</syntaxhighlight>

{{out}}
<pre>
Hello from the main function.
</pre>

=={{header|XBasic}}==
Applications in XBasic always start from a Sub Main called <code>FUNCTION Entry()</code>.
Nevertheless, to make an application start from a main routine:
* Create a new module called MMain
* Create a new function in the new module as follows:

<syntaxhighlight lang="xbasic">FUNCTION main ()
'This is the beginning of the program
END FUNCTION</syntaxhighlight>

Press F1 to start the application
<syntaxhighlight lang="xbasic">PROGRAM "Start from a main routine"

DECLARE FUNCTION Entry ()
DECLARE FUNCTION main ()

FUNCTION Entry ()
main ()
END FUNCTION

FUNCTION main ()
PRINT "Hello from main!"
END FUNCTION

END PROGRAM</syntaxhighlight>

=={{header|XPL0}}==
XPL0 programs are normally compiled and run from a main procedure, although this procedure is not explicitly named 'main'. It is possible to compile procedures without a main procedure that are later linked to a module with a main procedure. This feature was used frequently on old, slow 6502-based computers, such as the Apple II.

=={{header|Z80 Assembly}}==
This depends entirely on the hardware. WinAPE (an Amstrad CPC emulator) can run a program by typing <code>call &addr</code> where <code>addr</code> is the operand of the <code>org</code> directive at the beginning of the source document.

In your source code:
<syntaxhighlight lang="z80">org &8000</syntaxhighlight>

At the Amstrad CPC terminal, type this:
<pre>
call &8000
</pre>


=={{header|zkl}}==
=={{header|zkl}}==
Line 342: Line 798:


file foo.zkl:
file foo.zkl:
<lang zkl>"Hello".println()</lang>
<syntaxhighlight lang="zkl">"Hello".println()</syntaxhighlight>
forms an anonymous class whose constructor is a function with the above code. "zkl foo" does the expected.
forms an anonymous class whose constructor is a function with the above code. "zkl foo" does the expected.


Line 349: Line 805:
On the ZX Spectrum, there is no main function as such. However a saved program can be made to start running from a particular line number by providing the line number as a parameter to the save command. The following example will save the program in memory so that it starts running from line 500:
On the ZX Spectrum, there is no main function as such. However a saved program can be made to start running from a particular line number by providing the line number as a parameter to the save command. The following example will save the program in memory so that it starts running from line 500:


<lang zxbasic>SAVE "MYPROG" LINE 500: REM For a program with main code starting at line 500</lang>
<syntaxhighlight lang="zxbasic">SAVE "MYPROG" LINE 500: REM For a program with main code starting at line 500</syntaxhighlight>


{{omit from|Axe}}
{{omit from|Axe}}
{{omit from|BBC BASIC}}
{{omit from|Bc|Scripts start running from the top}}
{{omit from|Bc|Scripts start running from the top}}
{{omit from|Brlcad|Scripts start running from the top in mged}}
{{omit from|Brlcad|Scripts start running from the top in mged}}
Line 359: Line 816:
{{omit from|Dc|Scripts start running from the top}}
{{omit from|Dc|Scripts start running from the top}}
{{omit from|F_Sharp}}
{{omit from|F_Sharp}}
{{omit from|Go}}
{{omit from|GUISS|Scripts read from top down}}
{{omit from|GUISS|Scripts read from top down}}
{{omit from|Haskell}}
{{omit from|Haskell}}
{{omit from|Java|Uses a main method}}
{{omit from|Java|Uses a main method}}
{{omit from|NetRexx|Uses a main method}}
{{omit from|NetRexx|Uses a main method}}
{{omit from|Plain English|Programs start from a 'run' method}}
{{omit from|Python}}
{{omit from|Python}}
{{omit from|Rust}}
{{omit from|Swift}}
{{omit from|Swift}}
{{omit from|UNIX Shell|Scripts start running from the top}}
{{omit from|UNIX Shell|Scripts start running from the top}}
{{omit from|XPL0}}
{{omit from|zkl}}
{{omit from|zkl}}



Latest revision as of 21:25, 10 February 2024

Task
Start from a main routine
You are encouraged to solve this task according to the task description, using any language you may know.


Some languages (like Gambas and Visual Basic) support two startup modes.   Applications written in these languages start with an open window that waits for events, and it is necessary to do some trickery to cause a main procedure to run instead.   Data driven or event driven languages may also require similar trickery to force a startup procedure to run.


Task

Demonstrate the steps involved in causing the application to run a main procedure, rather than an event driven window at startup.

Languages that always run from main() can be omitted from this task.

6502 Assembly

This depends entirely on the hardware.

  • Apple ][: type "BRUN PROG" and press enter
  • Commodore 64: type "LOAD"*",8,1 and press enter. This is how programs on floppy disks are loaded. Commodore 64 cartridges bypass this step entirely and boot immediately.
  • NES/Famicom: Executes JMP ($FFFC) at the start automatically, thus entering the main program.

It should be noted that nothing needs to be called "main" but generally speaking the "main" program is whatever execution flows into at the start.

8086 Assembly

Whether a program runs automatically from main or needs to be called depends entirely on the hardware, but in MS-DOS you have to type the name of the program you wish to run. C:\>prog.exe

Ada

In Ada, the "Main" procedure doesn't have to follow a special naming scheme. Any parameterless procedure will do.

with Ada.Text_IO;
procedure Foo is
begin
   Ada.Text_IO.Put_Line("Bar");
end Foo;

ALGOL 68

An Algol 68 program consists of a sequence of declarations and expressions. The expressions are executed and so form the main program.

BEGIN
    print( ( "Hello, World!", newline ) )
END

Arturo

In Arturo, code is always read and executed from the top to the bottom of the script.

If we need a main function in any case, we can of course create it and call it.

main: function [][
    print "Yes, we are in main!"
]

main
Output:
Yes, we are in main!

AutoHotkey

AutoHotkey always starts at the top of the script. A main() function can be called from there, or event hooks set.

AWK

The awk language is data driven. However, it does support the use of begin blocks, so we could use one of those to provide us with a main startup procedure:

BEGIN {
  # This is our main startup procedure
  print "Hello World!"
}

BASIC

GWBASIC

Works with: GWBASIC

As is well known, GWBASIC cannot refer to anything with a name. Also, does not require an executable program to have a main() procedure. However, as in the other instances, there's nothing to stop you creating a subprocess and then calling it by its line number to start the program:

10 'SAVE "MAIN",A
20 GOSUB 100 ' Main
30 END
100 ' Sub Main
110   CLS
120   PRINT "This is the Main sub!"
130 RETURN

QBasic

Works with: QBasic version 1.1
Works with: QuickBasic version 4.5

QBasic does not require an executable program to have a main() procedure. However, there's nothing to stop you creating one and then calling it to start the program:

SUB main
    PRINT "Hello from main!"
END SUB

main

BASIC256

BASIC256 does not require an executable program to have a main() procedure. However, there's nothing to stop you creating one and then calling it to start the program:

subroutine main()
  print "Hello from main!"
end subroutine
 
call main()

Run BASIC

Run BASIC does not require an executable program to have a main() procedure. However, there's nothing to stop you creating one and then calling it to start the program:

sub main
  print "Hello from main!"
end sub

call main

True BASIC

Works with: QBasic

True BASIC does not require an executable program to have a main() procedure. However, there's nothing to stop you creating one and then calling it to start the program:

SUB main
    PRINT "Hello from main!"
END SUB

CALL main
END

Yabasic

Yabasic does not require an executable program to have a main() procedure. However, there's nothing to stop you creating one and then calling it to start the program:

sub main()
  print "Hello from main!"
end sub
 
main()

C

Code execution in C always starts at main(). Macros make possible programs such as the one below, although it's not the best way to write C code.

#include<stdio.h>

#define start main()

int start
{
	printf("Hello World !");
	return 0;
}
Hello World !

Clojure

Use Leiningen. It will allow you to describe many aspects of your project, including which namespace's -main function it should invoke at startup. When you use the 'lein new app' template, it will generate and configure a -main function for you. You can edit the project.clj to modify :main if you wish to start from some other point. For more details, read the documentation.

Component Pascal

In BlackBox Componente Builder any exported procedure without paramenter (command) can be invoked through commanders (CTRL-q ModuleName.command)

MODULE MainProcedure;
IMPORT StdLog;

PROCEDURE Do*;
BEGIN
	StdLog.String("From Do");StdLog.Ln
END Do;

PROCEDURE Main*;
BEGIN
	StdLog.String("From Main");StdLog.Ln
END Main;
END MainProcedure.

Execute:
^Q MainProcedure.Do
^Q MainProcedure.Main
Output:

From Do
From Main

EasyLang

proc main . .
   print "Hello from main!"
.
main

Erlang

When started Erlang enters a REPL (read-eval-print loop). To call a function called main in the module m you do: erl -run m main argument1 argument 2 ...

Factor

Use MAIN: to specify the starting point of a runnable vocabulary.

USE: io
IN: example

: hello ( -- ) "Hello, world!" print ;

MAIN: hello

This is optional for scripts and interactive development, but required to deploy a Factor program as an executable binary.

Forth

Forth still runs the interpreter when given a file to include in order to compile the source, but you can avoid the interactive interpreter by invoking an entry point ("main") then calling BYE to exit.

include foo.fs
...
: main  ... ;

main bye

This pattern is also used (e.g. GNU Forth) to interpret a Forth snippet from the command line.

$ gforth -e "2 2 + . bye"

Furthermore, professional Forth systems like PFE and SwiftForth have a means to make a "turnkey" application which omits the interactive interpreter, suitable for installing on a third-party system. The command would take an entry point and target executable name:

' main turnkey app.exe

FreeBASIC

FreeBASIC does not require an executable program to have a main() procedure. However, there's nothing to stop you creating one and then calling it to start the program:

' FB 1.05.0 Win64

Sub main()
  Print "Hello from main!"
End Sub

main
Sleep
Output:
Hello from main!

Gambas

In Gambas, to make an application startup from a main routine:

  • Create a new module called MMain
  • In the MMain module, create a public sub called Main as follows:
PUBLIC SUB Main()
  ' This is the start of the program
END
  • Right click the MMain module, then select Startup class from the context menu

Go

In Go all executable programs must have a main package which includes a function called main() with no parameters nor return value.

However, execution doesn't necessarily begin with main() itself. If there are top-level functions called init() with no parameters nor return value, these are executed first in declaration order and they can call other functions including main() itself.

Here's an example which illustrates this behavior. Note that main() gets called twice, first by the second init() function and then automatically by the runtime.

In practice, init() functions are generally used to initialize top-level variables which cannot (or cannot easily) be initialized in situ rather than to pre-empt the main() function in this way.

package main

import "fmt"

var count = 0

func foo() {
    fmt.Println("foo called")
}

func init() {
    fmt.Println("first init called")
    foo()
}

func init() {
    fmt.Println("second init called")
    main()
}

func main() {
    count++
    fmt.Println("main called when count is", count)
}
Output:
first init called
foo called
second init called
main called when count is 1
main called when count is 2

J

J, by default, starts an event loop.

If a file name is specified on the command line, that file is executed before dropping into the event loop.

Thus, if the script issues an exit command, that will happen before the event loop executes.

If you want the script to exit even when it hits an error, you can use an immex phrase, which will be the first thing executed by the event loop, before it prompts.

jq

A jq program consists of a (possibly empty) sequence of directives and function definitions followed by a single (but possibly compound) jq expression that is evaluated in the context of the prior definitions. The jq expression can take many forms, such as a single JSON value, or a pipeline of filters. In particular, it could be the invocation of a previously defined function named main as in this example:

def main:
    "Hello, World!";
main

The jq interpreter has two modes of operation: a data-driven mode (the default) and an autonomous mode (corresponding to the `-n` command-line option). In general, in the data-driven mode, the expression at the end of the jq program is evaluated once for each input, so that in the above example, the "Hello, World!" string would be emitted once for each input.

By contrast, if the `-n` command-line option is specified, then a single JSON `null` would be presented to the final expression, so that in the above example, the string would be emitted just once.

Julia

If the program, julia, is executed via the command line without a program filename argument, it will enter its REPL (Read–Evaluate-Print-Loop) by default, without executing any user code until that is entered via the REPL command line. If, instead, Julia is started with a Julia program filename as argument, it will execute that program and, after that program terminates, exit without seeking any REPL input.

Kotlin

The version of Kotlin which targets the JVM always starts from the main(args: Array<String>) function unless it is running in REPL mode when it simply executes lines of executable code in the order presented. The REPL is started by typing, kotlinc, without any parameters at the command prompt. For example:

Output:
Welcome to Kotlin version 1.1.1 (JRE 1.8.0_121-b13)
Type :help for help, :quit for quit
>>> println("Look no main!")
Look no main!
>>> :quit

Logtalk

Logtalk applications don't run a main procedure at startup by default but there are several ways to accomplish that. One of them is to include an initialization/1 in a source file. The argument of this directive is a goal that will be proved when the source file is compiled and loaded. For example:

:- initialization(main).

The initialization/1 can also be used within entities (objects and categories) to automatically run entity-specific initializations when the container source file is compiled and loaded. In alternative, it's usually possible to pass a goal as a command-line argument when running the application executable (the details depending on the backend Prolog compiler being used).

Mathematica/Wolfram Language

Mathematica automatically starts a REPL (read-eval-print loop), which is a kind of event loop. If that is not desired, pass -run on the command line. Note that if Mathematica is called via MathLink from within an external program, then the main loop has to be defined, which will usually differ from the standard one.

Nim

Nim does not require a procedure called "main" for program execution, but programmers are free to create a procedure with that name.

proc main() =
  echo "Hello World!"

main()

Oforth

If Oforth loads a file and this file does not launch anything, nothing happens but file interpretation, and oforth leaves.

For instance if file1.of is :

: main(n)
   "Sleeping..." println
   n sleep
   "Awake and leaving." println ;
Output:
>oforth file1.of

Nothing happens because oforth has nothing to perform.

If Oforth loads a file and this file launchs a function or method, it will be interpretred (and so, performed), and oforth leaves.

With this file (for instance file2.of) :

: main(n)
   "Sleeping..." println
   n sleep
   "Awake and leaving." println ;

10000 main
Output:
>oforth file2.of
Sleeping...
Awake and leaving.

The function is performed.

Another way is to load a file and to give what to run into the command line parameters. For instance, using file1.of

Output:
>oforth --P"10000 mysleep" file1.of
Sleeping...
Awake and leaving.

Of course, "main" as function name to launch is not required : every name is ok.

PARI/GP

GP scripts start from the top of the script. PARI code starts from the main function.

Pascal

Pascal programs are mostly compiled and run a 'main' procedure automatically, this procedure is not explicitly named main. Units (separate files of code without a main procedure) have initialisation code which also runs automatically.

Perl

Same as Raku.

BEGIN {...} # as soon as parsed
CHECK {...} # end of compile time
INIT {...}  # beginning of run time
END {...}   # end of run time

Phix

Library: Phix/basics

Any code which is not part of a routine is considered 'main' code. If you want a main() you have to explicitly invoke it.

procedure main()
    ...
end procedure
main()

PicoLisp

PicoLisp automatically starts a REPL (read-eval-print loop), which is a kind of event loop. If that is not desired, call (wait), or pass -wait on the command line. Per convention, the GUI event loop is started by calling (go), or by passing -go on the command line.

Processing

By default, Processing executes the given list of commands with no required main function/method. This is called "immediate mode."

println("hello world");
line(0, 0, width, height);

Most of the Processing API can be used in immediate mode--however, it has no event loop, so it cannot support animation, interaction (such as keyboard or mouse) or time-based media such as audio or video. Further, this mode cannot define new functions/methods, or classes. For example, this is invalid:

void hello() {
  println("hello world");
}
hello();

In order to define functions or use these language features, setup() and/or draw() must be defined in a Processing sketch. These serve as the equivalent of a main() entrypoint. For example, this is a valid sketch:

void setup() {
  hello();
}
void hello() {
  println("hello world");
}

setup() -- or draw() if there is no setup() -- acts as an entrypoint to the sketch, with draw() also serving as an event loop that by default is called at 60fps.

PureBasic

PureBasic is procedural and any code which is not part of a procedure is considered 'main' code. This code also does not use any explicit syntax (i.e. a 'main' module) to cause it to execute and it always executes first.

Quackery

To run the Quackery shell (i.e. REPL) type quackery in the OS monitor app.

To run a Quackery program from the monitor, type quackery [program-name].qky

To run a Quackery program from the Quackery shell, type $ "[program-name].qky" loadfile.

To run the Quackery shell from a Quackery program, include the word shell in the program.

To run a Quackery program from within a Quackery program, include the phrase $ "[program-name].qky" loadfile in the program.

To run a Quackery program during compilation of a Quackery program, include the phrase [ $ "[program-name].qky" loadfile ] now! in the program.

To run the Quackery shell from within the Quackery shell, type shell.

To run the Quackery shell during compilation within the Quackery shell, type [ shell ] now!.

Other variations are possible. To illustrate this, here is a program which, if typed in in the shell, or included in a .qky file, will temporarily suspend compilation to interact with the user. constant includes the functionality of now! but treats the top item of the stack as if it were part of the program text.

[ say "Please use the shell to calculate a value" cr
  say "and leave it on the stack. Type 'leave' when" cr
  say "you have done this." cr
  shell ]                             constant is my-value

Demonstrating this in the Quackery shell. Text after the duck's head prompt and the continuation ellipses is entered by the user.

 > quackery

Welcome to Quackery.

Enter "leave" to leave the shell.

Building extensions.

/O> [ say "Please use the shell to calculate a value" cr
...   say "and leave it on the stack. Type 'leave' when" cr
...   say "you have done this." cr
...   shell ]                             constant is my-value
... 
Please use the shell to calculate a value
and leave it on the stack. Type 'leave' when
you have done this.

/O> 123 456 +
... leave
... 

Be seeing you.


Stack empty.

/O> my-value echo
... 
579
Stack empty.

/O> leave
... 

Auf wiedersehen.


 > 

Racket

Racket can be configured to run a REPL, run a main function, or just run top-level expressions. A main function can be run by executing racket -tm program.rkt.

#/usr/bin/env racket -tm
#lang racket
(provide main)
(define (main . args) (displayln "Hello World!"))

Raku

(formerly Perl 6) When executed with the standard setting, Raku code always runs the mainline code automatically, followed by the MAIN function if you have one. However, it's possible to start up with an alternate setting that might want to create its own event loop or MAIN. In such cases you can always capture control at various phases with blocks that we call "phasers":

BEGIN {...} # as soon as parsed
CHECK {...} # end of compile time
INIT {...}  # beginning of run time
END {...}   # end of run time

REXX

The closest REXX has to this type of behavior is when a REXX program starts,
then executes (as per this discusion, say) an XEDIT session, and
then re-directs commands to the XEDIT session via the ADDRESS command.
XEDIT has native (built-in) support for the REXX language as a macro language.
The XEDIT mentioned above runs on the VM/CMS operating system.

/*REXX*/
address 'XEDIT'
  .
  .
  .
[XEDIT commands here.]
  .
  .
  .

Ring

func Main
     see "Hello World!" + nl

Output:

Hello World!

Ruby

Every Ruby source file can declare blocks of code to be run as the file is being loaded (the BEGIN blocks) and after the program has finished executing (the END blocks). BEGIN and END Blocks

BEGIN {
  # begin code
}

END {
  # end code
}

A program may include multiple BEGIN and END blocks. BEGIN blocks are executed in the order they are encountered. END blocks are executed in reverse order.

Scala

Library: Scala

No kidding and trickery

In Scala there are two concepts not available in another OO-languages e.g. Java. The concepts are object and trait. Both cannot have parameters. object's are singletons (one and only one instance of a parameter-less class) and are static. Exactly the same as a main. By use of the trait App a main method is preprogrammed and brought in an object which can be called on the command-line. There are more the one different object's possible each can be called by his object name on the command-line. In the trait executionStart field is initialized with the starting time. By submitting an -Dscala.time argument on the command-line the execution time can be reported. The field executionStart can also programmatically used.

Example:
object PrimaryMain extends App {
Console.println("Hello World: " + (args mkString ", "))
}

object MainTheSecond extends App {
Console.println("Goodbye, World: " + (args mkString ", "))
}

sed

A sed program repeats itself for each line of input, but your program can begin with commands that address line 1. (This requires that your input has a line 1. If your input is empty file, like /dev/null, then it is impossible to run commands.)

# This code runs only for line 1.
1 {
	i\
Explain-a-lot processed this file and
	i\
replaced every period with three exclamation points!!!
	i\

}

# This code runs for each line of input.
s/\./!!!/g

Seed7

Code execution in Seed7 always starts with main. This holds for text programs:

$ include "seed7_05.s7i";

const proc: main is func
  begin
    writeln("hello world");
  end func;

And for grahical programs:

$ include "seed7_05.s7i";
  include "draw.s7i";
  include "keybd.s7i";

const proc: main is func
  begin
    screen(200, 200);
    KEYBOARD := GRAPH_KEYBOARD;
    ignore(getc(KEYBOARD));
  end func;

Tcl

If a Tcl interpreter (such as tclsh or wish) is started without a script file, it will (typically) provide an interactive command prompt that supports read-eval-print-loop functionality. However, if a script file is supplied the file is executed and then the program either exits or, if Tk is in use, the application waits, servicing events, until the last window is deleted.

Visual Basic

In Visual Basic to make an application startup from a main routine:

  • Create a new module called MMain.bas
  • Create a new subroutine in the new module as follows:
SUB Main()
  ' This is the start of the program
END
  • From the menu in the application development environment, choose: File, Project Options.
  • Ensure that MMain.bas is selected, by clicking in the list
  • From the pulldown list, choose "Sub Main"
  • Click the OK button.

Visual Basic .NET

VB.NET console apps always start in Sub Main, but Windows Forms apps use the application framework by default, meaning the compiler generates a Sub Main that shows a selected startup form. To parse command-line parameters or cancel the application startup, either the appropriate methods in the MyApplication class can be overridden, or the application framework can be disabled, in which case it is allowed to set the startup object to be a method.

MyApplication

Comments copied from the metadata of System.Windows.Forms.dll.

OnInitialize can cancel startup by returning false, and the handler for Startup can cancel startup by setting e.Cancel to True.

Imports System.Collections.ObjectModel
Imports Microsoft.VisualBasic.ApplicationServices

Namespace My
    ' The following events are available for MyApplication:
    ' Startup: Raised when the application starts, before the startup form is created.
    ' Shutdown: Raised after all application forms are closed.  This event is not raised if the application terminates abnormally.
    ' UnhandledException: Raised if the application encounters an unhandled exception.
    ' StartupNextInstance: Raised when launching a single-instance application and the application is already active. 
    ' NetworkAvailabilityChanged: Raised when the network connection is connected or disconnected.

    Partial Friend Class MyApplication
        '''<summary>Sets the visual styles, text display styles, and current principal for the main application thread
        '''(if the application uses Windows authentication), and initializes the splash screen, if defined.</summary>
        '''<param name="commandLineArgs">A <see cref="ReadOnlyCollection(Of T)" /> of <see langword="String" />,
        '''containing the command-line arguments as strings for the current application.</param>
        '''<returns>A <see cref="T:System.Boolean" /> indicating if application startup should continue.</returns>
        Protected Overrides Function OnInitialize(commandLineArgs As ReadOnlyCollection(Of String)) As Boolean
            Console.WriteLine("oninitialize; args: " & String.Join(", ", commandLineArgs))
            Return MyBase.OnInitialize(commandLineArgs)
        End Function

        ' WindowsFormsApplicationBase.Startup occurs "when the application starts".
        Private Sub MyApplication_Startup(sender As Object, e As StartupEventArgs) Handles Me.Startup
            Console.WriteLine("startup; args: " & String.Join(", ", e.CommandLine))
        End Sub

        '''<summary>Provides the starting point for when the main application is ready to start running, after the
        '''initialization is done.</summary>
        Protected Overrides Sub OnRun()
            Console.WriteLine("onrun")
            MyBase.OnRun()
        End Sub
    End Class
End Namespace
Output  —  for input foo /bar baz "visual basic":
oninitialize; args: foo, /bar, baz, visual basic
startup; args: foo, /bar, baz, visual basic
onrun

Sub Main

In Visual Studio:

In project properties, create a Sub Main of the appropriate signature, uncheck 'Enable application framework', and set 'Startup object' to 'Sub Main'.

By editing vbproj:

Change

<MyType>WindowsForms</MyType>

to

<MyType>WindowsFormsWithCustomSubMain</MyType>

and

<StartupObject>[DEFAULT NAMESPACE OF APPLICATION].My.MyApplication</StartupObject>

to

<StartupObject>Sub Main</StartupObject>

Main can choose to not call Application.Run, in which case no form is created.

Module Main
    Sub Main(args As String())
        Console.WriteLine("main; args:" & String.Join(", ", args))
        Application.Run(New Form1())
    End Sub
End Module
Output  —  for input foo /bar baz "visual basic":
main; args:foo, /bar, baz, visual basic

V (Vlang)

main() is the usual entry point for a program.

fn main() {
	println("hello world")
}

However, this can be skipped in one file programs, allowing Vlang to be used like a script.

println("hello world")

Wren

Wren doesn't have (or need) a main function. Scripts just run from top to bottom (after a bytecode compilation stage).

However, it's easy enough to create a main function and call that to start execution of the script.

var main = Fn.new {
    System.print("Hello from the main function.")
}

main.call()
Output:
Hello from the main function.

XBasic

Applications in XBasic always start from a Sub Main called FUNCTION Entry(). Nevertheless, to make an application start from a main routine:

  • Create a new module called MMain
  • Create a new function in the new module as follows:
FUNCTION  main ()
    'This is the beginning of the program
END FUNCTION

Press F1 to start the application

PROGRAM	"Start from a main routine"

DECLARE FUNCTION  Entry ()
DECLARE FUNCTION  main ()

FUNCTION  Entry ()
  main ()
END FUNCTION

FUNCTION  main ()
  PRINT "Hello from main!"
END FUNCTION

END PROGRAM

XPL0

XPL0 programs are normally compiled and run from a main procedure, although this procedure is not explicitly named 'main'. It is possible to compile procedures without a main procedure that are later linked to a module with a main procedure. This feature was used frequently on old, slow 6502-based computers, such as the Apple II.

Z80 Assembly

This depends entirely on the hardware. WinAPE (an Amstrad CPC emulator) can run a program by typing call &addr where addr is the operand of the org directive at the beginning of the source document.

In your source code:

org &8000

At the Amstrad CPC terminal, type this:

call &8000

zkl

In zkl there is no main per se, the constructor of the top most enclosing class (usually the file as files define a class) is run. This remains the same even when a gui front end is pasted on.

file foo.zkl:

"Hello".println()

forms an anonymous class whose constructor is a function with the above code. "zkl foo" does the expected.

ZX Spectrum Basic

On the ZX Spectrum, there is no main function as such. However a saved program can be made to start running from a particular line number by providing the line number as a parameter to the save command. The following example will save the program in memory so that it starts running from line 500:

SAVE "MYPROG" LINE 500: REM For a program with main code starting at line 500