agentleFS
TsukiNi22TsukiNi22/ai-utils/skills/cpp/cpp-style/SKILL.md

cpp-style

Skill1 starsChanged 3 days agoMITView on GitHub

Tsukini's personal C++ coding style (from libutils) - naming (PascalCase types, camelCase methods, _member, snake_case tools, UPPER macros), 4-space indentation, brace placement, spacing, one-liners, loops, switch, lambdas, const correctness, casts, attributes. Use whenever writing, editing, refactoring or reviewing C++ code (.cpp/.hpp) for the user, so the code looks like theirs.

  • Pipes a download into a shell

2 other projects use a version of this.

Adopted by

Most recently taken up by

The file

We split this skill into the rules it gives an agent

10 rules. About 0 are common, 5 are distinctive, and 5 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈5

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 5

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    When editing an existing file, its local style wins over this document.

    line 11
  2. Distinctive:

    Every line of the group on that column: no line of the group left further right or left (a group whose setters sit on one column and two of …

    line 136
  3. Distinctive:

    Lengths far apart: levels: When the signatures of the lines to align fall in clearly separate lengths (a jump of more than ~12 columns …

    line 145
  4. Distinctive:

    No space is ever "for later".

    line 163
  5. Distinctive:

    Always this order, groups one after the other (no empty line between them):

    line 219
  6. Distinctive:

    Only what the file uses; an include that becomes unused is removed.

    line 244
  7. Very specific:

    No auto: always write the type, even when it is long.

    line 248
  8. Very specific:

    Default values at the declaration (int _fd = -1;, std::string _description = "...";), "[None]" as default text.

    line 258
  9. Very specific:

    Every attribute / alignment / hint goes through the libutils macros when the project uses libutils (cpp-class/scripts/detect_libutils.sh), …

    line 278
  10. Very specific:

    not there: the attribute files really used, hard imported in the project or installed on the system (bash …

    line 285

≈ “Common” is an estimate: at least 1 in 5 of the 364,980 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Tsukini C++ coding style

Extracted from the recent libutils code (C++20, clang++, -W -Wall -Wextra -Wpedantic -Wshadow). When editing an existing file, its local style wins over this document. File/class layout (header, sections, blocks): the cpp-class skill. Comments: the cpp-comments skill.

Naming

ElementStyleExamples
class / struct / enum / aliasPascalCaseIdHandler, ParsedUsage, ParsedUsages
interface / abstractI / A prefixISocket, ASocket -> TCPSocket
methodcamelCase, verb firstsetPayloadSeparator, getFd, hasRecvOverload, resetUsages
private / protected / internal function (wrapper impl included)<name>(<Name>)*_: camelCase + trailing _allocate_, cancel_, computeHash_, readChunkHeader_
free tool functionsnake_caseis_ip, resolve_hostname, rotate_point_3D
hook / callback functioncamelCasedefaultHelpHook, defaultInt32ParsingHook
member_camelCase_usedIds, _helpHook, _fd
local variable / parametercamelCase (bool included), short names fine in small scopes (i, j, f, it, e, s)alreadyFailed, equalFound, argOrigin
special bool parameter (a mode / switch with a default value)snake_case, only for theseconst bool safe_mode = true, const bool ignore_case = false, failsafe
macro / defineUPPER_SNAKESOCKET_CHUNK_SIZE, OVERFLOW_LIMIT
attribute macro (libutils)_lower_hot, _nodiscard, _migration(4, 0, 0)
enum valuePascalCase, trailing commaStatus::Up, InternalCode::UnknownId
template parameterT, Fn, <Name>Ttemplate<typename T>, ByteT
namespacelowercase, nested with ::utils::network, utils::system
fileclass name, or lowercase for a free-function moduleIdHandler.hpp, format.hpp

Getters getX(void) const, setters setX(...), boolean queries isX / hasX, removal removeX, resetX to restore the default. Plural for collections (_options, removeFlags).

Indentation & braces

  • 4 spaces, never tabs. No trailing whitespace. Lines can be long (no hard limit), but split conditions/arguments that become unreadable.
  • public:/private:/protected: indented by 4 inside the class, members by 8.
  • Out-of-line function / method / constructor: opening brace on its own line.
  • Class, struct, enum, namespace, if, else, for, while, switch, do, lambda: brace on the same line.
  • } else { / } else if (...) { on the closing brace line.
  • Namespace content is not indented.
  • Preprocessor conditionals (#if / #ifdef / #ifndef / #elif / #else / #endif): the directive is at the indentation of the code around it, and everything it contains (code and directives) is indented one level (4 spaces) more. Never a directive at column 0 in the middle of indented code, never content left at the level of its directive:
    _cold int utils::platform::close(int fd)
    {
        #ifdef UTILS_WINDOWS
            if (fd < 0) _unlikely {errno = EBADF; return -1;}
            return ::_close(fd);
        #else
            return ::close(fd);
        #endif
    }
    
    class SharedMemory {
        private:
            void* _ptr = nullptr;
            #ifdef UTILS_WINDOWS
                void* _handle = nullptr; // file mapping HANDLE
            #else
                int _fd = -1; // shm_open fd
            #endif
    };
    
    #ifdef UTILS_WINDOWS
        // Quote an argument for the command line (file level: the definitions are indented too)
        _cold static std::string quote(const std::string& arg)
        {
            /* ... */
        }
    #endif
    • In a header, the include guard is not a level for the C++ code: #ifndef X_H at column 0, #define X_H, the INCLUDE / DEFINE directives and their conditionals indented by 4 ( #ifdef A + #include ...), while the namespace, structs, classes and their conditionals stay at column 0 (#ifdef A + struct ...).
    • A conditional never spans several sections or mixes indentation levels: close it and open one per section (one #ifdef UTILS_WINDOWS in DEFINE for the macros, another one in STRUCT for the structs, another one in TYPEDEF for the aliases) rather than one block whose content jumps between column 0 and 4.
    • A whole function that only exists on one platform: prefer one #ifdef inside the body of each function (Unix / Windows implementations side by side) over one big file level block; a file that only builds on one platform is selected in the CMake (SRC_WINDOWS) instead of being wrapped in an #ifdef.
    • Multi-line macros (\): the continuation lines follow their #define, indented one level more.

Spacing

  • if (, for (, while (, switch (: space after the keyword; no space inside the parentheses.
  • Binary operators surrounded by spaces, no space for unary (!x, ++i, *it).
  • for (const std::string& x: list), class A: public B, enum class E: std::size_t: no space before :.
  • Init list on its own line, : at column 0: : _binary{binary}, _description{description} (an out-of-line constructor; an empty one defined in its class keeps it on its line, see below).
  • &/* glued to the type: const std::string& name, char* buf, auto &[a, b] for structured bindings.
  • template<typename T> without space. (void) for an empty parameter list, always.
  • One-liners: no space inside the braces and a ; after: {return this->_fd;};, {this->_help = false;};.
  • An empty constructor / destructor / operator defined in its class is one line, never a { / /* Nothing */ / }; block on several lines: its signature, its init list on the same line, { /* Nothing */ }; (a space inside the braces: a comment, not a statement), then its trailing comment; an operator that only returns: {return *this;};. The : of an init list on the line of its constructor is glued to the ) (like class A: public B), never ) :: HybridMemory(const std::size_t size, const MemoryMode mode = MemoryMode::Auto): HybridMemory(mode) {this->allocate_(size);}; // ... (xstyle rule CPP-INIT-COLON). The declarations keep their blank line between them (xstyle rule CPP-EMPTY-BODY, auto fix):
    HybridMemory& operator=(HybridMemory&& other) noexcept {return *this;}; // take the memory and the handler of other
    
    // ---------- Constructor --------- //
    HybridMemory(const utils::system::MemoryMode mode = utils::system::MemoryMode::Auto): _requested{mode} { /* Nothing */ }; // select the backend
    
    HybridMemory(const std::size_t size, std::shared_ptr<utils::system::IGpu> gpu): _requested{utils::system::MemoryMode::Custom}, _gpu{gpu} { /* Nothing */ }; // a user handler
    
    HybridMemory(HybridMemory&& other) noexcept { /* Nothing */ }; // take the memory and the handler of other
    
    // ----------- Destructor --------- //
    ~HybridMemory() noexcept { /* Nothing */ }; // release the memory
    Not (the multi-line form):
    HybridMemory(HybridMemory&& other) noexcept // take the memory and the handler of other
    {
        /* Nothing */
    };
  • Consecutive similar lines of one group share a column (overloads, the setters, the getters, using, case):
    _hot _nodiscard bool hasAcceptOverload(void) const override {return false;};
    _hot _nodiscard bool hasRecvOverload(void) const override   {return false;};
  • One-liner functions of a group are aligned tight: the { of every body sits on the column right after the longest signature of the group + one space, never a wider fixed column:
    _cold _nodiscard bool hasWindow(void) const              {return this->_window != nullptr;};
    _cold _nodiscard rtype::engine::IWindow& getWindow(void) {return *this->_window;};
    _cold _nodiscard rtype::engine::Layout& getRoot(void)    {return this->_root;};
    • Every line of the group on that column: no line of the group left further right or left (a group whose setters sit on one column and two of its getters on another is wrong).
    • A group is a run of consecutive lines of the same category (/* setter */, /* getter */, the overloads of one name, one enum's cases): a blank line or a /* label */ starts a new column; the setters are never aligned on the getters.
    • Count it, never guess it: the column is the length of the longest signature (its indent included) + 1; every other line gets exactly column - its length spaces. A space too many or too few is wrong (two spaces before { on the longest line, a shorter line padded past the column, a group left on an old column after a line was added or renamed). xstyle checks it (CPP-ONELINER-ALIGN) and fixes it (--fix CPP-ONELINER-ALIGN).
    • Lengths far apart: levels. When the signatures of the lines to align fall in clearly separate lengths (a jump of more than ~12 columns between them), align by level instead of one column for all: the short ones together on their own tight column, the long ones together on theirs, the levels one after the other (short first) with no blank line between them, even if that mixes setters and getters:
      _cold inline void setToggle(const bool toggle)    {this->_toggle = toggle;};
      _cold _nodiscard inline bool isToggle(void) const {return this->_toggle;};
      _cold inline void setRepeat(const std::chrono::milliseconds delay)      {this->_repeat = delay;};
      _cold _nodiscard inline std::chrono::milliseconds getRepeat(void) const {return this->_repeat;};
      A level needs two lines or more: a single short (or long) one never stands alone, it joins the closest level and takes its column:
      _cold _nodiscard inline bool isToggle(void) const                       {return this->_toggle;};
      _cold inline void setRepeat(const std::chrono::milliseconds delay)      {this->_repeat = delay;};
      _cold _nodiscard inline std::chrono::milliseconds getRepeat(void) const {return this->_repeat;};
      Lengths close together (the usual /* setter */ and /* getter */ groups): one column per group, as above. No space is ever "for later".
    • The trailing comment of a one-liner is glued: one space after };, never a second column of comments: _cold inline void seed(const brain::IType seed) {this->_seed = seed;}; // seed of the random generator. Include comments keep their own alignment (see cpp-comments), this rule is only for functions.
  • Trailing comments of members and declarations are glued to the code too (one space before //, no column): brain::UIType _neuron = 0; // number of neurons right under std::vector<brain::BrainNeuron> _neurons; // every neuron of the 2d space.
  • A function whose body is a single statement goes in the header, never in the .cpp: a definition that would fit in 2 lines in the .cpp (signature, then {return ...;}) is written as a one-liner in the Function block of the .hpp, with inline after the attributes (not on a virtual / override method, defined there without inline), and its declaration is removed from the Pre-Function block:
    _hot _nodiscard inline std::size_t byteLength(void) const {return (this->bitLength() + 7) / 8;};
    Same when editing / reviewing existing code: such a .cpp definition is moved to the header. It stays in the .cpp only when the header would need an include it doesn't have otherwise (cycle, heavy dependency).
  • Each declaration in its class block (reference/layout.md of cpp-class, xstyle rule CPP-CLASS-BLOCK): Pre-Function = declared only (body in the .cpp), Function = defined in the header ({...};, templates), Constructor / Destructor = theirs (never mixed), data members before the blocks. Moving a function from the .cpp to the header (or the other way) moves it between Pre-Function and Function. Operator is free: an operator placed elsewhere is only worth a hint in a review, never a style error.
  • One empty line between functions and between logical blocks; never two.

Statements

  • this-> on every member access (members and methods).
  • Short if/else/loop with one statement: on the same line or on the next indented line without braces:
    if (safe_mode) lock.lock();
    else (void)lock.try_lock();
    
    for (const std::string& id: ids)
        this->removeUsage(id);
    Several statements on one line inside braces are fine for tiny cases: {ids.push_back(fid); unknown = false; break;}.
  • Early return for trivial cases: if (this->_finished.empty()) return;.
  • Loops:
    • range-for first, with the explicit type (for (const std::string& id: ids)), structured bindings for (const auto &[fid, flag]: this->_flags) (the only syntax possible) with _ for unused parts;
    • index loops for (std::size_t i = 0; i < n; ++i) (prefer ++i, std::size_t for indexes);
    • while (true) + break with a comment per exit condition;
    • do { ... } while (cond); when the first iteration is mandatory;
    • empty-body search loop is accepted: for (index = 0; index < n && cond; ++index);.
  • switch: one line per case with break aligned when short:
    switch (cb & 0b11) {
        case 0: event.button = utils::iomanip::MouseButton::Left;     break;
        case 1: event.button = utils::iomanip::MouseButton::Middle;   break;
        default: event.button = utils::iomanip::MouseButton::Unknown; break;
    }
  • Lambdas: [&](const std::pair<std::string, bool>& p) {return p.first == id;} (explicit parameter types), captures listed explicitly when stored ([this, id, delay, fn](std::stop_token stoken) {).
  • Ternaries for short choices, parenthesized when nested.
  • Discarded return values are cast: (void)lock.try_lock();.

Includes

Always this order, groups one after the other (no empty line between them):

  1. the #define needed by the personal libraries (the user's own libraries: libutils _Section lines...);
  2. the personal libraries (<utils/utils.hpp>, "..." or <...>);
  3. the project headers in "...", each one with the #define it needs on the line just before it;
  4. the external and standard libraries in <...>, each one with the #define it needs on the line just before it.

Inside each group: the longest name first, down to the shortest (name = what is between the quotes / angle brackets, path included); between names of the same length, the most complex / specialized header first, the simplest last. A #define stays glued above its include and moves with it.

#define _Attribute
#define _System
#include <utils/utils.hpp>
#include "engine/EngineType.hpp"
#include "engine/Entity.hpp"
#define GLFW_INCLUDE_NONE
#include <GLFW/glfw3.h>
#include <unordered_map>
#include <memory>
#include <string>
  • In a header: indented by 4 spaces (inside the guard), each include with an aligned trailing comment listing what is used (cpp-comments); in a .cpp: no comments. The project headers: relative path in a header ("../EngineType.hpp"), path from include/ in a .cpp (cpp-class).
  • Inside a personal library itself (libutils), its own headers are project headers (group 3).
  • Only what the file uses; an include that becomes unused is removed.

Types & C++ usage

  • Fully qualified names, never using namespace (std::size_t, utils::exception::ErrorException).
  • No auto: always write the type, even when it is long. Allowed only for an iterator (auto it = this->_tasks.find(id);), the structured bindings (const auto &[a, b], mandatory syntax), or when the user explicitly asks for it.
  • No using except to name a custom type of the project (using Payloads = std::vector<utils::network::Payload>;, using ParsedUsages = ...;, migration aliases), or when the user explicitly asks for it. In a header, every using / typedef alias goes in a /* TYPEDEF */ section and every struct / union (forward declarations included) in a /* STRUCT */ section (cpp-class reference/layout.md). Never using std::...;, never a using to shorten a standard type in the code.
  • const everywhere it applies: by-value parameters too (const bool safe_mode, const std::size_t i), const& for objects, const methods, mutable for the mutex.
  • Default values at the declaration (int _fd = -1;, std::string _description = "...";), "[None]" as default text.
  • nullptr (never NULL), static_cast (never C casts except (void)), std::size_t for sizes.
  • Modern C++20: contains, starts_with, std::erase, std::jthread + std::stop_token, structured bindings, if constexpr, static_assert + type traits / concepts, std::optional, enum class.
  • Return std::optional<std::string> from check hooks: std::nullopt = valid, the string = error message.
  • Templates with a bool non-type parameter for behavior switches: template<bool force = false>.
  • noexcept on close, destructors and functions that must not throw. final/override on every override.
  • Locks: std::lock_guard lock(this->_lock);, std::unique_lock<std::mutex> lock(this->_lock, std::defer_lock);.
  • Rule of five explicit (= default / = delete), copy/move deleted by default.

Errors

  • With libutils: throw utils::exception::ErrorException(utils::exception::InternalCode::X, "info"); (FatalException unrecoverable, WarningException(...).formated() printed on std::cerr for warnings, failsafe parameter to switch between warning and throw).
  • Without libutils: standard exceptions (std::runtime_error, std::invalid_argument...) or the project ones.
  • Re-throw hook/callback errors wrapped with context: catch (const std::exception& e) {throw utils::exception::ErrorException(InternalCode::ArgParserHook, e.what());}.

Attributes

Every attribute / alignment / hint goes through the libutils macros when the project uses libutils (cpp-class/scripts/detect_libutils.sh), alignment included: _alignas(std::hardware_destructive_interference_size) std::atomic<std::size_t> _head = 0;, never a bare alignas(...) (<utils/utils.hpp> also guarantees std::hardware_*_interference_size, fallback 64).

Lookup order before writing any attribute:

  1. the libutils default macros (table below, libutils/reference/api/attribute.md);
  2. not there: the attribute files really used, hard imported in the project or installed on the system (bash cpp-class/scripts/list_attributes.sh <project_root>, cpp-class = that skill folder, lists every #define _x), a newer libutils may have it;
  3. still not there (or no libutils): the standard form, [[...]] ([[gnu::...]]), alignas(...), or __attribute__((...)) / __builtin_* when no standard spelling exists.
libutilsstandard
_hot / _cold[[gnu::hot]] / [[gnu::cold]]
_nodiscard[[nodiscard]]
_unused[[maybe_unused]]
_likely / _unlikely[[likely]] / [[unlikely]]
_fallthrough[[fallthrough]]
_noinline[[noinline]] ([[gnu::noinline]] for gcc)
_deprecated(info)[[deprecated(info)]]
_noaddress / _packed[[no_unique_address]] / [[gnu::packed]]
_assume(expr)[[assume(expr)]]
_alignas(n)alignas(n) (n often std::hardware_destructive_interference_size)
_hidden[[gnu::visibility("hidden")]]
_ctor / _dtor[[gnu::constructor]] / [[gnu::destructor]]
_likely_c(c) / _unlikely_c(c) / _expect(c, v)__builtin_expect(!!(c), 1) / (!!(c), 0) / (c, v)
_alloc_size(i) / _alloc_size_mul(i, j)[[gnu::alloc_size(i)]] / [[gnu::alloc_size(i, j)]]
_read_only(p, s) / _write_only(p, s)[[gnu::access(read_only, p, s)]] / [[gnu::access(write_only, p, s)]]
_nonnull(p)[[gnu::nonnull(p)]]
_legacy / _migration(x, y, z)[[deprecated("...")]]
  • Placement: before the return type (_cold _nodiscard int getFd(void) const), _likely/_unlikely after the condition (if (id == 0) _unlikely {, } else _likely {), _unused before the parameter type.
  • _hot on hot paths (alloc, send, parse, compute), _cold on setup/setters/getters/cancel, _nodiscard on every getter and function whose result matters.

Checking

xstyle (TsukiNi22/xstyle, installed by curl -fsSL https://tsukini22.github.io/my-universe/install.sh | bash -s then sudo dnf|apt|pacman install xstyle (packages of my-universe, sources: TsukiNi22/xstyle; no curl: wget -qO- instead of curl -fsSL)) checks this style, cpp-comments / cpp-class layout points and the libutils usage (LU-* rules), with a severity per rule and the fix proposed. When it is installed (command -v xstyle), run it on the files written or reviewed and fix what it reports: xstyle --rtk <files|dirs> -r, xstyle --rtk --fix [CODES] <paths> (preview with -n), xstyle -x CODE explains a rule, // xstyle: ignore CODE for a justified exception. Its findings are heuristic: a rule that contradicts the local style of the file loses (local style wins).

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.