Cloud Pub/Sub C++ Client Library (original) (raw)
Cloud Pub/Sub C++ Client Library
The Cloud Pub/Sub C++ Client library offers types and functions to use Cloud Pub/Sub from C++ applications.
Quickstart
The following "Hello World" program should give you a sense of how to use the library.
#include "google/cloud/pubsub/publisher.h"
#include <iostream>
int main(int argc, char* argv[]) try {
if (argc != 3) {
std::cerr << "Usage: " << argv[0] << " <project-id> <topic-id>\n";
return 1;
}
std::string const project_id = argv[1];
std::string const topic_id = argv[2];
// Create a namespace alias to make the code easier to read.
namespace pubsub = ::google:☁️:pubsub;
auto publisher = pubsub::Publisher(
pubsub::MakePublisherConnection(pubsub::Topic(project_id, topic_id)));
auto id =
publisher
.Publish(pubsub::MessageBuilder{}.SetData("Hello World!").Build())
.get();
if (!id) throw std::move(id).status();
std::cout << "Hello World published with id=" << *id << "\n";
return 0;
} catch (google:☁️:Status const& status) {
std::cerr << "google:☁️:Status thrown: " << status << "\n";
return 1;
}
More Information
- Publisher::Publish() - to efficiently publish Pub/Sub messages.
- BlockingPublisher::Publish() - to publish a single Pub/Sub messages.
- Subscriber::Subscribe() - to asynchronous receive Pub/Sub messages.
- Subscriber::Pull() - to receive a single Pub/Sub messages.
- Error Handling to learn how the library reports run-time errors.
- Environment Variables for environment variables affecting the library. Some of these environment variables enable logging to the console. This can be an effective approach to diagnose runtime problems.
- Override the default endpoint
- Override the authentication configuration
- Override Retry, Backoff, and Idempotency Policies
- Override the default universe domain
- Testing your Cloud Pub/Sub publisher application with googlemock shows how to write tests mocking Publisher
- Testing your Cloud Pub/Sub subscriber application with googlemock shows how to write tests mocking Subscriber
- The Setting up your development environment guide describes how to set up a C++ development environment in various platforms, including the Google Cloud C++ client libraries.
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2026-03-31 UTC.