NanoPB: How to handle optional fields in C++

See also: C version: How to handle optional fields in C

NanoPB is a code-size optimized Protocol Buffers implementation for embedded systems. This post shows how to handle optional fields (proto3 optional) in C++ with NanoPB.

Proto definition

First, create a .proto file with optional fields:

optional.proto
syntax = "proto3";

package example;

message OptionalMessage {
  optional uint32 id = 1;
  optional string name = 2;
  optional float temperature = 3;
  bool active = 4;  // Regular (non-optional) field
}

Generate NanoPB code

Generate the NanoPB code with a .options file to specify string buffer sizes:

Create optional.options:

example.txt
example.OptionalMessage.name max_size:64

Then generate:

example.sh
protoc --nanopb_out=. optional.proto

This will generate optional.pb.h and optional.pb.c.

C++ example

Here’s a complete C++ example handling optional fields:

optional_example.cpp
#include <stdio.h>
#include <string.h>
#include "optional.pb.h"
#include "pb_encode.h"
#include "pb_decode.h"

int main() {
    // Buffer for encoded message
    uint8_t buffer[256];
    size_t message_length;
    
    // --- ENCODING ---
    example_OptionalMessage message = example_OptionalMessage_init_zero;
    
    // Set optional fields
    message.id = 42;
    message.has_id = true;  // Important: set has_* flag
    
    strncpy(message.name, "Sensor1", sizeof(message.name) - 1);
    message.has_name = true;  // Important: set has_* flag
    
    message.temperature = 23.5f;
    message.has_temperature = true;  // Important: set has_* flag
    
    // Regular field (no has_* flag needed)
    message.active = true;
    
    // Create stream for encoding
    pb_ostream_t ostream = pb_ostream_from_buffer(buffer, sizeof(buffer));
    
    // Encode the message
    if (!pb_encode(&ostream, example_OptionalMessage_fields, &message)) {
        printf("Encoding failed: %s\n", PB_GET_ERROR(&ostream));
        return 1;
    }
    
    message_length = ostream.bytes_written;
    printf("Encoded %zu bytes\n", message_length);
    
    // Print hex dump of encoded data
    printf("Encoded data: ");
    for (size_t i = 0; i < message_length; i++) {
        printf("%02x ", buffer[i]);
    }
    printf("\n");
    
    // --- DECODING ---
    example_OptionalMessage decoded = example_OptionalMessage_init_zero;
    
    // Create stream for decoding
    pb_istream_t istream = pb_istream_from_buffer(buffer, message_length);
    
    // Decode the message
    if (!pb_decode(&istream, example_OptionalMessage_fields, &decoded)) {
        printf("Decoding failed: %s\n", PB_GET_ERROR(&istream));
        return 1;
    }
    
    // Print decoded values
    printf("Decoded values:\n");
    if (decoded.has_id) {
        printf("  id: %u\n", decoded.id);
    } else {
        printf("  id: (not set)\n");
    }
    
    if (decoded.has_name) {
        printf("  name: %s\n", decoded.name);
    } else {
        printf("  name: (not set)\n");
    }
    
    if (decoded.has_temperature) {
        printf("  temperature: %f\n", decoded.temperature);
    } else {
        printf("  temperature: (not set)\n");
    }
    
    printf("  active: %s\n", decoded.active ? "true" : "false");
    
    return 0;
}

Compile command

Compile the example with nanopb. NanoPB is typically used by including the source files directly in your project:

example.sh
g++ -o optional_example optional_example.cpp optional.pb.c pb_common.c pb_encode.c pb_decode.c -I.

Note: NanoPB source files (pb_common.c, pb_encode.c, pb_decode.c) need to be compiled directly with your project. You can obtain these from the NanoPB GitHub repository.

Python test script

To verify the encoding, you can use Python’s protobuf library:

test_optional.py
import optional_pb2

# Read the binary data
with open('encoded.bin', 'rb') as f:
    data = f.read()

# Decode
msg = optional_pb2.OptionalMessage()
msg.ParseFromString(data)

print("Python decoded values:")
print(f"  id: {msg.id if msg.HasField('id') else '(not set)'}")
print(f"  name: {msg.name if msg.HasField('name') else '(not set)'}")
print(f"  temperature: {msg.temperature if msg.HasField('temperature') else '(not set)'}")
print(f"  active: {msg.active}")

