PrevUpHome

cpp uses swift


cpp: c++ uses swift - Posted on Jan 30, 2024 - See https://www.swift.org/documentation/cxx-interop - Logs Home - d0005

cpp: c++ uses swift language

cpp: c++ uses swift language

Install swift on KaOS Linux/kubuntu

  1. Download swift: https://www.swift.org
  2. Extract swift to /swift/swift
  3. mkdir /swift/bin
  4. Add /swift/bin to environment variable PATH
  5. I don't want to expose swift shipped clang c++ compiler to mix with my own c++ compiler, so I add swift and swiftc to /swift/bin/:

/swift/bin/swift:

exec /swift/swift/bin/swift $@

/swift/bin/swiftc:

exec /swift/swift/bin/swiftc $@

Generate cpp header with exposed swift APIs

Generate c++ header

swiftc \
	-frontend -typecheck \
	swift-code.swift \
	-module-name code_box \
	-cxx-interoperability-mode=default \
	-emit-clang-header-path code_box.hpp

Use c++ header in c++

// code_box.cpp
#include "code_box.hpp"

int main()
{
}

Compile c++ code

clang++ code_box.cpp -std=c++23 \
	-I /swift/swift/include \
	-I /swift/swift/lib/swift \
	-o code_box

c++ example

#include <iostream>
//#include "code_box.hpp"

class swift_cpp_class
{
public:
	swift_cpp_class()
	{
		std::cout << "Hello c++!" << std::endl;
	}
};

int main()
{
	swift_cpp_class swift_cpp{};
}

cpp/c++

c++ std::exception:

std::cout.write(err.data(), err.size());

std::cout << std::endl;

caught:

  ==================================================
  #        The c++ programming language.           #
  #                                                #
  #        Home: cppfx.xyz                         #
  #        Join c++ Discord: yZcauUAUyC            #
  #        Deck                                    #
  ==================================================

PrevUpHome