How can my C main function call Swift?

I have a program that must have its main function in C, but the majority of the program will be in Swift. This will run on a Linux server. Looking at past posts it seemed like the situation with regards to calling Swift from C was ever-changing. What is the current state of things? Also swiftc wants to add a main function of its own and I need to know how to suppress that. Thanks.

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.

1 Like

Here is a related discussion: Best way to call a Swift function from C?.

1 Like

Thank you codafi, that solved my problems.

1 Like
Terms of Service

Privacy Policy

Cookie Policy