在專案中新增 C 和 C++ 程式碼
透過集合功能整理內容
你可以依據偏好儲存及分類內容。
如要在 Android 專案中新增 C 和 C++ 程式碼,只要將程式碼放入專案模組的 cpp
目錄中即可。當您建構專案時,這個程式碼會編譯為 Gradle 可封裝至應用程式的原生程式庫。您的 Java 或 Kotlin 程式碼可以透過 Java Native Interface (例如 JNI)。如要進一步瞭解如何使用 JNI 架構,請參閱 Android 適用的 JNI 提示。
Android Studio 支援 CMake,這對於跨平台專案非常實用。Android Studio 也支援 ndk-build
,其速度比 CMake 快,但僅支援 Android。目前不支援在相同模組中同時使用 CMake 和 ndk-build
。
如要將現有的 ndk-build
程式庫匯入至 Android Studio 專案,請參閱這篇文章,瞭解如何將 Gradle 連結至原生資料庫專案。
本頁面將說明如何使用必要的建構工具設定 Android Studio、透過 C/C++ 支援功能建立新專案,以及在您的專案中新增 C/C++ 檔案。
如要改為在現有專案中新增原生程式碼,請按照下列步驟操作:
-
建立新的原生來源檔案,並將其新增至 Android Studio 專案。
- 如果已有原生程式碼,或想要匯入預先建構的原生程式庫,請略過這個步驟。
-
設定 CMake,將原生原始碼建構到資料庫中。如要匯入預先建構的資料庫或平台程式庫並建立連結,就必須使用這個建構指令碼。
- 如果現有原生程式庫已含有
CMakeLists.txt
建構指令碼,或使用 ndk-build
且包含 Android.mk
建構指令碼,請略過這個步驟。
-
提供指向 CMake 或
ndk-build
指令碼檔案的路徑,藉此設定 Gradle。Gradle 會使用建構指令碼將原始碼匯入至 Android Studio 專案,並將原生資料庫封裝至應用程式。
設定專案後,就可以使用 JNI 架構透過 Java 或 Kotlin 程式碼存取原生函式。如要建構並執行應用程式,只要按一下「Run」圖示
即可。
注意:如果現有專案使用的是已淘汰的 ndkCompile
工具,請改用 CMake 或 ndk-build
。
下載 NDK 並建構工具
如要針對應用程式編譯及偵錯原生程式碼,您必須具備下列元件:
如需瞭解如何安裝這些元件,請參閱安裝及設定 NDK 和 CMake。
建立支援 C/C++ 的新專案
如要建立支援原生程式碼的新專案,其程序與建立任何其他 Android Studio 專案類似,但還有額外步驟:
- 在精靈的「Choose your project」區段,選取「Native C++」專案類型。
-
按一下「繼續」。
-
在精靈的下一個區段中填寫所有其他欄位。
-
按一下「Next」。
- 在精靈的「Customize C++ Support」區段,您可以使用「C++ Standard」欄位自訂專案。
-
在下拉式清單中,選取要使用的 C++ 標準化。選取「Toolchain Default」可使用預設的 CMake 設定。
-
按一下「Finish」。
Android Studio 建立新專案後,請開啟 IDE 左側的「Project」窗格,然後從選單中選取「Android」檢視畫面。如圖 1 所示,Android Studio 新增了「cpp」群組:
圖 1. 適用於原生來源和外部建構指令碼的 Android 檢視表群組。
注意:這個畫面不會反映磁碟中實際的檔案階層,但會將類似的檔案分組以簡化專案瀏覽作業。
cpp 群組可呈現所有原生來源檔案、標頭、CMake 或 ndk-build
的建構指令碼,以及專案中預先建構的程式庫。如果是新專案,Android Studio 會建立 C++ 範例來源檔案 native-lib.cpp
,並置入應用程式模組的 src/main/cpp/
目錄中。這個程式碼範例提供簡單的 C++ 函式 stringFromJNI()
,可傳回 "Hello from C++"
字串。如要瞭解如何在專案中新增其他來源檔案,請參閱如何建立新的原生來源檔案相關章節。
與 build.gradle
檔案指示 Gradle 如何建構應用程式的方式類似,CMake 與 ndk-build
也需要透過建構指令碼瞭解如何建構原生資料庫。如果是新專案,Android Studio 會建立 CMake 建構指令碼 CMakeLists.txt
,並置入模組的根目錄中。如要進一步瞭解此建構指令碼的內容,請參閱「設定 CMake」一文。
建構並執行範例應用程式
按一下「Run」圖示
後,Android Studio 會建構並啟動應用程式,在 Android 裝置或模擬器上顯示「Hello C++」訊息。以下概要說明建構及執行範例應用程式時會發生的事件:
- Gradle 呼叫外部建構指令碼
CMakeLists.txt
。
- CMake 按照建構指令碼中的指令,將 C++ 來源檔案
native-lib.cpp
編譯成共用物件資料庫,並將其命名為 libnative-lib.so
。然後 Gradle 會將其封裝到應用程式中。
- 在執行階段,應用程式的
MainActivity
會使用
System.loadLibrary()
載入原生資料庫。應用程式現在可以使用程式庫的原生函式 stringFromJNI()
。
-
MainActivity.onCreate()
呼叫 stringFromJNI()
,這項動作會傳回 "Hello from C++"
並用於更新 TextView
。
如要驗證 Gradle 是否已將原生資料庫封裝在應用程式中,請使用 APK 分析工具:
-
依序選取「Build」>「Build Bundles(s)/APK(s)」>「Build APK(s)」。
- 依序選取「Build」>「Analyze APK」。
- 從
app/build/outputs/
目錄中選取 APK 或 AAB,然後按一下「OK」。
- 如圖 2 所示,
libnative-lib.so
顯示在 APK 分析工具視窗中的 lib/<ABI>/
底下。
圖 2. 使用 APK 分析工具找出原生資料庫。
提示:如要測試使用其他原生程式碼的 Android 應用程式,請依序按一下「File」>「New」>「Import Sample」,然後從 Ndk 清單選取範例專案。
建立新 C/C++ 來源檔案
如要在現有專案中新增 C/C++ 來源檔案,請按照下列步驟操作:
- 如果應用程式的主要來源集中沒有
cpp/
目錄,請按照下列步驟操作:
- 開啟 IDE 左側的「Project」窗格,然後從選單中選取「Project」檢視畫面。
- 依序前往「your-module」>「src」。
- 在「main」目錄上按一下滑鼠右鍵,然後依序選取「New」>「Directory」。
- 輸入
cpp
做為目錄名稱,然後按一下「OK」。
- 在
cpp/
目錄上按一下滑鼠右鍵,然後依序選取「New」>「C/C++ Source File」。
- 輸入來源檔案的名稱,例如
native-lib
。
- 從「Type」選單中,選取來源檔案的副檔名,例如
.cpp
。
- 按一下「Edit File Types」圖示
,在選單中新增其他檔案類型,例如 .cxx
或 .hxx
。在隨即彈出的「New File Extensions」對話方塊中,從「Source Extension」和「Header Extension」選單中選取其他副檔名,然後按一下「OK」。
- 如要建立標頭檔案,請勾選「Create an associated header」核取方塊。
- 按一下「OK」。
在專案中新增 C/C++ 檔案之後,您還是需要設定 CMake,將檔案納入原生程式庫中。
其他資源
如要進一步瞭解如何在應用程式中支援 C/C++ 程式碼,請嘗試使用下列資源。
程式碼研究室
這個頁面中的內容和程式碼範例均受《內容授權》中的授權所規範。Java 與 OpenJDK 是 Oracle 和/或其關係企業的商標或註冊商標。
上次更新時間:2025-08-21 (世界標準時間)。
[[["容易理解","easyToUnderstand","thumb-up"],["確實解決了我的問題","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["缺少我需要的資訊","missingTheInformationINeed","thumb-down"],["過於複雜/步驟過多","tooComplicatedTooManySteps","thumb-down"],["過時","outOfDate","thumb-down"],["翻譯問題","translationIssue","thumb-down"],["示例/程式碼問題","samplesCodeIssue","thumb-down"],["其他","otherDown","thumb-down"]],["上次更新時間:2025-08-21 (世界標準時間)。"],[],[],null,["Add C and C++ code to your Android project by placing the code into a\n`cpp` directory in your project module. When you build your project, this\ncode is compiled into a native library that Gradle can package with your app.\nYour Java or Kotlin code can then call functions in your native library\nthrough the Java Native Interface (JNI). To learn more about using the JNI\nframework, read [JNI tips for\nAndroid](/training/articles/perf-jni).\n\nAndroid Studio supports CMake, which is useful for cross-platform projects.\nAndroid Studio also supports [`ndk-build`](/ndk/guides/ndk-build), which\ncan be faster than CMake but only supports Android. Using both CMake and\n`ndk-build` in the same module is not currently supported.\n\nTo import an existing `ndk-build` library into your Android Studio\nproject, learn how to\n[link Gradle to your native library project](/studio/projects/gradle-external-native-builds).\n\nThis page shows you how to [set up Android Studio](#download-ndk) with the\nnecessary build tools, [create a new project](#new-project) with C/C++\nsupport, and [add new C/C++ files](#create-sources) to your project.\n\n\nIf instead you want to add native code to an existing project,\nfollow these steps:\n\n1. [Create new native source files](#create-sources) and add the files to your Android Studio project.\n - Skip this step if you already have native code or want to import a prebuilt native library.\n2. [Configure CMake](/studio/projects/configure-cmake) to build your native source code into a library. This build script is required if you are importing and linking against prebuilt or platform libraries.\n - If you have an existing native library that already has a `CMakeLists.txt` build script or uses `ndk-build` and includes an [`Android.mk`](/ndk/guides/android_mk) build script, skip this step.\n3. [Configure\n Gradle](/studio/projects/gradle-external-native-builds) by providing a path to your CMake or `ndk-build` script file. Gradle uses the build script to import source code into your Android Studio project and package your native library into the app.\n\n\nOnce you configure your project, access your native functions from\nJava or Kotlin code using the [JNI framework](http://docs.oracle.com/javase/7/docs/technotes/guides/jni/spec/jniTOC.html). To build and run your app,\nclick **Run** .\n\n\n**Note:** If your existing project uses the deprecated\n`ndkCompile` tool, migrate to using either CMake or\n`ndk-build`.\n\nDownload the NDK and build tools\n\n\nTo compile and debug native code for your app, you need the following\ncomponents:\n\n- [The Android Native Development Kit\n (NDK)](/ndk): a toolset that lets you use C and C++ code with Android. NDK provides platform libraries that let you manage native activities and access physical device components, such as sensors and touch input.\n- [CMake](https://cmake.org/): an external build tool that works alongside Gradle to build your native library. You don't need this component if you only plan to use `ndk-build`.\n- [LLDB](http://lldb.llvm.org/): the debugger in Android Studio that [debugs native code](/studio/debug).\n\n\nFor information on installing these components, see [Install and configure the NDK and CMake](/studio/projects/install-ndk).\n\nCreate a new project with C/C++ support\n\n\nTo create a new project with support for native code, the process is similar to\n[creating any other Android\nStudio project](/studio/projects/create-project), but with an additional step:\n\n1. In the **Choose your project** section of the wizard, select the **Native C++** project type.\n2. Click **Next**.\n3. Complete all other fields in the next section of the wizard.\n4. Click **Next**.\n5. In the **Customize C++ Support** section of the wizard, you can customize your project with the **C++ Standard** field.\n - Use the drop-down list to select which standardization of C++ you want to use. Selecting **Toolchain\n Default** uses the default CMake setting.\n6. Click **Finish**.\n\n\nAfter Android Studio finishes creating your new project, open the\n**Project** pane from the left side of the IDE and select the\n**Android** view from the menu. As shown in figure 1, Android\nStudio adds the **cpp** group:\n\n\n**Figure 1.** Android view groups for your native sources\nand external build scripts.\n\n\n**Note:** This view does not reflect the actual file hierarchy\non disk, but groups similar files to simplify navigating your project.\n\n\nThe **cpp** group is where you can find all the native\nsource files, headers, build scripts for CMake or `ndk-build`, and prebuilt\nlibraries that are a part of your project. For new projects, Android Studio\ncreates a sample C++ source file, `native-lib.cpp`, and places it\nin the `src/main/cpp/` directory of your app module. This sample\ncode provides a simple C++ function, `stringFromJNI()`, that\nreturns the string `\"Hello from C++\"`. Learn how to add additional\nsource files to your project in the section about how to\n[create new native source files](#create-sources).\n\nSimilar to how `build.gradle` files instruct Gradle how to build\nyour app, CMake and `ndk-build` require a build script to know how to build\nyour native library. For new projects, Android Studio creates a CMake build\nscript,`CMakeLists.txt`, and places it in your module's root directory.\nTo learn more about the contents of this build script, read\n[Configure CMake](/studio/projects/configure-cmake).\n\nBuild and run the sample app\n\n\nWhen you click **Run** , Android Studio\nbuilds and launches an app that displays the text \"Hello from C++\" on your\nAndroid device or emulator. The following overview describes the events that\noccur to build and run the sample app:\n\n1. Gradle calls on your external build script, `CMakeLists.txt`.\n2. CMake follows commands in the build script to compile a C++ source file, `native-lib.cpp`, into a shared object library and names it `libnative-lib.so`. Gradle then packages it into the app.\n3. During runtime, the app's `MainActivity` loads the native library using [`System.loadLibrary()`](/reference/java/lang/System#loadLibrary(java.lang.String)). The library's native function, `stringFromJNI()`, is now available to the app.\n4. `MainActivity.onCreate()` calls `stringFromJNI()`, which returns `\"Hello from C++\"` and uses it to update the [`TextView`](/reference/android/widget/TextView).\n\n\nTo verify that Gradle packages the native library in the app, use the\n[APK Analyzer](/studio/debug/apk-analyzer):\n\n1. Select **Build \\\u003e Build Bundles(s) / APK(s) \\\u003e Build APK(s)**.\n2. Select **Build \\\u003e Analyze APK**.\n3. Select the APK or AAB from the `app/build/outputs/` directory and click **OK**.\n4. As shown in figure 2, you can see `libnative-lib.so` in the APK Analyzer window under `lib/\u003cABI\u003e/`.\n\n\n **Figure 2.** Locate a native library using the APK\n Analyzer.\n\n\n**Tip:** If you want to experiment with other Android apps that\nuse native code, click **File \\\u003e New \\\u003e Import Sample** and\nselect a sample project from the **Ndk** list.\n\nCreate new C/C++ source files\n\n\nTo add new C/C++ source files to an existing project, proceed as follows:\n\n1. If you don't already have a `cpp/` directory in the main source set of your app, create one as follows:\n 1. Open the **Project** pane in the left side of the IDE and select the **Project** view from the menu.\n 2. Navigate to **\u003cvar translate=\"no\"\u003eyour-module\u003c/var\u003e \\\u003e src**.\n 3. Right-click on the **main** directory and select **New \\\u003e\n Directory**.\n 4. Enter `cpp` as the directory name and click **OK**.\n2. Right-click the `cpp/` directory and select **New \\\u003e\n C/C++ Source File**.\n3. Enter a name for your source file, such as `native-lib`.\n4. From the **Type** menu, select the file extension for your source file, such as `.cpp`.\n - Click **Edit File Types** to add other file types to the menu, such as `.cxx` or `.hxx`. In the **New File Extensions** dialog box that pops up, select another file extension from the **Source Extension** and **Header Extension** menus and click **OK**.\n5. To create a header file, select the **Create an\n associated header** checkbox.\n6. Click **OK**.\n\n\u003cbr /\u003e\n\nAfter you add new C/C++ files to you project, you still need to\n[configure CMake](/studio/projects/configure-cmake) to include the files in\nyour native library.\n\nAdditional resources\n\nTo learn more about supporting C/C++ code in your app, try the following\nresource.\n\nCodelabs\n\n- [Create Hello-CMake with Android Studio](https://codelabs.developers.google.com/codelabs/android-studio-cmake/) This codelab shows you how to use the Android Studio CMake template to start Android NDK project development."]]