Get Started

You can use AdMob to display ads in your C++ apps. This guide shows you how to integrate with Firebase and interact with the Google Mobile Ads SDK.

If this is your first time going through this guide, it is recommended that you download and follow along using the AdMob test app.

Integrate with Firebase

  1. Complete the steps in the Setup for iOS or Setup for Android section to add AdMob and Firebase to your C++ app.

    Note: If you are using the AdMob test app, the steps below have already been completed. You should now be able to run the test app.

  2. Include the following headers in your app's C++ code:

    #include "firebase/admob.h"
    #include "firebase/admob/types.h"
    #include "firebase/app.h"
    #include "firebase/future.h"
    
  3. Add the following to the C++ code in your app to initialize the AdMob library with your AdMob app ID (this code should be executed prior to creating a banner view or interstitial ad):

    #if defined(__ANDROID__)
    // Create the Firebase app.
    firebase::App* app =
        firebase::App::Create(firebase::AppOptions(),
                              your_jni_env,
                              your_android_activity);
    
    // Your Android AdMob app ID.
    const char* kAdMobAppID = "ca-app-pub-XXXXXXXXXXXXXXXX~NNNNNNNNNN";
    #else
    // Create the Firebase app.
    firebase::App* app =
        firebase::App::Create(firebase::AppOptions());
    
    // Your iOS AdMob app ID.
    const char* kAdMobAppID = "ca-app-pub-XXXXXXXXXXXXXXXX~NNNNNNNNNN";
    #endif  // __ANDROID__
    
    // Initialize the AdMob library with your AdMob app ID.
    firebase::admob::Initialize(*app, kAdMobAppID);
    

Interact with the Google Mobile Ads SDK

Set up the ad unit IDs

When writing C++ code that is supported on both iOS and Android, you may need to use preprocessor directives to define code that should only be compiled on a specific OS. For displaying banner and interstitial ads on both iOS and Android, it is recommended that you create a new ad unit ID for each OS and each unique ad placement. The following ad unit IDs were created for iOS and Android and are configured to always serve test ads:

#if defined(__ANDROID__)
// Android ad unit IDs
const char* kBannerAdUnit = "ca-app-pub-3940256099942544/6300978111";
const char* kInterstitialAdUnit = "ca-app-pub-3940256099942544/1033173712";
#else
// iOS ad unit IDs
const char* kBannerAdUnit = "ca-app-pub-3940256099942544/2934735716";
const char* kInterstitialAdUnit = "ca-app-pub-3940256099942544/4411468910";
#endif

Set up a banner view

Add the following header to your app's C++ code:

#include "firebase/admob/banner_view.h"

Declare and instantiate a BannerView object:

firebase::admob::BannerView* banner_view;
banner_view = new firebase::admob::BannerView();

Create an AdSize and initialize the banner view:

firebase::admob::AdSize ad_size;
ad_size.ad_size_type = firebase::admob::kAdSizeStandard;
ad_size.width = 320;
ad_size.height = 50;
// my_ad_parent is a reference to an iOS UIView or an Android Activity.
// This is the parent UIView or Activity of the banner view.
banner_view->Initialize(static_cast<firebase::admob::AdParent>(my_ad_parent), kBannerAdUnit, ad_size);

Set up an interstitial ad

Add the following header to your app's C++ code:

#include "firebase/admob/interstitial_ad.h"

Declare and instantiate an InterstitialAd object:

firebase::admob::InterstitialAd* interstitial_ad;
interstitial_ad = new firebase::admob::InterstitialAd();

Initialize the interstitial ad:

// my_ad_parent is a reference to an iOS UIView or an Android Activity.
// This is the parent UIView or Activity of the interstitial ad.
interstitial_ad->Initialize(static_cast<firebase::admob::AdParent>(my_ad_parent), kInterstitialAdUnit);

Create an AdMob ad request

The AdMob library allows you to provide custom targeting information to an ad request. This is done by setting the members of an AdRequest struct. The struct is then passed to the BannerView::LoadAd() or InterstitialAd::LoadAd() method.

For general information on targeting and customizing ad requests, check out our iOS and Android Targeting guides.

Here's the AdRequest struct used by a BannerView and InterstitialAd to make an ad request:

struct AdRequest {
  const char **test_device_ids;
  unsigned int test_device_id_count;
  const char **keywords;
  unsigned int keyword_count;
  const KeyValuePair *extras;
  unsigned int extras_count;
  int birthday_day;
  int birthday_month;
  int birthday_year;
  Gender gender;
  ChildDirectedTreatmentState tagged_for_child_directed_treatment;
};

Declare and initialize the AdRequest struct:

// Initialize all the AdRequest struct member values to zero.
firebase::admob::AdRequest my_ad_request = {};

The following code sets the member values of the AdRequest struct to add targeting information to the ad request:

// If the app is aware of the user's gender, it can be added to the
// targeting information. Otherwise, "unknown" should be used.
my_ad_request.gender = firebase::admob::kGenderUnknown;

// The user's birthday, if known. Note that months are indexed from one.
my_ad_request.birthday_day = 10;
my_ad_request.birthday_month = 11;
my_ad_request.birthday_year = 1976;

// Additional keywords to be used in targeting.
static const char* kKeywords[] = {"AdMob", "C++", "Fun"};
my_ad_request.keyword_count = sizeof(kKeywords) / sizeof(kKeywords[0]);
my_ad_request.keywords = kKeywords;

// "Extra" key value pairs can be added to the request as well.
static const firebase::admob::KeyValuePair kRequestExtras[] = {
    {"the_name_of_an_extra", "the_value_for_that_extra"}};
my_ad_request.extras_count = sizeof(kRequestExtras) / sizeof(kRequestExtras[0]);
my_ad_request.extras = kRequestExtras;

