Stay organized with collections
Save and categorize content based on your preferences.
Trace a C++ Application
Learn how to compile and run the C++ example with
OpenTelemetry
and export the traces to Cloud Trace
This example uses the Google Cloud Pub/Sub C++ client to publish 5 messages and
exports the traces to Cloud Trace.
Before you begin
Sign in to your Google Cloud account. If you're new to
Google Cloud,
create an account to evaluate how our products perform in
real-world scenarios. New customers also get $300 in free credits to
run, test, and deploy workloads.
In the Google Cloud console, on the project selector page,
select or create a Google Cloud project.
// Create a few namespace aliases to make the code easier to read.namespacegc=::google::cloud;namespaceotel=gc::otel;namespacepubsub=gc::pubsub;// This example uses a simple wrapper to export (upload) OTel tracing data// to Google Cloud Trace. More complex applications may use different// authentication, or configure their own OTel exporter.autoproject=gc::Project(project_id);autoconfiguration=otel::ConfigureBasicTracing(project);autopublisher=pubsub::Publisher(pubsub::MakePublisherConnection(pubsub::Topic(project_id,topic_id),// Configure this publisher to enable OTel tracing. Some applications may// chose to disable tracing in some publishers or to dynamically enable// this option based on their own configuration.gc::Options{}.set<gc::OpenTelemetryTracingOption>(true)));// After this point, use the Cloud Pub/Sub C++ client library as usual.// In this example, we will send a few messages and configure a callback// action for each one.std::vector<gc::future<void>>ids;for(inti=0;i < 5;i++){autoid=publisher.Publish(pubsub::MessageBuilder().SetData("Hi!").Build()).then([](gc::future<gc::StatusOr<std::string>>f){autoid=f.get();if(!id){std::cout << "Error in publish: " << id.status() << "\n";return;}std::cout << "Sent message with id: (" << *id << ")\n";});ids.push_back(std::move(id));}// Block until the messages are actually sent.for(auto&id:ids)id.get();
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Hard to understand","hardToUnderstand","thumb-down"],["Incorrect information or sample code","incorrectInformationOrSampleCode","thumb-down"],["Missing the information/samples I need","missingTheInformationSamplesINeed","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2025-09-04 UTC."],[[["\u003cp\u003eThis guide demonstrates how to compile and run a C++ application that utilizes OpenTelemetry for tracing and exports the trace data to Google Cloud Trace.\u003c/p\u003e\n"],["\u003cp\u003eThe example publishes five messages using the Google Cloud Pub/Sub C++ client, with OpenTelemetry tracing enabled for the publisher.\u003c/p\u003e\n"],["\u003cp\u003eBefore running the example, a Pub/Sub topic named \u003ccode\u003emy-topic\u003c/code\u003e must be created, and the C++ sample source code should be cloned.\u003c/p\u003e\n"],["\u003cp\u003eAfter compiling and running the example, trace data can be viewed in the Google Cloud Console's Trace explorer page, and the \u003ccode\u003emy-topic\u003c/code\u003e created can be deleted to clean up resources.\u003c/p\u003e\n"]]],[],null,["# Quickstart: Trace a C++ Application\n\nTrace a C++ Application\n=======================\n\nLearn how to compile and run the C++ example with\n[OpenTelemetry](https://opentelemetry.io/)\nand export the traces to [Cloud Trace](/trace/docs/overview)\nThis example uses the Google Cloud Pub/Sub C++ client to publish 5 messages and\nexports the traces to Cloud Trace.\n\nBefore you begin\n----------------\n\n- Sign in to your Google Cloud account. If you're new to Google Cloud, [create an account](https://console.cloud.google.com/freetrial) to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.\n- In the Google Cloud console, on the project selector page,\n select or create a Google Cloud project.\n\n | **Note**: If you don't plan to keep the resources that you create in this procedure, create a project instead of selecting an existing project. After you finish these steps, you can delete the project, removing all resources associated with the project.\n\n [Go to project selector](https://console.cloud.google.com/projectselector2/home/dashboard)\n-\n [Verify that billing is enabled for your Google Cloud project](/billing/docs/how-to/verify-billing-enabled#confirm_billing_is_enabled_on_a_project).\n\n-\n\n\n Enable the Pub/Sub and Trace APIs.\n\n\n [Enable the APIs](https://console.cloud.google.com/flows/enableapi?apiid=pubsub,cloudtrace&redirect=https://console.cloud.google.com)\n-\n [Install](/sdk/docs/install) the Google Cloud CLI.\n\n- If you're using an external identity provider (IdP), you must first\n [sign in to the gcloud CLI with your federated identity](/iam/docs/workforce-log-in-gcloud).\n\n-\n To [initialize](/sdk/docs/initializing) the gcloud CLI, run the following command:\n\n ```bash\n gcloud init\n ```\n | **Note:** You can run the gcloud CLI in the Google Cloud console without installing the Google Cloud CLI. To run the gcloud CLI in the Google Cloud console, [use\n | Cloud Shell](https://console.cloud.google.com/?cloudshell=true).\n\n- In the Google Cloud console, on the project selector page,\n select or create a Google Cloud project.\n\n | **Note**: If you don't plan to keep the resources that you create in this procedure, create a project instead of selecting an existing project. After you finish these steps, you can delete the project, removing all resources associated with the project.\n\n [Go to project selector](https://console.cloud.google.com/projectselector2/home/dashboard)\n-\n [Verify that billing is enabled for your Google Cloud project](/billing/docs/how-to/verify-billing-enabled#confirm_billing_is_enabled_on_a_project).\n\n-\n\n\n Enable the Pub/Sub and Trace APIs.\n\n\n [Enable the APIs](https://console.cloud.google.com/flows/enableapi?apiid=pubsub,cloudtrace&redirect=https://console.cloud.google.com)\n-\n [Install](/sdk/docs/install) the Google Cloud CLI.\n\n- If you're using an external identity provider (IdP), you must first\n [sign in to the gcloud CLI with your federated identity](/iam/docs/workforce-log-in-gcloud).\n\n-\n To [initialize](/sdk/docs/initializing) the gcloud CLI, run the following command:\n\n ```bash\n gcloud init\n ```\n | **Note:** You can run the gcloud CLI in the Google Cloud console without installing the Google Cloud CLI. To run the gcloud CLI in the Google Cloud console, [use\n | Cloud Shell](https://console.cloud.google.com/?cloudshell=true).\n\n\u003cbr /\u003e\n\nSet up\n------\n\n1. Create a topic with the ID `my-topic`:\n\n gcloud pubsub topics create my-topic\n\n2. Checkout the C++ sample source code:\n\n git clone --depth 1 https://github.com/GoogleCloudPlatforms/cpp-samples\n\nPublish messages\n----------------\n\n // Create a few namespace aliases to make the code easier to read.\n namespace gc = ::google::cloud;\n namespace otel = gc::otel;\n namespace pubsub = gc::pubsub;\n\n // This example uses a simple wrapper to export (upload) OTel tracing data\n // to Google Cloud Trace. More complex applications may use different\n // authentication, or configure their own OTel exporter.\n auto project = gc::Project(project_id);\n auto configuration = otel::ConfigureBasicTracing(project);\n\n auto publisher = pubsub::Publisher(pubsub::MakePublisherConnection(\n pubsub::Topic(project_id, topic_id),\n // Configure this publisher to enable OTel tracing. Some applications may\n // chose to disable tracing in some publishers or to dynamically enable\n // this option based on their own configuration.\n gc::Options{}.set\u003cgc::OpenTelemetryTracingOption\u003e(true)));\n\n // After this point, use the Cloud Pub/Sub C++ client library as usual.\n // In this example, we will send a few messages and configure a callback\n // action for each one.\n std::vector\u003cgc::future\u003cvoid\u003e\u003e ids;\n for (int i = 0; i \u003c 5; i++) {\n auto id = publisher.Publish(pubsub::MessageBuilder().SetData(\"Hi!\").Build())\n .then([](gc::future\u003cgc::StatusOr\u003cstd::string\u003e\u003e f) {\n auto id = f.get();\n if (!id) {\n std::cout \u003c\u003c \"Error in publish: \" \u003c\u003c id.status() \u003c\u003c \"\\n\";\n return;\n }\n std::cout \u003c\u003c \"Sent message with id: (\" \u003c\u003c *id \u003c\u003c \")\\n\";\n });\n ids.push_back(std::move(id));\n }\n // Block until the messages are actually sent.\n for (auto& id : ids) id.get();\n\n1. Compile and run the example:\n\n cd cpp-samples/pubsub-open-telemetry\n bazel run //:quickstart -- $(gcloud config get project) my-topic\n\n2. After running this example, you'll see the following lines printed to\n console.\n\n Sent message with id: (9095112996778043)\n Sent message with id: (9095112996778044)\n Sent message with id: (9095112996778045)\n Sent message with id: (9095112996778046)\n Sent message with id: (9095112996778047)\n\nView traces\n-----------\n\nIn the Google Cloud console, go to the **Trace explorer** page:\n\n[Go to **Trace explorer**](https://console.cloud.google.com/traces/explorer)\n\n\u003cbr /\u003e\n\nYou can also find this page by using the search bar.\n\nClean up\n--------\n\n\nTo avoid incurring charges to your Google Cloud account for\nthe resources used on this page, follow these steps.\n\n1. Delete the topic created by the example:\n\n gcloud pubsub topics delete my-topic\n\nWhat's next\n-----------\n\n- Learn more about [C++ and OpenTelemetry](/trace/docs/setup/cpp-ot).\n- Find more [C++ examples](/docs/samples/?language=cpp).\n- Learn more about [Pub/Sub APIs](/pubsub/docs/reference/service_apis_overview).\n- Try more [C++ Pub/Sub OpenTelemetry Examples](https://github.com/GoogleCloudPlatform/cpp-samples/tree/main/pubsub-open-telemetry)."]]