Program Entry
The entry point of a Cangjie program is a special global function called main
. Only one main
is allowed at the top level of a package in the source files root directory.
If a module is compiled with the goal of generating an executable file, the compiler searches for main
only at the top level of the source files root directory. If no main
is found, the compiler reports an error. Otherwise, the compiler checks its parameters and return value types. Note that main
cannot be modified by access modifiers. When a package is imported, the main
defined in the package is not imported.
A main
function that serves as the program entry point is declared without the func
keyword and may either have no parameters or have one parameter of the Array<String>
type. Its return value type can be either Unit
or integer.
main
without parameters:
// main.cj
main(): Int64 { // Ok.
return 0
}
main
with parameters of the Array<String>
type:
// main.cj
main(args: Array<String>): Unit { // Ok.
for (arg in args) {
println(arg)
}
}
After compiling the above example using cjc main.cj
, run the ./main Hello, World
command. The following information will be displayed:
Hello,
World
The following are some incorrect examples:
// main.cj
main(): String { // Error, return type of 'main' is not 'Integer' or 'Unit'.
return ""
}
// main.cj
main(args: Array<Int8>): Int64 { // Error, 'main' cannot be defined with parameter whose type is not Array<String>.
return 0
}
// main.cj
// Error, multiple 'main's are found in source files.
main(args: Array<String>): Int32 {
return 0
}
main(): Int8 {
return 0
}