Расширьте возможности своих игр на C++ с помощью наших SDK Firebase C++, которые предоставляют интерфейс C++ поверх SDK Firebase.
Получите полный доступ к Firebase из своего кода на C++, без необходимости писать какой-либо платформенно-ориентированный код. SDK Firebase также переводит многие специфические для языка идиомы, используемые Firebase, в интерфейс, более привычный для разработчиков на C++.
Более подробную информацию о том, как расширить возможности ваших игр с помощью Firebase, вы найдете на нашей странице, посвященной играм Firebase .
Уже добавили Firebase в свой проект на C++? Убедитесь, что используете последнюю версию Firebase C++ SDK .
Предварительные требования
Установите предпочитаемый вами редактор или IDE, например Android Studio, IntelliJ или VS Code.
Получите Android SDK .
Убедитесь, что ваш проект соответствует следующим требованиям:
Для работы требуется API уровня 23 (Marshmallow) или выше.
Использует Gradle и настраивается с помощью CMake.
Для запуска приложения подключите физическое устройство или используйте эмулятор.
Эмуляторы должны использовать образ эмулятора с Google Play.
Для некоторых библиотек C++ на клиентском устройстве требуются сервисы Google Play; ознакомьтесь со списком на этой странице.
Войдите в Firebase, используя свою учетную запись Google.
Шаг 2 : Создайте проект Firebase.
Прежде чем добавить Firebase в свой проект C++, необходимо создать проект Firebase для подключения к вашему проекту C++. Подробнее о проектах Firebase можно узнать в разделе «Понимание проектов Firebase».
Шаг 3 : Зарегистрируйте свое приложение в Firebase.
Чтобы использовать Firebase в своем Android-приложении, вам необходимо зарегистрировать его в своем проекте Firebase. Регистрация приложения часто называется «добавлением» приложения в проект.
Перейдите в консоль Firebase .
В центре страницы обзора проекта нажмите на значок Android ( ) или «Добавить приложение» , чтобы запустить процесс настройки.
Введите имя пакета вашего приложения в поле «Имя пакета Android» .
Имя пакета однозначно идентифицирует ваше приложение на устройстве и в магазине Google Play.
Имя пакета часто называют идентификатором приложения .
Найдите имя пакета вашего приложения в файле Gradle вашего модуля (уровня приложения), обычно это
app/build.gradle(пример имени пакета:com.yourcompany.yourproject).Обратите внимание, что значение имени пакета чувствительно к регистру, и его нельзя изменить для этого приложения Firebase Android после его регистрации в вашем проекте Firebase.
(Необязательно) Введите псевдоним приложения — внутренний, удобный идентификатор, видимый только вам в консоли Firebase .
Нажмите «Зарегистрировать приложение» .
Шаг 4 : Добавьте файл конфигурации Firebase.
Нажмите «Скачать google-services.json» , чтобы получить файл конфигурации Firebase для Android.
Конфигурационный файл Firebase содержит уникальные, но не секретные идентификаторы для вашего проекта и приложения. Чтобы узнать больше об этом конфигурационном файле, посетите раздел «Понимание проектов Firebase» .
Вы можете в любой момент повторно загрузить свой конфигурационный файл Firebase .
Убедитесь, что к имени файла конфигурации не добавлены дополнительные символы, например
(2).
Откройте свой проект на C++ в IDE, затем добавьте файл конфигурации в свой проект:
Сборка Gradle — Добавьте файл конфигурации в ту же директорию, что и главный файл
build.gradle.Другие системы сборки — см. раздел «Пользовательские системы сборки» ниже, чтобы сгенерировать строковые ресурсы Android .
(Только для сборки Gradle) Чтобы включить сервисы Firebase в вашем проекте C++, добавьте плагин Google services Gradle в главный файл
build.gradle.Добавьте правила для включения плагина Gradle для сервисов Google. Также убедитесь, что у вас есть репозиторий Maven от Google.
buildscript { repositories { // Check that you have the following line (if not, add it): google() // Google's Maven repository } dependencies { // ... // Add the following lines: classpath 'com.google.gms:google-services:4.5.0' // Google services Gradle plugin implementation 'com.google.android.gms:18.10.1' } } allprojects { // ... repositories { // Check that you have the following line (if not, add it): google() // Google's Maven repository // ... } }Примените плагин Gradle для сервисов Google:
apply plugin: 'com.android.application' // Add the following line: apply plugin: 'com.google.gms.google-services' // Google services Gradle plugin android { // ... }
Настройка задач в консоли Firebase завершена. Перейдите к разделу «Добавление SDK Firebase C++» ниже.
Шаг 5 : Добавьте SDK Firebase C++
Описанные в этом разделе шаги представляют собой пример того, как добавить поддерживаемые продукты Firebase в ваш проект Firebase C++.
Загрузите Firebase C++ SDK , затем распакуйте его в удобное для вас место.
SDK Firebase C++ не является платформенно-зависимым, но содержит платформенно-специфичные библиотеки.
В файле
gradle.propertiesвашего проекта укажите расположение распакованного SDK:systemProp.firebase_cpp_sdk.dir=full-path-to-SDK
В файл
settings.gradleвашего проекта добавьте следующее содержимое:def firebase_cpp_sdk_dir = System.getProperty('firebase_cpp_sdk.dir') gradle.ext.firebase_cpp_sdk_dir = "$firebase_cpp_sdk_dir" includeBuild "$firebase_cpp_sdk_dir"
В файл Gradle вашего модуля (уровня приложения) (обычно
app/build.gradle) добавьте следующее содержимое.
Добавьте зависимости библиотек для продуктов Firebase, которые вы хотите использовать в своем приложении.Analytics включена
android.defaultConfig.externalNativeBuild.cmake { arguments "-DFIREBASE_CPP_SDK_DIR=$gradle.firebase_cpp_sdk_dir" } # Add the dependencies for the Firebase products you want to use in your app # For example, to use Analytics, Firebase Authentication, and Firebase Realtime Database apply from: "$gradle.firebase_cpp_sdk_dir/Android/firebase_dependencies.gradle" firebaseCpp.dependencies { analytics auth database }
Analytics отключена
android.defaultConfig.externalNativeBuild.cmake { arguments "-DFIREBASE_CPP_SDK_DIR=$gradle.firebase_cpp_sdk_dir" } # Add the dependencies for the Firebase products you want to use in your app # For example, to use Firebase Authentication and Firebase Realtime Database apply from: "$gradle.firebase_cpp_sdk_dir/Android/firebase_dependencies.gradle" firebaseCpp.dependencies { auth database }
В файл
CMakeLists.txtвашего проекта добавьте следующее содержимое.
Включите библиотеки для продуктов Firebase, которые вы хотите использовать в своем приложении.Analytics включена
# Add Firebase libraries to the target using the function from the SDK. add_subdirectory(${FIREBASE_CPP_SDK_DIR} bin/ EXCLUDE_FROM_ALL) # The Firebase C++ library `firebase_app` is required, # and it must always be listed last. # Add the Firebase SDKs for the products you want to use in your app # For example, to use Analytics, Firebase Authentication, and Firebase Realtime Database set(firebase_libs firebase_analytics firebase_auth firebase_database firebase_app ) target_link_libraries(${target_name} "${firebase_libs}")
Analytics отключена
# Add Firebase libraries to the target using the function from the SDK. add_subdirectory(${FIREBASE_CPP_SDK_DIR} bin/ EXCLUDE_FROM_ALL) # The Firebase C++ library `firebase_app` is required, # and it must always be listed last. # Add the Firebase SDKs for the products you want to use in your app # For example, to use Firebase Authentication and Firebase Realtime Database set(firebase_libs firebase_auth firebase_database firebase_app ) target_link_libraries(${target_name} "${firebase_libs}")
Синхронизируйте приложение, чтобы убедиться, что все зависимости имеют необходимые версии.
Если вы добавили Analytics , запустите приложение, чтобы отправить в Firebase подтверждение успешной интеграции. В противном случае, этап подтверждения можно пропустить.
В журналах вашего устройства отобразится подтверждение Firebase о завершении инициализации. Если вы запускали приложение на эмуляторе с доступом к сети, консоль Firebase уведомит вас о завершении подключения приложения.
Всё готово! Ваше приложение на C++ зарегистрировано и настроено для использования сервисов Firebase.
Доступные библиотеки
Узнайте больше о библиотеках Firebase для C++ в справочной документации и в нашем SDK с открытым исходным кодом на GitHub .
Доступные библиотеки для Android (с использованием CMake)
Обратите внимание, что библиотеки C++ для платформ Apple перечислены в версии этой страницы настроек для платформ Apple (iOS+) .
| Продукт Firebase | Библиотечные ссылки ( firebaseCpp.dependencies(для файла build.gradle ) | Библиотечные ссылки ( firebase_libs(для файла CMakeLists.txt ) |
|---|---|---|
| Analytics | analytics | firebase_analytics(обязательно) firebase_app |
| App Check | appCheck | firebase_app_check(обязательно) firebase_app |
| Authentication | auth | firebase_auth(обязательно) firebase_app |
| Cloud Firestore | firestore | firebase_firestore(обязательно) firebase_auth(обязательно) firebase_app |
| Cloud Functions | functions | firebase_functions(обязательно) firebase_app |
| Cloud Messaging | messaging | firebase_messaging(рекомендуется) firebase_analytics(обязательно) firebase_app |
| Cloud Storage | storage | firebase_storage(обязательно) firebase_app |
| Realtime Database | database | firebase_database(обязательно) firebase_app |
| Remote Config | remoteConfig | firebase_remote_config(рекомендуется) firebase_analytics(обязательно) firebase_app |
| УСТАРЕВШИЕ ИЛИ НЕ ПОДДЕРЖИВАЕМЫЕ БИБЛИОТЕКИ | ||
| Dynamic Links | dynamicLinks | firebase_dynamic_links(рекомендуется) firebase_analytics(обязательно) firebase_app |
Дополнительная информация по настройке мобильного устройства.
Получайте отчеты о сбоях NDK.
Firebase Crashlytics поддерживает отправку отчетов о сбоях для приложений, использующих нативные библиотеки Android. Для получения дополнительной информации см. раздел «Получение отчетов о сбоях Android NDK» .
Системы, созданные по индивидуальному заказу
Firebase предоставляет скрипт generate_xml_from_google_services_json.py для преобразования файла google-services.json в ресурсы .xml , которые можно включить в ваш проект. Этот скрипт применяет то же преобразование, что и плагин Gradle для сервисов Google Play при сборке приложений Android.
Если вы не используете Gradle для сборки (например, ndk-build, makefiles, Visual Studio и т. д.), вы можете использовать этот скрипт для автоматизации генерации строковых ресурсов Android .
ПроГард
Многие системы сборки Android используют ProGuard для сборки в режиме Release, чтобы уменьшить размер приложений и защитить исходный код Java.
Если вы используете ProGuard, вам потребуется добавить в конфигурацию ProGuard файлы из libs/android/*.pro , соответствующие используемым вами библиотекам Firebase C++.
Например, если вы используете Google Analytics в Gradle, ваш файл build.gradle будет выглядеть следующим образом:
android { // ... buildTypes { release { minifyEnabled true proguardFile getDefaultProguardFile('your-project-proguard-config.txt') proguardFile file(project.ext.your_local_firebase_sdk_dir + "/libs/android/app.pro") proguardFile file(project.ext.your_local_firebase_sdk_dir + "/libs/android/analytics.pro") // ... and so on, for each Firebase C++ library that you're using } } }
Требования к сервисам Google Play
Большинство библиотек Firebase C++ требуют наличия сервисов Google Play на Android-устройстве клиента. Если библиотека Firebase C++ возвращает kInitResultFailedMissingDependency при инициализации, это означает, что сервисы Google Play недоступны на устройстве клиента (то есть их необходимо обновить, повторно активировать, исправить разрешения и т. д.). Библиотека Firebase не может быть использована, пока ситуация на устройстве клиента не будет исправлена.
Вы можете выяснить, почему сервисы Google Play недоступны на устройстве клиента (и попытаться это исправить), используя функции из файла google_play_services/availability.h .
В таблице ниже указано, требуется ли наличие сервисов Google Play на клиентском устройстве для каждого поддерживаемого продукта Firebase.
| Библиотека Firebase на C++ | Требуются ли сервисы Google Play на клиентском устройстве? |
|---|---|
| Analytics | Не требуется |
| Authentication | Необходимый |
| Cloud Firestore | Необходимый |
| Cloud Functions | Необходимый |
| Cloud Messaging | Необходимый |
| Cloud Storage | Необходимый |
| Dynamic Links | Необходимый |
| Realtime Database | Необходимый |
| Remote Config | Необходимый |
Настройка рабочего процесса на рабочем столе ( бета-версия )
При создании игры зачастую гораздо проще сначала протестировать её на настольных платформах, а затем развернуть и протестировать на мобильных устройствах на более поздних этапах разработки. Для поддержки этого рабочего процесса мы предоставляем подмножество SDK Firebase C++ , которые могут работать на Windows, macOS, Linux и из редактора C++.
Для рабочих процессов на настольных компьютерах необходимо выполнить следующие действия:
- Настройте свой проект C++ для работы с CMake.
- Создайте проект Firebase.
- Зарегистрируйте свое приложение (iOS или Android) в Firebase.
- Добавьте файл конфигурации Firebase для мобильной платформы.
Создайте настольную версию файла конфигурации Firebase:
Если вы добавили файл
google-services.jsonдля Android , то при запуске приложения Firebase найдет этот мобильный файл и автоматически сгенерирует файл конфигурации Firebase для настольных компьютеров (google-services-desktop.json).Если вы добавили файл
GoogleService-Info.plistдля iOS , перед запуском приложения необходимо преобразовать этот мобильный файл в файл конфигурации Firebase для настольных компьютеров . Для преобразования файла выполните следующую команду из той же директории, что и файлGoogleService-Info.plist:generate_xml_from_google_services_json.py --plist -i GoogleService-Info.plist
Этот конфигурационный файл для настольных компьютеров содержит идентификатор проекта C++, который вы указали в процессе настройки консоли Firebase . Подробнее о конфигурационных файлах можно узнать в разделе «Понимание проектов Firebase» .
Добавьте SDK Firebase в свой проект на C++.
Приведенные ниже шаги служат примером того, как добавить любой поддерживаемый продукт Firebase в ваш проект C++. В этом примере мы рассмотрим добавление Firebase Authentication и Firebase Realtime Database .
Установите переменную среды
FIREBASE_CPP_SDK_DIRна путь к распакованному Firebase C++ SDK.В файл
CMakeLists.txtвашего проекта добавьте следующее содержимое, включая библиотеки для продуктов Firebase, которые вы хотите использовать. Например, чтобы использовать Firebase Authentication и Firebase Realtime Database :# Add Firebase libraries to the target using the function from the SDK. add_subdirectory(${FIREBASE_CPP_SDK_DIR} bin/ EXCLUDE_FROM_ALL) # The Firebase C++ library `firebase_app` is required, # and it must always be listed last. # Add the Firebase SDKs for the products you want to use in your app # For example, to use Firebase Authentication and Firebase Realtime Database set(firebase_libs firebase_auth firebase_database firebase_app) target_link_libraries(${target_name} "${firebase_libs}")
Запустите ваше приложение на C++.
Доступные библиотеки (для настольных компьютеров)
В состав Firebase C++ SDK входит поддержка рабочих процессов для настольных приложений, позволяющая использовать определенные части Firebase в автономных сборках для настольных приложений под управлением Windows, macOS и Linux.
| Продукт Firebase | Ссылки на библиотеки (с использованием CMake) |
|---|---|
| App Check | firebase_app_check(обязательно) firebase_app |
| Authentication | firebase_auth(обязательно) firebase_app |
| Cloud Firestore | firebase_firestorefirebase_authfirebase_app |
| Cloud Functions | firebase_functions(обязательно) firebase_app |
| Cloud Storage | firebase_storage(обязательно) firebase_app |
| Realtime Database | firebase_database(обязательно) firebase_app |
| Remote Config | firebase_remote_config(обязательно) firebase_app |
Firebase предоставляет оставшиеся библиотеки для настольных приложений в виде заглушек (нефункциональных) для удобства сборки под Windows, macOS и Linux. Таким образом, вам не нужно выполнять условную компиляцию кода для целевой платформы настольных приложений.
Настольная версия Realtime Database
SDK Realtime Database для настольных компьютеров использует REST для доступа к вашей базе данных, поэтому вам необходимо объявить индексы, которые вы используете с Query::OrderByChild() на настольной версии, иначе ваши обработчики событий будут работать некорректно.
Дополнительная информация по настройке рабочего стола
библиотеки Windows
Для Windows версии библиотек предоставляются на основе следующих критериев:
- Платформа сборки: 32-битный (x86) и 64-битный (x64) режимы
- Среда выполнения Windows: Многопоточность / MT против многопоточной DLL / MD
- Цель: Релиз против отладки
Обратите внимание, что следующие библиотеки были протестированы с использованием Visual Studio 2015 и 2017.
При разработке настольных приложений на C++ для Windows необходимо подключить к проекту следующие библиотеки Windows SDK. Для получения дополнительной информации обратитесь к документации вашего компилятора.
| Библиотека Firebase на C++ | Зависимости библиотеки Windows SDK |
|---|---|
| App Check | advapi32, ws2_32, crypt32 |
| Authentication | advapi32, ws2_32, crypt32 |
| Cloud Firestore | advapi32, ws2_32, crypt32, rpcrt4, ole32, shell32 |
| Cloud Functions | advapi32, ws2_32, crypt32, rpcrt4, ole32 |
| Cloud Storage | advapi32, ws2_32, crypt32 |
| Realtime Database | advapi32, ws2_32, crypt32, iphlpapi, psapi, userenv |
| Remote Config | advapi32, ws2_32, crypt32, rpcrt4, ole32 |
библиотеки macOS
Для macOS (Darwin) предоставляются версии библиотек для 64-битной платформы (x86_64). Для вашего удобства также предоставляются фреймворки.
Обратите внимание, что библиотеки macOS были протестированы с использованием Xcode 26.2.
При разработке настольных приложений на C++ для macOS, подключите к своему проекту следующие компоненты:
- библиотека системы
pthread - Системная платформа
CoreFoundationдля macOS -
Foundationсистемной структуры macOS - Системная структура
SecuritymacOS - Системная структура
GSSmacOS - Системная структура
Kerberosдля macOS -
SystemConfigurationmacOS
Для получения более подробной информации обратитесь к документации вашего компилятора.
библиотеки Linux
Для Linux доступны версии библиотеки для 32-битных (i386) и 64-битных (x86_64) платформ.
Обратите внимание, что тестирование библиотек Linux проводилось с использованием GCC 4.8.0, GCC 7.2.0 и Clang 5.0 на Ubuntu.
При сборке настольных приложений на C++ под Linux необходимо подключить системную библиотеку pthread к вашему проекту. Для получения дополнительной информации обратитесь к документации вашего компилятора. Если вы используете GCC 5 или более позднюю версию, укажите параметр -D_GLIBCXX_USE_CXX11_ABI=0 .
Следующие шаги
Ознакомьтесь с примерами приложений Firebase .
Изучите SDK с открытым исходным кодом на GitHub .
Подготовьтесь к запуску вашего приложения:
- Настройте оповещения о бюджете для вашего проекта в консоли Google Cloud .
- Отслеживайте использование и выставление счетов на панели мониторинга в консоли Firebase , чтобы получить общее представление об использовании вашего проекта в различных сервисах Firebase.
- Ознакомьтесь с контрольным списком запуска Firebase .
Расширьте возможности своих игр на C++ с помощью наших SDK Firebase C++, которые предоставляют интерфейс C++ поверх SDK Firebase.
Получите полный доступ к Firebase из своего кода на C++, без необходимости писать какой-либо платформенно-ориентированный код. SDK Firebase также переводит многие специфические для языка идиомы, используемые Firebase, в интерфейс, более привычный для разработчиков на C++.
Более подробную информацию о том, как расширить возможности ваших игр с помощью Firebase, вы найдете на нашей странице, посвященной играм Firebase .
Уже добавили Firebase в свой проект на C++? Убедитесь, что используете последнюю версию Firebase C++ SDK .
Предварительные требования
Установите предпочитаемый вами редактор или IDE, например Android Studio, IntelliJ или VS Code.
Получите Android SDK .
Убедитесь, что ваш проект соответствует следующим требованиям:
Для работы требуется API уровня 23 (Marshmallow) или выше.
Использует Gradle и настраивается с помощью CMake.
Для запуска приложения подключите физическое устройство или используйте эмулятор.
Эмуляторы должны использовать образ эмулятора с Google Play.
Для некоторых библиотек C++ на клиентском устройстве требуются сервисы Google Play; ознакомьтесь со списком на этой странице.
Войдите в Firebase, используя свою учетную запись Google.
Шаг 2 : Создайте проект Firebase.
Прежде чем добавить Firebase в свой проект C++, необходимо создать проект Firebase для подключения к вашему проекту C++. Подробнее о проектах Firebase можно узнать в разделе «Понимание проектов Firebase».
Step 3 : Register your app with Firebase
To use Firebase in your Android app, you need to register your app with your Firebase project. Registering your app is often called "adding" your app to your project.
Go to the Firebase console .
In the center of the project overview page, click the Android icon ( ) or Add app to launch the setup workflow.
Enter your app's package name in the Android package name field.
A package name uniquely identifies your app on the device and in the Google Play Store.
A package name is often referred to as an application ID .
Find your app's package name in your module (app-level) Gradle file, usually
app/build.gradle(example package name:com.yourcompany.yourproject).Be aware that the package name value is case-sensitive, and it cannot be changed for this Firebase Android app after it's registered with your Firebase project.
(Optional) Enter an App nickname , which is an internal, convenience identifier that is only visible to you in the Firebase console.
Click Register app .
Step 4 : Add the Firebase configuration file
Click Download google-services.json to obtain your Firebase Android config file.
The Firebase config file contains unique, but non-secret identifiers for your project and app. To learn more about this config file, visit Understand Firebase Projects .
You can download your Firebase config file again at any time.
Make sure the config file name is not appended with additional characters, like
(2).
Open your C++ project in an IDE, then add your config file to your project:
Gradle builds — Add your config file to the same directory as your top-level
build.gradlefile.Other build systems — See Custom build systems below to generate Android String Resources .
(Gradle builds only) To enable Firebase services in your C++ project, add the Google services Gradle plugin to your top-level
build.gradlefile.Add rules to include the Google services Gradle plugin. Check that you have Google's Maven repository, as well.
buildscript { repositories { // Check that you have the following line (if not, add it): google() // Google's Maven repository } dependencies { // ... // Add the following lines: classpath 'com.google.gms:google-services:4.5.0' // Google services Gradle plugin implementation 'com.google.android.gms:18.10.1' } } allprojects { // ... repositories { // Check that you have the following line (if not, add it): google() // Google's Maven repository // ... } }Apply the Google services Gradle plugin:
apply plugin: 'com.android.application' // Add the following line: apply plugin: 'com.google.gms.google-services' // Google services Gradle plugin android { // ... }
You're done with set up tasks in the Firebase console. Continue to Add Firebase C++ SDKs below.
Step 5 : Add Firebase C++ SDKs
The steps in this section are an example of how to add supported Firebase products to your Firebase C++ project.
Download the Firebase C++ SDK , then unzip the SDK somewhere convenient.
The Firebase C++ SDK is not platform-specific, but it does contain platform-specific libraries.
In your project's
gradle.propertiesfile, specify the location of the unzipped SDK:systemProp.firebase_cpp_sdk.dir=full-path-to-SDK
To your project's
settings.gradlefile, add the following content:def firebase_cpp_sdk_dir = System.getProperty('firebase_cpp_sdk.dir') gradle.ext.firebase_cpp_sdk_dir = "$firebase_cpp_sdk_dir" includeBuild "$firebase_cpp_sdk_dir"
To your module (app-level) Gradle file (usually
app/build.gradle), add the following content.
Include the library dependencies for the Firebase products that you want to use in your app.Analytics enabled
android.defaultConfig.externalNativeBuild.cmake { arguments "-DFIREBASE_CPP_SDK_DIR=$gradle.firebase_cpp_sdk_dir" } # Add the dependencies for the Firebase products you want to use in your app # For example, to use Analytics, Firebase Authentication, and Firebase Realtime Database apply from: "$gradle.firebase_cpp_sdk_dir/Android/firebase_dependencies.gradle" firebaseCpp.dependencies { analytics auth database }
Analytics not enabled
android.defaultConfig.externalNativeBuild.cmake { arguments "-DFIREBASE_CPP_SDK_DIR=$gradle.firebase_cpp_sdk_dir" } # Add the dependencies for the Firebase products you want to use in your app # For example, to use Firebase Authentication and Firebase Realtime Database apply from: "$gradle.firebase_cpp_sdk_dir/Android/firebase_dependencies.gradle" firebaseCpp.dependencies { auth database }
To your project's
CMakeLists.txtfile, add the following content.
Include the libraries for the Firebase products that you want to use in your app.Analytics enabled
# Add Firebase libraries to the target using the function from the SDK. add_subdirectory(${FIREBASE_CPP_SDK_DIR} bin/ EXCLUDE_FROM_ALL) # The Firebase C++ library `firebase_app` is required, # and it must always be listed last. # Add the Firebase SDKs for the products you want to use in your app # For example, to use Analytics, Firebase Authentication, and Firebase Realtime Database set(firebase_libs firebase_analytics firebase_auth firebase_database firebase_app ) target_link_libraries(${target_name} "${firebase_libs}")
Analytics not enabled
# Add Firebase libraries to the target using the function from the SDK. add_subdirectory(${FIREBASE_CPP_SDK_DIR} bin/ EXCLUDE_FROM_ALL) # The Firebase C++ library `firebase_app` is required, # and it must always be listed last. # Add the Firebase SDKs for the products you want to use in your app # For example, to use Firebase Authentication and Firebase Realtime Database set(firebase_libs firebase_auth firebase_database firebase_app ) target_link_libraries(${target_name} "${firebase_libs}")
Sync your app to ensure that all dependencies have the necessary versions.
If you added Analytics , run your app to send verification to Firebase that you've successfully integrated Firebase. Otherwise, you can skip the verification step.
Your device logs will display the Firebase verification that initialization is complete. If you ran your app on an emulator that has network access, the Firebase console notifies you that your app connection is complete.
You're all set! Your C++ app is registered and configured to use Firebase services.
Available libraries
Learn more about the C++ Firebase libraries in the reference documentation and in our open-source SDK release on GitHub .
Available libraries for Android (using CMake)
Note that C++ libraries for Apple platforms are listed on the Apple platforms (iOS+) version of this setup page .
| Firebase product | Library references ( firebaseCpp.dependenciesfor build.gradle file) | Library references ( firebase_libsfor CMakeLists.txt file) |
|---|---|---|
| Analytics | analytics | firebase_analytics(required) firebase_app |
| App Check | appCheck | firebase_app_check(required) firebase_app |
| Authentication | auth | firebase_auth(required) firebase_app |
| Cloud Firestore | firestore | firebase_firestore(required) firebase_auth(required) firebase_app |
| Cloud Functions | functions | firebase_functions(required) firebase_app |
| Cloud Messaging | messaging | firebase_messaging(recommended) firebase_analytics(required) firebase_app |
| Cloud Storage | storage | firebase_storage(required) firebase_app |
| Realtime Database | database | firebase_database(required) firebase_app |
| Remote Config | remoteConfig | firebase_remote_config(recommended) firebase_analytics(required) firebase_app |
| DEPRECATED OR UNSUPPORTED LIBRARIES | ||
| Dynamic Links | dynamicLinks | firebase_dynamic_links(recommended) firebase_analytics(required) firebase_app |
Additional information for mobile setup
Get NDK crash reports
Firebase Crashlytics supports crash reporting for apps using Android native libraries. To learn more, see Get Android NDK crash reports .
Custom build systems
Firebase provides the script generate_xml_from_google_services_json.py to convert google-services.json to .xml resources that you can include in your project. This script applies the same transformation that the Google Play services Gradle plugin performs when building Android applications.
If you don't build using Gradle (for example, you use ndk-build, makefiles, Visual Studio, etc.), you can use this script to automate the generation of Android String Resources .
ProGuard
Many Android build systems use ProGuard for builds in Release mode to shrink application sizes and protect Java source code.
If you use ProGuard, you'll need to add the files in libs/android/*.pro corresponding to the Firebase C++ libraries that you're using in your ProGuard configuration.
For example, with Gradle, if you're using Google Analytics , your build.gradle file would look like:
android { // ... buildTypes { release { minifyEnabled true proguardFile getDefaultProguardFile('your-project-proguard-config.txt') proguardFile file(project.ext.your_local_firebase_sdk_dir + "/libs/android/app.pro") proguardFile file(project.ext.your_local_firebase_sdk_dir + "/libs/android/analytics.pro") // ... and so on, for each Firebase C++ library that you're using } } }
Google Play services requirement
Most Firebase C++ libraries require Google Play services to be on the client's Android device. If a Firebase C++ library returns kInitResultFailedMissingDependency on initialization, it means Google Play services is not available on the client device (meaning that it needs to be updated, reactivated, permissions fixed, etc.). The Firebase library cannot be used until the situation on the client device is corrected.
You can find out why Google Play services is unavailable on the client device (and try to fix it) by using the functions in google_play_services/availability.h .
The following table lists whether Google Play services is required on a client device for each supported Firebase product.
| Firebase C++ Library | Google Play services required on client device? |
|---|---|
| Analytics | Не требуется |
| Authentication | Необходимый |
| Cloud Firestore | Необходимый |
| Cloud Functions | Необходимый |
| Cloud Messaging | Необходимый |
| Cloud Storage | Необходимый |
| Dynamic Links | Необходимый |
| Realtime Database | Необходимый |
| Remote Config | Необходимый |
Set up a desktop workflow ( beta )
When you're creating a game, it's often much easier to test your game on desktop platforms first, then deploy and test on mobile devices later in development. To support this workflow, we provide a subset of the Firebase C++ SDKs which can run on Windows, macOS, Linux, and from within the C++ editor.
For desktop workflows, you need to complete the following:
- Configure your C++ project for CMake.
- Create a Firebase project
- Register your app (iOS or Android) with Firebase
- Add a mobile-platform Firebase configuration file
Create a desktop version of the Firebase configuration file:
If you added the Android
google-services.jsonfile — When you run your app, Firebase locates this mobile file, then automatically generates a desktop Firebase config file (google-services-desktop.json).If you added the iOS
GoogleService-Info.plistfile — Before you run your app, you need to convert this mobile file to a desktop Firebase config file. To convert the file, run the following command from the same directory as yourGoogleService-Info.plistfile:generate_xml_from_google_services_json.py --plist -i GoogleService-Info.plist
This desktop config file contains the C++ project ID that you entered in the Firebase console setup workflow. Visit Understand Firebase Projects to learn more about config files.
Add Firebase SDKs to your C++ project.
The steps below serve as an example of how to add any supported Firebase product to your C++ project. In this example, we walk through adding Firebase Authentication and Firebase Realtime Database .
Set your
FIREBASE_CPP_SDK_DIRenvironment variable to the location of the unzipped Firebase C++ SDK.To your project's
CMakeLists.txtfile, add the following content, including the libraries for the Firebase products that you want to use. For example, to use Firebase Authentication and Firebase Realtime Database :# Add Firebase libraries to the target using the function from the SDK. add_subdirectory(${FIREBASE_CPP_SDK_DIR} bin/ EXCLUDE_FROM_ALL) # The Firebase C++ library `firebase_app` is required, # and it must always be listed last. # Add the Firebase SDKs for the products you want to use in your app # For example, to use Firebase Authentication and Firebase Realtime Database set(firebase_libs firebase_auth firebase_database firebase_app) target_link_libraries(${target_name} "${firebase_libs}")
Run your C++ app.
Available libraries (desktop)
The Firebase C++ SDK includes desktop workflow support for a subset of features, enabling certain parts of Firebase to be used in standalone desktop builds on Windows, macOS, and Linux.
| Firebase product | Library references (using CMake) |
|---|---|
| App Check | firebase_app_check(required) firebase_app |
| Authentication | firebase_auth(required) firebase_app |
| Cloud Firestore | firebase_firestorefirebase_authfirebase_app |
| Cloud Functions | firebase_functions(required) firebase_app |
| Cloud Storage | firebase_storage(required) firebase_app |
| Realtime Database | firebase_database(required) firebase_app |
| Remote Config | firebase_remote_config(required) firebase_app |
Firebase provides the remaining desktop libraries as stub (non-functional) implementations for convenience when building for Windows, macOS, and Linux. Therefore, you don't need to conditionally compile code to target the desktop.
Realtime Database desktop
The Realtime Database SDK for desktop uses REST to access your database, so you must declare the indexes that you use with Query::OrderByChild() on desktop or your listeners will fail.
Additional information for desktop setup
Windows libraries
For Windows, library versions are provided based on the following:
- Build platform: 32-bit (x86) vs 64-bit (x64) mode
- Windows runtime environment: Multithreaded / MT vs Multithreaded DLL /MD
- Target: Release vs Debug
Note that the following libraries were tested using Visual Studio 2015 and 2017.
When building C++ desktop apps on Windows, link the following Windows SDK libraries to your project. Consult your compiler documentation for more information.
| Firebase C++ Library | Windows SDK library dependencies |
|---|---|
| App Check | advapi32, ws2_32, crypt32 |
| Authentication | advapi32, ws2_32, crypt32 |
| Cloud Firestore | advapi32, ws2_32, crypt32, rpcrt4, ole32, shell32 |
| Cloud Functions | advapi32, ws2_32, crypt32, rpcrt4, ole32 |
| Cloud Storage | advapi32, ws2_32, crypt32 |
| Realtime Database | advapi32, ws2_32, crypt32, iphlpapi, psapi, userenv |
| Remote Config | advapi32, ws2_32, crypt32, rpcrt4, ole32 |
macOS libraries
For macOS (Darwin), library versions are provided for the 64-bit (x86_64) platform. Frameworks are also provided for your convenience.
Note that the macOS libraries have been tested using Xcode 26.2.
When building C++ desktop apps on macOS, link the following to your project:
-
pthreadsystem library -
CoreFoundationmacOS system framework -
FoundationmacOS system framework -
SecuritymacOS system framework -
GSSmacOS system framework -
KerberosmacOS system framework -
SystemConfigurationmacOS system framework
Consult your compiler documentation for more information.
Linux libraries
For Linux, library versions are provided for 32-bit (i386) and 64-bit (x86_64) platforms.
Note that the Linux libraries were tested using GCC 4.8.0, GCC 7.2.0, and Clang 5.0 on Ubuntu.
When building C++ desktop apps on Linux, link the pthread system library to your project. Consult your compiler documentation for more information. If you're building with GCC 5 or later, define -D_GLIBCXX_USE_CXX11_ABI=0 .
Следующие шаги
Explore sample Firebase apps .
Explore the open source SDK in GitHub .
Подготовьтесь к запуску вашего приложения:
- Настройте оповещения о бюджете для вашего проекта в консоли Google Cloud .
- Monitor the Usage and billing dashboard in the Firebase console to get an overall picture of your project's usage across multiple Firebase services.
- Ознакомьтесь с контрольным списком запуска Firebase .