How can I build C++ code into .framework with cinterop?

I’m doing a Multiplatform project, and want build a .framework for iOS platform.

I have to use C++ code in the project.

My project structure:

src/commain/cpp/cinterop.def

src/iosMain/cpp/NativeIF.cpp

src/iosMain/cpp/NativeIF.h

src/iosMain/cpp/CppImplement.cpp

src/iosMain/cpp/CppImplement.h

…other cpp source code

The code in src/commain/cpp/cinterop.def:

headers = NativeIF.h package = my.package.name 

The code in src/iosMain/cpp/NativeIF.h

#ifdef __cplusplus extern "C" { #endif void NativeInterface_1(); void NativeInterface_2(); #ifdef __cplusplus } #endif 

The code in src/iosMain/cpp/NativeIF.cpp

#include "NativeIF.h" #ifdef __cplusplus extern "C" { #endif void NativeInterface_1() { // some code of calling CppImplement.cpp } void NativeInterface_2() { // some code of calling CppImplement.cpp } #ifdef __cplusplus } #endif 

In my build.gradle.kts, I config the ios platform

val xcf = XCFramework(sdkName)

listOf( iosX64(), iosArm64(), iosSimulatorArm64(), ).forEach { it.binaries.framework { baseName = "mylibname" binaryOption("bundleId", "$bundleIdCommon.ios") binaryOption("bundleShortVersionString", sdkVersion) xcf.add(this) isStatic = true } it.compilations.getByName("main") { cinterops { val infomatchingNativeLib by cinterops.creating { defFile(project.file("src/commonMain/cpp/cinterop.def")) compilerOpts("-I/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS.sdk/usr/include/c++/v1") compilerOpts("-Isrc/iosMain/cpp") compilerOpts("-Isrc/commonMain/cpp/") ...other cpp files path } } } } 

The current situation is, the .framework file can be build successfully, and I can find the klib file in path of build/classes/kotlin/iosXXX/main/cinterop.

But when I import this .framework into my xcode project, and build, there will be errors:

ld: Undefined symbols: _NativeInterface_1, referenced from: _my_package_name_NativeInterface_1_wrapper0 in mylibname[arm64][2](mylibname.framework.o) _NativeInterface_2, referenced from: _my_package_name_NativeInterface_2_wrapper0 in mylibname[arm64][2](mylibname.framework.o) clang: error: linker command failed with exit code 1 (use -v to see invocation) 

I tried to write the implement of interface in cinterop.def directly, and wrap C++ implement with C.

But this way leads another link error in Xcode building, the C wrapper function of C++ can not be found.

  1. I use the .framework in a Swift project.
  2. I tried to use nm command to find the “NativeInterface_1” and “NativeInterface_2” in the .framework file, the result is:

U _NativeInterface_1 U _NativeInterface_2 

What should I do to resove this problem?

Andbody can give me some advices?

Thanks very much.

submitted by /u/Silver-End6488
[link] [comments]