How can my C main function call Swift?

You can use @_cdecl(...) to create C-compatible entrypoints to Swift functions. You can then declare them as externs in a header so C can see them. To suppress implicit main, you’ll need to ensure that your Swift code is built in -parse-as-library mode - otherwise the frontend will nominate the first input file as the main file. I had to put together a mixed program just like this when I was redoing the command line handling in stdlib*.

*Note that this test abuses @_silgen_name unnecessarily. Please use @_cdecl when you actually do this. If anybody would like to swap that attribute, I’d really appreciate it.

2 Likes