Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Speaking C

extern “C” and the ABI

When a C++ translation unit calls a function defined in a C library, the programmer adds the extern "C" specifier. The specifier directs the compiler to give the declared function C linkage, which disables name mangling and forces the calling convention defined by the C ABI for the target platform.

The ABI (application binary interface) is a contract between caller and callee. It defines the order in which arguments are placed, which registers hold return values, how the stack is cleaned, how variadic arguments are passed, how floating‑point values are promoted, and how structures are laid out in memory.

Name mangling exists because C++ encodes a function’s name, namespace, and parameter types into a single symbol so overloading works. C does not mangle names. Therefore a C function such as fopen is linked under the plain symbol fopen. A C++ declaration must carry C linkage, or the linker will look for a mangled name that does not exist. This is why every C header is wrapped in extern "C" { … } behind a guard, ensuring a C++ translation unit receives the correct linkage automatically.

The ABI is fixed per platform and shared by C and C++. A function with C linkage can be implemented in either language, but signatures must match exactly. Verify signatures when mixing C and C++ code. When a function is declared with extern "C" the C++ compiler pretends to be a C compiler for those details. This eliminates subtle mismatches that can corrupt the stack or misinterpret data.

extern "C" int c_func(int);

int main() {
    return c_func(42);
}

The example compiles with a C library that defines int c_func(int). The function can be called from C++ without any additional glue code.

C data shapes in C++

C strings are arrays of char terminated by a NUL byte. In C++ a borrowed view can be expressed with std::string_view. When the program needs ownership, copy the characters into a std::string. This avoids modifying memory owned by the C library.

C arrays map naturally to std::span. A span holds a pointer and a length without granting write access beyond the original array bounds. The span does not own the memory. It only observes it.

File handles such as FILE* are raw resources. The book’s RAII pattern wraps them in a class whose destructor calls fclose. The wrapper owns the handle, forbids copying, and transfers ownership via move semantics.

The mapping is not automatic. The programmer states it. A const char* from a C function is a borrowed view that is valid only as long as the C side keeps the buffer alive, so wrapping it in a std::string_view inherits that lifetime and must not outlive the buffer. Copying into a std::string breaks the dependency and is the right move when the value must persist. The same reasoning governs every C pointer: the C++ type you wrap it in must match what the C API actually guarantees.

errno and errors

Many C functions report failure by returning a sentinel value such as -1 and setting the global variable errno. The C++ library std::expected offers a modern way to model this pattern. The wrapper converts the sentinel return and the errno value into a rich error object. The example uses open to demonstrate conversion. When open fails the wrapper returns std::unexpected<std::string> that contains the error message from strerror(errno). The caller can test the std::expected and handle success or failure without consulting a global variable.

errno is thread‑local, but reading it later risks a race: another call can overwrite it before the value is captured. The wrapper records errno at the failure point, turning it into a value that travels with the result via std::expected. This avoids the race and applies to any C API that uses a sentinel plus a side channel.

#include <cstdio>
#include <cerrno>
#include <cstring>
#include <print>
#include <expected>
#include <string>

using namespace std;

auto open_file(const char* path) -> expected<FILE*, string> {
    FILE* f = fopen(path, "r");
    if (!f) {
        return unexpected<string>(strerror(errno));
    }
    return f;
}

int main() {
    // Attempt to open a file that the current user cannot read.
    // On Unix systems "/root/secret" is typically inaccessible.
    auto result = open_file("/root/secret");
    if (result) {
        std::println("opened");
        fclose(*result);
    } else {
        std::println("error: {}", result.error());
    }
    return 0;
}

The test expects the word “error” in the output when the call fails.

Wrapping a C API in RAII

Applying the RAII pattern at the language boundary writes safe C++ code that manages a C resource automatically. The wrapper stores the raw FILE* and calls fclose in its destructor. The class deletes copy operations because ownership cannot be duplicated. Move construction transfers the pointer and leaves the source empty. The wrapper also provides a convenient write_line method that writes a line and flushes the stream. The example creates a temporary file, writes a line, and then reads the file through a second wrapper instance. The destructor of each instance closes the file automatically.

The wrapper is the template for every C boundary. It owns exactly one resource, deletes copy so ownership cannot be duplicated, and moves the handle by transferring the pointer and nulling the source. The destructor runs even when an exception unwinds, which is the guarantee that makes the wrapper safe where a bare fclose after an early return is not. A std::unique_ptr with a custom deleter is the standard spelling of the same idea, but a hand-rolled wrapper with a small API is often clearer at the boundary.

#include <cstdio>
#include <print>
#include <string_view>
#include <span>
#include <string>