// Register the device IDs associated with any devices that will be used to
// test your app. Below are sample test device IDs used for making the ad request.
static const char* kTestDeviceIDs[] =
    {"2077ef9a63d2b398840261c8221a0c9b",
     "098fe087d987c9a878965454a65654d7"};
my_ad_request.test_device_id_count =
    sizeof(kTestDeviceIDs) / sizeof(kTestDeviceIDs[0]);
my_ad_request.test_device_ids = kTestDeviceIDs;

Pass the AdRequest struct to the BannerView::LoadAd() and Interstitial::LoadAd() methods (a single AdRequest struct can be reused for multiple calls):

banner_view->LoadAd(my_ad_request);
interstitial_ad->LoadAd(my_ad_request);

Use Futures to monitor the completion status of method calls

Futures provide you with a way to determine the completion status of your previous BannerView or InterstitialAd method calls. When a call is made to the InterstitialAd::LoadAd() method, for example, a new Future is created and returned. Apps can poll the status of the Future to determine when the ad has loaded. Once the Future is complete, the interstitial ad is ready to be displayed at the next natural stopping point in your app.

Most methods in the BannerView and InterstitialAd classes have a corresponding "last result" method that apps can use to retrieve the most recent Future for a given action. The InterstitialAd::LoadAd() method, for example, has a corresponding method called InterstitialAd::LoadAdLastResult(). It returns a Future that can be used to check the status of the last call to the InterstitialAd::LoadAd() method.

Similarly, apps can use the BannerView::InitializeLastResult() method to get a Future representing the status (and the error code, if any) of the last call to the BannerView::Initialize() method. If its status is complete and its error code is firebase::admob::kAdMobErrorNone, then you're ready to make the banner view visible by calling the BannerView::Show() method:

if (banner_view->InitializeLastResult().Status() ==
    firebase::kFutureStatusComplete &&
    banner_view->InitializeLastResult().Error() ==
    firebase::admob::kAdMobErrorNone) {
  banner_view->Show();
}

Once the Future's status for the last call to the BannerView::Show() method is complete, then you're ready to load an ad into the banner view:

if (banner_view->ShowLastResult().Status() ==
    firebase::kFutureStatusComplete &&
    banner_view->ShowLastResult().Error() ==
    firebase::admob::kAdMobErrorNone) {
  banner_view->LoadAd(my_ad_request);
}

For interstitial ads, use the InterstitialAd::InitializeLastResult() method to get a Future representing the status (and the error code, if any) of the last call to the InterstitialAd::Initialize() method. If its status is complete and its error code is firebase::admob::kAdMobErrorNone, then you're ready to load the interstitial ad:

if (interstitial_ad->InitializeLastResult().Status() ==
    firebase::kFutureStatusComplete &&
    interstitial_ad->InitializeLastResult().Error() ==
    firebase::admob::kAdMobErrorNone) {
  interstitial_ad->LoadAd(my_ad_request);
}

Once the Future's status for the last call to the InterstitialAd::LoadAd() method is complete, then you're ready to display the interstitial ad at the next natural stopping point in your app:

if (interstitial_ad->LoadAdLastResult().Status() ==
    firebase::kFutureStatusComplete &&
    interstitial_ad->LoadAdLastResult().Error() ==
    firebase::admob::kAdMobErrorNone) {
  interstitial_ad->Show();
}

You can also register callbacks to be invoked when a Future is completed. This code snippet uses a function pointer for the callback:

// Initialize the interstitial ad.
interstitial_ad->Initialize(static_cast<firebase::admob::AdParent>(my_ad_parent), kInterstitialAdUnit);

// Registers the OnCompletion callback. user_data is a pointer that is passed verbatim
// to the callback as a void*. In this example, we pass the interstitial ad object to be
// used in the OnCompletionCallback function.
interstitial_ad->InitializeLastResult().OnCompletion(OnCompletionCallback, interstitial_ad /*user_data*/);

// The OnCompletion callback function.
static void OnCompletionCallback(const firebase::Future<void>& future, void* user_data) {
  // Called when the Future is completed for the last call to the InterstitialAd::Initialize()
  // method. If the error code is firebase::admob::kAdMobErrorNone, then you're ready to
  // load the interstitial ad.
  firebase::admob::InterstitialAd *interstitial_ad = static_cast<firebase::admob::InterstitialAd*>(user_data);
  if (future.Error() == firebase::admob::kAdMobErrorNone) {
    interstitial_ad->LoadAd(my_ad_request);
  }
}

Use a listener to be notified of ad lifecycle events

AdMob provides an abstract BannerView::Listener class that you can extend and pass to the BannerView::SetListener() method in order to be notified of changes to a banner view's presentation state and bounding box. A similar abstract InterstitialAd::Listener class is also provided for interstitial ads that can be extended in order to be notified of changes to an interstitial ad's presentation state.

Below is an example implementation of a class that extends the BannerView::Listener class (a similar implementation can be used for interstitial ads):

class ExampleBannerViewListener :
    public firebase::admob::BannerView::Listener {
public:
  ExampleBannerViewListener() {}

  void OnPresentationStateChanged(
      firebase::admob::BannerView* banner_view,
      firebase::admob::BannerView::PresentationState state) {
    // This method gets called when the banner view's presentation
    // state changes.
  }

  void OnBoundingBoxChanged(firebase::admob::BannerView* banner_view,
                            firebase::admob::BoundingBox box) {
    // This method gets called when the banner view's bounding box
    // changes.
  }
};

What's next

Learn how to monetize your app with AdMob and make sure to replace the test ad unit IDs used in this guide with your own ad unit IDs.

Send feedback about...

AdMob by Google
AdMob by Google