What flags to you have to pass to the compiler to tell it to generate an executable from a file that isn’t called main.swift? How does it know to treat top‐level code as a function body? How does it decide what to name the main function? How does it set up the entry point? Is Windows any different?
Such a thing must be possible:
SwiftPM generates an executable from LinuxMain.swift.
CMake doesn’t care what the file name is; @compnerd’s example uses hello.swift and works across all platforms.
My main motivation for asking is the hope of finding a workaround for this, but as I hunt through the source of both SwiftPM and CMake, I’ve mostly just realized I have no idea how the compiler works in this area in the first place. I’m finding nothing mostly because I don’t even know what I’m looking for.
where hello.swift had your print statement in it. I tried it without the -o parameter, but nothing was generated. Unlike gcc and clang, swiftc doesn't seem to create a default executable if you don't give an output parameter.
If you actually built a file called Hello World.swift, did you either put the filename in double quotes, or escape the space? Otherwise, swiftc would try to compile a file named Hello (presumably, Hello.swift), and World.swift
I don't know if it's changed, but when I left Apple there were three ways for a file to be "main":
It is the only file in the compilation and you have not passed -parse-as-library
It is named main.swift
It contains a type with one of the main-ish attributes
I don't actually know how LinuxMain.swift works, but it wouldn't surprise me if the package manager is simply copying it to a temporary directory and renaming it to main.swift. You could toss a print(#file) in there to see if that's the case.
On the one hand, there's no reason why the main file needs to be named main.swift. On the other, there's no reason not to name it main.swift except if you're using the name of the file to decide how to process it for some reason (like SwiftPM). That's why no one's added that capability in all the years Swift's been public.
(Xcode actually always passes -parse-as-library, so Xcode targets have to use main.swift if they want top-level code.)