Plugin architecture
What you will learn on this page
Section titled “What you will learn on this page”- What a host, a plugin API, and a plugin each own, and why the plugin API is the only part both sides see.
- How to write a plugin interface in C++ from plain data and small abstract classes, and how to classify each type in it.
- How a registry checks a plugin’s name and version before it creates the plugin, and owns what it creates.
- Why one explicit list of plugins is safer than plugins that register themselves from global objects.
- How to add to an interface in a later version without breaking the plugins written for the earlier one.
- What changes when plugins are loaded at run time from shared libraries, and when a plain factory is all a program needs.
The problem: every format is the host’s code
Section titled “The problem: every format is the host’s code”The registrar’s program prints a course roster. It started with text, then CSV was added for a spreadsheet, then Markdown for a wiki. Each format was another branch.
That works while one team writes every format. Then two departments ask for their own formats, which they want to write, test, and ship themselves. Now the problems show:
- Every new format changes the host. A department cannot add a format without editing, rebuilding, and releasing the program.
- A format sees the whole domain. Each branch reads
domain::Coursedirectly, so a change to the course breaks every format, including the ones other people wrote. - Nothing says what a format may rely on. If the host changes how it calls a format, there is no way to tell which formats were written for the old way.
- One broken format breaks the program. A format that throws ends the export, or the program, for everybody.
A plugin architecture turns this around. The host publishes a small plugin API: the data a plugin is given and the interface it implements. A plugin is code written against that API, which the host finds and uses without naming it in the host’s own code. The host decides what to accept, and the plugin decides only how to do its one job.
Step 1: classify the parts
Section titled “Step 1: classify the parts”Ask of each part: who writes it, what does it know, and what makes it change?
| Part | Written by | Knows | Changes when |
|---|---|---|---|
The domain (domain::Course) |
the program’s team | the rules | the rules change |
The plugin API (report_api) |
the program’s team, as a promise | only itself | rarely, and with a new version |
| A plugin (CSV, Markdown, …) | anyone | the plugin API | its own format changes |
| The host (registry and export) | the program’s team | the domain and the plugin API | how plugins are accepted or used |
| The list of plugins | the program’s team | each plugin’s entry point | a plugin is added or removed |
The API is the only part on both sides, so it gets the most care: it holds no host type and no domain type, and it changes only by adding a new version. Inside it, each type is chosen for its job:
- The data a plugin is given,
RowandRoster, are plain structs with public members. They have no rules to protect, and a plugin only reads them, so getters would add nothing. They are copies, so the domain can change without the plugins knowing. - The plugin interface,
ReportPlugin, is an abstract class with one pure virtualrenderand a public virtual destructor, because the host owns each plugin through astd::unique_ptr<ReportPlugin>and destroys it through that base.renderisconst: making a report does not change the plugin. - An optional capability,
HasFileExtension, is a second abstract class. Its destructor is protected and not virtual, because nobody destroys a plugin through it, and the protected destructor makesdeletethrough it a compile error. - A plugin’s introduction,
PluginInfo, is a value: a name, the version the plugin was built against, and a function that creates it. The host can read the first two without creating the plugin.
The plugin API
Section titled “The plugin API”The version comes first, so it is easy to find and to change:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Raised when the interface below changes. A plugin records the version// it was built against; the host accepts versions from oldest_supported// to version, and refuses others before it creates the plugin.// constexpr makes each one a constant known when the program is compiled.// `inline` lets this header define the variables in every file that// includes it while the program still has exactly one of each.inline constexpr int version = 2; // the API this header describesinline constexpr int oldest_supported = 1; // version 1 plugins still loadThe rest of the API is the data, the two interfaces, and the introduction:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// What a report is made from: plain data, copied out of the domain.// Row and Roster hold only strings, an int, and a vector: no domain type,// no pointer into the host. A plugin gets its own copy, so nothing it// does with the data can reach back into the course.// One line of the report: who, and where they stand.struct Row { std::string student; std::string place; // "seated", or "waiting 1" for the first in line};// The whole report's input: the course's code and title, its number of// seats, and one Row per student.struct Roster { std::string course; // the course code as text, such as "CS101" std::string title; int capacity; std::vector<Row> rows; // the seated first, then the waitlist in order};
// Version 1: every report plugin renders a roster.// An abstract class: the host holds every plugin as a ReportPlugin and// calls render without knowing which format it is talking to.class ReportPlugin {public: // The host owns each plugin through std::unique_ptr<ReportPlugin> and // deletes it through this base type. A virtual destructor makes that // delete run the real plugin's destructor too, not only this one. virtual ~ReportPlugin() = default; // Turns the roster into the finished report text. `= 0` means "no // body here": every plugin must write its own, and ReportPlugin // itself cannot be created. `const`: rendering changes nothing in the // plugin. A plugin may throw; the host catches it (export_roster). virtual std::string render(const Roster& roster) const = 0;};
// Added in version 2, without changing ReportPlugin, so version 1// plugins still compile and work. A plugin may also implement it; the// host asks with dynamic_cast and uses ".txt" if it does not.class HasFileExtension {public: // Such as ".csv". The text must stay valid while the plugin exists, // so return a literal or a member, never a temporary string. // std::string_view only points at characters someone else owns; it // does not copy them, which is why the rule above matters. virtual std::string_view file_extension() const = 0;
protected: // Protected: only a class derived from this one can call it, so code // that holds a HasFileExtension* cannot delete the plugin through it // (that would not compile). Not virtual, because the plugin is always // deleted through ReportPlugin, whose destructor is virtual. ~HasFileExtension() = default;};
// How a plugin introduces itself to the host.// A plain value. The host can read name and api_version, and refuse the// plugin, before anything of the plugin runs: only `create` runs its code.struct PluginInfo { std::string name; // what the user types, such as "csv" int api_version; // the `version` the plugin was built against // A stored function that takes nothing and returns a new plugin // object. std::function can hold any callable of that shape, usually // a lambda. The unique_ptr in the result says the caller (the host's // registry) becomes the plugin object's only owner. An empty // std::function converts to false, which the registry checks. std::function<std::unique_ptr<ReportPlugin>()> create;};- The header includes only the standard library. A plugin can be written, built, and tested by someone who does not have the host’s source.
Rosteris what a report is made from, not what the course is.placeis already worded (“waiting 1”), so every plugin shows the same thing, and no plugin needs to know how a waitlist works.renderreturns a string. The host decides where it goes, a file or the screen, so a plugin is never handed a file and has no reason to open one. Nothing stops code in the same process from doing so anyway; the dynamic loading section comes back to trust.createis astd::function. It is called once, by the host, after the checks; until then, a plugin is only a name and a number.
A plugin
Section titled “A plugin”Each plugin is its own small library with one entry point. The host sees only these functions:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// One function per plugin. Each plugin's class is hidden in its .cpp// file; this is all the host sees of it.// Each function returns the plugin's PluginInfo: its name, the API version// it was built against, and its factory. Calling one creates no plugin// object yet; only calling the returned `create` does that. The version// comments repeat what each function returns; test_plugins.cpp checks them.namespace plugins {
report_api::PluginInfo text_report(); // built against version 2report_api::PluginInfo csv_report(); // built against version 2report_api::PluginInfo markdown_report(); // built against version 1
} // namespace pluginsThe CSV plugin, built against version 2, implements both interfaces:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// A field with a comma, a quote, or a line break is quoted, and quotes// inside it are doubled, so a title like "Design, Part 1" stays one field.// Input: the text of one cell. Result: that text as CSV wants it, either// unchanged or wrapped in quotes. No text is refused.std::string field(std::string_view text) { // find_first_of looks for any one of the four characters (comma, // quote, carriage return, newline) and returns npos ("not found") if // there is none. Then the text is safe as it is: return a copy. if (text.find_first_of(",\"\r\n") == std::string_view::npos) return std::string{text}; std::string quoted = "\""; // the opening quote // Copy the text one character at a time. A quote is written twice // (CSV's way of saying "a quote inside the field"); any other // character is copied as it is. std::string{c} makes a one-character // string, so both sides of the ?: have the same type. for (const char c : text) quoted += (c == '"') ? std::string{"\"\""} : std::string{c}; return quoted + '"'; // the closing quote}
// The CSV format. `final`: nothing may derive from it. It inherits from// both interfaces: ReportPlugin (every plugin) and HasFileExtension (the// optional version 2 capability), so the host can ask it for ".csv".class CsvReport final : public report_api::ReportPlugin, public report_api::HasFileExtension {public: // One header line, then one line per row. The course and title are // repeated on every line, so each line makes sense on its own in a // spreadsheet. Every value goes through field(). `override` asks the // compiler to check that this really replaces render from the base. std::string render(const report_api::Roster& roster) const override { std::string out = "course,title,student,place\n"; for (const report_api::Row& row : roster.rows) { out += field(roster.course) + ',' + field(roster.title) + ',' + field(row.student) + ',' + field(row.place) + '\n'; } return out; } // A string literal lives for the whole program, so the view the host // receives can never point at freed memory. std::string_view file_extension() const override { return ".csv"; }};How this code works: CSV quoting with field
CSV separates fields with commas, so a comma inside a value would split
it in two. field protects each value before render joins them.
- Is there anything to protect?
find_first_oflooks for a comma, a quote, a carriage return, or a newline. If there is none, the value is returned unchanged. That is the usual case:S1,CS101, andseatedall come back as they went in. - Otherwise, wrap it.
quotedstarts as one quote character. - Copy each character. A quote inside the value is written twice; that is how CSV tells “a quote that is part of the text” from “the quote that ends the field”. Every other character is copied as it is.
- Close it with one more quote.
A worked example, from the plugin’s first test. The title is
Design, "Part 1":
| Step | What happens | quoted so far |
|---|---|---|
| check | the comma at index 6 is found, so quote it | (not started) |
| start | the opening quote | " |
Design, copied |
no quotes among them | "Design, |
first " |
written twice | "Design, "" |
Part 1 copied |
"Design, ""Part 1 |
|
second " |
written twice | "Design, ""Part 1"" |
| close | the closing quote | "Design, ""Part 1""" |
render then writes one line per row, for example
CS101,"Design, ""Part 1""",S1,seated, which a spreadsheet reads as four
fields, with the title back as Design, "Part 1".
- The class is in an anonymous namespace, so no other file can
name it, derive from it, or depend on its members. Only
csv_report(), outside that namespace, can create one. fieldis a free function, also hidden. It is CSV’s rule for quoting, needs no object, and is tested throughrender.- The class is
final. Nobody is meant to extend a plugin; they write another one.
The Markdown plugin was written against version 1, before
HasFileExtension existed, and was never changed:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// An older plugin, written against version 1: it knows nothing of// HasFileExtension, and still works.// It derives from ReportPlugin only, so the host's dynamic_cast to// HasFileExtension finds nothing and the file gets the default ".txt".class MarkdownReport final : public report_api::ReportPlugin {public: // A Markdown heading, a blank line, then a table with one row per // student. No escaping: a "|" in a name or title would break the // table, which this example does not handle. std::string render(const report_api::Roster& roster) const override { std::string out = "## " + roster.course + " " + roster.title + "\n\n"; // The table's header row, then the "|---|---|" line that Markdown // needs under a header to know it is a table. out += "| Student | Place |\n|---|---|\n"; for (const report_api::Row& row : roster.rows) { out += "| " + row.student + " | " + row.place + " |\n"; } return out; }};In the build, each plugin’s CMake target links only arch_report_api,
so the domain’s headers are not on a plugin’s include path. A plugin
that tried to include course.hpp would not build.
The registry
Section titled “The registry”The registry is the host’s side of the agreement. It owns one instance of each accepted plugin:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Owns one instance of each accepted plugin. Filled in at start-up,// then only read, so a pointer from find() stays valid as long as the// registry does.class Registry {public: // The answer to add: did the plugin get in, and a sentence saying so // or saying why not. A refusal is an ordinary result, not an // exception, so one bad plugin cannot stop start-up. struct Registration { bool accepted; std::string message; // "accepted csv (API 2)", or why it was refused }; // Checks the plugin's name, version, and factory, in that order; only // if all are fine does it call `create` and keep the new object. A // factory that throws or returns null is refused. Never throws for a // bad plugin. `info` is taken by value: add keeps what it needs. Registration add(report_api::PluginInfo info);
// A pointer the caller may use but must not delete: the registry // still owns the plugin. Takes a std::string_view, so a caller can // pass "csv" or any piece of text without building a std::string. const report_api::ReportPlugin* find(std::string_view name) const; // null if none std::vector<std::string> names() const; // sorted
private: // Name to plugin. Each std::unique_ptr owns one plugin object, which // is destroyed with the registry. std::map keeps its keys sorted, // which is why names() comes out sorted. std::less<> (with empty // angle brackets) lets find compare a std::string_view against the // std::string keys directly, without building a std::string first. std::map<std::string, std::unique_ptr<report_api::ReportPlugin>, std::less<>> plugins_;};addreturns aRegistration, notbool. The message is whatmainprints, so a refused plugin says why.findreturns a non-owning pointer, or null. It points at the plugin object itself, which the registry owns throughstd::unique_ptrand never moves, so the pointer stays valid as long as the registry does. There is noremove, so nothing destroys a plugin earlier.std::less<>letsfindlook up astd::string_viewwithout building astd::string.
add checks the cheap things first, and creates the plugin last:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Four cheap checks (a name, a free name, the version, a factory), each leaving at once. Only// then is the plugin created, and it is refused if creating it throws or// gives nothing. Nothing is added to plugins_ until every step passed, so// a refused plugin leaves the registry unchanged.Registry::Registration Registry::add(report_api::PluginInfo info) { const std::string name = info.name; // a copy, used in every message // A small helper for every refusal, so they all read the same way: // refuse("why") gives {false, "refused csv: why"}. [&name] lets the // lambda read `name` without copying it. A plugin with no name is // called "a plugin" in the message, because there is no name to show. const auto refuse = [&name](const std::string& why) { return Registration{false, "refused " + (name.empty() ? "a plugin" : name) + ": " + why}; }; if (name.empty()) return refuse("it has no name"); // count is 1 if the name is already a key, else 0: the first plugin // to register a name keeps it, and later ones are refused. if (plugins_.count(name) != 0) return refuse("the name is already taken"); // Checked before create(): a plugin built for another version may not // even construct correctly against this program. Accepted: from // oldest_supported to version, both included (1 and 2 today). if (info.api_version < report_api::oldest_supported || info.api_version > report_api::version) { return refuse("built for API " + std::to_string(info.api_version) + "; this program supports " + std::to_string(report_api::oldest_supported) + " to " + std::to_string(report_api::version)); } // An empty std::function holds nothing to call (calling it would throw // std::bad_function_call), and converts to false. if (!info.create) return refuse("it has no factory");
// The first time any of the plugin's own code runs. `plugin` starts // empty (null) and receives the new object if create succeeds. std::unique_ptr<report_api::ReportPlugin> plugin; try { plugin = info.create(); } catch (const std::exception& error) { // Any standard exception: its what() text explains the failure. return refuse(std::string{"it failed to start: "} + error.what()); } catch (...) { // `...` catches anything else thrown, even `throw 42`, which has // no message to show. return refuse("it failed to start"); } if (!plugin) return refuse("it created nothing"); // a factory returned null // Hand ownership to the map: std::move lets the new map entry take the // object over, and the local `plugin` is left null. The duplicate check // above means emplace always inserts here. plugins_.emplace(name, std::move(plugin)); // The braces build a Registration: accepted, and the message. return {true, "accepted " + name + " (API " + std::to_string(info.api_version) + ")"};}How this code works: Registry::add
add is a row of gates. Each one either lets the plugin through or
leaves at once with return refuse(...), and nothing is stored until
the last gate is passed.
- Copy the name, because every message uses it, and build the
helper
refuse, which turns a reason into{false, "refused NAME: reason"}. - No name? Refused: the user could never ask for it.
- Name already taken? Refused: the first plugin keeps its name.
- Version outside 1 to 2? Refused, and the plugin’s
createis never called, so none of its code runs. - No factory? Refused: an empty
std::functionhas nothing to call. - Create it. This is the first time the plugin’s own code runs. If
it throws anything, the
catchturns that into a refusal; if it returns a null pointer, that is refused too. - Keep it.
std::move(plugin)hands the new object to the map. From here the registry is its only owner, andfindlends out plain pointers to it.
Trace: what main registers. These are the five calls in main, in
order, and the messages it prints:
| Call | Name | Version | Gate that decides | Message |
|---|---|---|---|---|
plugins::text_report() |
text |
2 | all passed | accepted text (API 2) |
plugins::csv_report() |
csv |
2 | all passed | accepted csv (API 2) |
plugins::markdown_report() |
markdown |
1 | all passed | accepted markdown (API 1) |
plugins::csv_report() |
csv |
2 | 3: name already taken | refused csv: the name is already taken |
plugin_from_a_newer_sdk() |
sheets |
3 | 4: version | refused sheets: built for API 3; this program supports 1 to 2 |
The sheets factory throws if called. Because its message names the
version, not “it failed to start”, the trace shows the factory was
never called.
- The version is checked before
create. A plugin built for version 3 expects things this program does not have; creating it could fail in ways that are hard to read, so it is never created. - A factory that throws is refused, whatever it throws, and the
other plugins still load. A department’s plugin whose factory
throws does not stop the program from starting. Only exceptions are
contained this way: a plugin that dereferences a null pointer, or
calls
std::terminate, still ends the program, because it runs in the program’s process. - A name can be taken only once. The first plugin keeps it. A silent replacement would make the output depend on the order of registration, which nobody would think to check.
Registration: one list
Section titled “Registration: one list”Something must tell the registry which plugins exist. In this
example, that is one function, called from main:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The one place that lists the program's plugins. Adding one is a new// library, its declaration in plugins.hpp, a line here, and two names in// CMakeLists.txt (the plugin list and the host's links); nothing else in// the host changes.// Input: the registry to fill (borrowed by reference; the caller owns it).// Result: the message from each add, in the order of the list, accepted// or refused alike, so the caller can show what happened.std::vector<std::string> add_builtin_plugins(Registry& registry) { std::vector<std::string> messages; // The braces make a std::initializer_list holding the three PluginInfo // values, in this order, and the loop visits each. Its items cannot // be changed, so add (which takes PluginInfo by value) gets a copy. for (const report_api::PluginInfo& info : {plugins::text_report(), plugins::csv_report(), plugins::markdown_report()}) { messages.push_back(registry.add(info).message); // keep only the sentence } return messages;}This is static registration: every plugin is linked into the
program, and the list is written down. Adding a plugin is a new
library, a declaration of its function in plugins/plugins.hpp, one
line here, and two names in CMakeLists.txt: the list of
plugin libraries, and the host’s links. The host’s registry and
export code do not change, which is the point.
The list is code the program’s team owns, so it is also where a plugin can be left out of a build, or put first, without asking its author.
It looks like it needs no list. It has three problems:
- Initialization order across files is not specified. The order
in which global objects in different source files are initialized
is unspecified, so this can run before the registry it uses exists,
unless
global_registry()creates it on first use. Even then, the order of registration follows the link order, so with “the first plugin keeps the name”, which of two plugins with the same name wins can change when the build changes. An implementation may also delay this initialization until something in the same file is used, which for a self-registering file may be never. - The linker can drop it. When a plugin is in a static library, and nothing refers to anything in its object file, the linker can leave that file out, with its registration. The format silently does not exist, and only in some programs.
- There must be a global registry. A test can still build its own registry, but the global one is filled as well, and every program that links the plugin gets it, whether it wants it or not.
Factory Method shows the same warning for a registry of makers. The explicit list costs one line per plugin, and in return the order, the set, and the failures are all visible in one place.
Using a plugin
Section titled “Using a plugin”The host gives a plugin a copy of what it needs, never the domain itself:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Copies the course into the plugin API's plain data. Plugins never see// domain::Course, so the domain can change without rebuilding them.// Rows: the seated students as "seated", then the waitlist in order as// "waiting 1", "waiting 2", and so on. The course is only read.report_api::Roster to_report(const domain::Course& course);
// "roster-CS101.csv" and the report; or a message naming the formats,// or saying that the plugin failed.// Inputs: the registry to look `format` up in, the format name the user// typed, and the course. All three are only borrowed for the call. The// result is always text (its own messages end in a newline): an unknown// format and a plugin that throws are reported in it, not thrown.std::string export_roster(const Registry& registry, std::string_view format, const domain::Course& course);VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
std::string export_roster(const Registry& registry, std::string_view format, const domain::Course& course) { // Borrowed, not owned: the registry keeps the plugin alive, and this // function only uses it before returning. const report_api::ReportPlugin* plugin = registry.find(format); if (plugin == nullptr) { // Join the sorted names with ", " between them: nothing before the // first name (known is still empty), ", " before each later one. // With text, csv, and markdown this builds "csv, markdown, text". std::string known; for (const std::string& name : registry.names()) known += (known.empty() ? "" : ", ") + name; return "unknown format '" + std::string{format} + "'; try " + known + '\n'; } // The host's own code, outside the try below: the plugin gets its own // copy, a local that lives until this function returns. const report_api::Roster roster = to_report(course); // Everything below calls the plugin, which is code the host did not // write: a failure in it ends this export, not the program. try { // A version 1 plugin does not implement HasFileExtension. // dynamic_cast asks, while the program runs, "is the object this // points at also a HasFileExtension?". It gives a pointer to that // part of the object if so, and nullptr if not; it never throws // for a pointer. This works because ReportPlugin has virtual // functions, which give each object the type information it needs. const auto* extension = dynamic_cast<const report_api::HasFileExtension*>(plugin); // The plugin's own extension if it has one, else the default. const std::string_view suffix = extension != nullptr ? extension->file_extension() : ".txt"; // std::string{suffix}: in C++20, + cannot join a std::string and a // std::string_view, so the view is first copied into a string. const std::string file = "roster-" + roster.course + std::string{suffix}; // The first line is the file name, then the plugin's report. return file + '\n' + plugin->render(roster); } catch (const std::exception& error) { // The plugin threw: turn it into a message. This export ends here, // and the caller (and the program) carries on. return "the " + std::string{format} + " plugin failed: " + error.what() + '\n'; } catch (...) { return "the " + std::string{format} + " plugin failed\n"; }}How this code works: One export, from main to a plugin and back
Follow > export csv from the output through the modules. The course is
CS101, “Software Design”, two seats, with S1 and S2 seated and S3
waiting.
main(the program) callshost::export_roster(registry, "csv", course). It lends all three: the registry and the course byconstreference, the format as astd::string_view. Nothing is copied yet.export_rosterasks the registry withregistry.find("csv"). The map finds thecsventry and returns a plain pointer to theCsvReportobject. The registry still owns it, through itsstd::unique_ptr;export_rosteronly borrows it for this call.- The host crosses the boundary with a copy.
to_report(course)builds aRoster: courseCS101, titleSoftware Design, capacity 2, rowsS1 seated,S2 seated,S3 waiting 1. This is the boundary: from here on, the plugin sees onlyreport_apitypes, neverdomain::Course. - The optional capability.
dynamic_castfinds thatCsvReportalso is aHasFileExtension, sosuffixis.csvand the file name isroster-CS101.csv. - The plugin does its work.
render(roster)returns the header line and three lines, one per row. - Back to
main.export_rosterreturns"roster-CS101.csv\n"followed by the report;mainprints it after> export csv. The localRosteris destroyed as the function returns; the plugin object stays in the registry for the next export.
Who owns what during the call:
| Object | Owner | Lives until |
|---|---|---|
course |
main, a local |
main returns |
registry |
main, a local |
main returns |
the CsvReport object |
the registry, through std::unique_ptr |
the registry is destroyed |
plugin (the pointer) |
nobody: it only borrows | export_roster returns |
roster (the copy) |
export_roster, a local |
export_roster returns |
| the returned text | main, as a temporary it prints |
the end of the print statement |
The other three exports take different turns. For markdown, step 4
gets nullptr, because a version 1 plugin is not a HasFileExtension,
so the file is roster-CS101.txt. For text, the plugin’s own
extension is also .txt. For xml, step 2 gets nullptr, and the
function returns at once with the sorted names joined by commas:
unknown format 'xml'; try csv, markdown, text. No Roster is built
and no plugin runs. If a plugin threw in step 4 or 5, a catch would
turn it into a message such as the broken plugin failed: template missing, as the last export test checks.
- An unknown format lists the known ones, from
names(), so the message stays right as plugins are added. - The extension is an optional capability.
dynamic_castasks whether this plugin also implementsHasFileExtension. The text and CSV plugins do; the version 1 Markdown plugin cannot, and gets.txt. Even in version 2 the interface is optional, so the host must always handle both. - A failure in the plugin ends this export, not the program. The
roster is copied first, by the host’s own code, outside the
try. Everything inside it calls the plugin,file_extensionas well asrender, and the host did not write that code, so it treats the plugin’s exceptions as a reported failure, like any other input it does not control. file_extensionreturns astd::string_view, so the API’s comment states the rule a plugin must follow: the text must outlive the call. A literal or a member does; a temporarystd::stringwould compile and leave the host reading freed memory.
The parts and what each one depends on:
Text description of the diagram
A component diagram with seven boxes. main creates the Registry, calls add_builtin_plugins, the one list, and exports with export_roster. The list calls the entry points of the plugins, text, csv, and markdown, and adds each PluginInfo to the Registry, which checks and owns. export_roster finds a plugin in the Registry, reads the domain Course, and calls render with a Roster through report_api, the data, interfaces, and version. The Registry owns the instances through report_api. The plugins implement report_api, shown as a dashed arrow. No arrow goes from the plugins to the host or to the domain, and in the host only the list names the plugins.
Diagram source (Mermaid)
flowchart LR
Main["main"]
List["add_builtin_plugins<br/>the one list"]
Reg["Registry<br/>checks and owns"]
Exp["export_roster<br/>copies and calls"]
Dom["domain Course"]
API["report_api<br/>data, interfaces, version"]
P["plugins<br/>text, csv, markdown"]
Main -->|creates| Reg
Main -->|calls| List
Main -->|exports with| Exp
List -->|calls entry points of| P
List -->|add PluginInfo| Reg
Exp -->|find| Reg
Exp -->|reads| Dom
Exp -->|render Roster| API
Reg -->|owns instances through| API
P -.->|implements| API(main also calls plugins::csv_report() once, to show that a
second plugin with a taken name is refused; that call is only for the
demonstration.)
Versioning the interface
Section titled “Versioning the interface”A plugin API is a promise to people whose code you cannot change. The version number says which promise a plugin was built against, and the host’s range says which promises it still keeps. In this example:
- Version 1 had
Row,Roster,ReportPlugin, andPluginInfo. - Version 2 added
HasFileExtension. It did not changeReportPlugin, so version 1 plugins still compile, still work, and are still accepted; the host gives them a default. - Version 3 does not exist yet. A plugin claiming it is refused, because it may rely on something this host does not have.
In this example the number is a literal each plugin’s author writes,
such as {"markdown", 1, ...}: it records which promise the author
wrote and tested against, even though every plugin is compiled
against the current header. Writing report_api::version there
instead would claim the newest version on every rebuild, whether or
not the author checked the plugin against it. With dynamic loading,
where each plugin is compiled once against the header it shipped
with, report_api::version compiled into the plugin is the right
value. A plugin that claims a version newer than the host, like
sheets below, really happens only then, or when plugins are built
from a newer copy of the API than the host’s.
The rule that made version 2 safe: add, do not change. Each kind of change has a different cost. “Rebuilt” means the plugin is compiled again against the new header; “not rebuilt” means an old, already compiled plugin is loaded by the new host, which only happens with dynamic loading.
| Change to the API | Plugin rebuilt | Plugin not rebuilt |
|---|---|---|
| Add a new optional interface | works | works; the host sees it is missing |
Add a pure virtual function to ReportPlugin |
does not compile | breaks |
| Add a virtual function with a default body | works | breaks: the plugin’s compiled class has no slot for it |
Add a member to Roster |
works if it has a default member initializer | not guaranteed: undefined, even if it seems to work |
Change what place means |
compiles, but wrong | runs, but wrong |
- A new member needs a default. The example builds with
-Wextra -Werror, and-Wextraincludes-Wmissing-field-initializers: code that builds aRosterwith braces and leaves out the new member stops compiling. With GCC 11.4 that includes designated initializers; with Clang 14 only positional ones. A member declared with a default, such asstd::string made_on = {};, gave no warning with either. A plugin that is not rebuilt is worse off: its compiled code still assumes the old type. A member added at the end may seem to work when only read throughconst Roster&, but the program is then using two different definitions of one type, which is undefined behaviour, and a member inserted in the middle, or one added toRow, breaks outright. - The last row is why the number matters even with static plugins. The compiler catches a changed signature; it does not catch a changed meaning. If “waiting 1” became “1” in version 3, every plugin written for version 2 would print the wrong thing.
- Dropping a version is raising
oldest_supported. Do it on purpose, announce it a release ahead, and let the refusal message say what to do. - A plugin can implement more than one version’s interfaces, which is how optional capabilities grow: a later version adds another small interface, and a plugin implements it when its author updates it.
Loading plugins at run time
Section titled “Loading plugins at run time”Every plugin in this example is linked into the program. That covers plugins written by other teams in the same organization, who can send a change to the list. It does not cover plugins that must be added after the program is built: by a customer, from a directory, or without a new release. Those are loaded from shared libraries at run time, and that changes several things. The example does not do this; the rest of this section describes it.
With dynamic loading, the registry’s checks and refusal messages keep
their purpose, but two things change. The version must be read
before any C++ type is touched, through a C function such as
extern "C" int lld_report_api_version(), because reading
PluginInfo::name, a std::string, from a library built with a
different standard library is already undefined. And the registry
owns the library handles as well as the instances, in the order the
lifetime bullet gives.
Running it
Section titled “Running it”main registers the built-in plugins, then tries a second CSV plugin
and one built for version 3:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// A plugin built against a newer SDK than this program's. The host must// refuse it without creating it.// Its PluginInfo says API 3, one more than this program's version 2. Its// factory throws, so if the registry ever called it, the refusal message// would say "it failed to start" instead of naming the version.// `-> std::unique_ptr<...>` states the lambda's return type: a body with// no return statement would otherwise make it void, which `create` cannot hold.report_api::PluginInfo plugin_from_a_newer_sdk() { return {"sheets", 3, []() -> std::unique_ptr<report_api::ReportPlugin> { throw std::logic_error("a refused plugin must not be created"); }};}VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Builds one course, fills the registry, then exports the course in four// formats. The registry is a local here: it owns the plugin objects, and// they are destroyed when main returns.int main() { // parse returns an optional (a code, or nothing if the text is not a // valid code). `*` takes the code out; "CS101" is valid, so it is // there. The helper id(), above, does the same for a StudentId. Two // seats: S1 and S2 are seated, and S3 goes on the waitlist. domain::Course course{*domain::CourseCode::parse("CS101"), "Software Design", 2}; for (const char* student : {"S1", "S2", "S3"}) course.enroll(id(student));
host::Registry registry; std::cout << "plugins:\n"; // text, csv, and markdown, all accepted: three "accepted" lines. for (const std::string& message : host::add_builtin_plugins(registry)) { std::cout << " " << message << '\n'; } std::cout << " " << registry.add(plugins::csv_report()).message << '\n'; // a second csv std::cout << " " << registry.add(plugin_from_a_newer_sdk()).message << '\n';
// "xml" is not registered, so its export prints the known formats. for (const char* format : {"text", "csv", "markdown", "xml"}) { std::cout << "> export " << format << '\n' << host::export_roster(registry, format, course); }}plugins: accepted text (API 2) accepted csv (API 2) accepted markdown (API 1) refused csv: the name is already taken refused sheets: built for API 3; this program supports 1 to 2> export textroster-CS101.txtCS101 Software Design (2 seats) S1 seated S2 seated S3 waiting 1> export csvroster-CS101.csvcourse,title,student,placeCS101,Software Design,S1,seatedCS101,Software Design,S2,seatedCS101,Software Design,S3,waiting 1> export markdownroster-CS101.txt## CS101 Software Design
| Student | Place ||---|---|| S1 | seated || S2 | seated || S3 | waiting 1 |> export xmlunknown format 'xml'; try csv, markdown, textReading the output:
- Three plugins are accepted, two at version 2 and Markdown at version 1, all with the same host.
- The second
csvis refused and the first one keeps the name. sheetsis refused by its version. Its factory would throw if called, andaddwould then say “it failed to start”. The message names the version instead, so the factory never ran.- Markdown’s file is
roster-CS101.txt: a version 1 plugin has no extension, and the host’s default applies. xmllists the formats there are, sorted, from the registry.
interface (abstract class) report_api::ReportPlugin
version 1, owned through unique_ptr
Member functions
virtual ~ReportPlugin();virtual std::string render(const Roster& roster) const = 0;
interface (abstract class) report_api::HasFileExtension
version 2, optional
Data members
~HasFileExtension();protected, not virtual
Member functions
virtual std::string_view file_extension() const = 0;
class report_api::PluginInfo
a struct, read before create
Member functions
std::string name;int api_version;std::function<std::unique_ptr<ReportPlugin>()> create;
class report_api::Roster
a struct of plain data, a copy
Member functions
std::string course;and title, capacitystd::vector<Row> rows;
class plugins::CsvReport
final, hidden, implements both interfaces
Member functions
std::string render(const report_api::Roster& roster) const override;std::string_view file_extension() const override;
class host::Registry
filled at start-up, then read
Data members
std::map<std::string, std::unique_ptr<report_api::ReportPlugin>, std::less<>> plugins_;
Member functions
Registration add(report_api::PluginInfo info);const report_api::ReportPlugin* find(std::string_view name) const;non-owning, or nullstd::vector<std::string> names() const;
Testing each part
Section titled “Testing each part”A plugin is tested through its API alone, with no host and no domain. This is what another team’s tests look like:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// A plugin is tested through its API alone: no host, no domain.// LLD_TEST(name) defines one test. LLD_CHECK(condition) records a failure// if the condition is false; LLD_CHECK_EQ(actual, expected) records one// if the two are not equal, and prints both. They come from the site's// small test header, lld_test.hpp. sample(title), defined above, builds// a Roster for CS101 with two seats, S1 seated and S3 "waiting 1".
// Sets up: a title with a comma and two quotes. Proves: the title is// wrapped in quotes and each inner quote is doubled, on every line.LLD_TEST(csv_quotes_a_field_with_a_comma_or_a_quote) { // Call the entry point, then its factory at once: `csv` is the // std::unique_ptr that owns the new CsvReport for the whole test. const auto csv = plugins::csv_report().create(); // The expected text is three string literals in a row, which C++ // joins into one. Inside them, \" is a quote character. LLD_CHECK_EQ(csv->render(sample("Design, \"Part 1\"")), std::string{"course,title,student,place\n" "CS101,\"Design, \"\"Part 1\"\"\",S1,seated\n" "CS101,\"Design, \"\"Part 1\"\"\",S3,waiting 1\n"});}
// Proves: each entry point reports the version the registry will check.// Only the PluginInfo is read; no plugin object is created.LLD_TEST(each_plugin_declares_the_version_it_was_built_against) { LLD_CHECK_EQ(plugins::text_report().api_version, 2); LLD_CHECK_EQ(plugins::csv_report().api_version, 2); LLD_CHECK_EQ(plugins::markdown_report().api_version, 1);}
// Sets up: one version 2 plugin (csv) and one version 1 plugin// (markdown). Proves: the same dynamic_cast the host uses finds the// extension on the first and gives nullptr for the second.LLD_TEST(only_version_2_plugins_report_a_file_extension) { const auto csv = plugins::csv_report().create(); const auto markdown = plugins::markdown_report().create(); // .get() lends the raw pointer; the unique_ptr still owns the object. const auto* csv_extension = dynamic_cast<const report_api::HasFileExtension*>(csv.get()); LLD_CHECK(csv_extension != nullptr); LLD_CHECK_EQ(std::string{csv_extension->file_extension()}, std::string{".csv"}); LLD_CHECK(dynamic_cast<const report_api::HasFileExtension*>(markdown.get()) == nullptr);}The registry is tested with a small fake plugin, Echo, so its
tests do not depend on any real format. One test checks that a
refused plugin is never created, by recording whether its factory
ran:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// These tests use a fake plugin, Echo (defined above), whose render just// returns the course code. echo(name, version) builds a PluginInfo for// it, so each test chooses the name and the version it needs.
// Sets up: one plugin at the current version. Proves: it is accepted with// the expected message, find returns it by name, and an unknown name// gives nullptr.LLD_TEST(an_accepted_plugin_can_be_found_by_name) { host::Registry registry; const host::Registry::Registration added = registry.add(echo("echo", report_api::version)); LLD_CHECK(added.accepted); LLD_CHECK_EQ(added.message, std::string{"accepted echo (API 2)"}); LLD_CHECK(registry.find("echo") != nullptr); LLD_CHECK(registry.find("other") == nullptr);}
// Sets up: the same name registered twice. Proves: the second add is// refused and says why. The first add's result is not needed here.LLD_TEST(a_second_plugin_with_the_same_name_is_refused) { host::Registry registry; registry.add(echo("echo", 2)); const host::Registry::Registration again = registry.add(echo("echo", 2)); LLD_CHECK(!again.accepted); LLD_CHECK_EQ(again.message, std::string{"refused echo: the name is already taken"});}
// Sets up: one plugin one version too new (3), and one too old (0).// Proves: both are refused, neither factory ran, and the registry is// still empty.LLD_TEST(a_version_outside_the_supported_range_is_refused_before_it_is_created) { host::Registry registry; bool created = false; // The factory captures `created` by reference ([&created]), so if // anything calls it, the test's own variable becomes true. The copy // of `newer` that add receives still refers to the same variable. report_api::PluginInfo newer{"newer", report_api::version + 1, [&created] { created = true; return std::make_unique<Echo>(); }}; LLD_CHECK(!registry.add(newer).accepted); LLD_CHECK(!registry.add(echo("older", report_api::oldest_supported - 1)).accepted); LLD_CHECK(!created); LLD_CHECK(registry.names().empty());}
// Sets up: a factory that throws a std::runtime_error, then a good// plugin. Proves: the refusal includes the exception's text, and the good// plugin is still accepted afterwards, alone in the registry.LLD_TEST(a_plugin_that_fails_to_start_is_refused_and_the_rest_still_load) { host::Registry registry; const host::Registry::Registration broken = registry.add( {"broken", 2, []() -> std::unique_ptr<report_api::ReportPlugin> { throw std::runtime_error("no template file"); }}); registry.add(echo("echo", 2)); LLD_CHECK_EQ(broken.message, std::string{"refused broken: it failed to start: no template file"}); LLD_CHECK(registry.names() == std::vector<std::string>{"echo"});}
// Sets up: a factory that throws an int, which is not a std::exception.// Proves: the catch (...) branch refuses it, with no exception text.LLD_TEST(a_factory_that_throws_anything_is_refused) { host::Registry registry; const host::Registry::Registration odd = registry.add({"odd", 2, []() -> std::unique_ptr<report_api::ReportPlugin> { throw 42; }}); LLD_CHECK_EQ(odd.message, std::string{"refused odd: it failed to start"});}The export tests check the copy into Roster, the default extension
for a version 1 plugin, and that a failing plugin produces a message:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// course(), defined above, makes CS101 with one seat: S1 is seated and S2// is waiting. Failing, also above, is a plugin whose render always throws// std::runtime_error("template missing").
// Proves: to_report puts the seated student first, then the waitlist,// and words the place as "waiting 1".LLD_TEST(the_roster_lists_the_seated_then_the_waitlist_in_order) { const report_api::Roster roster = host::to_report(course()); // std::size_t{2}: the same type as size(), so the two compare cleanly. LLD_CHECK_EQ(roster.rows.size(), std::size_t{2}); LLD_CHECK_EQ(roster.rows[0].place, std::string{"seated"}); LLD_CHECK_EQ(roster.rows[1].student, std::string{"S2"}); LLD_CHECK_EQ(roster.rows[1].place, std::string{"waiting 1"});}
// Proves: a plugin without HasFileExtension gets ".txt" in its file name.LLD_TEST(a_version_1_plugin_gets_the_default_extension) { host::Registry registry; registry.add(plugins::markdown_report()); const std::string out = host::export_roster(registry, "markdown", course()); // substr(0, find('\n')) keeps the text before the first newline: the // file-name line. LLD_CHECK_EQ(out.substr(0, out.find('\n')), std::string{"roster-CS101.txt"});}
// Proves: an unknown format is answered with the registered names// (here only markdown), not with an exception.LLD_TEST(an_unknown_format_names_the_ones_there_are) { host::Registry registry; registry.add(plugins::markdown_report()); LLD_CHECK_EQ(host::export_roster(registry, "xml", course()), std::string{"unknown format 'xml'; try markdown\n"});}
// Sets up: Failing, registered as "broken". Proves: its exception from// render becomes the returned message, and the test keeps running.LLD_TEST(a_plugin_that_fails_while_rendering_does_not_stop_the_program) { host::Registry registry; // The braces build the PluginInfo in place: name, version, factory. registry.add({"broken", 2, [] { return std::make_unique<Failing>(); }}); LLD_CHECK_EQ(host::export_roster(registry, "broken", course()), std::string{"the broken plugin failed: template missing\n"});}Static or dynamic plugins
Section titled “Static or dynamic plugins”| Question | Static (this example) | Dynamic (shared libraries) |
|---|---|---|
| Who can add a plugin? | anyone who can change the build | anyone who can put a file where the host looks |
| When is a plugin added? | when the program is built | when the program starts, or later |
| What catches an incompatible plugin? | the compiler, and the version for meaning | only the version check and the ABI |
| What may cross the boundary? | any C++ type | what both sides agree on; often only C types |
| A broken plugin | caught by the build and tests, if they cover it; can still crash the program | can crash the program, and may never have been tested with this host |
| Testing | ordinary unit tests | also needs tests that load the real files |
When it fits
Section titled “When it fits”- Other people add features, of one kind, through one narrow interface: report formats, importers, payment methods, editor commands, rules for each department.
- Those people release on their own schedule, so the host must keep working with plugins written for an older interface.
- The extension point is small and stable: “render this roster” is unlikely to change, so a promise about it is cheap to keep.
- Customers must add features without a new release, which is when dynamic loading is worth its cost.
It fits badly when:
- Plugins need the whole domain. If a “plugin” must read and change courses, students, and billing, the API becomes the domain, and every domain change is a breaking change. That is a module, as on Modular monolith, not a plugin.
- The host must control what plugins do in detail. A plugin decides how to do its job; if every step is checked or overridden, a configuration file or a set of options is simpler.
Common mistakes
Section titled “Common mistakes”- Passing domain objects to plugins. Every domain change becomes a plugin API change. Pass a copy made for the plugin.
- Changing an interface in place. Adding a pure virtual function
to
ReportPluginbreaks every existing plugin at once. Add a new interface, and a new version. - No version, or a version that is not checked. Without it, a plugin written for another interface fails somewhere deep inside the host, instead of being refused with a message.
- Creating a plugin to find out whether it is acceptable. Its constructor may already rely on what the host lacks. Check the name and version first.
- Letting a plugin’s failure end the program. A plugin is input the host does not control. Refuse a plugin that fails to start, and report one that fails while working.
- Self-registering globals. The order is unspecified, the linker can drop them, and they need a global registry.
- Unloading a library while its objects exist. With dynamic loading, destroy the instances first.
When the requirements change
Section titled “When the requirements change”- A department wants a PDF format. It writes a plugin against version 2, with its own tests, and the program’s team adds one line to the list and two names to the build. Nothing else in the host changes.
- Reports must include the date they were made. That is a change to the API: a new version, and a way to give older plugins what they expect. The exercise below works through it.
- Customers must add formats without a new release. The entry points move into shared libraries found in a directory, and the boundary needs the care described in the dynamic loading section. The registry and its checks stay.
- A plugin must not see students’ names. The host decides what
goes into
Roster, so it can hide or replace names before the copy is made, for every plugin at once.
Exercise
Section titled “Exercise”Exercise: Version a plugin interface
Version 3 of the report API must support two new needs:
- A report may show the date it was made, which the host knows and plugins do not.
- A plugin may give a display name for a menu, such as “Comma separated (CSV)”; plugins that do not give one are shown by their name.
Plugins built against version 1 and version 2 must keep working without being changed.
- For each need, decide whether it is an addition to
Roster, a new optional interface, or a change toReportPlugin, and say why. - What changes in the host: the version constants, the registry, and
export_roster? - Write the tests you would add, by name and what each checks.
- A year later, the team wants to stop supporting version 1. What do they change, and what does a version 1 plugin see?
Show the explained answer
-
The date is data the host gives, so it goes into
Roster, as a new member with a default:std::string made_on = {};. Plugins that do not read it need no change when they are rebuilt, and code that builds aRosterwith braces, such as the plugin tests’sample, still compiles under-Wextra -Werror. Without the default it would not, as the versioning table explains. With dynamic loading, plugins that are not rebuilt would be using a different definition ofRoster, so a separateRosterV3passed through a new interface would be the safe choice.The display name is data too, and a
PluginInfomember would let a menu be built without creating any plugin. But adding a member toPluginInfobreaks every plugin’s entry point, which builds one with braces, unless it has a default; and changing the one type every plugin builds is the riskiest change to make. So make it an optional capability: a new interfaceHasDisplayNamewithvirtual std::string_view display_name() const = 0;and a protected destructor, likeHasFileExtension. Neither need changesReportPlugin: adding a pure virtual function there would stop every existing plugin from compiling. -
versionbecomes 3, andoldest_supportedstays 1. The registry does not change: its range check reads the constants.export_rosterdoes not change either;to_report, which it calls, fillsmade_on. A menu asks each plugin withdynamic_castforHasDisplayName, and uses the name when it is missing.This is illustrative and was not compiled:
std::string menu_label(std::string_view name, const report_api::ReportPlugin& plugin) {const auto* named = dynamic_cast<const report_api::HasDisplayName*>(&plugin);return named != nullptr ? std::string{named->display_name()} : std::string{name};} -
Tests that pin down the promise:
a_version_3_plugin_is_acceptedanda_version_4_plugin_is_refused_before_it_is_created.a_version_1_plugin_is_still_accepted_and_gets_the_default_extension, using the unchanged Markdown plugin.a_plugin_without_a_display_name_is_shown_by_its_name, and one with a display name that shows it.the_roster_carries_the_date_it_was_made, onto_report.
Raising
versionalso changes an existing expectation: the registry test that expects “accepted echo (API 2)” usesreport_api::version, so its message becomes “API 3”. A test that breaks when the promise changes is doing its job; update it on purpose. -
They raise
oldest_supportedto 2. The registry then refuses the Markdown plugin with “refused markdown: built for API 1; this program supports 2 to 3”, and the program still starts. Before that release, they tell plugin authors, and the Markdown plugin is rebuilt against version 3 and declares it; it may now implementHasFileExtensiontoo. The host’s.txtdefault stays, becauseHasFileExtensionis optional in versions 2 and 3 as well. The tests that relied on a version 1 plugin,a_version_1_plugin_gets_the_default_extensionand the Markdown line ofeach_plugin_declares_the_version_it_was_built_against, change with it.
Summary
Section titled “Summary”- A plugin architecture has a host, a plugin API both sides see, and plugins the host uses without naming them in its own code.
- Make the API plain data copied for the plugin, and small abstract classes: no host type and no domain type.
- Give each plugin a version and a factory, and have the registry check the name and version before creating it.
- Prefer one explicit list of plugins to self-registering globals.
- Add, do not change: new needs become new optional interfaces or new data, in a new version, and the host keeps a default for older plugins.
- Treat a plugin as input the host does not control: refuse one that fails to start, and report one that fails while working.
- Dynamic loading adds discovery, an
extern "C"entry point, ABI and type information limits, library lifetime, and trust. Use it only when plugins must be added after the program is built. - If one team writes every extension, a factory is enough.