In computer programming, an entry point is the place in a program where the execution of a program begins, and where the program has access to command line arguments.
To start a program's execution, the loader or operating system passes control to its entry point. (During booting, the operating system itself is the program). This marks the transition from load time (and dynamic link time, if present) to run time.
For some operating systems and programming languages, the entry point is in a runtime library, a set of support functions for the language. The library code initializes the program and then passes control to the program proper. In other cases, the program may initialize the runtime library itself.
In simple systems, execution begins at the first statement, which is common in interpreted languages, simple executable formats, and . In other cases, the entry point is at some other known memory address which can be an absolute address or relative address (offset).
Alternatively, execution of a program can begin at a named point, either with a conventional name defined by the programming language or operating system or at a caller-specified name. In many C-family, this is a function called main; as a result, the entry point is often known as the main function.
In JVM languages, such as Java, the entry point is a static method called main; in CLI languages such as C# the entry point is a static method named Main.
Entry points are capable of passing on command arguments, variables, or other information as a local variable used by the Main() method. This way, specific options may be set upon execution of the program, and then interpreted by the program. Many programs use this as an alternative way to configure different settings, or perform a set variety of actions using a single program.
In C, C++, D, Zig, Rust and Kotlin programs this is a function named main; in Java it is a static method named main (although the class must be specified at the invocation time), and in C# it is a static method named Main.
In many major operating systems, the standard executable format has a single entry point. In the Executable and Linkable Format (ELF), used in Unix and Unix-like systems such as Linux, the entry point is specified in the e_entry field of the ELF header. In the GNU Compiler Collection (gcc), the entry point used by the linker is the _start symbol. Similarly, in the Portable Executable format, used in Microsoft Windows, the entry point is specified by the AddressOfEntryPoint field, which is inherited from COFF. In , the entry point is at the fixed offset of 0100h.
One exception to the single-entry-point paradigm is Android. Android applications do not have a single entry point there is no special main function. Instead, they have essential components (activities and services) which the system can load and run as needed.
An occasionally used technique is the fat binary, which consists of several executables for different targets packaged in a single file. Most commonly, this is implemented by a single overall entry point, which is compatible with all targets and branches to the target-specific entry point. Alternative techniques include storing separate executables in separate forks, each with its own entry point, which is then selected by the operating system.
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.
Usually, there is not a single exit point specified in a program. However, in other cases runtimes ensure that programs always terminate in a structured way via a single exit point, which is guaranteed unless the runtime itself crashes; this allows cleanup code to be run, such as atexit handlers. This can be done by either requiring that programs terminate by returning from the main function, by calling a specific exit function, or by the runtime catching exceptions or operating system signals.
The main function is generally the first programmer-written subroutine that runs when a program starts, and is invoked directly from the system-specific initialization contained in the runtime environment (crt0 or equivalent). However, some languages can execute user-written functions before main runs, such as the constructors of C++ global objects.
In other languages, notably many interpreted languages, execution begins at the first statement in the program.
A non-exhaustive list of programming languages follows, describing their way of defining the main entry point:
The main function is the entry point for application programs written in ISO-standard C or C++. Low-level system programming (such as for a bare-metal embedded system) might specify a different entry point (for example via a reset interrupt vector) using functionality not defined by the language standard.
If using trailing return types, C++ also supports the following signatures of :
If the signature is (with no /), if command-line arguments are supplied, they will simply be ignored by the program.
The parameters , argument count, and , argument vector, respectively give the number and values of the program's command-line arguments. The names of and may be any valid identifier, but it is common convention to use these names. Other platform-dependent formats are also allowed by the C and C++ standards, except that in C++ the return type must always be ;Section 3.6.1.2, Standard C++ 2011 edition. for example, Unix (though not POSIX.1) and Windows have a third argument giving the program's environment, otherwise accessible through in stdlib.h:
Darwin-based operating systems, such as macOS, have a fourth parameter containing arbitrary OS-supplied information, such as the path to the executing binary:
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: (traditionally ) and . The meaning of other possible return values is implementation-defined. In case a return value is not defined by the programmer, an implicit at the end of the function is inserted by the compiler; this behavior is required by the C++ standard.
It is guaranteed that is non-negative and that argv[argc] is a null pointer. By convention, the command-line arguments specified by and include the name of the program as the first element if is greater than 0; if a user types a command of "", the shell will initialise the rm process with and . 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.
On GCC and Clang, it is possible to call (or potentially even select a different function as the entry point) by passing the compiler flag and then defining the function . Arguments from command line to can be retrieved using inline assembly.
void _start() {
int altMain() {
int exitCode = altMain();
exit(exitCode);
}
printf("No main() function in this program.");
return 0;
}
The function is special; normally every C and C++ program must define it exactly once.
If declared, must be declared as if it has external linkage; it cannot be declared or .
In C++, must be in the global namespace (i.e. ), and cannot be overloaded. In C++ (unlike C) cannot be called recursively and cannot have its address taken. If is not defined in the global namespace (for example if it is only defined as a member function of a class), the compiler will not detect it. The name is not otherwise reserved, and may be used for member functions, classes, enumerations, or non-member functions in other namespaces.
using std::string;
using std::vector;
class Main {
public:
int main(int argc, char* argv) {
static void main(const vector
};
vector
}
In 2017, there was a proposal for a "modern" signature for , more similar to Java and C# (which instead of , these languages have main(String[]), taking an array of strings). The suggested signature was (as at the time, was not yet part of the language), however this proposal was rejected.
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.
Like Java, the entry point of a program typically resides in a named class, like so:
using System;
public class HelloWorld
{
static void Main(string[] args)
{
Console.WriteLine("Hello, world!");
}
}
Since C#7.1 there are four more possible signatures of the entry point, which allow asynchronous execution in the Main() Method.
The Task and Task<int> types are the asynchronous equivalents of void and int (note that Task<void> is invalid). async is required to allow the use of asynchronous calls (the await keyword) inside the method.
Or even simpler
One tells the compiler which option to use to generate the executable file.
(hello-main)
(format t "Hello World!~%"))
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.
print("Hello, world!");
}
In this example, the main function simply prints the text Hello, world! to the console when the program is run. This code will be executed automatically when the Dart program is run.
It is important to note that while the main function is the default entry point for a Dart program, it is possible to specify a different entry point if needed. This can be done using the @pragma("vm:entry-point") annotation in Dart. However, in most cases, the main function is the entry point that should be used for Dart programs.
PROGRAM HELLO
PRINT *, "Cint!"
END PROGRAM HELLO
Some versions of Fortran, such as those on the IBM System/360 and successor mainframes, do not support the PROGRAM statement. Many compilers from other software manufacturers will allow a fortran program to be compiled without a PROGRAM statement. In these cases, whatever module that has any non-comment statement where no SUBROUTINE, FUNCTION or BLOCK DATA statement occurs, is considered to be the Main program.
import "fmt"
func main() {
fmt.Println("Hello, World!")
}
There is no way to access arguments or a return code outside of the standard library in Go. These can be accessed via os.Args and os.Exit respectively, both of which are included in the "os" package.
Command line arguments are not given to main; they must be fetched using another IO action, such as [https://downloads.haskell.org/~ghc/latest/docs/html/libraries/base-4.11.1.0/System-Environment.html#v%3AgetArgs System.Environment.getArgs].
// unnamed class-based
void main();
void main(String args);
void main(String... args);
void main(String args);
Command-line arguments are passed in args. As in C and C++, the name "main()" is special. Java's main methods do not return a value directly, but one can be passed by using the System.exit() method.
Unlike C, the name of the program is not included in args, because it is the name of the class that contains the main method, so it is already known. Also unlike C, the number of arguments need not be included, since arrays in Java have a field that keeps track of how many elements there are.
The main function must be included within a class. This is because in Java everything has to be contained within a class. For instance, a hello world program in Java may look like:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, world!");
}
}
To run this program, one must call java HelloWorld in the directory where the compiled class file HelloWorld.class) exists. Alternatively, executable JAR files use a manifest file to specify the entry point in a manner that is filesystem-independent from the user's perspective.
Since Java 25, it is possible to create a "compact source file" which implicitly declares a final class in the unnamed package. This class extends java.lang.Object and does not implement any interfaces, has only a default constructor, and has the fields and methods declared in the compact source file. Furthermore, Java 25 moves the class java.io.IO to the package java.lang (thus implicitly importing it into all source files), based on System.out and System.in rather than java.io.Console. This allows a simplified Hello World program, perhaps more similar to C and C++ where main resides in the global namespace:
IO.println("Hello, world!");
}
// Async version:
async function main(): Promise
// In this pattern, only a call to main() is top-level
// A good idea may be to call main() and catch any errors,
// then cleanly log them like so
main().catch((err) => {
console.log("Hello world");
}
console.log("Hello world");
}
console.error(err);
process.exit(1);
});
If using Node.js, it is possible to emulate the Python-style pattern of
if (require.main === module) {
console.log("Running as main module");
}
main();
}
Since Julia version 1.11 there's also the possibility of defining a main function that will be called as an entry point, and it can e.g. look like this if using the associated @main macro:
For compatibility with prior Julia versions, such as Julia 1.10 (LTS), the above line can be made to work with one extra line from the documentation, and using this way can help since the new "feature is intended to aid in the unification of compiled and interactive workflows." Other ways documented elsewhere are no longer needed.
The former println above showing the older way for an entry point without defining a main function is still perfectly fine for scripts (and ARGS is available in both cases, there directly from the a global variable; and PROGRAM_FILE in either case). Note if you do both, scripts will still run the first line as usual, and from there onward so this would also call main and print twice. But neither is necessarily the first code run unless you invoke Julia with --startup-file=no since the default Julia startup file is run before anything else (it's empty after install, but can easily be forgotten e.g. when benchmarking, if you've added to it).
The exit status is 0 by default (on success, throwing changes that), and exit(my_exit_code) exits the program with a non-default one.
println("No arguments")
}
// With arguments:
fun main(args: Array
// concise-style:
fun main(args: Array println("First argument: ${args[0]}")
}
In the Java Virtual Machine, the JVM bytecode will represent this as a static method of a class, as the JVM does not support top-level functions. For example, if the file is named :
public static void main(String[] args) {
// ...
}
}
to procname
... ; Startup commands (such as print [Welcome])
end
make "startup [procname]
The variable startup is used for the startup list of actions, but the convention is that this calls a procedure that runs the actions. That procedure may be of any name.
Command-line arguments are available in an array named Sys.argv and the exit status is 0 by default.
Example:
writeln('Hello, world!');
end.
Command-line arguments are counted in ParamCount and accessible as strings by ParamStr(n), with n between 0 and ParamCount.
Versions of Pascal that support units or modules may also contain an unnamed block in each, which is used to initialize the module. These blocks are executed before the main program entry point is called.
Command-line arguments are available in the special array @ARGV. Unlike C, @ARGV does not contain the name of the program, which is $0.
Example:
int main(int argc, array(string) argv)
Alternatively, a program can be structured with an explicit main function containing the code to be executed when a program is executed directly, but which can also be invoked by importing the program as a module and calling the function. This can be done by the following idiom, which relies on the internal variable __name__ being set to __main__ when a program is executed, but not when it is imported as a module (in which case it is instead set to the module name); there are many variants of this structure: comments Code Like a Pythonista: Idiomatic Python βon Python scripts used as modules
def main(argv: liststr) -> int:
if __name__ == "__main__":
argc: int = len(argv) # get length of argv
n: int = int(argv[1])
print(n + 1)
return 0
sys.exit(main(sys.argv))
In this idiom, the call to the named entry point main is explicit, and the interaction with the operating system (receiving the arguments, calling system exit) are done explicitly by library calls, which are ultimately handled by the Python runtime. This contrasts with C, where these are done implicitly by the runtime, based on convention.
getInteger = int(n)
end function
Command line arguments (if any) can be read using the function:
It has the following properties:
Methods defined outside of a class or module scope are defined as private methods of the "main" object. Since the class of "main" is Object, such methods become private methods of almost every object:
from (irb):8
from /usr/bin/irb:12:in `
irb(main):009:0> false.foo
NoMethodError: private method `foo' called for false:FalseClass
from (irb):9
from /usr/bin/irb:12:in `
The number and values of command-line arguments can be determined using the ARGV constant array:
tty(main):001:0> ARGV
ARGV
=> "foo",
tty(main):002:0> ARGV.size
ARGV.size
=> 2
The 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. class ARGF β on Ruby ARGV
Similar to Python, one could use:
# Put "main" code here
end
to execute some code only if its file was specified in the ruby invocation.
println!("Hello, World!");
}
Additionally, as of Rust 1.26.0, the main function may return a Result:
fn main() -> Result<(), Error> {
println!("Hello, World!");
Ok(()) // Return a type Result of value Ok with the content (), the unit type.
}
Rust does not have parameters in the main() function like C++ and Java or other C-style languages. Instead, it accesses command-line arguments using std::env::args(), which returns std::env::Args and can then be converted to Vec<String> using .collect().
fn main() -> Result<(), Error> {
let args: Args = env::args(); // get the command line args
let args_vec: Vec
for arg in args_vec {
println!("{}", arg);
}
Ok(())
}
let hello = "hello"
let world = "world"
let helloWorld = hello + " " + world
print(helloWorld) // hello world
Cocoa- and Cocoa Touch-based applications written in Swift are usually initialized with the @NSApplicationMain and @UIApplicationMain attributes, respectively. Those attributes are equivalent in their purpose to the main.m file in Objective-C projects: they implicitly declare the main function that calls UIApplicationMain(_:_:_:_:) which creates an instance of UIApplication.
The following code is the default way to initialize a Cocoa Touch-based iOS app and declare its application delegate.
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
}
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
return true
}
Debug.Print "Hello World!"
MsgBox "Arguments if any are: " & Command$
End Sub
|
|