How to use C++ standard library via Swift C++ interoperability

I've recently been interested in swift c++ interoperability. I'm not quite sure how mature this is now but I found a repo cpp_example, which seems to use some C++ features like namespace or class.
However, this example doesn't use c++ header inside so, I tried but failed

  • the headers were not found when I added c++ include statements like #include <iostream> at the top
  • build error occurred with the flag swift build -Xcxx -I /{path-to-toolchain}/usr/include/c++/v1

Is there any way using c++ headers or not available?

Swift doesn't currently have any official direct C++ interop. The Swift for TensorFlow project has been dabbling with it I believe (as well as some other people individually), and I'm not sure if any of that work has been merged into the current master branch.

@nuclearace
Thanks! As you mentioned, I'm using Swift for Tensorflow 5. The cpp_example contains some c++ feature like namespace and class structure and it worked in my environment properly with S4TF so, I think the compiler implements at least some part of c++ compilation flow.
However, I couldn't find a way to include c++ header by S4TF, even it's possible or not.

Is there anyone who knows about this?

I believe the limited c++ support currently in the compiler requires that you use a module map to define your c++ module, and then import that. You'll also need to pass the hidden -enable-cxx-interop option to the frontend. As @nuclearace said though, the feature is experimental, so a lot of c++ constructs won't import properly yet.

“experimental” is generous - AIUI, it’s even more preliminary than that. The last patch got hung up about how to represent C++ upcasts.

Take a look at the compiler tests to see what is supported.

Thanks, I got it. I'll check out the support and the tests.

@owenv Do we have any way to see which flags are used to build a pre-built swift compiler like swift --show-build-flags because I'm going to build from source if it's not built with it.

Sorry for the confusion. The flag I was referring to is one you pass to the compiler when building your project, not one the compiler needs to be built with. It should work with any recent-sh master snapshot from swift.org, and you can pass it by including -Xfrontend -enable-cxx-interop when invoking swiftc. You can check and see if the compiler you have supports it by looking for it in the output of swift -frontend --help-hidden.

1 Like

Ok, I see. I'll try it. Many Thanks owenv!

Terms of Service

Privacy Policy

Cookie Policy