How to specify main func within a class

This may seem like a very basic question, but you'd be surprised how many self-proclaimed bloggers and tutorial writers there are claiming to offer answers to this question, which seems to be either plainly wrong or which are elaborate answers that have little to do with the question.

Here is what I understand should work:
@main
class Foo {
public static main() -> Void {
print ("it runs")
}
}
Unfortunately this gives an linker error: Undefined reference to Foo...main...
with a bunch of gobbly-gook around Foo and main.
What is the correct way to specify main these days in Linux for a command line program? Thanks.

That is correct code [Edit: almost—see below], provided it is compiled with a build tool that supports it. For example, I don’t think SwiftPM handles @main yet.

P.S. Naming a file main.swift should still work the same as it always has.

You're missing a func in the snippet, but also see https://bugs.swift.org/browse/SR-12683 and the workaround to add -parse-as-library.

Terms of Service

Privacy Policy

Cookie Policy