First, compile the Python protobuf definitions:

example.sh
protoc --python_out=. optional.proto

Then modify the C++ example to save the encoded data to a file:

example.cpp
// After encoding, add this:
FILE *f = fopen("encoded.bin", "wb");
fwrite(buffer, 1, message_length, f);
fclose(f);

Example with missing optional fields

Here’s an example where some optional fields are not set:

optional_partial_example.cpp
#include <stdio.h>
#include <string.h>
#include "optional.pb.h"
#include "pb_encode.h"
#include "pb_decode.h"

int main() {
    uint8_t buffer[256];
    size_t message_length;
    
    // --- ENCODING ---
    example_OptionalMessage message = example_OptionalMessage_init_zero;
    
    // Only set some optional fields
    message.id = 42;
    message.has_id = true;
    
    // name and temperature not set (has_* flags remain false)
    
    // Regular field always set
    message.active = true;
    
    pb_ostream_t ostream = pb_ostream_from_buffer(buffer, sizeof(buffer));
    
    if (!pb_encode(&ostream, example_OptionalMessage_fields, &message)) {
        printf("Encoding failed: %s\n", PB_GET_ERROR(&ostream));
        return 1;
    }
    
    message_length = ostream.bytes_written;
    printf("Encoded %zu bytes (partial)\n", message_length);
    
    // --- DECODING ---
    example_OptionalMessage decoded = example_OptionalMessage_init_zero;
    
    pb_istream_t istream = pb_istream_from_buffer(buffer, message_length);
    
    if (!pb_decode(&istream, example_OptionalMessage_fields, &decoded)) {
        printf("Decoding failed: %s\n", PB_GET_ERROR(&istream));
        return 1;
    }
    
    printf("Decoded values:\n");
    printf("  id: %s\n", decoded.has_id ? "set" : "not set");
    printf("  name: %s\n", decoded.has_name ? "set" : "not set");
    printf("  temperature: %s\n", decoded.has_temperature ? "set" : "not set");
    printf("  active: %s\n", decoded.active ? "true" : "false");
    
    return 0;
}

Key points

When to use optional fields

Expected output (full example)

example.txt
Encoded 19 bytes
Encoded data: 08 2a 12 07 53 65 6e 73 6f 72 31 1d 00 00 bc 41 30 01 
Decoded values:
  id: 42
  name: Sensor1
  temperature: 23.500000
  active: true

Expected output (partial example)

example.txt
Encoded 4 bytes (partial)
Encoded data: 08 2a 30 01 
Decoded values:
  id: set
  name: not set
  temperature: not set
  active: true

Note how the partial encoding is much smaller (4 bytes vs 19 bytes) because optional fields are omitted.

example.txt

## More NanoPB posts

- [Basic scalar types in C++](/2026/05/09/nanopb-cpp-basic-scalar-types/)
- [Basic scalar types in C](/2026/05/09/nanopb-c-basic-scalar-types/)
- [String types in C++](/2026/05/09/nanopb-cpp-string-types/)
- [String types in C](/2026/05/09/nanopb-c-string-types/)
- [Bytes types in C++](/2026/05/09/nanopb-cpp-bytes-types/)
- [Bytes types in C](/2026/05/09/nanopb-c-bytes-types/)
- [Optional fields in C](/2026/05/09/nanopb-c-optional-fields/)
- [Repeated fields/arrays in C++](/2026/05/09/nanopb-cpp-repeated-fields/)
- [Repeated fields/arrays in C](/2026/05/09/nanopb-c-repeated-fields/)
- [Enums in C++](/2026/05/09/nanopb-cpp-enums/)
- [Enums in C](/2026/05/09/nanopb-c-enums/)
- [Nested messages in C++](/2026/05/09/nanopb-cpp-nested-messages/)
- [Nested messages in C](/2026/05/09/nanopb-c-nested-messages/)
- [Oneof/union types in C++](/2026/05/09/nanopb-cpp-oneof-types/)
- [Oneof/union types in C](/2026/05/09/nanopb-c-oneof-types/)
- [Custom array converters in C++](/2026/05/09/nanopb-cpp-custom-array-converters/)
- [Custom array converters in C](/2026/05/09/nanopb-c-custom-array-converters/)

Check out similar posts by category: Embedded, C/C++, Protocol Buffers