// Simple RAII wrapper for FILE*
class file_handle {
    FILE* f_ = nullptr;
public:
    explicit file_handle(const char* path, const char* mode) : f_(std::fopen(path, mode)) {
        if (!f_) std::println("open failed");
        else std::println("opened");
    }
    // Delete copy – ownership cannot be duplicated.
    file_handle(const file_handle&) = delete;
    file_handle& operator=(const file_handle&) = delete;
    // Move transfers ownership.
    file_handle(file_handle&& other) noexcept : f_(other.f_) { other.f_ = nullptr; }
    file_handle& operator=(file_handle&& other) noexcept {
        if (this != &other) {
            if (f_) std::fclose(f_);
            f_ = other.f_; other.f_ = nullptr;
        }
        return *this;
    }
    ~file_handle() { if (f_) { std::fclose(f_); std::println("closed"); } }
    // Write a line and flush.
    void write_line(std::string_view line) {
        if (f_) {
            std::fwrite(line.data(), 1, line.size(), f_);
            std::fputc('\n', f_);
            std::fflush(f_);
        }
    }
    // Read the entire file into a string.
    std::string read_all() const {
        if (!f_) return {};
        // Seek to beginning.
        std::rewind(f_);
        std::string out;
        char buf[256];
        while (std::size_t n = std::fread(buf, 1, sizeof(buf), f_)) {
            out.append(buf, n);
        }
        return out;
    }
};

int main() {
    // Create a temporary file.
    const char* path = "tmp_ch28.txt";
    {
        file_handle fh(path, "w");
        fh.write_line("hello world");
    } // destructor closes file.
    // Reopen for reading.
    file_handle fh2(path, "r");
    std::string contents = fh2.read_all();
    std::println("content: {}", contents);
    return 0;
}

The test looks for the substring “hello world” in the program output.

Ownership at the boundary

The rule of ownership is simple. The C API owns any object that the documentation says the caller must free. Otherwise a returned pointer is borrowed. The gsl::owner annotation marks owned pointers, clarifying the contract for readers and static analysis tools. When ownership is transferred, the caller must release the resource with the matching free function. Borrowed pointers must not be freed. Misusing ownership leads to use‑after‑free or leaks, which the annotation helps prevent.

// gsl::owner<FILE*> file = fopen("path", "r");

Spans over C arrays

When a C library supplies an array the C++ side must receive it as a std::span. The span conveys the length of the array and prevents out-of-bounds writes. The wrapper can iterate safely using range-based for loops. The example defines a function sum_span that takes a std::span<const int> and returns the sum of its elements using std::accumulate. The test passes a C array to the function and expects the sum “15”.

A std::span carries a length, so the C++ side never guesses how many elements a C array holds, which is the classic source of buffer overruns. The span itself does no bounds checking at runtime, so it is not a replacement for a checked container. It is a non-owning view that tells the reader the exact extent of the borrowed data, which is exactly the information a C array pointer omits. When a C library hands back a pointer and a count separately, the C++ side combines them into a single std::span at the boundary, so the pair never travels separately through C++ code.

#include <print>
#include <span>
#include <numeric>

int sum_span(std::span<const int> s) {
    return std::accumulate(s.begin(), s.end(), 0);
}

int main() {
    int arr[] = {1,2,3,4,5};
    int total = sum_span(arr);
    std::println("sum: {}", total);
    return 0;
}

C23 helpers in C++26

C23 introduces <stdbit.h> and <stdckdint.h>. The header <stdbit.h> defines bit utilities such as stdc_bit_width. The header <stdckdint.h> defines overflow-checked arithmetic functions like ckd_add. These helpers are usable from C++26 code without additional wrappers. The example adds two int values with ckd_add. If overflow occurs the function returns -1 and sets errno. The test expects the word “overflow” when the addition exceeds the range of int.

Checked arithmetic matters because signed overflow is undefined behaviour in both C and C++. ckd_add performs the addition and reports whether it overflowed, so the code handles the failure instead of relying on undefined behaviour. Before this helper, the portable way to check was a comparison of the operands and the result, which is easy to get wrong. stdc_bit_width and the other <stdbit.h> utilities bring a full set of bit operations into C++ without a hand-rolled implementation.

#include <cstdio>
#include <cerrno>
#include <climits>
#include <print>
#include <stdckdint.h>

int main() {
    int a = INT_MAX;
    int b = 1;
    int sum = 0;
    if (ckd_add(&sum, a, b)) {
        std::println("overflow");
    } else {
        std::println("sum: {}", sum);
    }
    return 0;
}

Try this

Wrap the C standard library function qsort behind a range-friendly C++ interface. The wrapper must accept a std::span<T> and a comparator auto cmp. Inside the wrapper the call to qsort must use a static bridge function that forwards to the supplied comparator. The wrapper must hide the void* pointer and the function-pointer signature from the caller.

The bridge function is the crux. qsort takes a plain void* and a C function pointer, so the wrapper cannot pass a C++ lambda directly. It passes a static function that receives the array pointer, casts it back to the element type, and calls the supplied comparator through a const void* argument the comparator understands. The caller never sees the void* or the function-pointer signature. It passes a std::span and a normal C++ comparator, and the wrapper hides the C machinery.

**