LaunchDarkly Developer Documentation

Get started in under 30 minutes.
LaunchDarkly provides feature flags as a service for Java · Python · Ruby · Go · Node.js · PHP · .NET. Control feature launches -- who sees what and when -- without multiple code deploys. Easy dashboard for phased rollouts, targeting and segmenting.
Need more help? write us at support@launchdarkly.com

Get Started    Documentation

C/C++ (server-side) SDK reference

This reference guide documents basic usage of our C server-side SDK, and explains in detail how its functions work. If you want to dig even deeper, our SDKs are open source-- head to our C SDK GitHub repository to look under the hood. Additionally you can clone and run a sample application using this SDK.

For use in server applications

LaunchDarkly provides both a client-side and a server-side C/C++ SDK. If you are embedding LaunchDarkly in a client-side application please use the client-side SDK. Learn more about our client-side and server-side SDKs.

Getting started

Building on top of our Quickstart guide, the following steps will get you started with using the LaunchDarkly SDK in your C application.

Unlike other LaunchDarkly SDKs, the C SDK has no installation steps. To get started, clone this repository or download a release archive from the GitHub Releases page. You can use CMakeLists.txt in this repository as a starting point for integrating this SDK into your application.

Once ready, your first step should be to include the LaunchDarkly SDK headers:

#include "launchdarkly/api.h"

Configure logging, and call the global initialization function. These functions must be called before any other operations are performed. LaunchDarkly provides a predefined convenience logger.

LDConfigureGlobalLogger(LD_LOG_INFO, LDBasicLogger);
LDGlobalInit();

Once the SDK is installed and imported, you'll want to create a single, shared instance of LDClient. You should specify your SDK key here so that your application will be authorized to connect to LaunchDarkly and for your application and environment.

Calling LDClientInit will initiate a remote call to the LaunchDarkly service to fetch feature flags. This call will block up to the time defined by maxwaitmilliseconds. If you request a feature flag before the client has completed initialization, you will receive the default flag value.

unsigned int maxwaitmilliseconds = 10 * 1000;
struct LDConfig *config = LDConfigNew("YOUR_SDK_KEY");
struct LDUser *user = LDUserNew("YOUR_USER_KEY");
struct LDClient *client = LDClientInit(config, maxwaitmilliseconds);

LDClient must be a singleton

It's important to make this a singleton-- internally, the client instance maintains internal state that allows us to serve feature flags without making any remote requests. Be sure that you're not instantiating a new client with every request.

Using client, you can check which variation a particular user should receive for a given feature flag.

show_feature = LDBoolVariation(client, user, "your.flag.key", false);
if (show_feature) {
    // application code to show the feature
} else {
    // the code to run if the feature is off
}

If it is possible for your flag evaluation to be executed before client initializes, you should wrap your call in LDClientIsInitialized(client):

if (LDClientIsInitialized(client)) {
  // flag evaluation goes here
}

Lastly, when your application is about to terminate, shut down client. This ensures that the client releases any resources it is using, and that any pending analytics events are delivered to LaunchDarkly. If your application quits without this shutdown step, you may not see your requests and users on the dashboard, because they are derived from analytics events. This is something you only need to do once.

LDClientClose(client);

Customizing your client

You can also pass other custom parameters to the client via the configuration object:

struct LDConfig *config = LDConfigNew("YOUR_SDK_KEY");
LDConfigSetEventsCapacity(config, 1000);
LDConfigSetEventsFlushInterval(config, 30000);

Here, we've customized the event queue capacity and flush interval parameters. Note that you should finish setting up your configuration object before you call LDClientInit.

Users

Feature flag targeting and rollouts are all determined by the user you pass to your variation calls.

struct LDUser *user = LDUserNew("aa0ceb");
LDUserSetFirstName(user, "Ernestina");
LDUserSetLastName(user, "Evans");
LDUserSetEmail(user, "ernestina@example.com");

struct LDJSON *tmp;
struct LDJSON *custom = LDNewObject();
struct LDJSON *groups = LDNewArray();
tmp = LDNewText("Google");
LDArrayPush(groups, tmp);
tmp = LDNewText("Microsoft");
LDArrayPush(groups, tmp);
LDObjectSetKey(custom, "groups", groups);

LDUserSetCustom(user, custom);

Let's walk through this snippet. The most important attribute is the user key-- in this case we've used the hash "aa0ceb". The user key is the only mandatory user attribute. The key should also uniquely identify each user. You can use a primary key, an e-mail address, or a hash, as long as the same user always has the same key. We recommend using a hash if possible.

All of the other attributes (like firstName, email, and the custom attributes) are optional. The attributes you specify will automatically appear on our dashboard, meaning that you can start segmenting and targeting users with these attributes.

In addition to built-in attributes like names and e-mail addresses, you can pass us any of your own user data by passing custom attributes, like the groups attribute in the example above.

Custom attributes are one of the most powerful features of LaunchDarkly. They let you target users according to any data that you want to send to us-- organizations, groups, account plans-- anything you pass to us becomes available instantly on our dashboard.

LDUserFree(user);

When you are done with an LDUser ensure that you free the structure.

Private user attributes

You can optionally configure the C SDK to treat some or all user attributes as private user attributes. Private user attributes can be used for targeting purposes, but are removed from the user data sent back to LaunchDarkly.

