Skip to content

Cannot use @main with swift_binary srcs #913

@luispadron

Description

@luispadron

Summary

In newer versions of Swift its possible to define the main entry point using @main. The only requirement is the type has a public static main() method.

When using rules_swift to build a swift_binary that uses @main we get a compilation error:

example.swift:12:1: error: 'main' attribute cannot be used in a module that contains top-level code
@main
^

This happens when the example.swift is part of the swift_binary srcs attribute.

This same code works and is executable when using swift_library and adding it as a dep of swift_binary. However, if you do this then swift_library cannot be tested with swift_test because of: #911

Example

// example.swift

import Foundation

protocol DefinesMain {
}

extension DefinesMain {
    public static func main() {
        print("Hello, world!")
    }
}

@main
struct Entry: DefinesMain {

}
# BUILD.bazel

swift_binary(
    name = "example",
    srcs = ["example.swift"],
)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions