ccgo 3.7.1

A high-performance C++ cross-platform build CLI
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
# Kotlin Multiplatform

Complete guide to building Kotlin Multiplatform (KMP) libraries with native C++ code using CCGO.

## Overview

CCGO enables seamless integration of C++ libraries into Kotlin Multiplatform projects, allowing you to:

- **Share C++ code** across all KMP platforms (Android, iOS, macOS, Linux, Windows)
- **Unified build system** - Build native libraries for all platforms with a single command
- **Type-safe bindings** - Generate Kotlin expect/actual declarations for C++ APIs
- **Native performance** - Direct JNI/Objective-C interop without overhead
- **Gradle integration** - First-class support in KMP Gradle builds

**Supported KMP targets:**
- Android (ARM64, ARMv7, x86_64, x86)
- iOS (arm64, simulator)
- macOS (x86_64, arm64)
- Linux (x86_64)
- Windows (x86_64)

## Prerequisites

### Required Tools

```bash
# Install CCGO
pip install ccgo

# Verify installation
ccgo --version
```

### Platform SDKs

| Platform | Requirements |
|----------|-------------|
| Android | Android SDK, NDK 21+ |
| iOS | macOS with Xcode |
| macOS | macOS with Xcode |
| Linux | GCC or Clang |
| Windows | Visual Studio or MinGW |

## Quick Start

### Create New KMP Project

```bash
# Create new KMP project with C++ support
ccgo new my-kmp-lib

# Navigate to project
cd my-kmp-lib

# Build for all platforms
ccgo build kmp
```

### Project Structure

```
my-kmp-lib/
├── CCGO.toml                    # CCGO configuration
├── build.gradle.kts             # Root Gradle build
├── settings.gradle.kts
├── src/
│   ├── commonMain/
│   │   └── kotlin/
│   │       └── com/example/
│   │           └── MyLib.kt     # Kotlin expect declarations
│   ├── androidMain/
│   │   └── kotlin/
│   │       └── com/example/
│   │           └── MyLib.android.kt  # Android actual (JNI)
│   ├── iosMain/
│   │   └── kotlin/
│   │       └── com/example/
│   │           └── MyLib.ios.kt      # iOS actual (Objective-C)
│   └── nativeMain/             # Desktop platforms
│       └── kotlin/
│           └── com/example/
│               └── MyLib.native.kt   # cinterop bindings
├── cpp/
│   ├── include/
│   │   └── mylib/
│   │       └── mylib.h         # C++ public headers
│   ├── src/
│   │   └── mylib.cpp           # C++ implementation
│   ├── jni/                    # JNI wrappers for Android
│   │   └── mylib_jni.cpp
│   └── objc/                   # Objective-C wrappers for iOS
│       ├── MyLibWrapper.h
│       └── MyLibWrapper.mm
└── target/                     # Build outputs
    ├── android/
    ├── ios/
    ├── macos/
    ├── linux/
    └── windows/
```

## Configuration

### CCGO.toml

```toml
[package]
name = "mylib"
version = "1.0.0"
type = "kmp"

[kmp]
# Kotlin package name
package_name = "com.example.mylib"

# KMP targets
targets = ["android", "ios", "macos", "linux", "windows"]

# Android configuration
[kmp.android]
min_sdk = 21
target_sdk = 33
namespace = "com.example.mylib"

# iOS configuration
[kmp.ios]
min_deployment_target = "12.0"
framework_name = "MyLib"

# macOS configuration
[kmp.macos]
min_deployment_target = "10.14"

[dependencies]
# C++ dependencies
cpp = [
    { name = "openssl", version = "1.1.1" }
]
```

### build.gradle.kts

```kotlin
plugins {
    kotlin("multiplatform") version "1.9.20"
    id("com.android.library") version "8.1.0"
}

kotlin {
    // Android target
    androidTarget {
        compilations.all {
            kotlinOptions {
                jvmTarget = "1.8"
            }
        }
    }

    // iOS targets
    listOf(
        iosX64(),
        iosArm64(),
        iosSimulatorArm64()
    ).forEach {
        it.binaries.framework {
            baseName = "MyLib"
        }
    }

    // macOS
    macosX64()
    macosArm64()

    // Linux
    linuxX64()

    // Windows (via MinGW)
    mingwX64()

    sourceSets {
        val commonMain by getting {
            dependencies {
                implementation("org.jetbrains.kotlin:kotlin-stdlib:1.9.20")
            }
        }

        val androidMain by getting {
            dependencies {
                // JNI bindings automatically included
            }
        }

        val iosMain by getting {
            dependencies {
                // Framework bindings automatically included
            }
        }

        val nativeMain by getting {
            dependencies {
                // cinterop bindings for desktop platforms
            }
        }
    }
}

android {
    namespace = "com.example.mylib"
    compileSdk = 33

    defaultConfig {
        minSdk = 21
    }

    // Link native libraries built by CCGO
    sourceSets {
        getByName("main") {
            jniLibs.srcDirs("${projectDir}/target/android")
        }
    }
}
```

## Building KMP Libraries

### Build All Platforms

```bash
# Build native code for all KMP targets
ccgo build kmp

# Output structure:
# target/
# ├── android/
# │   ├── armeabi-v7a/libmylib.so
# │   ├── arm64-v8a/libmylib.so
# │   └── x86_64/libmylib.so
# ├── ios/
# │   └── MyLib.framework
# ├── macos/
# │   └── libmylib.dylib
# ├── linux/
# │   └── libmylib.so
# └── windows/
#     └── mylib.dll
```

### Build Specific Platform

```bash
# Android only
ccgo build kmp --target android

# iOS only
ccgo build kmp --target ios

# Desktop platforms
ccgo build kmp --target macos
ccgo build kmp --target linux
ccgo build kmp --target windows
```

### Gradle Integration

```bash
# Build Kotlin code and native libraries
./gradlew build

# Publish to Maven Local
./gradlew publishToMavenLocal

# Create iOS XCFramework
./gradlew linkReleaseFrameworkIos
```

## Native Interop

### Android (JNI)

**C++ Header:**
```cpp
// include/mylib/mylib.h
#pragma once
#include <string>

namespace mylib {
    class Calculator {
    public:
        static int add(int a, int b);
        static std::string greet(const std::string& name);
    };
}
```

**JNI Wrapper:**
```cpp
// cpp/jni/mylib_jni.cpp
#include <jni.h>
#include "mylib/mylib.h"

extern "C" {

JNIEXPORT jint JNICALL
Java_com_example_mylib_Calculator_add(JNIEnv* env, jclass clazz,
                                       jint a, jint b) {
    return mylib::Calculator::add(a, b);
}

JNIEXPORT jstring JNICALL
Java_com_example_mylib_Calculator_greet(JNIEnv* env, jclass clazz,
                                         jstring name) {
    const char* cName = env->GetStringUTFChars(name, nullptr);
    std::string result = mylib::Calculator::greet(cName);
    env->ReleaseStringUTFChars(name, cName);
    return env->NewStringUTF(result.c_str());
}

} // extern "C"
```

**Kotlin Expect/Actual:**
```kotlin
// commonMain/kotlin/Calculator.kt
expect object Calculator {
    fun add(a: Int, b: Int): Int
    fun greet(name: String): String
}

// androidMain/kotlin/Calculator.android.kt
actual object Calculator {
    init {
        System.loadLibrary("mylib")
    }

    actual external fun add(a: Int, b: Int): Int
    actual external fun greet(name: String): String
}
```

### iOS (Objective-C++)

**Objective-C++ Wrapper:**
```objc
// cpp/objc/MyLibWrapper.h
#import <Foundation/Foundation.h>

@interface MyLibCalculator : NSObject
+ (NSInteger)add:(NSInteger)a b:(NSInteger)b;
+ (NSString*)greet:(NSString*)name;
@end

// cpp/objc/MyLibWrapper.mm
#import "MyLibWrapper.h"
#include "mylib/mylib.h"

@implementation MyLibCalculator

+ (NSInteger)add:(NSInteger)a b:(NSInteger)b {
    return mylib::Calculator::add((int)a, (int)b);
}

+ (NSString*)greet:(NSString*)name {
    std::string result = mylib::Calculator::greet([name UTF8String]);
    return [NSString stringWithUTF8String:result.c_str()];
}

@end
```

**Kotlin Actual:**
```kotlin
// iosMain/kotlin/Calculator.ios.kt
import platform.Foundation.*
import kotlinx.cinterop.*

actual object Calculator {
    actual fun add(a: Int, b: Int): Int {
        return MyLibCalculator.add(a.toLong(), b.toLong()).toInt()
    }

    actual fun greet(name: String): String {
        return MyLibCalculator.greet(name) ?: ""
    }
}
```

### Desktop (cinterop)

**def File:**
```
# nativeInterop/cinterop/mylib.def
headers = mylib.h
headerFilter = mylib/*
package = com.example.mylib.native

compilerOpts.linux = -I/usr/include
compilerOpts.macos = -I/usr/local/include
linkerOpts.linux = -L/usr/lib -lmylib
linkerOpts.macos = -L/usr/local/lib -lmylib
```

**Kotlin Actual:**
```kotlin
// nativeMain/kotlin/Calculator.native.kt
import com.example.mylib.native.*
import kotlinx.cinterop.*

actual object Calculator {
    actual fun add(a: Int, b: Int): Int {
        return mylib_add(a, b)
    }

    actual fun greet(name: String): String {
        return mylib_greet(name)?.toKString() ?: ""
    }
}
```

## Testing

### Unit Tests

```kotlin
// commonTest/kotlin/CalculatorTest.kt
import kotlin.test.Test
import kotlin.test.assertEquals

class CalculatorTest {
    @Test
    fun testAdd() {
        assertEquals(5, Calculator.add(2, 3))
    }

    @Test
    fun testGreet() {
        assertEquals("Hello, World!", Calculator.greet("World"))
    }
}
```

### Run Tests

```bash
# All platforms
./gradlew allTests

# Android
./gradlew testDebugUnitTest

# iOS simulator
./gradlew iosSimulatorArm64Test

# Desktop
./gradlew macosX64Test
./gradlew linuxX64Test
./gradlew mingwX64Test
```

## Publishing

### Maven Central

```bash
# Publish all platforms
ccgo publish kmp --registry official

# Or use Gradle
./gradlew publishAllPublicationsToMavenCentral
```

### Consuming the Library

```kotlin
// In another KMP project
dependencies {
    implementation("com.example:mylib:1.0.0")
}
```

## Common Issues

### JNI Method Not Found

**Problem:**
```
java.lang.UnsatisfiedLinkError: No implementation found for ...
```

**Solution:**
```bash
# Verify library is built
ls target/android/arm64-v8a/libmylib.so

# Check JNI method signature
javap -s com.example.mylib.Calculator

# Verify method naming matches
# Java: Java_com_example_mylib_Calculator_add
```

### iOS Framework Not Found

**Problem:**
```
Module 'MyLib' not found
```

**Solution:**
```bash
# Rebuild iOS framework
ccgo build kmp --target ios

# Verify framework structure
ls -la target/ios/MyLib.framework/

# Add framework to Xcode search paths
```

### Desktop Library Loading Failed

**Problem:**
```
java.lang.UnsatisfiedLinkError: Can't load library
```

**Solution:**
```bash
# Linux: Set LD_LIBRARY_PATH
export LD_LIBRARY_PATH=/path/to/target/linux:$LD_LIBRARY_PATH

# macOS: Set DYLD_LIBRARY_PATH
export DYLD_LIBRARY_PATH=/path/to/target/macos:$DYLD_LIBRARY_PATH

# Windows: Add to PATH
set PATH=%PATH%;C:\path\to\target\windows
```

## Best Practices

### 1. API Design

- Keep C++ API simple and C-compatible for easier bindings
- Use primitive types when possible (int, double, const char*)
- Avoid C++ templates and complex types in public headers
- Provide clear error handling (return codes, exceptions)

### 2. Memory Management

```cpp
// Good: Clear ownership
char* create_string() {
    char* str = (char*)malloc(100);
    strcpy(str, "Hello");
    return str;  // Caller must free
}

void free_string(char* str) {
    free(str);
}

// Better: Use smart pointers internally
std::string get_string() {
    return "Hello";
}
```

### 3. Thread Safety

```cpp
// Make shared state thread-safe
class ThreadSafeCounter {
    std::mutex mutex;
    int count = 0;

public:
    int increment() {
        std::lock_guard<std::mutex> lock(mutex);
        return ++count;
    }
};
```

### 4. Platform-Specific Code

```cpp
#ifdef __ANDROID__
    // Android-specific code
#elif defined(__APPLE__)
    #include <TargetConditionals.h>
    #if TARGET_OS_IOS
        // iOS-specific code
    #elif TARGET_OS_OSX
        // macOS-specific code
    #endif
#elif defined(__linux__)
    // Linux-specific code
#elif defined(_WIN32)
    // Windows-specific code
#endif
```

## Performance Optimization

### 1. Minimize JNI Calls

```kotlin
// Bad: Multiple JNI calls
fun processArray(data: IntArray): IntArray {
    return data.map { Calculator.add(it, 1) }.toIntArray()
}

// Good: Single JNI call
external fun processArray(data: IntArray): IntArray  // C++ processes entire array
```

### 2. Use Direct ByteBuffers

```kotlin
// Efficient for large data transfer
val buffer = ByteBuffer.allocateDirect(1024 * 1024)
processData(buffer)  // Zero-copy JNI access
```

### 3. Cache JNI References

```cpp
// Cache class and method IDs
static jclass calculatorClass = nullptr;
static jmethodID addMethod = nullptr;

JNIEXPORT jint JNI_OnLoad(JavaVM* vm, void* reserved) {
    JNIEnv* env;
    vm->GetEnv((void**)&env, JNI_VERSION_1_6);

    calculatorClass = (jclass)env->NewGlobalRef(
        env->FindClass("com/example/mylib/Calculator"));
    addMethod = env->GetMethodID(calculatorClass, "add", "(II)I");

    return JNI_VERSION_1_6;
}
```

## Examples

### Complete Project

See [ccgo-kmp-example](https://github.com/zhlinh/ccgo-kmp-example) for a complete KMP project.

### Minimal Example

Available in CCGO templates:
```bash
ccgo new my-kmp --template kmp-minimal
```

## Resources

### Official Documentation

- [Kotlin Multiplatform]https://kotlinlang.org/docs/multiplatform.html
- [Kotlin/Native Interop]https://kotlinlang.org/docs/native-c-interop.html
- [JNI Specification]https://docs.oracle.com/javase/8/docs/technotes/guides/jni/

### CCGO Documentation

- [CLI Reference]../reference/cli.md
- [CCGO.toml Reference]../reference/ccgo-toml.md
- [Android Platform]android.md
- [iOS Platform]ios.md
- [Publishing Guide]../features/publishing.md

### Community

- [GitHub Discussions]https://github.com/zhlinh/ccgo/discussions
- [Issue Tracker]https://github.com/zhlinh/ccgo/issues

## Next Steps

- [Build System Overview]../features/build-system.md
- [Dependency Management]../features/dependency-management.md
- [Publishing to Maven Central]../features/publishing.md
- [Android Development]android.md
- [iOS Development]ios.md