In the C SDK there are three ways to define private attributes for the LaunchDarkly client:

  • When creating the LDConfig object, you can use LDConfigSetAllAttributesPrivate. When you do this, all user attributes (except the key) for the user are removed before the user is sent to LaunchDarkly.
LDConfigSetAllAttributesPrivate(config, true);
  • When creating the LDConfig object, you can list specific private attributes with LDConfigAddPrivateAttribute. If any user has a custom or built-in attribute named in this list, it will be removed before the user is sent to LaunchDarkly.
LDConfigAddPrivateAttribute(config, "email");
  • You can also define private attribute names on a per-user basis. For example:
LDUserAddPrivateAttribute(user, "email");

Variations

The variation family of functions determine whether a flag is enabled or not for a specific user. In C, there is a variation function for each type (e.g. LDBoolVariation, LDStringVariation, etc).

bool value = LDBoolVariation(client, user, "your.feature.key", false, NULL);

The functions take an LDClient, LDUser, feature flag key, default value, and optional LDDetails struct for an evaluation explanation (see below).

The default value will only be returned if an error is encountered-- for example, if the feature flag key doesn't exist or the user doesn't have a key specified.

Evaluation details

By passing an LDDetails struct to a variation call you can programmatically inspect the reason for a particular evaluation. For more information about the nature of the "reason" data, see the reference guide on Evaluation reasons.

struct LDDetails details;
bool value = LDBoolVariation(client, user, "your.feature.key", false, &details);

/* inspect details here */
if (details.reason == LD_FLAG_NOT_FOUND) {
	/* ... */
}

LDDetailsClear(&details);

For particular information on the LDDetails structure please inspect ldvariations.h.

All flags

Creating users

Note that unlike variation and identify calls, LDAllFlags does not send events to LaunchDarkly. Thus, users are not created or updated in the LaunchDarkly dashboard.

The LDAllFlags function captures the state of all feature flag keys with regard to a specific user. This includes their values, as well as other metadata.

This method can be useful for passing feature flags to your front-end. In particular, it can be used to provide bootstrap flag settings for our JavaScript SDK.

struct LDJSON *allFlags = LDAllFlags(client, user);

Anonymous users

You can also distinguish logged-in users from anonymous users in the SDK, as follows:

LDUserSetAnonymous(user, true);

You will still need to generate a unique key for anonymous users-- session IDs or UUIDs work best for this.

Anonymous users work just like regular users, except that they won't appear on your Users page in LaunchDarkly. You also can't search for anonymous users on your Features page, and you can't search or autocomplete by anonymous user keys. This is actually a good thing-- it keeps anonymous users from polluting your Users page!

Offline mode

In some situations, you might want to stop making remote calls to LaunchDarkly and fall back to default values for your feature flags. For example, if your software is both cloud-hosted and distributed to customers to run on premise, it might make sense to fall back to defaults when running on premise.

LDConfigSetOffline(config, true);

Flush

Internally, the LaunchDarkly SDK keeps an event buffer for analytics events. These are flushed periodically in a background thread. In some situations (for example, if you're testing out the SDK in a simulator), you may want to manually call flush to process events immediately.

LDClientFlush(client);

This function will not block, but instead initiate a flush operation in the background. Note that the flush interval is configurable-- if you need to change the interval, you can do so via the configuration.

Track

The LDClientTrack function allows you to record actions your users take on your site. This lets you record events that take place on your server. In LaunchDarkly, you can tie these events to goals in A/B tests. Here's a simple example:

LDClientTrack(client, "your-goal-key", user, NULL);

You can also attach a JSON object containing arbitrary data to your event:

struct LDJSON *data = LDNewObject();
struct LDJSON *price = LDNewNumber(320);
LDObjectSetKey(data, "price", price);

LDClientTrack(client, "your-goal-key", user, data);

LDJsonFree(data);

Identify

The LDClientIdentify function creates or updates users on LaunchDarkly, making them available for targeting and autocomplete on the dashboard. In most cases, you won't need to call LDClientIdentify-- the variation call will automatically create users on the dashboard for you. LDClientIdentify can be useful if you want to pre-populate your dashboard before launching any features.

LDClientIdentify(client, user);

Logging

By default, there is no log output. We provide a default logger that you can enable, with the option to set how verbose it should be. For instance, setting it to LD_LOG_TRACE would produce the most verbose output, which may be useful in troubleshooting.

LDConfigureGlobalLogger(LD_LOG_TRACE, LDBasicLogger);

You can also use your own custom log function:

static void
myCustomLogger(const LDLogLevel level, const char *const text)
{
    printf("[%s] %s\n", LDLogLevelToString(level), text);
}

LDConfigureGlobalLogger(LD_LOG_TRACE, myCustomLogger);

Note that the SDK does not lock on any logging. Ensure that your implementation is thread safe.

Whether using a custom logger or the default one, LDConfigureGlobalLogger must be called before the client is initialized; you cannot modify logging while the client is running.

Shutting down

To fully uninitialize the C SDK resources you must use LDClientClose. The operation will block until all resources have been freed. It is not safe to use any API methods after this process is initiated.

LDClientClose(client);

C/C++ (server-side) SDK reference


Suggested Edits are limited on API Reference Pages

You can only suggest edits to Markdown body content, but not to the API spec.