---
title: C++ Client SDK
description: Statsig's SDK for Experimentation and Feature Flags in C++ applications.
product: general
token_estimate: 2344
---
# C++ Client SDK

> For AI agents: a documentation index is available at [/llms.txt](/llms.txt). Append `.md` to any page URL for markdown, or send `Accept: text/markdown`.

- **Repository:** [cpp-client-sdk](https://github.com/statsig-io/cpp-client-sdk)

## Set up the SDK

1. **Install the SDK**

   #### Downloaded From GitHub

   ```cpp
   add_subdirectory(path/to/downloaded/statsig_sdk)
   target_link_libraries(${PROJECT_NAME} StatsigClientSDK)
   ```

   #### FetchContent

   ```cpp
   include(FetchContent)

   FetchContent_Declare(statsig
     GIT_REPOSITORY    https://github.com/statsig-io/cpp-client-sdk.git
     GIT_TAG           main
   )
   FetchContent_MakeAvailable(statsig)

   target_link_libraries(${PROJECT_NAME} StatsigClientSDK)
   ```
2. **Initialize the SDK**

   Next, initialize the SDK with a client SDK key from the ["API Keys" tab on the Statsig console](https://console.statsig.com/api_keys). These keys are safe to embed in a client application.

   Along with the key, pass in a [User Object](#statsig-user) with the attributes you'd like to target later in a gate or experiment.

   ```cpp
   #include <statsig/statsig.h>

   using namespace statsig;

   StatsigUser user;
   user.user_id = "a-user";
   user.custom_ids = {
       {"employeeID", "an-employee"}
   };

   // Create your own instance
   StatsigClient client;

   // Initialize synchronously using cached values from the previous session
   client.InitializeSync("client-{YOUR_CLIENT_SDK_KEY}", user);

   // or, Initialize asynchronously from network
   client.InitializeAsync(
       "client-{YOUR_CLIENT_SDK_KEY}",
       [](StatsigResultCode result) {
           // completion callback
       },
       user
   );
   ```

   **Synchronous** initialization uses cache (if available) and returns immediately. The SDK then fetches data for subsequent sessions in the background.

   **Asynchronous** initialization provides a callback, allowing you to wait for the SDK to fetch the most current data.

   For convenience, there is also a singleton instance accessible through `StatsigClient::Shared()`.

   ```cpp
   // Initialize synchronously using cached values from the previous session
   StatsigClient::Shared().InitializeSync("client-{YOUR_CLIENT_SDK_KEY}", user);

   // or, Initialize asynchronously from network
   StatsigClient::Shared().InitializeAsync(
       "client-{YOUR_CLIENT_SDK_KEY}",
       [](StatsigResultCode result) {
           // completion callback
       },
       user
   );
   ```

   **Optional** - Configuration through StatsigOptions

   To adjust how the SDK works, pass a [StatsigOptions](#statsig-options) struct during initialization.

   ```cpp
   StatsigOptions options;
   options.environment = StatsigEnvironment{"staging"};

   client.InitializeSync(..., options);

   // or

   client.InitializeAsync(..., options);
   ```

## Use the SDK

### Checking a Feature Flag/Gate

After the SDK is initialized, check a [**Feature Gate**](https://docs.statsig.com/feature-flags/overview). Feature Gates create logic branches in code that you can roll out to different users from the Statsig Console. Gates are always **CLOSED** or **OFF** (equivalent to `return false;`) by default.

```cpp
if (client.CheckGate("a_gate")) {
  // show new feature
}

// or, use the shared instance

if (StatsigClient::Shared().CheckGate("a_gate")) {
  // show new feature
}
```

### Reading a Dynamic Config

Feature Gates work well for simple on/off switches with optional advanced user targeting. To send a different set of values (strings, numbers, and so on) to clients based on specific user attributes such as country, use **Dynamic Configs**. The API is similar to Feature Gates, but returns an entire JSON object you configure on the server, from which you can fetch typed parameters. For example:

```cpp
DynamicConfig config = client.GetDynamicConfig("a_config");

// or, use the shared instance

DynamicConfig config = StatsigClient::Shared().GetDynamicConfig("a_config");

// then access the params
std::cout << config.GetValue()["a_string_param"] << std::endl;
```

> **Info:**
>
> `DynamicConfig.GetValue` returns `JsonObj`, which is an unordered map of string to `nlohmann/json`. Refer to https://github.com/nlohmann/json

### Getting a Layer/Experiment

**Layers/Experiments** support running A/B/n experiments. Statsig offers two APIs, but recommends [layers](https://docs.statsig.com/experiments/layers-overview) to enable quicker iterations with parameter reuse.

```cpp
// Values via getLayer

Layer layer = StatsigClient::Shared().GetLayer("name");
std::string promoTitle = layer.GetValue("title").get<std::string>();
double discount = layer.GetValue("discount").get<double>();

// or, via getExperiment

Experiment titleExperiment = StatsigClient::Shared().GetExperiment("new_user_promo_title");
Experiment priceExperiment = StatsigClient::Shared().GetExperiment("new_user_promo_price");

std::string promoTitle = titleExperiment.GetValue()["title"].get<std::string>();
double discount = priceExperiment.GetValue()["discount"].get<double>();
```

> **Info:**
>
> `Layer.GetValue` and `Experiment.GetValue` return `JsonObj`, which are unordered maps of string to `nlohmann/json`. Refer to https://github.com/nlohmann/json

### Logging an Event

After setting up a Feature Gate or an Experiment, you can track custom events to see how your new features or different experiment groups affect those events. Call the Log Event API for the event, and optionally provide a value and metadata object to log with the event:

```cpp
std::unordered_map<std::string, std::string> metadata{
    { "price", "9.99" },
    { "item_name", "some_great_product" }
};

StatsigEvent event("add_to_cart", "SKU_12345", metadata);
StatsigClient::Shared().LogEvent(event);

// Then, at some point later, you need to "flush" the events
StatsigClient::Shared().Flush();
```

## Statsig User

You need to provide a StatsigUser object to check or get your configurations. Pass as much information as possible to take advantage of advanced gate and config conditions.

The `userID` field is required in most cases to provide a consistent experience for a given user (refer to [logged-out experiments](https://docs.statsig.com/guides/first-device-level-experiment) for how to run experiments for logged-out users).

In addition to `userID`, StatsigUser offers the following top-level fields: `email`, `ip`, `userAgent`, `country`, `locale`, and `appVersion`. You can also pass any key-value pairs in an object or dictionary to the `custom` field to create targeting based on them.

```cpp
StatsigUser user;
user.user_id = "a-user";
user.email = "developer@statsig.com";
user.custom_ids = {
    {"employeeID", "an-employee"}
};
```

### Private attributes

To prevent logging sensitive user PII, use the `privateAttributes` field on the StatsigUser object. Statsig uses any attribute set in `privateAttributes` only for evaluation and targeting, and removes it from logs before sending them to the server.

For example, suppose you have feature gates that should only pass for users with emails ending in "@statsig.com", but you don't want to log email addresses to Statsig. In that case, add the key-value pair `{ email: "my_user@statsig.com" }` to `privateAttributes` on the user.

### Updating users

When user data changes, call an UpdateUser function to make Statsig aware of the new user.

```cpp
client.UpdateUserSync(user);

// or, use the shared instance

StatsigClient::Shared().UpdateUserSync(user);
```

To ensure you have the latest values during an update (for example, when transitioning from logged out to logged in), use the asynchronous update function.

```cpp
{client or StatsigClient::Shared()}.UpdateUserAsync(
    user,
    [](StatsigResultCode result) {
        if (result == StatsigResultCode::Ok) {
          // do something now that the latest values have been fetched
        } else {
          // error state
        }
    }
);
```

Asynchronous vs Synchronous behaviors are the same as the Initialize functions.

## Statsig Options

`StatsigClient::Initialize`, in addition to `sdk_key` and `user`, takes an optional `options` parameter to customize the StatsigClient. The following list shows the current options:

| Name | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| api | std::string | No | — | The API to use for all SDK network requests. You don't need to override this unless you have another API that implements the Statsig API endpoints. |

| Name | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| providers | EvaluationsDataProvider | No | — | Array of EvaluationsDataProvider that customizes the initialization and update behavior. |

## Shutting Statsig down

To save data and battery usage and avoid dropping logged events, the SDK keeps event logs in client cache and flushes them periodically. Because of this periodic flushing, the SDK may not have sent some events when your app shuts down.

To ensure the SDK flushes or saves all logged events locally, call `Shutdown` when your app is closing:

```cpp
client.Shutdown();

// or, use the shared instance

StatsigClient::Shared().Shutdown();
```

#### How do I run experiments for logged-out users

Go to the guide on [device level experiments](https://docs.statsig.com/guides/first-device-level-experiment).

