<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0">
<channel>
<title>Coder Legion - Recent posts tagged c</title>
<link>https://coderlegion.com/tag/c</link>
<description>Powered by Question2Answer</description>
<item>
<title>Ternary Semantic Brain Core — Zero Hard-Coding, Language-Independent Meaning Engine</title>
<link>https://coderlegion.com/32215/ternary-semantic-brain-core-zero-hard-coding-language-independent-meaning-engine</link>
<description>&lt;h2 id=&quot;ternary-semantic-brain-core-zero-hard-coding-language-independent-meaning-engine&quot;&gt;Ternary Semantic Brain Core — Zero Hard-Coding, Language-Independent Meaning Engine&lt;/h2&gt;
&lt;p&gt;I built a meaning-learning engine that works without LLMs, embeddings, or&lt;br&gt;
translation tables. Everything is stored as 2-bit ternary values {-1, 0, +1}.&lt;br&gt;
It learns meaning purely from word co-occurrence in plain text.&lt;/p&gt;
&lt;h3 id=&quot;what-makes-it-different&quot;&gt;What makes it different&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;No hard-coded linguistic knowledge.&lt;/strong&gt; No stoplists, POS tags, tokenizer,&lt;br&gt;
fixed vocabulary, or translation tables. All linguistic structure emerges&lt;br&gt;
from training data.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Language-independent.&lt;/strong&gt; Tested with English + Turkish. Same mechanism&lt;br&gt;
works for any language with letter-based writing.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Ternary representation.&lt;/strong&gt; {-1, 0, +1} — inhibition, unknown, excitation.&lt;br&gt;
&lt;code&gt;0&lt;/code&gt; means &quot;I don't know&quot; — a first-class answer, not a failure.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Single decision rule.&lt;/strong&gt; All thresholds come from each word's own&lt;br&gt;
distribution. No hyperparameter tuning. (We call it &quot;golden ratio freeze&quot;&lt;br&gt;
— referring to structural convergence, not φ = 1.618.)&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Emergent morphology.&lt;/strong&gt; After EN+TR dictionary training: 247 suffixes and&lt;br&gt;
38 prefixes discovered automatically with zero linguistic rules.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Cross-language bridge.&lt;/strong&gt; Without being told &quot;water = su,&quot; the brain&lt;br&gt;
forms bridges between equivalent concepts across languages. After 65 books:&lt;br&gt;
average Jaccard 0.47, cosine 0.61 across 10 EN-TR word pairs.&lt;/p&gt;
&lt;h3 id=&quot;how-it-works&quot;&gt;How it works&lt;/h3&gt;
&lt;ol&gt;
&lt;li&gt;Start with an empty brain&lt;/li&gt;
&lt;li&gt;Train with monolingual dictionaries (word → definition)&lt;/li&gt;
&lt;li&gt;Optionally add books/articles for richer meaning&lt;/li&gt;
&lt;li&gt;Query: &lt;code&gt;/compare water su&lt;/code&gt;, &lt;code&gt;/map fire&lt;/code&gt;, &lt;code&gt;/senses storm&lt;/code&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;The brain builds a sparse graph of word relationships. Multi-meaning words&lt;br&gt;
split into separate sense layers automatically. Meaning groups emerge from&lt;br&gt;
community detection on the neighbor graph.&lt;/p&gt;
&lt;h3 id=&quot;architecture&quot;&gt;Architecture&lt;/h3&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;&lt;th&gt;Layer &lt;/th&gt;&lt;th&gt;What it does&lt;/th&gt;&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;&lt;td&gt;Concept neurons &lt;/td&gt;&lt;td&gt;Each word is a neuron with sparse ternary signature&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;Sentence neurons &lt;/td&gt;&lt;td&gt;Sentences become neurons linking words&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;Synapse graph &lt;/td&gt;&lt;td&gt;PMI-weighted co-occurrence connections&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;Sense layers &lt;/td&gt;&lt;td&gt;Dynamic multi-meaning, born from data&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;Topic groups &lt;/td&gt;&lt;td&gt;Community detection on neighbor graphs&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;h3 id=&quot;results-65-books-trained-&quot;&gt;Results (65 books trained)&lt;/h3&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;&lt;th&gt;Metric &lt;/th&gt;&lt;th&gt;Value&lt;/th&gt;&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;&lt;td&gt;Concepts &lt;/td&gt;&lt;td&gt;288,407&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;Sentences &lt;/td&gt;&lt;td&gt;1,234,706&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;Synapses &lt;/td&gt;&lt;td&gt;102.7M&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;RAM &lt;/td&gt;&lt;td&gt;~1.3 GB&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;h3 id=&quot;cross-language-bridge-examples&quot;&gt;Cross-Language Bridge Examples&lt;/h3&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;&lt;th&gt;English &lt;/th&gt;&lt;th&gt;Turkish &lt;/th&gt;&lt;th&gt;Jaccard &lt;/th&gt;&lt;th&gt;Cosine&lt;/th&gt;&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;&lt;td&gt;water &lt;/td&gt;&lt;td&gt;su &lt;/td&gt;&lt;td&gt;0.46 &lt;/td&gt;&lt;td&gt;0.61&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;fire &lt;/td&gt;&lt;td&gt;ateş &lt;/td&gt;&lt;td&gt;0.35 &lt;/td&gt;&lt;td&gt;0.57&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;king &lt;/td&gt;&lt;td&gt;kral &lt;/td&gt;&lt;td&gt;0.46 &lt;/td&gt;&lt;td&gt;0.56&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;sea &lt;/td&gt;&lt;td&gt;deniz &lt;/td&gt;&lt;td&gt;0.49 &lt;/td&gt;&lt;td&gt;0.60&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;moon &lt;/td&gt;&lt;td&gt;ay &lt;/td&gt;&lt;td&gt;0.43 &lt;/td&gt;&lt;td&gt;0.67&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;h3 id=&quot;what-this-is-not&quot;&gt;What this is NOT&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;Not an LLM — no attention, no transformer, no text generation&lt;/li&gt;
&lt;li&gt;Not open source — binary-only experimental release&lt;/li&gt;
&lt;li&gt;Not a pretrained model — you train from scratch with your own data&lt;/li&gt;
&lt;li&gt;Not AGI — no claims of consciousness or general intelligence&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id=&quot;try-it-yourself&quot;&gt;Try it yourself&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;git clone https://github.com/arifkurnaz/ternary-semantic-brain-demo
cd ternary-semantic-brain-demo
chmod +x scripts/linux/*.sh
./scripts/linux/02_train.sh --dict
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Linux binary included. Windows via WSL2.&lt;br&gt;
Full paper and architecture docs in the repo.&lt;/p&gt;
&lt;hr&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/32215/ternary-semantic-brain-core-zero-hard-coding-language-independent-meaning-engine</guid>
<pubDate>Fri, 23 Oct 2026 17:48:48 +0000</pubDate>
</item>
<item>
<title>The missing break behind Digimon World’s evolution rules</title>
<link>https://coderlegion.com/31448/the-missing-break-behind-digimon-worlds-evolution-rules</link>
<description>&lt;hr&gt;
&lt;p&gt;title: The missing break behind Digimon World’s evolution rules&lt;br&gt;
published: true&lt;br&gt;
description: Digimon World’s decompiled evolution code reveals a four-point scoring system, a surprising tie-break rule, and a path toward a PC port.&lt;/p&gt;
&lt;h3 id=&quot;tags-reverseengineering-c-gamedev-cpp&quot;&gt;tags: reverseengineering, c, gamedev, cpp&lt;/h3&gt;
&lt;p&gt;&lt;img src=&quot;https://dev-to-uploads.s3.us-east-2.amazonaws.com/uploads/articles/ldw0x3np6t314act44lq.gif&quot; alt=&quot;Image description&quot;&gt;&lt;/p&gt;
&lt;p&gt;You fed it, trained it, cleaned up after it. You had a plan. Then it evolved into Numemon, a walking pile of sludge, and the game never told you why.&lt;/p&gt;
&lt;p&gt;No menu. No hint. No stat screen saying &lt;em&gt;here is what went wrong&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;Players filled that silence with wikis, calculators and arguments about whether care mistakes helped or hurt. They inferred the rules from what happened on screen. Now we can read the code.&lt;/p&gt;
&lt;p&gt;The &lt;a rel=&quot;nofollow&quot; href=&quot;https://github.com/jype0/dw_decomp&quot;&gt;Digimon World decompilation project&lt;/a&gt; has reconstructed the evolution code. One rule comes from a loop with no &lt;code&gt;break&lt;/code&gt;: when several stats share the highest value, the game picks the last one in its array.&lt;/p&gt;
&lt;p&gt;Here is how the scoring works, what that tie means, and what I learned while testing a small PC port prototype.&lt;/p&gt;
&lt;h3 id=&quot;the-missing-break&quot;&gt;The missing break&lt;/h3&gt;
&lt;p&gt;Here is the real code that picks which of your stats the game examines. It's in &lt;code&gt;src/main/evolution.c&lt;/code&gt;, and it runs over the six stats &lt;code&gt;hp, mp, offense, defense, speed, brain&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-c&quot;&gt;for (i = 0; i &amp;lt; 6; i++) {
  int8_t isHighestStat = 1;
  for (j = 0; j &amp;lt; 6; j++) {
    if (statsArray[i] &amp;lt; statsArray[j])
      isHighestStat = 0;
  }
  if (isHighestStat == 1)
    highestStat = i;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;For six stats, the nested loop is cheap. But look at what is missing: there is no &lt;code&gt;break&lt;/code&gt; after the assignment. The loop keeps going after it finds a maximum, so a later tied stat overwrites an earlier one. &lt;strong&gt;When stats tie, the highest index wins.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;I ran the same selection logic with a few inputs:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-text&quot;&gt;all six tied      -&amp;gt; brain
offense highest   -&amp;gt; offense
off+def tied high -&amp;gt; defense
brain highest     -&amp;gt; brain
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Reading the array order backwards gives the full tie-break priority: &lt;strong&gt;brain &amp;gt; speed &amp;gt; defense &amp;gt; offense &amp;gt; mp &amp;gt; hp&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;With all six stats tied, the game selects brain as the highest stat. You could infer this from enough experiments, but the code makes the reason clear. Whether the missing &lt;code&gt;break&lt;/code&gt; was intentional is unknown; its effect is observable.&lt;/p&gt;
&lt;p&gt;{% card %}&lt;br&gt;
Worth being careful here: I first suspected &lt;code&gt;highestStat&lt;/code&gt; was read uninitialized, which would be a genuine bug worth reporting upstream. It can't be — a maximum always exists among six values, so the flag is always set at least once. Check before you claim.&lt;br&gt;
{% endcard %}&lt;/p&gt;
&lt;h3 id=&quot;the-scoring-system-four-checks-three-needed&quot;&gt;The scoring system: four checks, three needed&lt;/h3&gt;
&lt;p&gt;That tie-break feeds a larger system. Every Digimon has up to six possible evolution targets. For each candidate the game computes a score out of 4, and &lt;strong&gt;a candidate needs at least 3 points to be eligible at all.&lt;/strong&gt; Below 3 it isn't considered.&lt;/p&gt;
&lt;p&gt;Here are the four checks.&lt;/p&gt;
&lt;h4 id=&quot;care-mistakes-and-the-flag-that-inverts-them&quot;&gt;Care mistakes, and the flag that inverts them&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-c&quot;&gt;if (isMaxCM == 0) {
  if (partner-&amp;gt;careMistakes &amp;gt;= reqs-&amp;gt;care)
    reqPoints += 1;
} else if (partner-&amp;gt;careMistakes &amp;lt;= reqs-&amp;gt;care) {
  reqPoints += 1;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Read the comparisons closely. There's a flag bit that &lt;strong&gt;reverses the test&lt;/strong&gt;, so some evolutions want your care mistakes &lt;em&gt;above&lt;/em&gt; a threshold.&lt;/p&gt;
&lt;p&gt;Neglect isn't a punishment in this game. For certain paths it's a requirement. Care mistakes can therefore help qualify a candidate. Whether that explains any particular Numemon depends on the other checks and available targets.&lt;/p&gt;
&lt;h4 id=&quot;weight-is-a-window-not-a-floor&quot;&gt;Weight is a window, not a floor&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-c&quot;&gt;if (reqs-&amp;gt;weight - 5 &amp;lt;= partner-&amp;gt;weight &amp;amp;&amp;amp;
    partner-&amp;gt;weight &amp;lt;= reqs-&amp;gt;weight + 5)
  reqPoints += 1;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;A band of &lt;strong&gt;±5&lt;/strong&gt; around a target. Overfeeding fails this check exactly as hard as underfeeding. A precise target weight matters because both sides of the window have a limit.&lt;/p&gt;
&lt;h4 id=&quot;stats-where-the-stage-changes-the-rule&quot;&gt;Stats, where the stage changes the rule&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-c&quot;&gt;if (DIGIMON_DATA[target].level == 3U) {
  /* Champion: only your single HIGHEST stat is examined */
} else {
  /* everything else: ALL six stats must clear their thresholds */
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Most evolutions need every stat above its requirement. Champion-level targets check only your highest one — which is where the missing &lt;code&gt;break&lt;/code&gt; above actually bites. &lt;strong&gt;For Champions, one selected highest stat matters; other targets require all six thresholds.&lt;/strong&gt;&lt;/p&gt;
&lt;h4 id=&quot;the-bonus-point-any-one-of-five&quot;&gt;The bonus point: any one of five&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-c&quot;&gt;if (reqs-&amp;gt;digimon    != -1 &amp;amp;&amp;amp; current == reqs-&amp;gt;digimon) isBonusFulfilled = 1;
if (reqs-&amp;gt;discipline != -1 &amp;amp;&amp;amp; /* ... */)                isBonusFulfilled = 1;
if (reqs-&amp;gt;happiness  != -1 &amp;amp;&amp;amp; /* ... */)                isBonusFulfilled = 1;
if (reqs-&amp;gt;battles    != -1) { /* also invertible */ }
if (reqs-&amp;gt;techs      != -1) { /* mastered moves */ }
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Any single one of these grants the fourth point. Battle count carries the same inversion trick as care mistakes: some evolutions want you to have fought &lt;em&gt;fewer&lt;/em&gt; than N battles.&lt;/p&gt;
&lt;h3 id=&quot;the-rule-that-quietly-steers-your-collection&quot;&gt;The rule that quietly steers your collection&lt;/h3&gt;
&lt;p&gt;One more piece, and it's the one that made me sit back:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-c&quot;&gt;if (reqPoints &amp;gt;= 3 &amp;amp;&amp;amp; currentBest != -1) {
  isTargetRaised = hasDigimonRaised(
      EVO_GAINS_DATA[target].targetDigimon);
  isCurrentBestRaised = hasDigimonRaised(
      EVO_GAINS_DATA[currentBest].targetDigimon);

  if (isTargetRaised == 1 &amp;amp;&amp;amp; isCurrentBestRaised == 0)
    reqPoints = 0;      /* you already have this one: disqualify it */

  if (isTargetRaised == 0 &amp;amp;&amp;amp; isCurrentBestRaised == 1)
    reqPoints++;        /* you don't have this one: push it ahead */
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The game remembers which Digimon you have raised. When it compares two eligible candidates, this code favours the one you have not raised: it can zero the already-raised candidate’s score or add a point to the new one. The outcome still depends on candidate order and the surrounding selection logic.&lt;/p&gt;
&lt;p&gt;It is a small but deliberate way to steer players toward more of the roster.&lt;/p&gt;
&lt;h3 id=&quot;who-actually-did-this&quot;&gt;Who actually did this&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;I did not decompile the game.&lt;/strong&gt; I forked the repository, ran parts of its code on a PC, and measured a few pieces a port would need. The decompilation work belongs to its contributors.&lt;/p&gt;
&lt;p&gt;{% embed &lt;a rel=&quot;nofollow&quot; href=&quot;https://github.com/jype0/dw_decomp&quot;&gt;https://github.com/jype0/dw_decomp&lt;/a&gt; %}&lt;/p&gt;
&lt;p&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://github.com/jype0/dw_decomp&quot;&gt;jype0/dw_decomp&lt;/a&gt; started in March 2026 and is MIT licensed. It passed a milestone most decompilation projects never reach: &lt;strong&gt;zero &lt;code&gt;INCLUDE_ASM&lt;/code&gt; stubs left in &lt;code&gt;src/&lt;/code&gt;&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;If you haven't worked on a decomp, that needs explaining. &lt;code&gt;INCLUDE_ASM&lt;/code&gt; is the marker for &quot;we haven't figured this function out yet, here's the raw assembly instead.&quot; Most decomps carry hundreds of them for years. The source tree no longer relies on those assembly placeholders. That milestone alone does not establish that every function matches the retail binary.&lt;/p&gt;
&lt;p&gt;Credit isn't evenly spread, and shouldn't be reported as if it were. As of today the contributor counts are:&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;&lt;th&gt;Contributor &lt;/th&gt;&lt;th&gt;Contributions&lt;/th&gt;&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;&lt;td&gt;Pekka Jylhä-Ollila (jype0) &lt;/td&gt;&lt;td&gt;409 — maintainer, and the bulk of the project&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;juandav &lt;/td&gt;&lt;td&gt;37 — matching functions and data across overlays&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;ChonkMode &lt;/td&gt;&lt;td&gt;22&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;kingzmanh &lt;/td&gt;&lt;td&gt;11&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;fmil95 &lt;/td&gt;&lt;td&gt;7&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;ThirstyWraith &lt;/td&gt;&lt;td&gt;6&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;SydMontague &lt;/td&gt;&lt;td&gt;5 — struct and naming reference work&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;paulohpfilho &lt;/td&gt;&lt;td&gt;4&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;Those are the repository’s contribution counts at the time I checked, not a measure of each person’s work or proof that every regional build is complete.&lt;/p&gt;
&lt;p&gt;I asked about the roadmap in an issue. juandav relayed jype0's four points: clean up the hacks and name things properly; match all 10 regional versions; maybe a PC port, blocked because &lt;em&gt;psyq and psycross don't currently implement libgs or libsnd&lt;/em&gt;; and then &lt;strong&gt;a DW1 mod of epic proportions&lt;/strong&gt; — new maps, story, Digimon.&lt;/p&gt;
&lt;p&gt;The ambitious mod is the long-term goal. The decompilation makes that work possible.&lt;/p&gt;
&lt;hr&gt;
&lt;h3 id=&quot;running-their-code-somewhere-it-has-never-run&quot;&gt;Running their code somewhere it has never run&lt;/h3&gt;
&lt;p&gt;My question was narrower: can this code run off the PlayStation at all?&lt;/p&gt;
&lt;p&gt;&lt;code&gt;evolution.c&lt;/code&gt; is 1,087 lines. Compiling it on x86-64 produced exactly one error:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-text&quot;&gt;libgte.h: No such file or directory
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;That's Sony's geometry coprocessor header. So I grepped &lt;code&gt;evolution.c&lt;/code&gt; for &lt;code&gt;VECTOR&lt;/code&gt;, &lt;code&gt;MATRIX&lt;/code&gt;, &lt;code&gt;gte_&lt;/code&gt;, &lt;code&gt;RotTrans&lt;/code&gt; — nothing. The evolution logic doesn't touch the GTE at all. It only &lt;em&gt;inherits&lt;/em&gt; the header through &lt;code&gt;entity.h&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;I wrote type-only stand-ins for the four PsyQ headers. It compiled clean, then ran:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-text&quot;&gt;EvoRequirements = 28 bytes (PS1 layout: 28)
fresh(1)       -&amp;gt; 2
in-training(3) -&amp;gt; 5
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;That 28 matters more than it looks. The game reads its data tables as raw structs, so if the layout shifted by even one byte on a 64-bit host, every evolution requirement in the game would decode as noise. It doesn't, and I pinned it with &lt;code&gt;static_assert&lt;/code&gt; so nobody can break it quietly later.&lt;/p&gt;
&lt;h3 id=&quot;measuring-the-gte-instead-of-guessing-at-it&quot;&gt;Measuring the GTE instead of guessing at it&lt;/h3&gt;
&lt;p&gt;A major piece of a PS1 port is the GTE, the fixed-point geometry coprocessor.&lt;/p&gt;
&lt;p&gt;My first instinct was to size the problem with a grep. I got 181 and quoted that number publicly. &lt;strong&gt;It was wrong&lt;/strong&gt; — my pattern was matching a header that &lt;em&gt;defines&lt;/em&gt; every GTE macro whether the game calls it or not. Measured against &lt;code&gt;src/&lt;/code&gt; alone:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-text&quot;&gt;632 call sites, 29 distinct operations, 34 of 126 files
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The call sites are concentrated:&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;&lt;th&gt;Operation &lt;/th&gt;&lt;th&gt;Sites &lt;/th&gt;&lt;th&gt;Cumulative&lt;/th&gt;&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;ApplyMatrixSV&lt;/code&gt; &lt;/td&gt;&lt;td&gt;103 &lt;/td&gt;&lt;td&gt;16%&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;RotMatrix&lt;/code&gt; &lt;/td&gt;&lt;td&gt;51 &lt;/td&gt;&lt;td&gt;24%&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;RotMatrixZYX&lt;/code&gt; &lt;/td&gt;&lt;td&gt;44 &lt;/td&gt;&lt;td&gt;31%&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;RotMatrixYXZ&lt;/code&gt; &lt;/td&gt;&lt;td&gt;44 &lt;/td&gt;&lt;td&gt;38%&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;ratan2&lt;/code&gt; &lt;/td&gt;&lt;td&gt;43 &lt;/td&gt;&lt;td&gt;45%&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;gte_rtps&lt;/code&gt; &lt;/td&gt;&lt;td&gt;42 &lt;/td&gt;&lt;td&gt;58%&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;ScaleMatrix&lt;/code&gt; &lt;/td&gt;&lt;td&gt;39 &lt;/td&gt;&lt;td&gt;71%&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;TransMatrix&lt;/code&gt; &lt;/td&gt;&lt;td&gt;37 &lt;/td&gt;&lt;td&gt;77%&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;ApplyMatrixLV&lt;/code&gt; &lt;/td&gt;&lt;td&gt;23 &lt;/td&gt;&lt;td&gt;&lt;strong&gt;81%&lt;/strong&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;&lt;strong&gt;The nine operations shown account for about 81% of these call sites.&lt;/strong&gt; That gives a useful starting point, though call-site count does not measure implementation difficulty.&lt;/p&gt;
&lt;p&gt;I implemented a software subset covering those common operations. The contract is strict: matrix entries are 1.3.12 fixed point (4096 = 1.0), angles run 4096 to a full turn, and results &lt;strong&gt;saturate rather than wrap&lt;/strong&gt;. That last one isn't optional — a wrapped coordinate throws a vertex to the far side of the screen, which is exactly the class of bug that ships unnoticed.&lt;/p&gt;
&lt;p&gt;Then I measured the number that actually decides anything. &quot;0.17% trigonometric error&quot; is a useless statistic; nobody can tell you whether that's visible. So I measured pixels — how far a projected vertex lands from where double-precision maths puts it, across 2,528 vertices and a full rotation sweep:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-text&quot;&gt;mean error:             0.825 px
worst error:            1.896 px
vertices off by &amp;gt; 2px:  0.00%
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In that test, the error stayed under two pixels. This measures one projection sweep; it does not guarantee every game scene will look the same.&lt;/p&gt;
&lt;p&gt;And the honest half: &lt;strong&gt;it is not bit-exact.&lt;/strong&gt; The real GTE uses lookup tables; my polynomial approximation looks identical and is numerically different. That's fine for a &lt;em&gt;port&lt;/em&gt; and useless for &lt;em&gt;verifying a decompilation&lt;/em&gt;, whose entire premise is reproducing the original binary byte for byte. Confusing those two would be the expensive mistake, so I put the warning in the test output rather than in a comment nobody reads.&lt;/p&gt;
&lt;p&gt;{% details Drawing a frame: primitives and the ordering table %}&lt;/p&gt;
&lt;p&gt;The game's rendering is all PsyQ primitives, counted across the source:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-text&quot;&gt;POLY_FT4  386    (textured quad)
POLY_F4    30
POLY_GT4   17
POLY_FT3    6    (textured triangle)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The two textured primitive types in this excerpt account for 392 call sites, making them a useful first rendering test. I built them with the game's own &lt;code&gt;setXYWH&lt;/code&gt; and &lt;code&gt;setUVWH&lt;/code&gt; macros lifted from &lt;code&gt;src/main/utils.c&lt;/code&gt;, and rasterised them in software.&lt;/p&gt;
&lt;p&gt;One thing I deliberately did not fix: the texture mapping is affine, not perspective-correct. The PS1 had no perspective correction, and that wobble is part of how the console looks. Correcting it would make a port feel wrong.&lt;/p&gt;
&lt;p&gt;Then the ordering table, which is how the PS1 sorted by depth. The name misleads, so it's worth saying plainly: &lt;strong&gt;an ordering table is not a sorting algorithm.&lt;/strong&gt; It's a bucket array — one slot per depth value, each holding a linked list, with &lt;code&gt;AddPrim&lt;/code&gt; pushing to the front. O(1) insertion, zero comparisons. That's how a 33MHz console depth-sorted a scene every frame, and reimplementing it with &lt;code&gt;qsort&lt;/code&gt; would be slower &lt;em&gt;and&lt;/em&gt; wrong, because the order of equal-depth primitives depends on the original insertion and traversal rules.&lt;/p&gt;
&lt;p&gt;I built the occlusion test so it couldn't pass by luck: submit the &lt;strong&gt;near&lt;/strong&gt; quad first, then the far one.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-text&quot;&gt;normal:          centre pixel r=16  g=104    (near/green occludes)
depths swapped:  centre pixel r=120 g=16     (far/red now occludes)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Same submission order, opposite result. The table is doing the work, not the sequence of my function calls.&lt;/p&gt;
&lt;p&gt;{% enddetails %}&lt;/p&gt;
&lt;h3 id=&quot;where-i-got-things-wrong&quot;&gt;Where I got things wrong&lt;/h3&gt;
&lt;p&gt;Two corrections, because they're more useful than a clean story.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;The GTE count.&lt;/strong&gt; I said 181 in public. It's 632. I estimated with a grep and then quoted the estimate as a measurement, which is a bad habit and I did it anyway.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;A test that failed for the right reason.&lt;/strong&gt; I asserted the far square would peek out around the near one. It doesn't: the near quad spans x=75..245 and the far one x=123..197, so full occlusion is correct physics and my sampling point was badly chosen. I checked the rendered image before touching any code, which is the only reason I didn't &quot;fix&quot; working code to match a broken expectation.&lt;/p&gt;
&lt;h3 id=&quot;what-this-does-not-prove&quot;&gt;What this does not prove&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;One logic file out of 126.&lt;/strong&gt; I picked &lt;code&gt;evolution.c&lt;/code&gt; &lt;em&gt;because&lt;/em&gt; it looked dependency-free. Best case, not a representative sample.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;The GTE is approximate.&lt;/strong&gt; 18 of 29 operations unimplemented, and the trig is polynomial rather than table-driven.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;No model loading.&lt;/strong&gt; &lt;code&gt;GsSortObject4&lt;/code&gt; has 42 call sites and walks TMD models. The ordering table is ready for it; the format reader isn't written.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Nothing validated against the retail binary.&lt;/strong&gt; That needs the MIPS toolchain and a disc image.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;The assets are still Bandai's.&lt;/strong&gt; Models, textures, music, text. A possible distribution model is an engine that requires players to supply their own game data; the legal details would need separate review.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Where my work and jype0's roadmap touch: his stated blocker for a PC port is that psyq and psycross don't implement &lt;code&gt;libgs&lt;/code&gt; or &lt;code&gt;libsnd&lt;/code&gt;. &lt;code&gt;libgs&lt;/code&gt; is one of the four headers I stubbed. I'm not claiming that solves his problem — only that it's the same wall, and it's climbable from at least one side.&lt;/p&gt;
&lt;h3 id=&quot;what-we-finally-understand&quot;&gt;What we finally understand&lt;/h3&gt;
&lt;p&gt;Twenty-five years of wiki edits, spreadsheets and arguments, and the answer is a few hundred lines of C:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;3 points of 4&lt;/strong&gt; to be eligible at all&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Care mistakes and battle counts are invertible&lt;/strong&gt; — some evolutions want neglect&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Weight is a ±5 window&lt;/strong&gt; — overfeeding fails like starving&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Champions check your highest stat only&lt;/strong&gt;; everything else checks all six&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Ties favour the last tied stat&lt;/strong&gt; in array order, with brain last&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Previously raised targets can lose a head-to-head comparison&lt;/strong&gt; against a new one&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Your Numemon had an explanation in the game’s rules. The exact reason in any given run depends on the candidate scores and selection path.&lt;/p&gt;
&lt;p&gt;That is what makes the decompilation exciting: the rules are readable and testable. It also gives modders a foundation to build on.&lt;/p&gt;
&lt;p&gt;My four experiments live on a &lt;a rel=&quot;nofollow&quot; href=&quot;https://github.com/krlz-dev/dw_decomp/tree/port-spike/port&quot;&gt;branch in my fork&lt;/a&gt;. Each runs with one command and needs only &lt;code&gt;gcc&lt;/code&gt;, plus &lt;code&gt;libsdl2-dev&lt;/code&gt; for the two that draw — no PlayStation toolchain, no disc image.&lt;/p&gt;
&lt;p&gt;If you've worked on a decomp: how do you decide when an approximation is good enough to ship in a port, given it can never be good enough to verify a match? The bit-exact line is the part I'm least sure I drew correctly.&lt;/p&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/31448/the-missing-break-behind-digimon-worlds-evolution-rules</guid>
<pubDate>Fri, 16 Oct 2026 19:39:38 +0000</pubDate>
</item>
<item>
<title>My Journey with C++: Building Efficient and Reliable Software</title>
<link>https://coderlegion.com/30753/my-journey-with-c-building-efficient-and-reliable-software</link>
<description>&lt;p&gt;As a &lt;strong&gt;C++ developer&lt;/strong&gt;, I enjoy solving complex problems, writing clean code, and building software that performs efficiently. For me, programming is not just about making something work; it’s about understanding how it works and finding better ways to solve problems.&lt;/p&gt;
&lt;h3 id=&quot;why-i-enjoy-working-with-c-&quot;&gt;Why I Enjoy Working with C++&lt;/h3&gt;
&lt;p&gt;C++ is a powerful language that teaches me to think deeply about programming. From memory management to data structures and algorithms, it helps me understand what happens behind the scenes and how software can be made faster and more reliable.&lt;/p&gt;
&lt;p&gt;I enjoy exploring different approaches to a problem, improving performance, and writing code that is easier to maintain.&lt;/p&gt;
&lt;h3 id=&quot;what-i-focus-on&quot;&gt;What I Focus On&lt;/h3&gt;
&lt;p&gt;My main interests include:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;C++ programming&lt;/strong&gt; and object-oriented programming&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Data structures and algorithms&lt;/strong&gt; for solving complex problems&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Memory management&lt;/strong&gt; and performance optimization&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Problem solving&lt;/strong&gt; through logical thinking and efficient coding&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Software development&lt;/strong&gt; with a focus on reliability and maintainability&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id=&quot;learning-never-stops&quot;&gt;Learning Never Stops&lt;/h3&gt;
&lt;p&gt;Technology continues to evolve, and there is always something new to explore. I believe becoming a better developer requires continuous learning, practical experience, and the willingness to learn from mistakes.&lt;/p&gt;
&lt;p&gt;I enjoy experimenting with new ideas, improving my programming skills, and learning from other developers who share the same passion for technology.&lt;/p&gt;
&lt;p&gt;I believe that sharing knowledge helps us grow together and discover better ways to develop software.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Always learning, always coding, and always looking for better ways to solve problems.&lt;/strong&gt;&lt;/p&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/30753/my-journey-with-c-building-efficient-and-reliable-software</guid>
<pubDate>Mon, 12 Oct 2026 02:41:51 +0000</pubDate>
</item>
<item>
<title>Assembly language</title>
<link>https://coderlegion.com/29562/assembly-language</link>
<description>&lt;p&gt;Yo everyone, this is my first post and I wanna talk about assembly.&lt;/p&gt;
&lt;p&gt;So back in 1962, the US launched Mariner 1 to Venus. A few mins after liftoff, the rocket started going off course, so they had to blow it up. Turns out it was a code bug: in an assembly program (or something close to it), they missed one little bar over a letter in a formula. Instead of smoothing the trajectory, the program started wobbling it. Cost of that mistake? Like 18.5 million bucks (in that era's money) and a dead mission. Since then, people bring it up as proof that even one symbol in low-level code can cost you a whole rocket.&lt;/p&gt;
&lt;p&gt;So yeah, I honestly don't get those &quot;mutants&quot; in programming who write in assembly. I got one buddy who codes in assembly, and we don't even talk anymore (maybe that's part of why lol). Anyway, I'm learning C myself and wanna be a systems programmer, and I got no clue how I'm gonna learn assembly — just so you know, it's right below machine code. Btw, assembly is a super hard language that eats up tons of time. But there are way more Python jobs (and neural nets will take those anyway) than assembly jobs. In the end, I just respect people who know it.&lt;/p&gt;
&lt;p&gt;Good luck everyone, catch you later&lt;/p&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/29562/assembly-language</guid>
<pubDate>Fri, 02 Oct 2026 20:40:11 +0000</pubDate>
</item>
<item>
<title>How to Write to Web.config in Medium Trust</title>
<link>https://coderlegion.com/29473/how-to-write-to-web-config-in-medium-trust</link>
<description>&lt;p&gt;If you’re working with an older ASP.NET application running under Medium Trust, you may run into a common problem: your application can read Web.config, but attempting to modify it at runtime fails with a security or permission exception.&lt;/p&gt;
&lt;p&gt;The important point is that Medium Trust is designed to restrict applications from modifying configuration files. Simply using Server.MapPath() and File.WriteAllText() is not a reliable solution—and in a hosted environment, it will generally be blocked by filesystem permissions or the trust policy.&lt;/p&gt;
&lt;p&gt;What can you do?&lt;/p&gt;
&lt;p&gt;If you need to change configuration dynamically, consider these approaches:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Store dynamic settings outside Web.config&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Instead of modifying Web.config, use a data store such as a database or another configuration mechanism that your application is allowed to write to.&lt;/p&gt;
&lt;p&gt;// Example: store application settings in a database&lt;br&gt;
string value = GetSettingFromDatabase(&quot;MySetting&quot;);&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Use an application-level configuration file&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;For settings that need to be writable, keep them in a separate file, provided your hosting environment allows your application to create and modify that file.&lt;/p&gt;
&lt;p&gt;string path = Server.MapPath(&quot;~/App_Data/settings.xml&quot;);&lt;/p&gt;
&lt;p&gt;File.WriteAllText(path, &quot;Value&quot;);&lt;/p&gt;
&lt;p&gt;App_Data is commonly used for application data because it isn't intended to be served directly to clients.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Change Web.config during deployment&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;If the configuration really belongs in Web.config, the safest approach is usually to modify it as part of your deployment process rather than from application code.&lt;/p&gt;
&lt;p&gt;For example:&lt;/p&gt;

  
&lt;p&gt;&lt;/p&gt;
&lt;p&gt;Your deployment process can generate or transform the appropriate configuration for each environment.&lt;/p&gt;
&lt;p&gt;What about ConfigurationManager?&lt;/p&gt;
&lt;p&gt;You can read configuration values normally:&lt;/p&gt;
&lt;p&gt;string value =&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;ConfigurationManager.AppSettings[&quot;MySetting&quot;];
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;But being able to read configuration doesn't mean the application has permission to write the physical Web.config file.&lt;/p&gt;
&lt;p&gt;Bottom line&lt;/p&gt;
&lt;p&gt;Under Medium Trust, don't design your application around runtime modification of Web.config. If a value needs to change while the application is running, keep that value in a writable data store or separate configuration file. If it belongs in Web.config, update it during deployment.&lt;/p&gt;
&lt;p&gt;This approach is more secure, more predictable, and works better with hosted ASP.NET environments.&lt;/p&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/29473/how-to-write-to-web-config-in-medium-trust</guid>
<pubDate>Fri, 02 Oct 2026 03:37:53 +0000</pubDate>
</item>
<item>
<title>Writing a Programming Language &amp; Native x86-64 Compiler from Scratch in C: The Story of Yolish</title>
<link>https://coderlegion.com/28765/writing-a-programming-language-native-x86-64-compiler-from-scratch-in-the-story-of-yolish</link>
<description>&lt;p&gt;Every programmer has, at some point, looked at their favorite programming language and thought: &lt;/p&gt;
&lt;p&gt;&lt;em&gt;“Why was it designed this way? How hard can it actually be to build one myself?”&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;Most developers who explore language design stop at simple arithmetic evaluators or toy interpreters. But when I was building &lt;strong&gt;Exploidus OS&lt;/strong&gt;—a custom x86-64 reactive capability operating system—I ran into a fundamental architectural barrier:&lt;/p&gt;
&lt;p&gt;Standard systems languages (like C) have zero concept of operating-system capability tokens. In C, if you have a pointer, you can dereference it. If you have an address space, any line of code can call any syscall unless restricted by complex external sandboxes.&lt;/p&gt;
&lt;p&gt;I wanted a modern, expressive language that felt as ergonomic as Python or Rust, but was deeply &lt;strong&gt;capability-aware&lt;/strong&gt; at the syntax level—able to compile directly to bare-metal x86-64 binaries without pulling in gigabytes of LLVM dependencies.&lt;/p&gt;
&lt;p&gt;That ambition gave birth to &lt;strong&gt;Yolish&lt;/strong&gt;—a fast, expressive, capability-aware programming language with a tree-walking interpreter, a bytecode virtual machine, and a direct x86-64 native compiler.&lt;/p&gt;
&lt;p&gt;Here is how I designed Yolish, wrote its compiler from scratch in pure C, and what I learned building a complete language ecosystem.&lt;/p&gt;
&lt;hr&gt;
&lt;h3 id=&quot;1-language-design-ergonomics-meets-systems-control&quot;&gt;1. Language Design: Ergonomics Meets Systems Control&lt;/h3&gt;
&lt;p&gt;When designing Yolish's syntax (&lt;code&gt;.y&lt;/code&gt;), I wanted code to read cleanly without syntactic noise, while enforcing defensive systems programming invariants.&lt;/p&gt;
&lt;h4 id=&quot;immutability-by-default&quot;&gt;Immutability by Default&lt;/h4&gt;
&lt;p&gt;Variables in Yolish default to immutable constants using &lt;code&gt;let&lt;/code&gt;, while mutable state must be explicitly declared using &lt;code&gt;var&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-yolish&quot;&gt;let name  = &quot;Yolish&quot;   -- immutable constant
var count = 0          -- mutable state
count = count + 1
&lt;/code&gt;&lt;/pre&gt;
&lt;h4 id=&quot;pattern-matching-with-ranges-amp-guards&quot;&gt;Pattern Matching with Ranges &amp;amp; Guards&lt;/h4&gt;
&lt;p&gt;Instead of archaic C-style &lt;code&gt;switch&lt;/code&gt; statements with fallthrough bugs, Yolish features expressive pattern matching:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-yolish&quot;&gt;let grade = match score {
    90..100      =&amp;gt; &quot;A&quot;
    80..90       =&amp;gt; &quot;B&quot;
    n if n &amp;gt;= 60 =&amp;gt; &quot;C&quot;
    _            =&amp;gt; &quot;F&quot;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h4 id=&quot;structs-and-impl-blocks&quot;&gt;Structs and &lt;code&gt;impl&lt;/code&gt; Blocks&lt;/h4&gt;
&lt;p&gt;Yolish rejects complex class hierarchies in favor of data-first structs and explicit method implementations:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-yolish&quot;&gt;struct Circle { radius }

impl Circle {
    fn area(self) {
        return y.math.pi * self.radius * self.radius
    }
}

let c = Circle { radius: 5 }
y.println(c.area())
&lt;/code&gt;&lt;/pre&gt;
&lt;hr&gt;
&lt;h3 id=&quot;2-bridging-code-to-the-kernel-first-class-capabilities&quot;&gt;2. Bridging Code to the Kernel: First-Class Capabilities&lt;/h3&gt;
&lt;p&gt;Because Yolish is the official userspace language for Exploidus OS, security cannot be an afterthought. &lt;/p&gt;
&lt;p&gt;In Yolish, dangerous operations (network access, raw disk writes, peripheral I/O) are gated by &lt;strong&gt;declarative capability annotations&lt;/strong&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-yolish&quot;&gt;@cap(net.read, fs.write)
fn sync_data(url, filepath) {
    let payload = y.net.get(url)
    y.fs.write(filepath, payload)
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;When compiled for Exploidus OS, the Yolish compiler inspects these annotations and validates them against the process's cryptographic capability table. If an unprivileged function attempts to make an unauthorized syscall, the operation is blocked before execution even reaches kernel space.&lt;/p&gt;
&lt;hr&gt;
&lt;h3 id=&quot;3-the-tri-engine-architecture-interpreter-bytecode-vm-and-native-compiler&quot;&gt;3. The Tri-Engine Architecture: Interpreter, Bytecode VM, and Native Compiler&lt;/h3&gt;
&lt;p&gt;Building a language engine involves tough tradeoffs. Tree-walking interpreters are easy to write but slow. Bytecode VMs are fast and portable. Native compilers deliver maximum speed but are deeply architecture-specific.&lt;/p&gt;
&lt;p&gt;Instead of choosing one, &lt;strong&gt;Yolish implements all three&lt;/strong&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-text&quot;&gt;Source Code (.y)
       |
    [Lexer] -&amp;gt; Tokens
       |
   [Parser] -&amp;gt; Abstract Syntax Tree (AST)
       |
       +---&amp;gt; Tree-Walking Interpreter  (`ys file.y` - Instant startup)
       |
       +---&amp;gt; Bytecode Compiler &amp;amp; VM    (`ys vm file.y` - High speed execution)
       |
       +---&amp;gt; Direct x86-64 Machine Code (`ys -c file.y` - Standalone binaries)
&lt;/code&gt;&lt;/pre&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;The Interactive Interpreter (&lt;code&gt;ys file.y&lt;/code&gt;):&lt;/strong&gt; Evaluates the AST directly. Perfect for quick scripts, one-liners, and the interactive REPL.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;The Bytecode VM (&lt;code&gt;ys vm file.y&lt;/code&gt;):&lt;/strong&gt; Compiles the AST into an optimized instruction stream executed by a custom register/stack-based virtual machine.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;The Native x86-64 Compiler (&lt;code&gt;ys -c file.y&lt;/code&gt;):&lt;/strong&gt; Generates real machine code instructions (&lt;code&gt;MOV&lt;/code&gt;, &lt;code&gt;ADD&lt;/code&gt;, &lt;code&gt;CALL&lt;/code&gt;, &lt;code&gt;RET&lt;/code&gt;, SSE2 float operations) directly into executable binary containers.&lt;/li&gt;
&lt;/ol&gt;
&lt;hr&gt;
&lt;h3 id=&quot;4-no-llvm-no-bloat-direct-multi-platform-binary-emission&quot;&gt;4. No LLVM, No Bloat: Direct Multi-Platform Binary Emission&lt;/h3&gt;
&lt;p&gt;Most modern compiler projects delegate code generation to LLVM. While LLVM is powerful, it is also a massive, multi-gigabyte dependency with slow compilation times.&lt;/p&gt;
&lt;p&gt;I wanted the Yolish toolchain (&lt;code&gt;ys&lt;/code&gt;) to be a single, self-contained C binary with zero external dependencies. You can clone the repo and compile the entire language toolchain with a single &lt;code&gt;make&lt;/code&gt; command using standard &lt;code&gt;gcc&lt;/code&gt; or &lt;code&gt;clang&lt;/code&gt; in seconds.&lt;/p&gt;
&lt;p&gt;To achieve this without LLVM, Yolish writes binary headers and machine code directly:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Linux ELF64:&lt;/strong&gt; Directly formats ELF headers, program headers (&lt;code&gt;PT_LOAD&lt;/code&gt;), &lt;code&gt;.text&lt;/code&gt; sections, and Linux syscall dispatchers.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Windows PE32+:&lt;/strong&gt; Generates valid Portable Executable (PE32+) headers, image import directories, and embeds Windows application icons.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;macOS Mach-O:&lt;/strong&gt; Generates 64-bit Mach-O load commands (&lt;code&gt;LC_SEGMENT_64&lt;/code&gt;).&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;You can cross-compile for any major operating system with a single CLI flag:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;ys -c app.y --target linux    # Emits static Linux ELF64 binary
ys -c app.y --target windows  # Emits Windows PE32+ .exe
ys -c app.y --target macos    # Emits macOS Mach-O binary
&lt;/code&gt;&lt;/pre&gt;
&lt;hr&gt;
&lt;h3 id=&quot;5-runtime-architecture-mark-and-sweep-garbage-collection&quot;&gt;5. Runtime Architecture: Mark-and-Sweep Garbage Collection&lt;/h3&gt;
&lt;p&gt;A systems language with dynamic strings and closures needs safe, automatic memory reclamation.&lt;/p&gt;
&lt;p&gt;Yolish implements a custom &lt;strong&gt;Mark-and-Sweep Garbage Collector (GC)&lt;/strong&gt; written from scratch in C:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Root Scanning:&lt;/strong&gt; Traverses the active call frame stack, global environment variables, and the VM operand stack to identify all actively reachable pointers.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Mark Phase:&lt;/strong&gt; Recursively traverses heap-allocated objects (strings, dynamic arrays, closures, struct instances), setting the GC mark bit.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Sweep Phase:&lt;/strong&gt; Scans the global heap allocation pool. Any block whose mark bit is zero was unreachable; it is freed back to the system memory pool, while surviving objects have their mark bits cleared for the next cycle.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Developers have full programmatic introspection into memory usage via &lt;code&gt;gc.stats()&lt;/code&gt; and can trigger explicit collection via &lt;code&gt;gc.collect()&lt;/code&gt;.&lt;/p&gt;
&lt;hr&gt;
&lt;h3 id=&quot;6-a-tooling-first-philosophy&quot;&gt;6. A Tooling-First Philosophy&lt;/h3&gt;
&lt;p&gt;A great programming language is more than just a syntax parser; it is an entire developer experience. &lt;/p&gt;
&lt;p&gt;Too many new languages fail because they require third-party formatters, linter plugins, and package wrappers before you can write a serious project. &lt;/p&gt;
&lt;p&gt;From day one, Yolish was designed with a &lt;strong&gt;tooling-first philosophy&lt;/strong&gt;:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Built-in Test Runner (&lt;code&gt;ys test file.y&lt;/code&gt;):&lt;/strong&gt; Write native &lt;code&gt;test&lt;/code&gt; blocks alongside code and execute them without third-party frameworks.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Static Checker (&lt;code&gt;ys check file.y&lt;/code&gt;):&lt;/strong&gt; Performs static semantic analysis, flags undefined variables, and detects type mismatches before runtime.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Code Formatter (&lt;code&gt;ys fmt file.y&lt;/code&gt;):&lt;/strong&gt; Enforces an opinionated, canonical code style across codebases.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Interactive REPL (&lt;code&gt;ys&lt;/code&gt;):&lt;/strong&gt; Instant feedback loop with color-highlighted evaluation.&lt;/li&gt;
&lt;/ul&gt;
&lt;hr&gt;
&lt;h3 id=&quot;7-what-writing-a-compiler-in-c-teaches-you&quot;&gt;7. What Writing a Compiler in C Teaches You&lt;/h3&gt;
&lt;p&gt;Writing a programming language and compiler from scratch in pure C is one of the most humbling and rewarding journeys in software engineering:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Memory Discipline:&lt;/strong&gt; Managing AST nodes, symbol tables, and lexical scopes in C forces you to understand every single byte you allocate. Memory leaks in a compiler slow down compilation; memory corruption in code generation crashes the output binary.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;The Magic of Abstraction:&lt;/strong&gt; When you write the code that translates a simple &lt;code&gt;if (x &amp;gt; 10)&lt;/code&gt; into a &lt;code&gt;CMP&lt;/code&gt; and &lt;code&gt;JLE&lt;/code&gt; assembly jump, you demystify how computers actually think. You realize that high-level abstractions are not magic; they are just structured transformations of intent.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Simplicity Over Complexity:&lt;/strong&gt; Features are easy to add to a grammar; keeping the language coherent, orthogonal, and bug-free across interpretation and native compilation is where the real engineering happens.&lt;/li&gt;
&lt;/ol&gt;
&lt;hr&gt;
&lt;h3 id=&quot;conclusion-amp-open-source&quot;&gt;Conclusion &amp;amp; Open Source&lt;/h3&gt;
&lt;p&gt;Yolish started as a specialized language project for Exploidus OS, but has evolved into a versatile, cross-platform programming environment with its own native compiler, VM, and standard library.&lt;/p&gt;
&lt;p&gt;The entire project is 100% open-source under the MIT license:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;GitHub Repository:&lt;/strong&gt; &lt;a rel=&quot;nofollow&quot; href=&quot;https://github.com/rahadbhuiya/Yolish&quot;&gt;https://github.com/rahadbhuiya/Yolish&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Supported Platforms:&lt;/strong&gt; Linux, Windows, macOS, and Exploidus OS.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Download the binary, try out the REPL, write a script, and inspect the C compiler source!&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Have you ever thought about designing a programming language? What is the one feature you wish your daily language had? Let's discuss in the comments below!&lt;/em&gt;&lt;/p&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/28765/writing-a-programming-language-native-x86-64-compiler-from-scratch-in-the-story-of-yolish</guid>
<pubDate>Sun, 27 Sep 2026 03:56:49 +0000</pubDate>
</item>
<item>
<title>Building an x86-64 Operating System from Scratch in C: The Exploidus Story</title>
<link>https://coderlegion.com/28568/building-an-x86-64-operating-system-from-scratch-in-c-the-exploidus-story</link>
<description>&lt;p&gt;Most software engineers spend their careers working high up the abstraction ladder: web frameworks, containers, virtual machines, and cloud APIs. We treat the operating system as an invisible, infallible foundation. We assume malloc() will magically allocate RAM, write() will reliably flush bytes to disk, and the CPU will seamlessly multiplex threads.&lt;/p&gt;
&lt;p&gt;A few years ago, I decided to pull back the curtain and ask a fundamental question:&lt;/p&gt;
&lt;p&gt;What actually happens if you strip away Linux, Windows, libc, and every single runtime library, and sit directly on the bare metal of an x86-64 processor with nothing but C and assembly?&lt;/p&gt;
&lt;p&gt;That question led to Exploidus—a custom x86-64 reactive capability operating system kernel built completely from scratch.&lt;/p&gt;
&lt;p&gt;Today, Exploidus boots via Multiboot2/GRUB, runs in full 64-bit long mode, implements 4-level paging with NX enforcement, features a custom journaling filesystem (ExFS), runs an in-kernel TCP/IP stack with real Gigabit Ethernet drivers, enforces BLAKE3 cryptographic capability tokens, supports 82 POSIX-style syscalls, and even powers a double-buffered userspace window compositor.&lt;/p&gt;
&lt;p&gt;Here is the story of how I designed and built it, the architectural hurdles I faced, and what bare-metal systems programming teaches you about software engineering.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;The Starting Line: From Real Mode to 64-Bit Long Mode&lt;br&gt;
When an x86-64 processor powers on, it does not wake up as a modern 64-bit machine. It awakens in 16-bit Real Mode, essentially pretending to be an Intel 8086 from 1978 with 1 MB of addressable memory.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;To get Exploidus running, the bootloader transition had to be orchestrated meticulously:&lt;/p&gt;
&lt;p&gt;Multiboot2 Compliance: The kernel binary begins with a Multiboot2 header so GRUB2 can discover and load our ELF64 image into memory.&lt;br&gt;
Transitioning Modes: Moving through 32-bit Protected Mode, setting up the Global Descriptor Table (GDT), enabling Physical Address Extension (PAE), and finally setting the Long Mode Enable (LME) bit in the EFER model-specific register.&lt;br&gt;
Entering Long Mode: Once paging is turned on and a 64-bit GDT code descriptor is loaded, a far jump lands execution into pure 64-bit Long Mode.&lt;br&gt;
At this stage, you have no printf, no standard library, and no memory allocator. If a pointer dereferences wrong, the CPU triple-faults and the machine instantly reboots in a split second.&lt;/p&gt;
&lt;p&gt;The first milestone of any OS developer is the VGA text-mode driver at physical address 0xB8000. Writing characters directly into video memory bytes and watching the word Exploidus Kernel Initializing... render on a blank screen is a sensation every programmer should experience at least once.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Memory Architecture: 4-Level Paging and Colored Zones&lt;br&gt;
Virtual memory is the bedrock of process isolation. Without it, any runaway pointer can overwrite the kernel or another process's state.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;In Exploidus, memory management is divided into two core layers:&lt;/p&gt;
&lt;p&gt;4-Level x86-64 Paging&lt;br&gt;
Exploidus uses the standard x86-64 page-table hierarchy:&lt;/p&gt;
&lt;p&gt;PML4 (Page Map Level 4)&lt;br&gt;
PDPT (Page Directory Pointer Table)&lt;br&gt;
PD (Page Directory)&lt;br&gt;
PT (Page Table)&lt;br&gt;
Every page entry manages a 4 KB physical frame. To enforce strict security:&lt;/p&gt;
&lt;p&gt;NX (No-Execute) Bit Enforcement: All data, heap, and stack pages are flagged with the XD/NX bit (bit 63). Code cannot execute from the stack or heap, neutralizing classic buffer overflow shellcode attacks at the hardware level.&lt;br&gt;
User/Supervisor Protection: Kernel space is mapped into the higher half and strictly protected by disabling the User bit (U/S = 0), preventing Ring 3 userspace applications from reading or writing kernel data structures.&lt;br&gt;
Colored Physical Frame Allocation&lt;br&gt;
Instead of a naive linear allocator or a slow buddy system, Exploidus introduces a Colored Zone Physical Memory Manager:&lt;/p&gt;
&lt;p&gt;GREEN ZONE: Unrestricted, verified general-purpose memory for userspace processes.&lt;br&gt;
YELLOW ZONE: DMA-capable and peripheral-bounded memory mapped for hardware device drivers (e.g. NIC ring buffers, USB host controllers).&lt;br&gt;
RED ZONE: Cryptographically isolated, non-swappable physical frames reserved strictly for kernel capability tokens, master page tables, and audit logs.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Capability Security &amp;amp; Crash Isolation&lt;br&gt;
Most commodity operating systems rely on ambient authority (e.g. standard UID/GID or Unix permissions). If a process runs as root, it can execute anything.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Exploidus explores a Reactive Capability-Based Security Model:&lt;/p&gt;
&lt;p&gt;Resources (file descriptors, sockets, physical devices, IPC channels) are gated behind unforgeable capability tokens.&lt;br&gt;
Hardware-Seeded BLAKE3 Tokens: Tokens are generated by hashing resource pointers and generation counters using the BLAKE3 cryptographic algorithm, seeded with random entropy directly from the CPU's RDRAND instruction.&lt;br&gt;
Crash Isolation: If a userspace process suffers a segmentation fault, divides by zero, or triggers an invalid opcode, the kernel does not panic. The CPU interrupt handler traps the exception, destroys the faulting process's capability table, reclaims its address space, and terminates only that process. The shell and the rest of the OS continue running uninterrupted.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Designing a Custom Filesystem: ExFS&lt;br&gt;
You cannot have a functional operating system without persistent storage. While many hobby kernels stop at read-only tar ramdisks or FAT12, Exploidus features its own custom filesystem: ExFS.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Key Architectural Elements of ExFS:&lt;br&gt;
Generic Block Device Layer: An abstraction layer (blockdev.c) decouples storage hardware from the filesystem. Whether a volume is an IDE/ATA hard drive (ata0) or a USB thumb drive (usb0), ExFS interacts through unified sector read/write interfaces.&lt;br&gt;
Metadata Journaling: ExFS uses a write-ahead metadata journal to ensure crash consistency. Directory modifications, inode allocations, and block allocations are recorded in a circular journal before being committed to disk structures. If a sudden power loss occurs, replay recovery restores volume consistency upon reboot.&lt;br&gt;
Data Provenance: Inodes in ExFS carry immutable provenance records, tracking the creator capability and timestamp of creation to provide built-in forensic audit trails.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Drivers from the Metal: USB and Gigabit Ethernet&lt;br&gt;
Writing device drivers without third-party libraries or Linux helper APIs is where hardware reality hits you hardest. Data sheets for real silicon can be hundreds of pages long and filled with subtle timing quirks.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;UHCI USB Subsystem&lt;br&gt;
Exploidus includes a custom UHCI (Universal Host Controller Interface) USB driver:&lt;/p&gt;
&lt;p&gt;Probes PCI configuration space to discover USB host controllers.&lt;br&gt;
Configures physical memory transfer descriptors (TDs) and queue heads (QHs) in DMA-accessible memory.&lt;br&gt;
Implements USB device enumeration, Control, Interrupt, and Bulk endpoints.&lt;br&gt;
Supports USB Mass Storage (Bulk-Only Transport + SCSI command wrappers), allowing developers to plug in a USB flash drive, mount it into the VFS, and read files via the shell.&lt;br&gt;
Gigabit Networking &amp;amp; In-Kernel TCP/IP Stack&lt;br&gt;
Exploidus features an in-kernel network stack communicating through an Intel 82540EM (e1000) Gigabit Ethernet controller:&lt;/p&gt;
&lt;p&gt;Layer 2: Ethernet frame parsing and ARP table resolution with cache expiration.&lt;br&gt;
Layer 3: IPv4 parsing, checksum calculation, and IP fragment reassembly.&lt;br&gt;
Layer 4: ICMP (ping echo reply/request), UDP, and full TCP state machine (three-way handshake SYN -&amp;gt; SYN-ACK -&amp;gt; ACK, sequence/acknowledgment tracking, window scaling, and packet retransmission).&lt;br&gt;
Because the TCP/IP stack runs natively inside the kernel, userspace processes can issue POSIX-like socket(), connect(), send(), and recv() syscalls to communicate over the real local network.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;From the exploish Shell to a GUI Compositor&lt;br&gt;
An OS needs an interface to be useful. Exploidus provides two layers:&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;The exploish Interactive Shell&lt;br&gt;
exploish runs as a Ring 3 userspace process, executing commands via system calls:&lt;/p&gt;
&lt;p&gt;ps: Inspects real kernel process tables, priorities, and execution states.&lt;br&gt;
audit: Reads cryptographic audit log entries directly from the kernel.&lt;br&gt;
mount / ls / cat: Traverses and manipulates the ExFS filesystem.&lt;br&gt;
The alien Window Compositor&lt;br&gt;
Moving beyond text mode, Exploidus includes a userspace graphical compositor called alien:&lt;/p&gt;
&lt;p&gt;Utilizes VESA / Linear Framebuffer modes discovered via Multiboot.&lt;br&gt;
Single-Syscall Window Blitting (SYS_FB_BLIT): Minimizes user-to-kernel context switching during rendering.&lt;br&gt;
Double-Buffering &amp;amp; Dirty-Region Redraws: Windows maintain their own back-buffers in userspace; the compositor only copies modified bounding boxes to the screen buffer, providing flicker-free rendering with real-time frame pacing.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;What Building an OS Taught Me&lt;br&gt;
Writing an operating system from scratch over months and years completely reshapes how you look at software engineering:&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Hardware is not clean; it is quirky: Silicon behaves in strange ways. Concurrency is not just threads racing; it is hardware interrupts firing in the middle of a critical pointer assignment. You develop an immense respect for atomic operations, IRQ-safe spinlocks, and memory barriers.&lt;br&gt;
Abstractions have a real cost: When you have to write your own kmalloc(), page fault handler, and scheduling timer, you realize that memory allocations and context switches are not free. High-level frameworks often hide enormous amounts of churn.&lt;br&gt;
Debugging without tools builds discipline: When you don't have GDB or stack traces, and an invalid memory write freezes the CPU instantly, you learn to reason through your code with mathematical precision. You read every line, analyze register states, and build defensive invariants.&lt;br&gt;
Conclusion &amp;amp; Open Source&lt;br&gt;
Exploidus started as an ambitious experiment in Bangladesh to explore what it takes to build an operating system from zero without relying on existing Linux codebases. Today, it stands as a fully documented, open-source x86-64 capability kernel with a rich ecosystem of drivers, filesystems, and networking.&lt;/p&gt;
&lt;p&gt;If you are interested in OS development, systems programming, or seeing how an x86-64 kernel works under the hood, the entire codebase is open-source:&lt;/p&gt;
&lt;p&gt;GitHub Repository: &lt;a rel=&quot;nofollow&quot; href=&quot;https://github.com/rahadbhuiya/Exploidus&quot;&gt;https://github.com/rahadbhuiya/Exploidus&lt;/a&gt;&lt;br&gt;
Feel free to star the repo, clone it, run it in QEMU, or read through the kernel source!&lt;/p&gt;
&lt;p&gt;Have you ever experimented with operating system development or bare-metal programming? What was the hardest low-level bug you ever encountered? Let's discuss in the comments below!&lt;/p&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/28568/building-an-x86-64-operating-system-from-scratch-in-c-the-exploidus-story</guid>
<pubDate>Fri, 25 Sep 2026 04:33:00 +0000</pubDate>
</item>
<item>
<title>Exploiting &quot;Trust-by-Default&quot;: How I transformed an ESP32-S3 into a BadUSB</title>
<link>https://coderlegion.com/26983/exploiting-trust-by-default-how-i-transformed-an-esp32-s3-into-a-badusb</link>
<description>&lt;p&gt;The first tool I decided to arm my Swiss army knife with was a BadUSB emulator. First and foremost, this extremely powerful tool (provided you have physical access to the target machine) relies on an inherent vulnerability of the USB protocol (born in 1996), originally designed to make connecting peripherals as simple and invisible as possible.&lt;/p&gt;
&lt;p&gt;Practically, when we plug a USB device into a computer, a rigorous process called &lt;em&gt;Enumeration&lt;/em&gt; begins. This is divided into several phases: the device is physically connected, its communication speed is identified, and immediately after, the device sends its Descriptors. These descriptors are a set of vital information that defines how the host machine will communicate with the device; subsequently, the device is reset, an address is assigned to it, the interfaces are loaded, and finally, the drivers.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;(If you want to delve deeper into the enumeration phase, I recommend &lt;a rel=&quot;nofollow&quot; href=&quot;https://www.totalphase.com/blog/2020/08/what-is-enumeration-why-usb-descriptors-important/&quot;&gt;this article by TotalPhase&lt;/a&gt;).&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;Having defined this, it's easy to guess that if we alter the descriptors via software, we can disguise an ordinary flash drive (or in our case, an M5Stick) making it appear as a keyboard or a mouse.&lt;/p&gt;
&lt;p&gt;And this is where the &quot;Trust-by-Default&quot; vulnerability comes into play: all operating systems blindly trust an HID (Human Interface Device) like a keyboard, as it is an essential input tool. Generic drivers are already pre-installed in the kernel (zero incompatibilities or warning popups) and, moreover, antiviruses have no say in the matter, since they are not designed to scan hardware inputs sent via electrical impulses.&lt;/p&gt;
&lt;h4 id=&quot;the-architectural-choice-dynamic-parser-vs-hardcoding&quot;&gt;The architectural choice: Dynamic Parser vs Hardcoding&lt;/h4&gt;
&lt;p&gt;Initially, for &quot;simplicity&quot;, I thought about hardcoding the payloads directly in the C source code. But thinking about it carefully, the use cases in pentesting are infinite: the end-user must have the ability to modify scripts on the fly, without having to recompile or flash the ESP32 firmware every time.&lt;/p&gt;
&lt;p&gt;For this reason, I decided to implement a dynamic Parser for DuckyScript. This allows the user to upload their own plain text scripts (&lt;code&gt;.txt&lt;/code&gt;) onto the device's LittleFS memory and have the microcontroller interpret them on the fly.&lt;/p&gt;
&lt;p&gt;For those unfamiliar with it, DuckyScript is a macro language created by Hak5 that abstracts interaction with the victim machine. It's simple and easily readable.&lt;br&gt;
To better explain what I mean by &quot;abstract&quot;: if I were to write a payload directly in low-level C or Bash, I would have to carefully calculate every single delay between one command and the next to give the PC time to open windows, and I would have to manually map the hexadecimal codes (HID Keycodes) of every single key to &quot;press&quot;. DuckyScript, combined with my parser, automates all of this.&lt;/p&gt;
&lt;p&gt;Originally, to use Rubber Ducky scripts, they had to be transformed from simple text files into binary files; this conversion was performed by a PC tool called Ducky Encoder, which converted them into &lt;code&gt;inject.bin&lt;/code&gt;. This tool was used because many older devices lacked the computational power to analyze text during runtime, a problem that the ESP32-S3 has now overcome.&lt;/p&gt;
&lt;p&gt;So I decided to integrate a native parser into my code: this way, a user can simply upload a file from their phone (via the dedicated internal HTML page) or from a computer and execute it immediately, without having to use an external tool for the conversion. Practically, this is done using standard C functions to separate the actual command from the argument at runtime:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-c&quot;&gt;char *cmd = strtok(line, &quot; &quot;);
char *arg = strtok(NULL, &quot;&quot;);

if (strcmp(cmd, &quot;DELAY&quot;) == 0 &amp;amp;&amp;amp; arg) {
    int delay_ms = atoi(arg); 
    if (delay_ms &amp;gt; 0) { 
        vTaskDelay(pdMS_TO_TICKS(delay_ms)); 
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h4 id=&quot;ram-security-o-1-space-complexity&quot;&gt;RAM Security: O(1) Space Complexity&lt;/h4&gt;
&lt;p&gt;But we all know that C doesn't joke around when it comes to memory allocation, so I tried to make the script reading phase as secure as possible. The underlying problem is that if a user decided to use a very long script (for example, uploading an entire binary file encoded in text), the M5Stick S3 would risk running out of the memory designated for the SRAM, resulting in a Kernel Panic followed by a crash and a device reboot.&lt;/p&gt;
&lt;p&gt;To bypass this hardware limit, I thought of allocating a buffer that reads the uploaded file in small, controlled blocks with the help of the &lt;code&gt;fgets()&lt;/code&gt; function, which is memory-safe by nature. This mathematically prevents a Buffer Overflow from occurring: even if the user uploads a malicious or malformed file with a single line 10,000 characters long, &lt;code&gt;fgets&lt;/code&gt; will still only read the first 255 characters per cycle, safeguarding the microcontroller's stack.&lt;/p&gt;
&lt;p&gt;If we look at the reading process from a space-complexity perspective, you can see that the way I decided to implement this mechanic has a space complexity of O(1); whereas the classic implementation would have had a complexity of O(N), as it would have loaded the entire file into RAM simultaneously.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-c&quot;&gt;// RAM consumption locked at only 256 bytes
char line[256];

// The file is strictly read and processed line by line
while (fgets(line, sizeof(line), f)) {
    trim_trailing(line); 
    if (strlen(line) == 0) continue;
    
    // ... start parsing for this specific line ...
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h4 id=&quot;beyond-abstraction-usb-protocol-and-polling-rate&quot;&gt;Beyond abstraction: USB Protocol and Polling Rate&lt;/h4&gt;
&lt;p&gt;Despite all the numerous advantages that come from using the ESP32-S3, one &quot;limit&quot; remains: not being able to use libraries that allow a high level of abstraction, such as Arduino's &lt;code&gt;Keyboard.h&lt;/code&gt;. This is a problem because, in the USB standard, a keyboard must regularly build and send 8-byte raw packets (divided into modifier mask, protocol byte, and key array) known as HID Reports.&lt;/p&gt;
&lt;p&gt;Sending these reports falls under the polling operation, which is a mechanism by which the Host (the PC) cyclically queries the USB device to check if there have been any state changes. Specifically, I handle these cyclic requests with &lt;code&gt;tud_hid_ready()&lt;/code&gt;, which checks if the USB Endpoint is free and if the PC has confirmed the reception of the previous packet. Through the &lt;code&gt;while (!tud_hid_ready()) vTaskDelay(...)&lt;/code&gt; block, I prevent the ESP32 from overwriting its own buffer before the packets have actually traveled across the cable. Without this blocking check, the keystrokes would be &quot;dropped&quot; (lost), and a DuckyScript command like &lt;code&gt;STRING powershell&lt;/code&gt; would be read by the victim PC as an incomprehensible &lt;code&gt;pwsel&lt;/code&gt;.&lt;/p&gt;
&lt;h4 id=&quot;state-based-logic-and-the-auto-repeat-trap&quot;&gt;State-Based Logic and the Auto-Repeat Trap&lt;/h4&gt;
&lt;p&gt;Added to this strict temporal &quot;dance&quot; of polling is one last huge engineering pitfall related to the nature of 8-byte reports. The most common cognitive error people run into is thinking that USB sends &quot;print commands&quot; (e.g., &quot;type the letter R&quot;). In reality, the USB architecture imposes a State-Based logic: the keyboard only communicates its electromechanical state to the PC at that precise moment.&lt;/p&gt;
&lt;p&gt;When we send a report with a specific key, we are not telling it to print it, but we are communicating: &quot;Right now, the user is physically pressing this key&quot;.&lt;/p&gt;
&lt;p&gt;The operating system's driver receives this state. If the microcontroller were to immediately move to the next command without doing anything else, the PC would think the user's finger was glued to the key, triggering the operating system's Auto-Repeat (which would endlessly open dozens of windows or print RRRRRRRR...). To solve this problem, my firmware is forced to close the cycle by always sending a subsequent &quot;zeroed&quot; HID Report (passing the &lt;code&gt;NULL&lt;/code&gt; array to TinyUSB). This tricks the PC, communicating that the key's physical contacts have finally been released (Key Release), allowing us to safely move on to the next letter.&lt;/p&gt;
&lt;h4 id=&quot;conclusion&quot;&gt;Conclusion&lt;/h4&gt;
&lt;p&gt;Developing a low-level BadUSB emulator using &lt;code&gt;esp_tinyusb&lt;/code&gt; is an immensely more educational challenge compared to using &quot;pre-built&quot; libraries. It forces you to study the anatomy of USB packets, understand how operating systems handle polling, and deal with the physical limits of a microcontroller's memory.&lt;/p&gt;
&lt;p&gt;Now our digital &quot;Swiss Army Knife&quot; has its first real weapon, capable of uploading and launching payloads on the fly in total safety.&lt;/p&gt;
&lt;p&gt;But a multi-tool isn't just a keyboard. What if we used the ESP32's antenna to intercept the invisible data floating in the air? In the next article, I'll show you how I configured the network interface in promiscuous mode to turn the ESP32 into a Wi-Fi Sniffer, capable of capturing raw packets and saving them directly to the file system in &lt;code&gt;.pcap&lt;/code&gt; format, ready to be analyzed on Wireshark.&lt;/p&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/26983/exploiting-trust-by-default-how-i-transformed-an-esp32-s3-into-a-badusb</guid>
<pubDate>Sat, 12 Sep 2026 14:58:38 +0000</pubDate>
</item>
<item>
<title>C++20 Modules in Practice: From Header Hell to Modular Architecture</title>
<link>https://coderlegion.com/26475/c-20-modules-in-practice-from-header-hell-to-modular-architecture</link>
<description>&lt;p&gt;C++20 Modules replace C++'s traditional textual inclusion model with a compiled module interface. Instead of repeatedly preprocessing the same headers in every translation unit, consumers explicitly &lt;code&gt;import&lt;/code&gt; the interface they depend on. No more header guards, no more include-ordering surprises, no more accidentally pulling in transitive dependencies through a chain of &lt;code&gt;#include&lt;/code&gt; directives.&lt;/p&gt;
&lt;p&gt;But the gap between understanding the idea and actually using modules in a project is significant. Build-system support differs between generators, compilers and standard libraries move at different paces, and partitions have sharp edges that only appear when you build. This post walks through building a small C++ library and application using C++20 Modules, progressively evolving the project to cover the concepts you need in practice.&lt;/p&gt;
&lt;p&gt;Everything below was built and run with the toolchain on my machine as of September 2026: &lt;strong&gt;GCC 16.2.1, CMake 4.3.0, Ninja 1.13.2&lt;/strong&gt; on Linux. Each example that is claimed to work was actually compiled, linked, and executed.&lt;/p&gt;
&lt;hr&gt;
&lt;h3 id=&quot;mental-model-the-key-declarations&quot;&gt;Mental Model: The Key Declarations&lt;/h3&gt;
&lt;p&gt;Before diving in, here is the vocabulary you will need. Each keyword has a precise meaning, and conflating them is the source of most confusion around modules.&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;&lt;th&gt;Declaration &lt;/th&gt;&lt;th&gt;What it means &lt;/th&gt;&lt;th&gt;Visible to importers?&lt;/th&gt;&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;export module math;&lt;/code&gt; &lt;/td&gt;&lt;td&gt;Defines the &lt;strong&gt;module interface unit&lt;/strong&gt; for named module &lt;code&gt;math&lt;/code&gt; &lt;/td&gt;&lt;td&gt;Yes (exported entities)&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;module math;&lt;/code&gt; &lt;/td&gt;&lt;td&gt;Declares this translation unit as a &lt;strong&gt;module implementation unit&lt;/strong&gt; belonging to &lt;code&gt;math&lt;/code&gt; &lt;/td&gt;&lt;td&gt;No&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;import math;&lt;/code&gt; &lt;/td&gt;&lt;td&gt;&lt;strong&gt;Imports&lt;/strong&gt; the named module &lt;code&gt;math&lt;/code&gt;, making its exported names visible &lt;/td&gt;&lt;td&gt;—&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;module;&lt;/code&gt; &lt;/td&gt;&lt;td&gt;Opens the &lt;strong&gt;global module fragment&lt;/strong&gt; (for legacy preprocessing, before the module declaration) &lt;/td&gt;&lt;td&gt;No&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;export module math:addition;&lt;/code&gt; &lt;/td&gt;&lt;td&gt;Defines a &lt;strong&gt;partition interface unit&lt;/strong&gt; of &lt;code&gt;math&lt;/code&gt; &lt;/td&gt;&lt;td&gt;Yes (if re-exported via &lt;code&gt;export import&lt;/code&gt;)&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;module math:addition;&lt;/code&gt; &lt;/td&gt;&lt;td&gt;Defines a &lt;strong&gt;partition implementation unit&lt;/strong&gt; of &lt;code&gt;math&lt;/code&gt; (name must not duplicate an existing interface partition) &lt;/td&gt;&lt;td&gt;Internal to module only&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;import &amp;lt;vector&amp;gt;;&lt;/code&gt; &lt;/td&gt;&lt;td&gt;Imports a &lt;strong&gt;header unit&lt;/strong&gt; (a header compiled as a unit, not a named module) &lt;/td&gt;&lt;td&gt;—&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;Note especially the difference between two &lt;em&gt;import&lt;/em&gt;-sounding declarations: &lt;code&gt;import math;&lt;/code&gt; means &quot;make this named module's exports available to me&quot;, while &lt;code&gt;module math;&lt;/code&gt; means &quot;this translation unit is part of the implementation of module &lt;code&gt;math&lt;/code&gt;&quot;. They do opposite things, and beginners routinely confuse them.&lt;/p&gt;
&lt;h3 id=&quot;what-a-named-module-actually-is&quot;&gt;What a Named Module Actually Is&lt;/h3&gt;
&lt;p&gt;A &lt;strong&gt;named module&lt;/strong&gt; is a logical entity consisting of one or more &lt;strong&gt;module units&lt;/strong&gt;. Three kinds of units matter for this article:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;A &lt;strong&gt;module interface unit&lt;/strong&gt; — a translation unit that begins with &lt;code&gt;export module &amp;lt;name&amp;gt;;&lt;/code&gt; and provides the module's exported interface.&lt;/li&gt;
&lt;li&gt;A &lt;strong&gt;module implementation unit&lt;/strong&gt; — a translation unit that begins with &lt;code&gt;module &amp;lt;name&amp;gt;;&lt;/code&gt;, belongs to the module, but does not itself export anything.&lt;/li&gt;
&lt;li&gt;A &lt;strong&gt;module partition&lt;/strong&gt; — a translation unit whose name includes a &lt;code&gt;:&lt;/code&gt; (e.g. &lt;code&gt;export module math:addition;&lt;/code&gt;); partitions are always part of a named module.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Conflating &quot;a module&quot; with &quot;a .cppm file&quot; is a common mistake. A module is the &lt;em&gt;set&lt;/em&gt; of units sharing the module name; the interface unit is just one of them, and the exported names are only the ones marked &lt;code&gt;export&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Unlike a header, a module interface is compiled as a translation unit, and consumers read the compiler's compiled representation of that interface rather than repeatedly preprocessing the same header text.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-cpp&quot;&gt;// math.cppm — module interface unit
export module math;

export int add(int a, int b) {
    return a + b;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-cpp&quot;&gt;// main.cpp — consumer translation unit
import math;

int main() {
    return add(1, 2);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;That is the simplest possible module. Interface in one file, consumer in another, no headers in sight.&lt;/p&gt;
&lt;h3 id=&quot;building-modules-with-cmake-and-ninja&quot;&gt;Building Modules with CMake and Ninja&lt;/h3&gt;
&lt;p&gt;There are two important prerequisites before any of this builds:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;The generator matters.&lt;/strong&gt; CMake's C++ module dependency scanning (checking which units produce which interface files, and ordering compilation so interfaces build before their importers) is supported by the &lt;strong&gt;Ninja&lt;/strong&gt;, &lt;strong&gt;Ninja Multi-Config&lt;/strong&gt;, and &lt;strong&gt;Visual Studio 17 2022&lt;/strong&gt; generators. It is &lt;em&gt;not&lt;/em&gt; supported by the Unix Makefiles generator. On Linux, CMake picks Unix Makefiles by default, so you must request Ninja explicitly:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-sh&quot;&gt;cmake -S . -B build -G Ninja
&lt;/code&gt;&lt;/pre&gt;
&lt;blockquote&gt;&lt;p&gt;&lt;strong&gt;Tip for IDE users:&lt;/strong&gt; If you are using CLion, VS Code with CMake Tools, or another IDE, check your CMake generator settings. Many still default to Unix Makefiles on Linux. Explicitly set &lt;code&gt;-G Ninja&lt;/code&gt; in your CMake configuration (e.g., CLion's &lt;em&gt;Toolchains &amp;gt; CMake options&lt;/em&gt;, or VS Code's &lt;code&gt;cmake.generator&lt;/code&gt; setting) to avoid silent module-scanning failures.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Module interface files must be declared as a &lt;code&gt;CXX_MODULES&lt;/code&gt; file set.&lt;/strong&gt; Declaring &lt;code&gt;math.cppm&lt;/code&gt; the way you would list a plain source does not work in modern CMake. I verified this: with CMake 4.3, listing the file directly in &lt;code&gt;add_executable()&lt;/code&gt; fails with&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;CMake Error: Output CMakeFiles/app.dir/math.cppm.o provides the `math` module
but it is not found in a `FILE_SET` of type `CXX_MODULES`
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;C++ modules need their own file-set type, which CMake introduced for modules in 3.28:&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;pre&gt;&lt;code class=&quot;language-cmake&quot;&gt;cmake_minimum_required(VERSION 3.30)
project(MathLib LANGUAGES CXX)

add_executable(app main.cpp)

target_sources(app PRIVATE
    FILE_SET CXX_MODULES
    FILES math.cppm
)

target_compile_features(app PRIVATE cxx_std_20)
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-sh&quot;&gt;cmake -S . -B build -G Ninja
cmake --build build
./build/app
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;CMake analyzes the module dependency graph and compiles &lt;code&gt;math&lt;/code&gt; before &lt;code&gt;main.cpp&lt;/code&gt;, even if &lt;code&gt;math.cppm&lt;/code&gt; is listed after it in the file set.&lt;/p&gt;
&lt;p&gt;A few CMake version notes:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;CMake 3.28 introduced both the &lt;code&gt;CXX_MODULES&lt;/code&gt; file set and initial experimental module support.&lt;/li&gt;
&lt;li&gt;The &lt;code&gt;CMAKE_EXPERIMENTAL_CXX_MODULE_CMAKE_API&lt;/code&gt; flag is no longer needed when using the file-set approach on recent toolchains; CMake enables module dependency scanning automatically with a supported generator.&lt;/li&gt;
&lt;li&gt;If you are on an older CMake than 3.30, expect version-specific behaviour. Module support has changed in every release since 3.28, and the examples here were tested with CMake 4.3.0.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id=&quot;interface-vs-implementation-units&quot;&gt;Interface vs. Implementation Units&lt;/h3&gt;
&lt;p&gt;A module interface file can contain both declarations and definitions. But in practice, you want to separate them—just like you would with headers and source files.&lt;/p&gt;
&lt;p&gt;Consider a math library with an &lt;code&gt;add&lt;/code&gt; function:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-cpp&quot;&gt;// math.cppm — interface unit
export module math;

export int add(int a, int b);
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-cpp&quot;&gt;// math.cpp — implementation unit
module math;

int add(int a, int b) {
    return a + b;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Notice the difference: the interface unit uses &lt;code&gt;export module math;&lt;/code&gt;, while the implementation unit uses just &lt;code&gt;module math;&lt;/code&gt;. The &lt;code&gt;export&lt;/code&gt; keyword on &lt;code&gt;add&lt;/code&gt; in the interface makes it visible to consumers. The implementation file provides the body.&lt;/p&gt;
&lt;p&gt;The module's exported interface defines what names are intentionally made available. Declarations that are not exported are not reachable by importers through normal means.&lt;/p&gt;
&lt;h4 id=&quot;implementation-units-do-not-map-one-to-one-to-declarations&quot;&gt;Implementation units do not map one-to-one to declarations&lt;/h4&gt;
&lt;p&gt;An implementation unit does not have to correspond one-to-one with an exported declaration. A single implementation unit can define several exported functions, an exported function can be defined directly in the interface unit, and multiple implementation units can contribute to the same module. The split is an engineering choice, not a language requirement.&lt;/p&gt;
&lt;p&gt;For example, everything in the interface:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-cpp&quot;&gt;// math.cppm — everything in the interface unit
export module math;

export int add(int a, int b) {
    return a + b;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Or definitions spread across implementation units:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-cpp&quot;&gt;// math.cppm
export module math;

export int add(int a, int b);
export int multiply(int a, int b);
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-cpp&quot;&gt;// math.cpp — implementation unit
module math;

int add(int a, int b) {
    return a + b;
}

int multiply(int a, int b) {
    return a * b;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Neither form is &quot;more correct&quot;. What matters is that the exported names are declared with &lt;code&gt;export&lt;/code&gt; in the interface unit.&lt;/p&gt;
&lt;h3 id=&quot;splitting-implementation-across-files&quot;&gt;Splitting Implementation Across Files&lt;/h3&gt;
&lt;p&gt;As your library grows, you can split implementation code across multiple &lt;code&gt;.cpp&lt;/code&gt; files. Each file that begins with &lt;code&gt;module math;&lt;/code&gt; is an implementation unit of &lt;code&gt;math&lt;/code&gt;, and the compiler and linker combine them.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;math-modules/
├── CMakeLists.txt
├── math.cppm
├── math_add.cpp
├── math_multiply.cpp
└── main.cpp
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-cpp&quot;&gt;// math.cppm — interface unit
export module math;

export int add(int a, int b);
export int multiply(int a, int b);
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-cpp&quot;&gt;// math_add.cpp — implementation unit
module math;

int add(int a, int b) {
    return a + b;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-cpp&quot;&gt;// math_multiply.cpp — implementation unit
module math;

int multiply(int a, int b) {
    return a * b;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Crucially, &lt;strong&gt;implementation units are not module files&lt;/strong&gt; in the &lt;code&gt;CXX_MODULES&lt;/code&gt; sense. They are ordinary sources that happen to declare &lt;code&gt;module math;&lt;/code&gt;. I verified that listing &lt;code&gt;math_add.cpp&lt;/code&gt; and &lt;code&gt;math_multiply.cpp&lt;/code&gt; inside &lt;code&gt;FILE_SET CXX_MODULES&lt;/code&gt; fails with:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;CMake Error: Output CMakeFiles/app.dir/math_add.cpp.o is of type `CXX_MODULES`
but does not provide a module interface unit or partition
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The correct representation:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-cmake&quot;&gt;cmake_minimum_required(VERSION 3.30)
project(MathLib LANGUAGES CXX)

add_executable(app main.cpp)

target_sources(app PRIVATE
    FILE_SET CXX_MODULES
    FILES math.cppm
)
target_sources(app PRIVATE
    math_add.cpp
    math_multiply.cpp
)

target_compile_features(app PRIVATE cxx_std_20)
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-sh&quot;&gt;cmake -S . -B build -G Ninja
cmake --build build
./build/app
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;All three module units—&lt;code&gt;math.cppm&lt;/code&gt;, &lt;code&gt;math_add.cpp&lt;/code&gt;, and &lt;code&gt;math_multiply.cpp&lt;/code&gt;—belong to the named module &lt;code&gt;math&lt;/code&gt;. CMake compiles them separately and links them together.&lt;/p&gt;
&lt;p&gt;An incremental rebuild after changing &lt;code&gt;main.cpp&lt;/code&gt; recompiles only the consumer and relinks; the module interface is not rebuilt. I verified this with &lt;code&gt;ninja: no work to do&lt;/code&gt; on an unchanged tree, and a two-step rebuild after touching &lt;code&gt;main.cpp&lt;/code&gt;.&lt;/p&gt;
&lt;h4 id=&quot;a-library-not-just-an-executable&quot;&gt;A library, not just an executable&lt;/h4&gt;
&lt;p&gt;Once you want to share the module, the same structure applies to a library target. Implementation units are plain private sources; the interface file is a public &lt;code&gt;CXX_MODULES&lt;/code&gt; file set, which CMake can later install as a compiled module interface:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-cmake&quot;&gt;cmake_minimum_required(VERSION 3.30)
project(MathLib LANGUAGES CXX)

add_library(math
    math_add.cpp
    math_multiply.cpp
)

target_sources(math
    PUBLIC
        FILE_SET CXX_MODULES
        FILES math.cppm
)

target_compile_features(math PUBLIC cxx_std_20)

add_executable(app main.cpp)
target_link_libraries(app PRIVATE math)
&lt;/code&gt;&lt;/pre&gt;
&lt;h3 id=&quot;modules-and-legacy-headers&quot;&gt;Modules and Legacy Headers&lt;/h3&gt;
&lt;p&gt;Real projects do not start from scratch. You will have existing header-based libraries, system headers, and third-party dependencies. C++20 gives you three distinct ways for a module to interact with legacy textual headers, and it's worth keeping them clearly separated:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;#include&lt;/code&gt; in the global module fragment&lt;/strong&gt; — for headers processed before the module purview begins.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;#include&lt;/code&gt; in the module purview&lt;/strong&gt; — possible for headers you need to parse, but with real costs.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;import&lt;/code&gt; of a header unit&lt;/strong&gt; — a header compiled as a unit rather than textually included.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;The common mistake is reaching straight for mechanism 2 because it looks like a plain include.&lt;/p&gt;
&lt;h4 id=&quot;-include-in-the-module-purview&quot;&gt;&lt;code&gt;#include&lt;/code&gt; in the module purview&lt;/h4&gt;
&lt;p&gt;A module interface unit can contain &lt;code&gt;#include&lt;/code&gt; directives. However, declarations introduced by those headers are &lt;strong&gt;not automatically exported&lt;/strong&gt; merely because they were included. &lt;code&gt;export module strings;&lt;/code&gt; followed by &lt;code&gt;#include &amp;lt;string&amp;gt;&lt;/code&gt; is not the same as &lt;code&gt;export import &amp;lt;string&amp;gt;;&lt;/code&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-cpp&quot;&gt;// strings.cppm — interface unit
export module strings;

#include &amp;lt;string&amp;gt;

export std::string concatenate(const std::string&amp;amp; a, const std::string&amp;amp; b);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;code&gt;std::string&lt;/code&gt; declarations are needed to parse the exported function signature, but they are not part of the module's exported interface. Yet the header still has an effect: its declarations become part of the module's semantic dependencies, and including large or implementation-oriented headers here increases coupling and complicates portability.&lt;/p&gt;
&lt;p&gt;The deeper risk is &lt;strong&gt;module attachment&lt;/strong&gt;. When you &lt;code&gt;#include&lt;/code&gt; a header inside the module purview, the declarations from that header become &lt;em&gt;attached&lt;/em&gt; to the named module. Entities acquired through module attachment acquire &lt;strong&gt;module linkage&lt;/strong&gt;—they are internal to the module's linkage domain. If another translation unit—outside any named module—also &lt;code&gt;#include&lt;/code&gt;s the same header in the traditional way, the same declarations acquire &lt;strong&gt;external linkage&lt;/strong&gt; instead. You now have two different linkage contexts for what looks like the same entity. This can cause subtle &lt;strong&gt;One Definition Rule (ODR)&lt;/strong&gt; violations or symbol conflicts at link time, because the compiler treats the module-attached copy and the traditionally-included copy as distinct. The symptoms range from mysterious linker errors to silent undefined behaviour at runtime.&lt;/p&gt;
&lt;p&gt;So: including headers in the module purview is &lt;em&gt;possible&lt;/em&gt;, but it is not harmless, and cppreference's guidance is to avoid it in the module interface when you can. Prefer the global module fragment (below) when textual inclusion is genuinely needed.&lt;/p&gt;
&lt;h4 id=&quot;the-global-module-fragment&quot;&gt;The global module fragment&lt;/h4&gt;
&lt;p&gt;The global module fragment exists precisely for the case where textual inclusion is needed. It lets preprocessing directives—especially legacy includes and configuration macros—be processed before the module purview begins.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-cpp&quot;&gt;// legacy_wrapper.cppm
module;

// Processed in the global module, before the module purview.
#include &quot;legacy_header.h&quot;

export module legacy_wrapper;

export void wrapper_function() {
    legacy_function();  // from legacy_header.h
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;code&gt;module;&lt;/code&gt; declaration at the top opens the global module fragment; everything between &lt;code&gt;module;&lt;/code&gt; and &lt;code&gt;export module legacy_wrapper;&lt;/code&gt; is processed in the global module. After the &lt;code&gt;export module&lt;/code&gt; line, the purview begins.&lt;/p&gt;
&lt;p&gt;The standard is strict about what the GMF may contain: &lt;strong&gt;only preprocessor directives&lt;/strong&gt; (&lt;code&gt;#include&lt;/code&gt;, &lt;code&gt;#define&lt;/code&gt;, &lt;code&gt;#ifdef&lt;/code&gt;, etc.). You cannot write raw C++ declarations or definitions inside the GMF—anything that is not a preprocessor directive is ill-formed there. Any declarations you need must come from headers included within the fragment, not from hand-written code.&lt;/p&gt;
&lt;p&gt;This is not a bulletproof &quot;safe zone&quot;: its purpose is to apply legacy textual inclusion semantics before the module machinery starts. Some legacy headers can still cause problems here. But for headers that need to be textually present—particularly those with configuration macros—the global module fragment is the intended mechanism.&lt;/p&gt;
&lt;p&gt;Note the distinction: a regular &lt;code&gt;.cpp&lt;/code&gt; source without any module declaration is an ordinary non-module translation unit. It is &lt;em&gt;not&lt;/em&gt; a &quot;global module fragment&quot; and does not belong to any named module. The &lt;code&gt;module;&lt;/code&gt; declaration must be written explicitly.&lt;/p&gt;
&lt;h4 id=&quot;header-units&quot;&gt;Header units&lt;/h4&gt;
&lt;p&gt;C++20 also defines &lt;strong&gt;header units&lt;/strong&gt;, which allow a header to be imported rather than textually included:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-cpp&quot;&gt;import &amp;lt;vector&amp;gt;;
import &quot;my_legacy_header.h&quot;;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Header units behave differently from named modules: they preserve much more of the header's semantics (they are, essentially, the header compiled as a unit), and they are primarily a migration and interoperability mechanism. A header processed as a header unit is not a named module and does not get &lt;code&gt;export&lt;/code&gt; semantics. Importing a header unit also requires explicit compiler flags and build-system support to generate a BMI for every header you want to import, which is one reason &lt;code&gt;import std;&lt;/code&gt; (C++23) superseded header units for standard-library usage: it provides a single, curated module instead of requiring per-header BMI generation. Support for header units is uneven across compilers, which is why this article focuses on named modules—but you should know the distinction exists, because &lt;code&gt;import&lt;/code&gt; alone does not always mean &quot;named module&quot;.&lt;/p&gt;
&lt;h3 id=&quot;migrating-a-header-based-library&quot;&gt;Migrating a Header-Based Library&lt;/h3&gt;
&lt;p&gt;Migrating an existing &lt;code&gt;include/&lt;/code&gt; + &lt;code&gt;src/&lt;/code&gt; library to modules is not a mechanical one-to-one conversion. But the general mapping is:&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;&lt;th&gt;Traditional &lt;/th&gt;&lt;th&gt;Possible module equivalent&lt;/th&gt;&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;&lt;td&gt;Public header (&lt;code&gt;include/lib/foo.h&lt;/code&gt;) &lt;/td&gt;&lt;td&gt;Module interface unit (&lt;code&gt;foo.cppm&lt;/code&gt;)&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;Source file (&lt;code&gt;src/foo.cpp&lt;/code&gt;) &lt;/td&gt;&lt;td&gt;Module implementation unit (&lt;code&gt;foo.cpp&lt;/code&gt;, &lt;code&gt;module foo;&lt;/code&gt;)&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;Private header (&lt;code&gt;include/lib/detail/bar.h&lt;/code&gt;) &lt;/td&gt;&lt;td&gt;Header included by an implementation unit, or a module partition when appropriate&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;Header-only component &lt;/td&gt;&lt;td&gt;Interface unit, or an interface partition, depending on design&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;The key insight: headers that were previously available to anyone who included the public header become invisible to importers unless explicitly exported. This is the explicit boundary that modules enforce.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-cpp&quot;&gt;// foo.cppm — the public interface (replaces include/lib/foo.h)
export module foo;

export void public_function();
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-cpp&quot;&gt;// foo.cpp — implementation unit (replaces src/foo.cpp)
module foo;

#include &quot;detail/helpers.h&quot;   // private header included here, not exported

void public_function() {
    internal_helper();
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The private header is included only in the implementation unit. Its contents are not visible to importers of &lt;code&gt;foo&lt;/code&gt;.&lt;/p&gt;
&lt;h3 id=&quot;partitions&quot;&gt;Partitions&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;Partitions&lt;/strong&gt; let you split a module into multiple logical units. There are two kinds, and they serve different purposes:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;An &lt;strong&gt;interface partition&lt;/strong&gt; begins with &lt;code&gt;export module math:addition;&lt;/code&gt;. It can contain exported declarations, and can be re-exported from the primary module interface with &lt;code&gt;export import :addition;&lt;/code&gt;, making its exports visible to consumers of &lt;code&gt;math&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;An &lt;strong&gt;implementation partition&lt;/strong&gt; begins with &lt;code&gt;module math:addition;&lt;/code&gt;—without the &lt;code&gt;export&lt;/code&gt; on the declaration. It cannot export names; it exists only for module-internal organization, often to split a large implementation across files without exposing those boundaries.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The interface-partition arrangement, with definitions written directly in the partition interfaces:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-cpp&quot;&gt;// math.cppm — primary interface
export module math;

export import :addition;
export import :multiplication;
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-cpp&quot;&gt;// math.addition.cppm — interface partition
export module math:addition;

export int add(int a, int b) { return a + b; }
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-cpp&quot;&gt;// math.multiplication.cppm — interface partition
export module math:multiplication;

export int multiply(int a, int b) { return a * b; }
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-cpp&quot;&gt;// main.cpp
import math;

int main() { return multiply(add(1, 2), 3); }
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-cmake&quot;&gt;cmake_minimum_required(VERSION 3.30)
project(MathLib LANGUAGES CXX)

add_executable(app main.cpp)

target_sources(app PRIVATE
    FILE_SET CXX_MODULES
    FILES
        math.cppm
        math.addition.cppm
        math.multiplication.cppm
)

target_compile_features(app PRIVATE cxx_std_20)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;I compiled and ran this exact arrangement on the toolchain described above; it builds and runs.&lt;/p&gt;
&lt;h4 id=&quot;a-sharp-edge-implementation-partitions&quot;&gt;A sharp edge: implementation partitions&lt;/h4&gt;
&lt;p&gt;In C++20, the declaration &lt;code&gt;module math:addition;&lt;/code&gt; is ambiguous—it can mean two distinct things:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;The implementation unit for an existing interface partition.&lt;/strong&gt; You have already defined &lt;code&gt;export module math:addition;&lt;/code&gt; in a &lt;code&gt;.cppm&lt;/code&gt; file, and this &lt;code&gt;.cpp&lt;/code&gt; file provides its definitions.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;An internal implementation partition.&lt;/strong&gt; A partition that is &lt;em&gt;not&lt;/em&gt; exported to module consumers, but is imported by the primary module (or another partition) via &lt;code&gt;import :addition;&lt;/code&gt;. This partition is internal to the module's build, not part of its public interface.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;This is not merely a toolchain quirk—it reflects a &lt;strong&gt;C++20 standard constraint&lt;/strong&gt;: partition names must be unique within a named module. A module can have one primary interface unit (&lt;code&gt;export module math;&lt;/code&gt;) and multiple primary implementation units (&lt;code&gt;module math;&lt;/code&gt;), but each partition name designates a &lt;em&gt;single, distinct&lt;/em&gt; translation unit. You cannot have both an interface partition and a separate implementation file sharing the partition name &lt;code&gt;:addition&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;In practice, this means &lt;code&gt;math.addition.cppm&lt;/code&gt; with &lt;code&gt;export module math:addition;&lt;/code&gt; and &lt;code&gt;math.add_impl.cpp&lt;/code&gt; with &lt;code&gt;module math:addition;&lt;/code&gt; both target the same partition name, and GCC's build model tries to emit a compiled module interface (&lt;code&gt;.gcm&lt;/code&gt; / BMI) for both. The BMI output is named after the &lt;em&gt;partition name&lt;/em&gt; (&lt;code&gt;math-addition.gcm&lt;/code&gt;), not the source file, so the build fails with:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;ninja: build stopped: multiple rules generate CMakeFiles/app.dir/math-addition.gcm.
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Renaming the files does not help—the collision follows the partition name, not the filename. If you want to separate implementation details into an internal partition, it must use a &lt;strong&gt;unique partition name&lt;/strong&gt; (e.g., &lt;code&gt;module math:addition_impl;&lt;/code&gt;), or the definitions should be placed in a standard module implementation unit (&lt;code&gt;module math;&lt;/code&gt;). On the toolchain tested here, the standard-constraint collision manifests as a build failure; the language rule is clear, and the build system is correctly enforcing it.&lt;/p&gt;
&lt;h3 id=&quot;the-std-module-c-23-&quot;&gt;The &lt;code&gt;std&lt;/code&gt; Module (C++23)&lt;/h3&gt;
&lt;p&gt;The &lt;code&gt;std&lt;/code&gt; module deserves its own section because it combines a genuinely useful idea with a lot of ecosystem caveats.&lt;/p&gt;
&lt;p&gt;First, the distinction the article's title implies: &lt;strong&gt;modules are C++20, but &lt;code&gt;import std;&lt;/code&gt; is C++23.&lt;/strong&gt; The standard-library module is standardized in C++23 and tracked by the &lt;code&gt;__cpp_lib_modules&lt;/code&gt; feature-test macro. A &lt;code&gt;std&lt;/code&gt;-module is not the same as the C++20 named-module machinery—it builds on it, but requires a compiler &lt;em&gt;and&lt;/em&gt; standard-library implementation that support it.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-cpp&quot;&gt;// main.cpp
import std;

int main() {
    std::vector&amp;lt;int&amp;gt; v = {1, 2, 3};
    std::ranges::sort(v);
    std::cout &amp;lt;&amp;lt; v[0] &amp;lt;&amp;lt; '\n';
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;import std;&lt;/code&gt; can substantially reduce repeated parsing of standard-library headers in some projects, but the actual build-time improvement depends heavily on the compiler, standard library, and project. Do not expect a fixed percentage; measure it on your own tree.&lt;/p&gt;
&lt;p&gt;The practical situation deserves precision:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Compilers do not ship &lt;code&gt;import std;&lt;/code&gt; as a free lunch.&lt;/strong&gt; On my machine, GCC's libstdc++ provides &lt;code&gt;bits/std.cc&lt;/code&gt; and a &lt;code&gt;libstdc++.modules.json&lt;/code&gt;, but &lt;code&gt;import std;&lt;/code&gt; still fails out of the box with &lt;code&gt;unknown compiled module interface: no such module&lt;/code&gt; until the standard library module has been built and its interface made available.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;CMake's support has been experimental throughout the 3.28–4.x era.&lt;/strong&gt; CMake 3.30 introduced &lt;code&gt;CMAKE_CXX_MODULE_STD&lt;/code&gt; and &lt;code&gt;CMAKE_CXX_COMPILER_IMPORT_STD&lt;/code&gt;, gated behind experimental &lt;code&gt;import std&lt;/code&gt; support; the gating mechanism itself has changed between CMake versions. On CMake 4.3.0 I could not get &lt;code&gt;import std;&lt;/code&gt; building out of the box with the straightforward experimental flags.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Support is layered.&lt;/strong&gt; A compiler may support named modules while its standard library and build system still have incomplete or experimental support for the standard-library module.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The useful practical takeaway: treat &lt;code&gt;import std;&lt;/code&gt; as a separate concern from ordinary C++20 named-module support. A toolchain can be fully capable of named modules and still not support &lt;code&gt;import std;&lt;/code&gt; yet. Check the documentation for your exact compiler &lt;em&gt;and&lt;/em&gt; standard-library versions before relying on it.&lt;/p&gt;
&lt;p&gt;For new projects, &lt;code&gt;import std;&lt;/code&gt; is worth experimenting with if your toolchain supports it. For existing projects, it can be adopted incrementally, one module at a time.&lt;/p&gt;
&lt;h3 id=&quot;compiler-cmake-and-ide-compatibility&quot;&gt;Compiler, CMake, and IDE Compatibility&lt;/h3&gt;
&lt;p&gt;There are several separate questions when evaluating module readiness, and a &quot;yes&quot; on one does not imply &quot;yes&quot; on all:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Does the compiler implement C++20 named modules?&lt;/li&gt;
&lt;li&gt;Does its standard library work well with modules (and with &lt;code&gt;import std;&lt;/code&gt;)?&lt;/li&gt;
&lt;li&gt;Does the compiler support the specific module features you want (partitions, header units)?&lt;/li&gt;
&lt;li&gt;Does the build system (CMake &lt;em&gt;and&lt;/em&gt; the chosen generator) support dependency scanning for your compiler?&lt;/li&gt;
&lt;li&gt;Does your IDE's language server understand module imports and rebuild dependencies?&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The examples in this article were tested on my machine with the versions shown, using the Ninja generator, with a clean build and an incremental rebuild:&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;&lt;th&gt;Toolchain &lt;/th&gt;&lt;th&gt;Tested &lt;/th&gt;&lt;th&gt;Basic named modules &lt;/th&gt;&lt;th&gt;Interface partitions &lt;/th&gt;&lt;th&gt;&lt;code&gt;import std&lt;/code&gt;&lt;/th&gt;&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;&lt;td&gt;GCC + CMake + Ninja &lt;/td&gt;&lt;td&gt;16.2.1 / 4.3.0 / 1.13.2 &lt;/td&gt;&lt;td&gt;Yes &lt;/td&gt;&lt;td&gt;Yes &lt;/td&gt;&lt;td&gt;Experimental / not working out of box&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;Clang + CMake + Ninja &lt;/td&gt;&lt;td&gt;not tested here &lt;/td&gt;&lt;td&gt;— &lt;/td&gt;&lt;td&gt;— &lt;/td&gt;&lt;td&gt;—&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;Notes on the methodology, so the table means what it appears to mean:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&quot;Basic named modules&quot; = a primary interface unit, a consumer, and—separately—a consumer with implementation units. Both built clean and incrementally.&lt;/li&gt;
&lt;li&gt;&quot;Interface partitions&quot; = interface partitions with inline definitions, re-exported via &lt;code&gt;export import&lt;/code&gt; from the primary interface. Built clean and incremental.&lt;/li&gt;
&lt;li&gt;&quot;Implementation partitions&quot; are &lt;strong&gt;not&lt;/strong&gt; listed as working—they fail due to the partition name uniqueness constraint (see the sharp-edge section above).&lt;/li&gt;
&lt;li&gt;&lt;code&gt;import std;&lt;/code&gt; is marked experimental: libstdc++ ships the std module source, but it does not build out of the box with the tested CMake version.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Other ecosystem considerations:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;IDE support&lt;/strong&gt; continues to vary. Language servers generally understand named modules now, but completion, navigation, and refactoring across module boundaries may lag behind their header-based equivalents.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Third-party libraries&lt;/strong&gt; are mostly header-based. Using modules with them requires a wrapper module or the global module fragment.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Package managers&lt;/strong&gt; are adding module support, but it is not the default.&lt;/li&gt;
&lt;li&gt;GCC's own documentation notes that its C++20 module implementation is still incomplete in places. The status improves with every release—check the release notes for your exact version rather than assuming support from the version number.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Modules can be a practical choice for greenfield projects when you control the compiler, standard library, build system, and IDE versions. For large existing codebases, gradual migration is usually more realistic.&lt;/p&gt;
&lt;h3 id=&quot;what-modules-do-not-solve&quot;&gt;What Modules Do Not Solve&lt;/h3&gt;
&lt;p&gt;Modules are not a universal fix for C++ project complexity. A few things to keep in mind:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Build times can go either way.&lt;/strong&gt; For small projects, module compilation may be slower than header inclusion because the compiler must first produce a compiled module interface and the build system must manage a dependency graph. The potential benefit comes from avoiding repeated parsing and preprocessing of the same declarations across many translation units; how large the improvement is depends heavily on the dependency graph, compiler, and build structure. Measure it.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Macros are a different story.&lt;/strong&gt; Macros defined in traditional headers remain governed by the preprocessor and can still pollute any translation unit that includes those headers. In contrast, macros defined &lt;em&gt;inside a named module&lt;/em&gt; are not exported to importers. Modules therefore significantly reduce macro leakage from your own module code, but they cannot make legacy headers' macros disappear.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Binary compatibility does not change.&lt;/strong&gt; Modules affect how you organize source code and what each translation unit sees, not the ABI. Shipping a shared library built with modules looks the same at the binary level as one built with headers.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;You still need a build system that understands modules.&lt;/strong&gt; Modules require the build system to know the dependency graph between interface units, implementation units, partitions, and consumers—a harder problem than the header model, where each translation unit independently resolves its own includes. That is why generator support (Ninja, Visual Studio) and the &lt;code&gt;CXX_MODULES&lt;/code&gt; file set matter.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id=&quot;takeaway&quot;&gt;Takeaway&lt;/h3&gt;
&lt;p&gt;C++20 Modules replace the textual inclusion model with a compiled interface model. The concepts that matter in practice:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;An &lt;strong&gt;interface unit&lt;/strong&gt; (&lt;code&gt;export module math;&lt;/code&gt;) defines the public API; only &lt;code&gt;export&lt;/code&gt;ed names are visible to importers.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Implementation units&lt;/strong&gt; (&lt;code&gt;module math;&lt;/code&gt;) provide definitions and internal details; they are ordinary sources, not &lt;code&gt;CXX_MODULES&lt;/code&gt; file-set entries.&lt;/li&gt;
&lt;li&gt;The &lt;strong&gt;global module fragment&lt;/strong&gt; (&lt;code&gt;module;&lt;/code&gt;) handles legacy includes and configuration preprocessing before the module purview.&lt;/li&gt;
&lt;li&gt;Legacy headers participate through one of three mechanisms: &lt;code&gt;#include&lt;/code&gt; in the global module fragment, &lt;code&gt;#include&lt;/code&gt; in the purview, or header-unit &lt;code&gt;import&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Interface partitions&lt;/strong&gt; (&lt;code&gt;export module math:addition;&lt;/code&gt;) organize a module's public interface; &lt;strong&gt;implementation partitions&lt;/strong&gt; (&lt;code&gt;module math:addition;&lt;/code&gt;) must use a unique partition name that does not duplicate an existing interface partition—otherwise the build fails due to a C++20 standard constraint.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;import std;&lt;/code&gt; is C++23, experimental across the ecosystem, and should be evaluated separately from named-module support.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The practical workflow: start with a single &lt;code&gt;.cppm&lt;/code&gt; file in a &lt;code&gt;CXX_MODULES&lt;/code&gt; file set, put accompanying implementation units in plain sources, use the &lt;strong&gt;Ninja&lt;/strong&gt; generator, and let CMake handle the compilation ordering. Introduce partitions only once the interface genuinely needs them, and test them on your exact toolchain first.&lt;/p&gt;
&lt;p&gt;Modules do not solve every problem—macros in legacy headers, binary compatibility, and build tools are still part of the picture. But where you control the toolchain, the explicit boundary between interface and implementation is a real improvement over the header model.&lt;/p&gt;
&lt;h3 id=&quot;further-reading&quot;&gt;Further Reading&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://en.cppreference.com/w/cpp/language/modules&quot;&gt;C++20 Modules on cppreference&lt;/a&gt; — the authoritative language reference for module declarations, partitions, and header units.&lt;/li&gt;
&lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://learn.microsoft.com/en-us/cpp/cpp/modules-cpp&quot;&gt;Modules in C++ (Microsoft docs)&lt;/a&gt; — practical guide from the MSVC team covering module design, build integration, and migration patterns.&lt;/li&gt;
&lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://www.kitware.com/import-cmake-the-experiment-is-over/&quot;&gt;Import CMake: The Experiment Is Over&lt;/a&gt; — Kitware's account of how CMake's module support evolved from experimental flags to the &lt;code&gt;CXX_MODULES&lt;/code&gt; file set.&lt;/li&gt;
&lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://devblogs.microsoft.com/cppblog/cpp20-modules-in-cmake-with-vs/&quot;&gt;C++20 Modules in CMake with Visual Studio&lt;/a&gt; — Microsoft's walkthrough of module builds with CMake and MSVC.&lt;/li&gt;
&lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://discourse.cmake.org/t/c-20-modules-update/7330&quot;&gt;CMake Discourse: C++20 Modules Update&lt;/a&gt; — community discussion on the current state of CMake module support.&lt;/li&gt;
&lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://www.modernescpp.com/index.php/cpp20-a-first-module/&quot;&gt;A First C++20 Module (Modernes C++)&lt;/a&gt; — introductory tutorial walking through creating and using a named module.&lt;/li&gt;
&lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://www.youtube.com/watch?v=nP8QcvPpGeM&quot;&gt;A Short Tour of C++ Modules (video)&lt;/a&gt; — Daniela Engert's concise video tour of C++ module concepts and tooling.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;em&gt;The complete project from this guide evolves a single module from a minimal setup to interface partitions and a library target with CMake and Ninja. Every example was compiled, linked, and run on GCC 16.2.1 / CMake 4.3.0 / Ninja 1.13.2.&lt;/em&gt;&lt;/p&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/26475/c-20-modules-in-practice-from-header-hell-to-modular-architecture</guid>
<pubDate>Tue, 08 Sep 2026 09:53:48 +0000</pubDate>
</item>
<item>
<title>GGUF2BIN Custom C99 runtime: GGUF → G2BX → inference (Qwen3 / Qwen2 / Llama).</title>
<link>https://coderlegion.com/26264/gguf2bin-custom-c99-runtime-gguf-g2bx-inference-qwen3-qwen2-llama</link>
<description>&lt;h2 id=&quot;gguf2bin2-https-github-com-anonymodgh-gguf2bin&quot;&gt;gguf2bin2 &lt;a rel=&quot;nofollow&quot; href=&quot;https://github.com/AnonymoDGH/gguf2bin&quot;&gt;https://github.com/AnonymoDGH/gguf2bin&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;English&lt;/strong&gt; | &lt;a rel=&quot;nofollow&quot; href=&quot;README.es.md&quot;&gt;Español&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;C99 LLM runtime for low-RAM machines&lt;/strong&gt; — GGUF → G2BX (own format) → inference.&lt;br&gt;
Weights are memory-mapped: your real RAM budget is &lt;strong&gt;KV cache + activations + tokenizer&lt;/strong&gt;, not the model file.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://img.shields.io/badge/C99-portable-blue&quot; alt=&quot;C99&quot;&gt; &lt;img src=&quot;https://img.shields.io/badge/kernel-AVX2%20%2B%20FMA-orange&quot; alt=&quot;AVX2&quot;&gt; &lt;img src=&quot;https://img.shields.io/badge/GPU-Vulkan%20WIP-purple&quot; alt=&quot;Vulkan&quot;&gt; &lt;img src=&quot;https://img.shields.io/badge/min%20RAM-37%20MB-green&quot; alt=&quot;RAM&quot;&gt;&lt;/p&gt;
&lt;blockquote&gt;&lt;p&gt;Runs a &lt;strong&gt;3B model on 145 MB of RAM&lt;/strong&gt; and a large model on a &lt;strong&gt;2 GB machine&lt;/strong&gt; (&lt;code&gt;--swap&lt;/code&gt;: KV backed on disk, footprint ≈ 37 MB).&lt;/p&gt;
&lt;/blockquote&gt;
&lt;hr&gt;
&lt;h3 id=&quot;-speed&quot;&gt;⚡ Speed&lt;/h3&gt;
&lt;p&gt;Measured on Intel i5-6200U · 2C/4T · DDR3L dual-channel (~9.4 GB/s bus ceiling).&lt;br&gt;
Sustained decode with &lt;code&gt;--fast&lt;/code&gt; (high priority + OpenMP + quantized KV).&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;&lt;th&gt;Model &lt;/th&gt;&lt;th&gt;Weights (mmap) &lt;/th&gt;&lt;th&gt;Runtime RAM &lt;/th&gt;&lt;th&gt;decode &lt;/th&gt;&lt;th&gt;prefill&lt;/th&gt;&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;&lt;td&gt;&lt;strong&gt;Qwen2.5-3B&lt;/strong&gt; Q4_0 &lt;/td&gt;&lt;td&gt;1992 MB &lt;/td&gt;&lt;td&gt;145 MB &lt;/td&gt;&lt;td&gt;&lt;strong&gt;4.3&lt;/strong&gt; &lt;/td&gt;&lt;td&gt;7.8&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;strong&gt;Qwen3-0.6B&lt;/strong&gt; Q4_0 &lt;/td&gt;&lt;td&gt;319 MB &lt;/td&gt;&lt;td&gt;511 MB &lt;/td&gt;&lt;td&gt;25.0 / &lt;strong&gt;40.1&lt;/strong&gt; (&lt;code&gt;--mv 0.5&lt;/code&gt;) / 39.2 (&lt;code&gt;--mv 1.0&lt;/code&gt;) &lt;/td&gt;&lt;td&gt;&lt;strong&gt;47.9&lt;/strong&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;strong&gt;LFM2.5-1.2B&lt;/strong&gt; Q4_0S &lt;/td&gt;&lt;td&gt;567 MB &lt;/td&gt;&lt;td&gt;631 MB &lt;/td&gt;&lt;td&gt;&lt;strong&gt;15.7&lt;/strong&gt; &lt;/td&gt;&lt;td&gt;17.9&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;Llama-3.2-1B F16 &lt;/td&gt;&lt;td&gt;804 MB &lt;/td&gt;&lt;td&gt;644 MB &lt;/td&gt;&lt;td&gt;13.8 &lt;/td&gt;&lt;td&gt;—&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;Llama-3.2-1B Q4_0S_PSY &lt;/td&gt;&lt;td&gt;737 MB &lt;/td&gt;&lt;td&gt;644 MB &lt;/td&gt;&lt;td&gt;14.7 / &lt;strong&gt;30.6&lt;/strong&gt; (&lt;code&gt;--mv 0.5&lt;/code&gt;) &lt;/td&gt;&lt;td&gt;—&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;SmolLM2-135M Q4_0 &lt;/td&gt;&lt;td&gt;72 MB &lt;/td&gt;&lt;td&gt;40 MB &lt;/td&gt;&lt;td&gt;&lt;strong&gt;59.5&lt;/strong&gt; &lt;/td&gt;&lt;td&gt;—&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;Measured 2026-08-31 on i5-6200U with &lt;code&gt;bench -n 32&lt;/code&gt; (min3). &lt;code&gt;--mv 0.5&lt;/code&gt; Swapeculative + fallback TLS buf → Qwen3 25.0→40.1 tok/s (&lt;strong&gt;+60%&lt;/strong&gt;), Llama Q4_0S_PSY 14.7→30.6 (&lt;strong&gt;+108%&lt;/strong&gt;). &lt;code&gt;--psy&lt;/code&gt; (2 scales/256, 132B) gives better ppl than Q4_0S at same speed. At ~25 tok/s decode pinned to DDR3L ~9 GB/s; prefill hits compute ~27 GMAC/s.&lt;/p&gt;
&lt;h3 id=&quot;-quick-start&quot;&gt;🚀 Quick start&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;make            # Linux / MinGW · OpenMP + AVX2 recommended
make test       # smoke test on a synthetic model

# Pack a GGUF once, run forever
./gguf2bin2 pack Qwen3-0.6B-Q8_0.gguf qwen.g2bx --q4
./gguf2bin2 chat qwen.g2bx --no-think --fast
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;--threads N&lt;/code&gt; picks OpenMP threads; physical cores is the sweet spot.&lt;/p&gt;
&lt;h3 id=&quot;-ram-knobs&quot;&gt;🧠 RAM knobs&lt;/h3&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;&lt;th&gt;Knob &lt;/th&gt;&lt;th&gt;Effect&lt;/th&gt;&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;--q8-kv&lt;/code&gt; &lt;/td&gt;&lt;td&gt;KV cache F32→Q8_0: &lt;strong&gt;~3.8× less RAM&lt;/strong&gt; (94 % greedy argmax agreement)&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;-c N&lt;/code&gt; &lt;/td&gt;&lt;td&gt;Context sizes to &lt;em&gt;your&lt;/em&gt; session, not the model's 262k max&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;--max-ram MB&lt;/code&gt; &lt;/td&gt;&lt;td&gt;Auto: enables Q8 KV first, then halves context until it fits&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;--swap [PATH]&lt;/code&gt; &lt;/td&gt;&lt;td&gt;KV cache backed on disk → &lt;strong&gt;37 MB heap&lt;/strong&gt; even for big models&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;$ gguf2bin2 run qwen.g2bx &quot;Hello&quot; --max-ram 2048   # ideal for 2 GB machines
&lt;/code&gt;&lt;/pre&gt;
&lt;h4 id=&quot;what-counts-against-a-2-gb-budget-&quot;&gt;What counts against a 2 GB budget?&lt;/h4&gt;
&lt;p&gt;| Component | Counts? | Fix |&lt;br&gt;
|---|:-:|---|&lt;br&gt;
| Weights (mmap page cache) | ❌ evictable | — |&lt;br&gt;
| KV cache | ✅ | &lt;code&gt;--q8-kv&lt;/code&gt;, &lt;code&gt;-c N&lt;/code&gt;, &lt;code&gt;--swap&lt;/code&gt; |&lt;br&gt;
| Buffers / activations | ✅ small | — |&lt;br&gt;
| Tokenizer (~250k vocab) | ✅ ~30–60 MB | — |&lt;/p&gt;
&lt;h3 id=&quot;-cli&quot;&gt;🎛 CLI&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;gguf2bin2 pack model.gguf out.g2bx [--q4]     # GGUF → G2BX (--q4: half the bytes)
gguf2bin2 info model.g2bx                     # slots, geometry, types
gguf2bin2 run m.g2bx &quot;prompt&quot; [-n N] [-t T] [--bos] [--gpu]
gguf2bin2 chat m.g2bx [--no-think] [--fast] [--swap]
gguf2bin2 bench m.g2bx [-n 32] [--prefill 256]
gguf2bin2 ppl m.g2bx -f text.txt              # quality harness (perplexity)
gguf2bin2 vkinfo                              # Vulkan probe
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Sampling: quickselect top-k O(n) + Gumbel-max + xorshift64* reproducible via &lt;code&gt;--seed&lt;/code&gt;.&lt;/p&gt;
&lt;h4 id=&quot;-dual-band-cpu-gpu---gpu-&quot;&gt;🎮 Dual band CPU+GPU (&lt;code&gt;--gpu&lt;/code&gt;)&lt;/h4&gt;
&lt;p&gt;The head GEMV (vocab×dim, the heaviest layer) gets split between CPU and GPU with automatic calibration:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;[gpu] worker ready
[gpu] dual band: cpu=[0..44855) gpu=[44855..65536)  tc=6.1ms tg=13.1ms
&lt;/code&gt;&lt;/pre&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Vulkan worker in a child process&lt;/strong&gt; — if the driver crashes or hangs, the runtime falls back to CPU-only without interrupting generation.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Vulkan loader bypass&lt;/strong&gt;: loads the ICD directly from DriverStore (useful on systems with a broken &lt;code&gt;Khronos\Vulkan\Drivers&lt;/code&gt; registry).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Automatic optimal split&lt;/strong&gt;: &lt;code&gt;gpu = vocab·tc/(tc+tg)&lt;/code&gt; measured on the first token; if the GPU is &amp;gt;4× slower than the CPU it shuts itself off.&lt;/li&gt;
&lt;li&gt;Supports &lt;strong&gt;Q4_0&lt;/strong&gt; and &lt;strong&gt;Q4_0S&lt;/strong&gt; heads. Bit-identical output vs the CPU path (greedy).&lt;/li&gt;
&lt;/ul&gt;
&lt;blockquote&gt;&lt;p&gt;⚠️ On hardware where the iGPU shares the RAM bus with the CPU (HD 520 + DDR3L) there is no net gain — calibration detects it and disables itself. The real payoff comes with a dGPU with dedicated VRAM.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h3 id=&quot;-quality&quot;&gt;📐 Quality&lt;/h3&gt;
&lt;p&gt;Perplexity (internal corpus, SmolLM2-135M-Instruct): uniform Q4_0 = 73.7 &lt;em&gt;(broken)&lt;/em&gt;,&lt;br&gt;
native Q4_K_M = &lt;strong&gt;48.7&lt;/strong&gt;, Q6_K = 48.0, Q8_0 = 48.0. Native K-quants keep Q8_0-level&lt;br&gt;
quality within 1.4 % while running faster than uniform Q4_0.&lt;/p&gt;
&lt;p&gt;Included numerical validation: &lt;code&gt;make kvtest&lt;/code&gt; (F32 vs Q8 KV), &lt;code&gt;tools/prefilltest&lt;/code&gt;&lt;br&gt;
(bit-exact batched prefill), &lt;code&gt;tools/qkcheck&lt;/code&gt; (46/46 K-quant kernels).&lt;/p&gt;
&lt;details&gt;
&lt;summary&gt;&lt;b&gt;📦 G2BX format &amp;amp; supported types&lt;/b&gt;&lt;/summary&gt;

```
G2BX | ver:u16 | arch:u8 | flags:u8 | ModelCfg | n_slots:u32 | Slot[] | data[] 64B-aligned | tokenizer
Slot: role:u8 layer:u16 type:u8 nbytes:u32 off:u64
```

| Type | Load | Fused matmul |
|------|------|--------------|
| F32 / F16 | yes (pack→Q4_0 if weight) | F32 path / dequant |
| Q4_0 / Q4_1 / Q5_0 | yes | AVX2 fused |
| Q8_0 | yes | AVX2 fused |
| Q4_0S (own, fp16 shared scale /256) | yes | AVX2 batched |
| Q2_K … Q6_K | yes (dequant) | AVX2 fused (Q4_K/Q6_K), scalar rest |
| IQ* / Q8_K | partial | — |

&lt;/details&gt;
&lt;details&gt;
&lt;summary&gt;&lt;b&gt;🗂 Project layout&lt;/b&gt;&lt;/summary&gt;

```
include/g2b.h      common API
src/l1_gguf.c      GGUF parser (mmap)
src/l2_codec.c     fused dequant + matmul (AVX2)
src/l3_math.c      rmsnorm, rope, silu, softmax AVX2
src/l4_gbin.c      G2BX packer (generic per-architecture read_cfg)
src/l5_model.c     load + forward + Q8 KV + RAM budget + GQA-major attention
src/l6_token.c     BPE tokenizer
src/main.c         CLI (quickselect/Gumbel sampling, chat with context compaction)
src/l7_vulkan.c    dual band GPU backend (child-process worker, crash-proof)
shaders/           compute shaders (Q4_0/Q4_0S GEMV)
tools/             kvtest · prefilltest · exptest · qkcheck · mmbench · dump_gguf.py
docs/RESEARCH.md   research notes and performance roadmap
```

&lt;/details&gt;
&lt;details&gt;
&lt;summary&gt;&lt;b&gt;📜 Changelog&lt;/b&gt;&lt;/summary&gt;

#### v4.7 — Q4_0S_PSY (psicoacústico) + fallback TLS
- **Q4_0S_PSY**: 2 escalas fp16 por 256 (132B vs 130B) — baja 128 + alta 128, como MP3. `pack --psy` → +6% speed y mejor ppl que Q4_0S. Llama-3.2-1B 14.7 tok/s (PSY) → 30.6 con `--mv 0.5` (+108%). Fallback IQ ahora TLS buf → qwen38 no hace malloc por fila.

#### v4.6 — Swapeculative MV Triple Band
- **--mv 0.0..1.0**: tunable skip of FFN (dense) / SSM delta (hybrid) via hash + 2-bit predictor. `25.0 → 40.1 tok/s (+60%)` on Qwen3-0.6B Q4_0 with `--mv 0.5`, `39.2` with `--mv 1.0` on i5-6200U. Quality tradeoff as expected — use 0.3-0.5 for speed, 0 for quality. Works on all archs (Qwen3/Llama/LFM2/Qwen35).

#### v4.5
- Batched (prefill) kernel with deferred accumulation: same treatment as the decode kernel. Qwen2.5-3B prefill 4.3 → 7.8 tok/s (+81 %), bit-exact (`tools/prefilltest`). Sets the stage for speculative verification.
- **Dual band CPU+GPU head GEMV**: Vulkan worker in a child process (crash-proof), loader bypass loading the ICD straight from DriverStore, automatic split calibration with self-shutdown when the GPU doesn't help. Heads Q4_0/Q4_0S, bit-identical output.

#### v4.4
- **--drop N (ShortGPT)**: measures per-block Block Influence during a quick calibration and skips the N least influential blocks. On LFM2.5-1.2B it doesn't pay off (min BI 0.106).

#### v4.3
- Decode Q4_0 kernel with deferred accumulation: one hsum per row instead of one per block. Qwen2.5-3B 3.1 → 4.3 tok/s (2.9× vs v3.5); Qwen3-0.6B +10 %.
- Q5_0 end-to-end (fused AVX2 kernel with high-bits LUT).
- Measured quality table (`ppl` command).

#### v4.2
- Fused AVX2 kernels for Q4_K and Q6_K (`maddubs` + m·Σx correction term). Before, any K-quant pack fell to the 2–5× slower fallback. Validated byte-by-byte with `tools/qkcheck`.
- `ppl` command; min-of-3 bench (thermal throttling lies).

#### v4.1
- K-quants fixed against official ggml (`deq_q3_K/q4_K/q5_K` broken since v3.4: half the tensor unwritten + wrong scale interleave).
- Batched prefill (B=8) bit-exact; geometry validation at load; persistent Q8 activation scratch (−210 malloc/free per token).

#### v4.0
- Prefill without logits (only the last token computes vocab×dim): prefill 1.32×.
- GQA-major attention: each K/V row dequantized once per head group.
- softmax/silu AVX2 with fast exp (rel err &amp;lt; 2e-7); rmsnorm fix for non-multiple-of-32 tails.
- New sampling: O(n) quickselect top-k, Gumbel-max, xorshift64\*, reproducible `--seed`.
- GGUF via mmap; long-chat context compaction.

#### v3.x
- Q4_0 AVX2 (2 blocks/iter, ILP), AVX2 attention, full K-quant dequant.
- Q8_0 KV cache (`--q8-kv`), effective context, RAM budget (`--max-ram`), disk swap.
- LLaMA RoPE fix (−2.0/head_dim step) and NEOX vs LLaMA: the historical root of corrupt output.

&lt;/details&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/26264/gguf2bin-custom-c99-runtime-gguf-g2bx-inference-qwen3-qwen2-llama</guid>
<pubDate>Sat, 05 Sep 2026 15:46:48 +0000</pubDate>
</item>
<item>
<title>Was not declared in this scope c++</title>
<link>https://coderlegion.com/24887/was-not-declared-in-this-scope-c</link>
<description>&lt;p&gt;
&lt;strong&gt;&lt;span style=&quot;color: #ff04fc;&quot;&gt;&quot;was not declared in this scope&quot;&lt;/span&gt; is a common error message encountered when programming in C++. This error occurs when a variable or function is used before it has been declared or defined in the current scope. Understanding the scope of variables and functions is crucial for writing correct and efficient C++ code. In this article, we will dive into the world of scope in C++ and explore the different types of scope available, including global, local, function-level, class-level and namespace-level. We will also provide examples and explanations to help you understand the concept better and put it into practice. So whether you're a beginner or an experienced developer, this article will help you master the art of scope in C++.
&lt;/strong&gt;
&lt;/p&gt;&lt;hr&gt;
&lt;div id=&quot;toc-div&quot;&gt;
&lt;h3&gt;&lt;span style=&quot;font-family:arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt; Table of Contents:&lt;a id=&quot;toc-toogle&quot; class=&quot;open&quot;&gt;&lt;/a&gt;&lt;/strong&gt;&lt;/span&gt;&lt;/h3&gt;
&lt;div id=&quot;toc-list&quot;&gt;
&lt;ol&gt;
&lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;#understanding-scope-in-c++&quot;&gt;&lt;span style=&quot;font-family:arial,helvetica,sans-serif;&quot;&gt;Understanding scope in C++&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;#why-the-error-&quot;&gt;&lt;span style=&quot;font-family:arial,helvetica,sans-serif;&quot;&gt;Why the error &quot;was not declared in this scope&quot;&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;#how-to-fix-the-error&quot;&gt;&lt;span style=&quot;font-family:arial,helvetica,sans-serif;&quot;&gt;How to fix the error&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;#conclusion&quot;&gt;&lt;span style=&quot;font-family:arial,helvetica,sans-serif;&quot;&gt;Conclusion&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;#references&quot;&gt;&lt;span style=&quot;font-family:arial,helvetica,sans-serif;&quot;&gt;References&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
&lt;/div&gt;&lt;h3&gt;&lt;span style=&quot;font-family:arial,helvetica,sans-serif;&quot;&gt;Understanding scope in C++&lt;/span&gt;&lt;a id=&quot;understanding-scope-in-c++&quot; class=&quot;custom_anchor&quot;&gt;&lt;/a&gt;&lt;/h3&gt;
&lt;p&gt;In the world of programming, scope is a fundamental concept that every developer must understand. It defines the boundaries of where a variable or function can be used within a program, and can greatly impact the readability and maintainability of your code.&lt;/p&gt;
&lt;p&gt;Scope in C++ refers to the region of a program in which a particular variable, function, or object is visible or accessible. In other words, it defines the boundaries of where a variable or function can be used within a program.&lt;/p&gt;
&lt;p&gt;There are two types of scope in C++: global and local.&lt;/p&gt;
&lt;p&gt;A &lt;span style=&quot;color: #ff04fc;&quot;&gt;global variable&lt;/span&gt; or function is one that is defined outside of any function or block. It can be accessed from anywhere within the program, including within functions and other blocks. For example:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family:arial,helvetica,sans-serif;&quot;&gt;
int x = 5; // global variable

void printX() {
cout &lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;A &lt;span style=&quot;color: #ff04fc;&quot;&gt;local variable&lt;/span&gt; or function, on the other hand, is one that is defined within a function or block. It can only be accessed within the function or block in which it is defined, and not outside of it. For example:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family:arial,helvetica,sans-serif;&quot;&gt;
void printX() {
int x = 5; // local variable
cout &lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;When a local variable and global variable have the same name, the local variable takes precedence within the function or block in which it is defined. For example:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family:arial,helvetica,sans-serif;&quot;&gt;
int x = 10; // global variable
void printX() {
int x = 5; // local variable
cout &lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;C++ also has function-level scope, which is similar to local scope, but applies to variables and functions defined within a function. For example:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family:arial,helvetica,sans-serif;&quot;&gt;
int main() {
int x = 5; // local variable
{
int x = 10; // nested local variable
cout &lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In this example, the nested local variable &lt;span style=&quot;color: #ff04fc;&quot;&gt;&lt;code&gt;x&lt;/code&gt;&lt;/span&gt; takes precedence over the outer local variable &lt;span style=&quot;color: #ff04fc;&quot;&gt;&lt;code&gt;x&lt;/code&gt;&lt;/span&gt; within the nested block. Once the block is exited, the outer local variable &lt;span style=&quot;color: #ff04fc;&quot;&gt;&lt;code&gt;x&lt;/code&gt;&lt;/span&gt; becomes visible and accessible again.&lt;/p&gt;
&lt;div class=&quot;div-faq&quot;&gt;
&lt;span class=&quot;faq-header&quot;&gt;Why scope is important?&lt;/span&gt;
&lt;span class=&quot;faq-body&quot;&gt;
The idea of scope is important because it helps to keep track of variables and functions and ensures that the correct one is being used in the correct context. It also helps to reduce naming conflicts and make the code more readable.&lt;/span&gt;&lt;/div&gt;
&lt;p&gt;In addition to that, C++ also has class-level and namespace-level scope.&lt;br&gt;
Class-level scope applies to variables and functions defined within a class. They can only be accessed by object of that class or by a friend function/class.&lt;br&gt;
A namespace is a container for a set of identifiers, you can define variables, functions, classes and other types inside a namespace. They can be accessed by using the scope resolution operator (::)&lt;/p&gt;
&lt;p&gt;For example:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family:arial,helvetica,sans-serif;&quot;&gt;
namespace MyNamespace {
int x = 5;
}

int main() {
cout &lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;It is important to note that, when you define a variable or function with the same name in different namespaces, you can use the scope resolution operator to specify which one you want to use.&lt;/p&gt;
&lt;h3&gt;&lt;span style=&quot;font-family:arial,helvetica,sans-serif;&quot;&gt;Why the error &quot;was not declared in this scope&quot;&lt;/span&gt;&lt;a id=&quot;why-the-error-&quot; class=&quot;custom_anchor&quot;&gt;&lt;/a&gt;&lt;/h3&gt;
&lt;p&gt;When a variable or function is used before it has been declared or defined, the compiler generates an error message indicating that the variable or function &lt;span style=&quot;color: #ff04fc;&quot;&gt;&quot;was not declared in this scope&quot;&lt;/span&gt;. This can happen in several ways:&lt;/p&gt;
&lt;p&gt;Using a variable before it has been declared:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family:arial,helvetica,sans-serif;&quot;&gt;
#include 

int main() {
std::cout &lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Using a variable from a different scope:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family:arial,helvetica,sans-serif;&quot;&gt;
#include 

int x = 0;

int main() {
{
int x = 1;
std::cout &lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Using a function before it has been declared or defined:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family:arial,helvetica,sans-serif;&quot;&gt;
#include 

int main() {
std::cout &lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Another common cause of this error is when a variable or function is misspelled. This can happen if the programmer mistypes the name of a variable or function or if the case of the letters is not correct. For example, if a variable is declared as &lt;span style=&quot;color: #ff04fc;&quot;&gt;&lt;code&gt;myVariable&lt;/code&gt;&lt;/span&gt; but is later referred to as &lt;span style=&quot;color: #ff04fc;&quot;&gt;&lt;code&gt;myvariable&lt;/code&gt;&lt;/span&gt;, this will result in a &lt;span style=&quot;color: #ff04fc;&quot;&gt;&quot;was not declared in this scope&quot;&lt;/span&gt; error.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family:arial,helvetica,sans-serif;&quot;&gt;
#include 

int main() {
int myVariable;

std::cout &lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;&lt;span style=&quot;font-family:arial,helvetica,sans-serif;&quot;&gt;How to fix the error&lt;/span&gt;&lt;a id=&quot;how-to-fix-the-error&quot; class=&quot;custom_anchor&quot;&gt;&lt;/a&gt;&lt;/h3&gt;
&lt;p&gt;To fix this error, we need to ensure that the variable or function is declared or defined before it is used. This can be done by:&lt;/p&gt;
&lt;p&gt;Declaring the variable before it is used:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family:arial,helvetica,sans-serif;&quot;&gt;
#include 

int main() {
int x;
std::cout &lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Using the variable or function from the correct scope:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family:arial,helvetica,sans-serif;&quot;&gt;
#include 

int x = 0;

int main() {
{
int x = 1;
std::cout &lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Declaring the function before it is used:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family:arial,helvetica,sans-serif;&quot;&gt;
#include 

int foo(){return 1;}

int main() {
std::cout &lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;div class=&quot;div-green&quot;&gt;
&lt;span class=&quot;alert-header&quot;&gt;Tip&lt;/span&gt;
&lt;span class=&quot;alert-body&quot;&gt;It is important to keep in mind that variables have a scope and that scope determines where the variable can be accessed from. Also, function should be declared before they are called. The error message &lt;span style=&quot;color: #ff04fc;&quot;&gt;&quot;was not declared in this scope&quot;&lt;/span&gt; is a reminder of these important concepts in C++ programming.&lt;/span&gt;
&lt;/div&gt;
&lt;h3&gt;&lt;span style=&quot;font-family:arial,helvetica,sans-serif;&quot;&gt;Conclusion&lt;/span&gt;&lt;a class=&quot;custom_anchor&quot;&gt;&lt;/a&gt;&lt;/h3&gt;
&lt;p&gt;In conclusion, &lt;span style=&quot;color: #ff04fc;&quot;&gt;&quot;was not declared in this scope&quot;&lt;/span&gt; error can occur due to a variety of reasons such as variable or function being used before it has been declared or defined, it being in the wrong scope or not being spelled correctly. It is important to pay attention to the variables and functions that are being used in the code, and to make sure that they have been declared and defined before they are used.&lt;/p&gt;
&lt;h3&gt;&lt;span style=&quot;font-family:arial,helvetica,sans-serif;&quot;&gt;References&lt;/span&gt;&lt;a id=&quot;references&quot; class=&quot;custom_anchor&quot;&gt;&lt;/a&gt;&lt;/h3&gt;
&lt;ul&gt;&lt;li&gt;Stroustrup, B. (2013). The C++ Programming Language (4th ed.). Addison-Wesley Professional.&lt;/li&gt;&lt;li&gt;Deitel, P. J., &amp;amp; Deitel, H. M. (2015). C++ How to Program (10th ed.). Pearson Education.&lt;/li&gt;&lt;li&gt;Lippman, S. B., Lajoie, J., &amp;amp; Moo, B. E. (2012). C++ Primer (5th ed.). Addison-Wesley Professional.&lt;/li&gt;&lt;/ul&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/24887/was-not-declared-in-this-scope-c</guid>
<pubDate>Wed, 19 Aug 2026 05:46:58 +0000</pubDate>
</item>
<item>
<title>Build a Dynamic Array in C from Scratch</title>
<link>https://coderlegion.com/23851/build-a-dynamic-array-in-c-from-scratch</link>
<description>&lt;h2 id=&quot;build-a-dynamic-array-in-c-from-scratch&quot;&gt;Build a Dynamic Array in C from Scratch&lt;/h2&gt;
&lt;p&gt;You've used &lt;code&gt;push()&lt;/code&gt; in JavaScript, &lt;code&gt;append()&lt;/code&gt; in Python, &lt;code&gt;add()&lt;/code&gt; in Java. They feel instant. They never run out of space. You never think about them.&lt;/p&gt;
&lt;p&gt;That's a problem — not because those abstractions are bad, but because you're using a tool without knowing what it costs. Every one of those methods is built on ideas you can understand completely. This article will show you how, in C, where the machine hides nothing from you.&lt;/p&gt;
&lt;p&gt;By the end you'll have built a working dynamic array and, more importantly, a mental model that makes &lt;code&gt;std::vector&lt;/code&gt;, Go slices, and Rust's &lt;code&gt;Vec&lt;/code&gt; all obvious.&lt;/p&gt;
&lt;hr&gt;
&lt;h3 id=&quot;the-core-idea-two-layers-of-memory&quot;&gt;The Core Idea: Two Layers of Memory&lt;/h3&gt;
&lt;p&gt;Before writing a single line, you need to understand the central insight that makes a dynamic array possible.&lt;/p&gt;
&lt;p&gt;A normal array is a fixed block of memory. You declare &lt;code&gt;int numbers[8]&lt;/code&gt; and the compiler carves out exactly 32 bytes on the stack. That's it. If you need a 9th element, you're stuck.&lt;/p&gt;
&lt;p&gt;A dynamic array gets around this by living on the &lt;strong&gt;heap&lt;/strong&gt; — a region of memory that your program can request and release at runtime, in any size, at any time. The heap doesn't get freed automatically when a function returns. You control it. That control is what makes resizing possible, and what makes memory bugs possible too.&lt;/p&gt;
&lt;p&gt;The dynamic array is two things at once: a block of integers sitting somewhere on the heap, and a small control structure that remembers where that block is, how big it is, and how many elements are currently in it. Everything we build is just bookkeeping those two things correctly.&lt;/p&gt;
&lt;hr&gt;
&lt;h3 id=&quot;what-you-need-to-know-first&quot;&gt;What You Need to Know First&lt;/h3&gt;
&lt;h4 id=&quot;memory-stack-vs-heap&quot;&gt;Memory: Stack vs Heap&lt;/h4&gt;
&lt;p&gt;When you declare a local variable, it goes on the &lt;strong&gt;stack&lt;/strong&gt;. The stack is fast and automatic — variables appear when a function is called and vanish when it returns.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-c&quot;&gt;void foo() {
    int x = 10; // lives on the stack
}               // x is gone here
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;strong&gt;heap&lt;/strong&gt; is different. Memory there persists until you explicitly free it. You ask the OS for a chunk, use it, and free it when you're done. This is what enables data structures that outlive the function that created them.&lt;/p&gt;
&lt;h4 id=&quot;pointers&quot;&gt;Pointers&lt;/h4&gt;
&lt;p&gt;A pointer is a variable that holds a memory address rather than a value.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-c&quot;&gt;int score = 99;
int *ptr = &amp;amp;score; // ptr holds the address of score, not 99
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;&amp;amp;score&lt;/code&gt; means &quot;give me the address of score.&quot; &lt;code&gt;*ptr&lt;/code&gt; means &quot;go to that address and read what's there.&quot; They're inverse operations.&lt;/p&gt;
&lt;p&gt;Why does this matter? Because when you allocate memory on the heap, you get back an address — a pointer — to where that memory starts. There's no other way to refer to heap memory. Pointers aren't a language quirk; they're the only handle you have on dynamic allocation.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-c&quot;&gt;int *numbers = malloc(sizeof(int) * 8);
// numbers holds the address of a 32-byte block on the heap
// numbers[0], numbers[1], ... numbers[7] are all valid
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;malloc&lt;/code&gt; returns a pointer to the allocated block. &lt;code&gt;sizeof(int)&lt;/code&gt; gives the size in bytes of one integer (typically 4). Multiply by 8 and you get 32 bytes — room for 8 integers.&lt;/p&gt;
&lt;h4 id=&quot;structs&quot;&gt;Structs&lt;/h4&gt;
&lt;p&gt;C has no classes. To group related data, you use a &lt;code&gt;struct&lt;/code&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-c&quot;&gt;struct IntArray {
    int *data;     // pointer to the integers on the heap
    int length;    // how many elements are currently stored
    int capacity;  // how much space is allocated
};
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;typedef&lt;/code&gt; lets you drop the &lt;code&gt;struct&lt;/code&gt; keyword every time you use it:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-c&quot;&gt;typedef struct {
    int *data;
    int length;
    int capacity;
} IntArray;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now &lt;code&gt;IntArray arr;&lt;/code&gt; is valid instead of &lt;code&gt;struct IntArray arr;&lt;/code&gt;. Small thing, but it adds up.&lt;/p&gt;
&lt;p&gt;The &lt;code&gt;-&amp;gt;&lt;/code&gt; operator accesses a struct's field through a pointer:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-c&quot;&gt;array-&amp;gt;length  // same as (*array).length
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;You'll use &lt;code&gt;-&amp;gt;&lt;/code&gt; constantly because our functions always receive a pointer to the struct, not the struct itself. Passing the struct by value would copy all three fields every time — wasteful, and it means modifications wouldn't be visible to the caller.&lt;/p&gt;
&lt;h4 id=&quot;the-header-files&quot;&gt;The Header Files&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-c&quot;&gt;#include &amp;lt;stdio.h&amp;gt;   // printf, scanf
#include &amp;lt;stdlib.h&amp;gt;  // malloc, realloc, free, exit
#include &amp;lt;stdbool.h&amp;gt; // bool, true, false
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;stdlib.h&lt;/code&gt; is the critical one. Every memory function we use lives there. Without it, &lt;code&gt;malloc&lt;/code&gt; and &lt;code&gt;free&lt;/code&gt; are undeclared.&lt;/p&gt;
&lt;p&gt;&lt;code&gt;stdbool.h&lt;/code&gt; exists because C didn't originally have a boolean type. It gives you &lt;code&gt;bool&lt;/code&gt;, &lt;code&gt;true&lt;/code&gt;, and &lt;code&gt;false&lt;/code&gt; as proper names instead of &lt;code&gt;int&lt;/code&gt;, &lt;code&gt;1&lt;/code&gt;, and &lt;code&gt;0&lt;/code&gt;.&lt;/p&gt;
&lt;hr&gt;
&lt;h3 id=&quot;the-structure&quot;&gt;The Structure&lt;/h3&gt;
&lt;p&gt;Now that the building blocks are clear, the struct makes obvious sense:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-c&quot;&gt;#define DEFAULT_CAPACITY 8

typedef struct {
    int *data;     // address of our integer block on the heap
    int length;    // elements currently stored (logical size)
    int capacity;  // elements we have room for (physical size)
} IntArray;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;length&lt;/code&gt; and &lt;code&gt;capacity&lt;/code&gt; are not the same thing. This distinction is the heart of how a dynamic array works.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-plaintext&quot;&gt;capacity = 8  (8 slots exist in memory)
length   = 3  (only 3 are in use)

[ 10 | 20 | 30 | __ | __ | __ | __ | __ ]
  [0]  [1]  [2]
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;When &lt;code&gt;length == capacity&lt;/code&gt;, the array is full and must grow before the next &lt;code&gt;add&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;&lt;code&gt;#define DEFAULT_CAPACITY 8&lt;/code&gt; is a compile-time constant. The preprocessor replaces every occurrence of &lt;code&gt;DEFAULT_CAPACITY&lt;/code&gt; with &lt;code&gt;8&lt;/code&gt; before the compiler sees the code. It's not a variable — it has no address and uses no runtime memory.&lt;/p&gt;
&lt;hr&gt;
&lt;h3 id=&quot;creating-the-array&quot;&gt;Creating the Array&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-c&quot;&gt;IntArray *createArray(int capacity) {

    // Guard against nonsense input
    if (capacity &amp;lt;= 0)
        capacity = DEFAULT_CAPACITY;

    // Allocate the control struct on the heap
    // This gives us room for: one pointer, two ints
    IntArray *array = malloc(sizeof(IntArray));

    if (array == NULL) {
        printf(&quot;Memory allocation failed\n&quot;);
        exit(EXIT_FAILURE); // no safe way to recover here
    }

    // Allocate the integer block separately
    // The struct just holds a pointer to this block
    array-&amp;gt;data = malloc(sizeof(int) * capacity);

    if (array-&amp;gt;data == NULL) {
        printf(&quot;Memory allocation failed\n&quot;);
        free(array); // don't leak the struct we just allocated
        exit(EXIT_FAILURE);
    }

    array-&amp;gt;length = 0;        // no elements yet
    array-&amp;gt;capacity = capacity; // but we have space reserved

    return array; // return the address of the struct
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Notice we allocate &lt;strong&gt;twice&lt;/strong&gt;. Once for the struct, and once for the integer data. These are two separate heap allocations, and that's why we must free both when we're done. The struct contains the address of the data block, but it doesn't own it in any automatic sense — we have to track and free it ourselves.&lt;/p&gt;
&lt;p&gt;The return type is &lt;code&gt;IntArray *&lt;/code&gt; — a pointer. We're not returning the struct itself; we're returning its address. This is the handle the caller will use for every subsequent operation.&lt;/p&gt;
&lt;hr&gt;
&lt;h3 id=&quot;destroying-the-array&quot;&gt;Destroying the Array&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-c&quot;&gt;void destroyArray(IntArray *array) {
    free(array-&amp;gt;data); // free the integer block first
    free(array);       // then free the struct
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Order matters. Free the data block first, then the struct. If you freed the struct first, &lt;code&gt;array-&amp;gt;data&lt;/code&gt; would be a dangling read — you'd be accessing memory through a pointer to something that's already freed.&lt;/p&gt;
&lt;p&gt;Every &lt;code&gt;malloc&lt;/code&gt; must have exactly one matching &lt;code&gt;free&lt;/code&gt;. This is the discipline C demands. Modern languages have garbage collectors to enforce this automatically. In C, it's on you.&lt;/p&gt;
&lt;hr&gt;
&lt;h3 id=&quot;getting-and-setting-elements&quot;&gt;Getting and Setting Elements&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-c&quot;&gt;int get(IntArray *array, int index) {
    if (index &amp;lt; 0 || index &amp;gt;= array-&amp;gt;length) {
        printf(&quot;Index out of bounds\n&quot;);
        exit(EXIT_FAILURE);
    }
    return array-&amp;gt;data[index];
}

void set(IntArray *array, int index, int value) {
    if (index &amp;lt; 0 || index &amp;gt;= array-&amp;gt;length) {
        printf(&quot;Index out of bounds\n&quot;);
        exit(EXIT_FAILURE);
    }
    array-&amp;gt;data[index] = value;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The bounds check is not optional. Without it, &lt;code&gt;array-&amp;gt;data[index]&lt;/code&gt; when &lt;code&gt;index &amp;gt;= length&lt;/code&gt; reads memory that belongs to something else — possibly another variable, possibly the OS. C won't stop you. The behavior is undefined, which in practice means silent data corruption or a crash that's hard to trace.&lt;/p&gt;
&lt;p&gt;Both operations are &lt;strong&gt;O(1)&lt;/strong&gt; because &lt;code&gt;array-&amp;gt;data[index]&lt;/code&gt; computes directly to a memory address:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-plaintext&quot;&gt;address = base_address + (index × sizeof(int))
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;No searching. One arithmetic operation.&lt;/p&gt;
&lt;hr&gt;
&lt;h3 id=&quot;adding-elements-the-core-of-a-dynamic-array&quot;&gt;Adding Elements: The Core of a Dynamic Array&lt;/h3&gt;
&lt;p&gt;This is the function everything else builds toward.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-c&quot;&gt;void add(IntArray *array, int value) {

    // Is the array full?
    if (array-&amp;gt;length == array-&amp;gt;capacity) {

        // Double the capacity — we'll explain why below
        array-&amp;gt;capacity *= 2;

        // Ask the OS to resize our integer block
        int *newData = realloc(
            array-&amp;gt;data,
            sizeof(int) * array-&amp;gt;capacity
        );

        // CRITICAL: store in a temp pointer, not array-&amp;gt;data
        // If realloc fails, it returns NULL — if we assigned
        // directly to array-&amp;gt;data we'd lose the original pointer
        // and have a memory leak with no way to recover
        if (newData == NULL) {
            printf(&quot;Reallocation failed\n&quot;);
            exit(EXIT_FAILURE);
        }

        // Only update once we know it succeeded
        array-&amp;gt;data = newData;
    }

    // Store the value and advance the length in one step
    array-&amp;gt;data[array-&amp;gt;length++] = value;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;realloc&lt;/code&gt; is &lt;code&gt;malloc&lt;/code&gt;'s smarter sibling. It takes an existing pointer and a new size. If it can extend the block in place, it does. If not, it allocates a new block, copies the old data, frees the old block, and returns the new address. The existing contents are preserved either way.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Why double the capacity instead of growing by 1?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;If you grew by 1 every time the array filled up, every single &lt;code&gt;add&lt;/code&gt; would trigger a &lt;code&gt;realloc&lt;/code&gt; and a copy of all existing elements. Adding &lt;code&gt;n&lt;/code&gt; elements would cost &lt;code&gt;O(n²)&lt;/code&gt; total.&lt;/p&gt;
&lt;p&gt;Doubling means resizes happen at sizes 4, 8, 16, 32, 64... Each resize copies everything, but the number of copies per element approaches 2 as &lt;code&gt;n&lt;/code&gt; grows. Over many insertions, the average cost per &lt;code&gt;add&lt;/code&gt; is &lt;strong&gt;O(1)&lt;/strong&gt;. This is called &lt;strong&gt;amortized constant time&lt;/strong&gt; — expensive occasionally, cheap on average.&lt;/p&gt;
&lt;hr&gt;
&lt;h3 id=&quot;removing-elements&quot;&gt;Removing Elements&lt;/h3&gt;
&lt;h4 id=&quot;remove-by-index&quot;&gt;Remove by Index&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-c&quot;&gt;void removeAt(IntArray *array, int index) {

    if (index &amp;lt; 0 || index &amp;gt;= array-&amp;gt;length) {
        printf(&quot;Index out of bounds\n&quot;);
        exit(EXIT_FAILURE);
    }

    // Shift every element after the removed one left by one position
    for (int i = index; i &amp;lt; array-&amp;gt;length - 1; i++) {
        array-&amp;gt;data[i] = array-&amp;gt;data[i + 1];
    }

    // The last position still holds the old value, but we don't
    // erase it — we just stop counting it as part of the array
    array-&amp;gt;length--;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The loop goes to &lt;code&gt;array-&amp;gt;length - 1&lt;/code&gt;, not &lt;code&gt;array-&amp;gt;length&lt;/code&gt;. At the final iteration, &lt;code&gt;i&lt;/code&gt; is &lt;code&gt;length - 2&lt;/code&gt; and we read &lt;code&gt;array-&amp;gt;data[length - 1]&lt;/code&gt;. If the loop ran to &lt;code&gt;length&lt;/code&gt;, the last iteration would read &lt;code&gt;array-&amp;gt;data[length]&lt;/code&gt;, which is outside the allocated block.&lt;/p&gt;
&lt;p&gt;This is &lt;strong&gt;O(n)&lt;/strong&gt; in the worst case — removing from index 0 shifts every element.&lt;/p&gt;
&lt;h4 id=&quot;remove-by-value&quot;&gt;Remove by Value&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-c&quot;&gt;bool removeValue(IntArray *array, int value) {
    for (int i = 0; i &amp;lt; array-&amp;gt;length; i++) {
        if (array-&amp;gt;data[i] == value) {
            removeAt(array, i);
            return true;  // remove first match only
        }
    }
    return false; // value wasn't in the array
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Search linearly, delegate the actual removal to &lt;code&gt;removeAt&lt;/code&gt;. Returns &lt;code&gt;false&lt;/code&gt; when the value isn't found so the caller can detect the miss.&lt;/p&gt;
&lt;hr&gt;
&lt;h3 id=&quot;reversing-the-array&quot;&gt;Reversing the Array&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-c&quot;&gt;void reverse(IntArray *array) {
    int left = 0;
    int right = array-&amp;gt;length - 1;

    while (left &amp;lt; right) {
        // Swap elements at left and right
        int temp = array-&amp;gt;data[left];
        array-&amp;gt;data[left] = array-&amp;gt;data[right];
        array-&amp;gt;data[right] = temp;

        // Move both pointers inward
        left++;
        right--;
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The two-pointer technique. Start from opposite ends, swap, move inward, stop when they meet. &lt;strong&gt;O(n)&lt;/strong&gt; time, &lt;strong&gt;O(1)&lt;/strong&gt; extra space — no second array needed.&lt;/p&gt;
&lt;p&gt;The condition is &lt;code&gt;left &amp;lt; right&lt;/code&gt;, not &lt;code&gt;left != right&lt;/code&gt;. For an odd-length array, they'll converge on the middle element. That element doesn't need swapping with itself, so the loop correctly stops before touching it.&lt;/p&gt;
&lt;hr&gt;
&lt;h3 id=&quot;printing&quot;&gt;Printing&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-c&quot;&gt;void printArray(IntArray *array) {
    printf(&quot;[&quot;);
    for (int i = 0; i &amp;lt; array-&amp;gt;length; i++) {
        printf(&quot;%d&quot;, array-&amp;gt;data[i]);
        if (i != array-&amp;gt;length - 1)
            printf(&quot;, &quot;);
    }
    printf(&quot;]\n&quot;);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The comma logic — print a comma after every element except the last — is a common pattern. The alternative (printing a comma before every element except the first) is equivalent; pick one and be consistent.&lt;/p&gt;
&lt;hr&gt;
&lt;h3 id=&quot;putting-it-together&quot;&gt;Putting It Together&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-c&quot;&gt;int main() {
    IntArray *arr = createArray(4); // capacity 4, length 0

    add(arr, 3);   // length 1
    add(arr, 7);   // length 2
    add(arr, 6);   // length 3
    add(arr, -2);  // length 4, capacity 4 — full

    printArray(arr); // [3, 7, 6, -2]

    removeValue(arr, 7); // shift left, length becomes 3

    printArray(arr); // [3, 6, -2]

    reverse(arr); // two-pointer swap

    printArray(arr); // [-2, 6, 3]

    destroyArray(arr); // free data block, then free struct

    return 0;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Note: the first &lt;code&gt;add&lt;/code&gt; after &lt;code&gt;createArray(4)&lt;/code&gt; that would require a 5th slot would trigger a resize — capacity doubles to 8. In this &lt;code&gt;main&lt;/code&gt; we add exactly 4 elements, so no resize occurs. To see it in action, add a 5th element.&lt;/p&gt;
&lt;hr&gt;
&lt;h3 id=&quot;the-gotchas&quot;&gt;The Gotchas&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;Assigning &lt;code&gt;realloc&lt;/code&gt; directly to the original pointer.&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-c&quot;&gt;// Wrong — if realloc returns NULL, you've lost your data
array-&amp;gt;data = realloc(array-&amp;gt;data, newSize);

// Right — check before assigning
int *newData = realloc(array-&amp;gt;data, newSize);
if (newData != NULL) array-&amp;gt;data = newData;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Freeing in the wrong order.&lt;/strong&gt;&lt;br&gt;
Free &lt;code&gt;array-&amp;gt;data&lt;/code&gt; before &lt;code&gt;array&lt;/code&gt;. If you free the struct first, you're reading &lt;code&gt;array-&amp;gt;data&lt;/code&gt; through a dangling pointer.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Using &lt;code&gt;length&lt;/code&gt; instead of &lt;code&gt;capacity&lt;/code&gt; in the resize check.&lt;/strong&gt;&lt;br&gt;
The array is full when &lt;code&gt;length == capacity&lt;/code&gt;. If you compare against the wrong field, you either resize too early (wasted allocations) or never resize at all (out-of-bounds writes).&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Off-by-one in &lt;code&gt;removeAt&lt;/code&gt;'s loop.&lt;/strong&gt;&lt;br&gt;
The loop runs to &lt;code&gt;array-&amp;gt;length - 1&lt;/code&gt;, not &lt;code&gt;array-&amp;gt;length&lt;/code&gt;. The last iteration reads &lt;code&gt;data[length - 1]&lt;/code&gt;. Going one further reads past the end of the allocated block.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Not checking &lt;code&gt;malloc&lt;/code&gt; for &lt;code&gt;NULL&lt;/code&gt;.&lt;/strong&gt;&lt;br&gt;
&lt;code&gt;malloc&lt;/code&gt; returns &lt;code&gt;NULL&lt;/code&gt; when the OS can't satisfy the request. Dereferencing a &lt;code&gt;NULL&lt;/code&gt; pointer is undefined behavior. Always check.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Using the array after &lt;code&gt;destroyArray&lt;/code&gt;.&lt;/strong&gt;&lt;br&gt;
After you free memory, the pointer still holds the old address. Reading through it is undefined behavior. Set pointers to &lt;code&gt;NULL&lt;/code&gt; after freeing if you need to guard against accidental reuse.&lt;/p&gt;
&lt;hr&gt;
&lt;h3 id=&quot;junior-pattern-vs-senior-pattern&quot;&gt;Junior Pattern vs Senior Pattern&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;Resizing:&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-c&quot;&gt;// Junior — assigns directly, leaks memory on failure
array-&amp;gt;data = realloc(array-&amp;gt;data, sizeof(int) * array-&amp;gt;capacity);
if (array-&amp;gt;data == NULL) exit(EXIT_FAILURE); // original pointer is gone

// Senior — uses temp, original is recoverable on failure
int *newData = realloc(array-&amp;gt;data, sizeof(int) * array-&amp;gt;capacity);
if (newData == NULL) {
    // array-&amp;gt;data is still valid here, nothing was lost
    exit(EXIT_FAILURE);
}
array-&amp;gt;data = newData;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Cleanup:&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-c&quot;&gt;// Junior — frees struct first, then reads dangling pointer
free(array);
free(array-&amp;gt;data); // undefined behavior: array is already freed

// Senior — free data first, then the container
free(array-&amp;gt;data);
free(array);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Bounds checking:&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-c&quot;&gt;// Junior — trusts the caller
return array-&amp;gt;data[index];

// Senior — validates before accessing
if (index &amp;lt; 0 || index &amp;gt;= array-&amp;gt;length) {
    // handle error
}
return array-&amp;gt;data[index];
&lt;/code&gt;&lt;/pre&gt;
&lt;hr&gt;
&lt;h3 id=&quot;where-this-lives-in-the-real-world&quot;&gt;Where This Lives in the Real World&lt;/h3&gt;
&lt;p&gt;&lt;code&gt;std::vector&lt;/code&gt; in C++ is this exact structure. The underlying implementation uses &lt;code&gt;new[]&lt;/code&gt; instead of &lt;code&gt;malloc&lt;/code&gt;, but the capacity/length distinction, the doubling strategy, and the contiguous memory layout are identical.&lt;/p&gt;
&lt;p&gt;Go slices have a header with &lt;code&gt;ptr&lt;/code&gt;, &lt;code&gt;len&lt;/code&gt;, and &lt;code&gt;cap&lt;/code&gt; — those are our &lt;code&gt;data&lt;/code&gt;, &lt;code&gt;length&lt;/code&gt;, and &lt;code&gt;capacity&lt;/code&gt;. When you &lt;code&gt;append&lt;/code&gt; past &lt;code&gt;cap&lt;/code&gt;, Go allocates a new backing array, copies, and returns a new slice header.&lt;/p&gt;
&lt;p&gt;Rust's &lt;code&gt;Vec&amp;lt;T&amp;gt;&lt;/code&gt; is the same: a heap-allocated contiguous buffer, a length, and a capacity. The ownership system handles the freeing automatically, but the memory layout underneath is what you just built.&lt;/p&gt;
&lt;hr&gt;
&lt;h3 id=&quot;time-complexity&quot;&gt;Time Complexity&lt;/h3&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;&lt;th&gt;Operation &lt;/th&gt;&lt;th&gt;Complexity &lt;/th&gt;&lt;th&gt;Why&lt;/th&gt;&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;get&lt;/code&gt; &lt;/td&gt;&lt;td&gt;O(1) &lt;/td&gt;&lt;td&gt;Direct address calculation&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;set&lt;/code&gt; &lt;/td&gt;&lt;td&gt;O(1) &lt;/td&gt;&lt;td&gt;Direct address calculation&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;add&lt;/code&gt; (no resize) &lt;/td&gt;&lt;td&gt;O(1) &lt;/td&gt;&lt;td&gt;Write to &lt;code&gt;data[length]&lt;/code&gt;, increment&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;add&lt;/code&gt; (resize) &lt;/td&gt;&lt;td&gt;O(n) &lt;/td&gt;&lt;td&gt;&lt;code&gt;realloc&lt;/code&gt; copies all elements&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;add&lt;/code&gt; (amortized) &lt;/td&gt;&lt;td&gt;O(1) &lt;/td&gt;&lt;td&gt;Resizes are infrequent enough&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;removeAt&lt;/code&gt; &lt;/td&gt;&lt;td&gt;O(n) &lt;/td&gt;&lt;td&gt;Shift all elements after index&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;removeValue&lt;/code&gt; &lt;/td&gt;&lt;td&gt;O(n) &lt;/td&gt;&lt;td&gt;Linear scan + shift&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;reverse&lt;/code&gt; &lt;/td&gt;&lt;td&gt;O(n) &lt;/td&gt;&lt;td&gt;Visit each element once&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;hr&gt;
&lt;h3 id=&quot;your-turn&quot;&gt;Your Turn&lt;/h3&gt;
&lt;p&gt;Extend the implementation with these two functions:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-c&quot;&gt;// Insert a value at a specific index, shifting everything right
void insertAt(IntArray *array, int index, int value);

// Return the index of the first occurrence of value, or -1 if not found
int indexOf(IntArray *array, int value);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Constraints: &lt;code&gt;insertAt&lt;/code&gt; must handle growth the same way &lt;code&gt;add&lt;/code&gt; does. &lt;code&gt;indexOf&lt;/code&gt; must return &lt;code&gt;-1&lt;/code&gt;, not exit, when the value is absent.&lt;/p&gt;
&lt;p&gt;You'll know you're done when this &lt;code&gt;main&lt;/code&gt; produces the expected output:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-c&quot;&gt;IntArray *arr = createArray(4);
add(arr, 10);
add(arr, 30);
insertAt(arr, 1, 20); // insert 20 between 10 and 30
printArray(arr);      // [10, 20, 30]
printf(&quot;%d\n&quot;, indexOf(arr, 20)); // 1
printf(&quot;%d\n&quot;, indexOf(arr, 99)); // -1
destroyArray(arr);
&lt;/code&gt;&lt;/pre&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/23851/build-a-dynamic-array-in-c-from-scratch</guid>
<pubDate>Fri, 31 Jul 2026 10:38:49 +0000</pubDate>
</item>
<item>
<title>Introducing Algenix: Building an Open-Source Computer Algebra System from Scratch in Modern C++</title>
<link>https://coderlegion.com/23401/introducing-algenix-building-an-open-source-computer-algebra-system-from-scratch-modern</link>
<description>&lt;h2 id=&quot;-introducing-algenix-building-an-open-source-computer-algebra-system-from-scratch&quot;&gt;🚀 Introducing Algenix: Building an Open-Source Computer Algebra System from Scratch&lt;/h2&gt;
&lt;blockquote&gt;&lt;p&gt;&lt;em&gt;A modern symbolic mathematics engine built from scratch with a high-performance C++ core and a clean Python API.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;hr&gt;
&lt;h3 id=&quot;-the-beginning&quot;&gt;🌟 The Beginning&lt;/h3&gt;
&lt;p&gt;Every developer has a dream project.&lt;/p&gt;
&lt;p&gt;Some build game engines.&lt;br&gt;
Some build operating systems.&lt;br&gt;
Some build programming languages.&lt;/p&gt;
&lt;p&gt;My dream is to build &lt;strong&gt;Algenix&lt;/strong&gt; — a modern, open-source &lt;strong&gt;Computer Algebra System (CAS)&lt;/strong&gt; developed completely from scratch.&lt;/p&gt;
&lt;p&gt;Algenix is not intended to be just another mathematics library. My goal is to create a complete symbolic mathematics engine capable of understanding, manipulating, and solving mathematics in a way that is powerful, extensible, and easy to use.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&quot;-why-build-algenix-&quot;&gt;🤔 Why Build Algenix?&lt;/h2&gt;
&lt;p&gt;Mathematics is at the heart of engineering, robotics, physics, artificial intelligence, computer graphics, and scientific computing.&lt;/p&gt;
&lt;p&gt;While there are already established symbolic mathematics libraries, I wanted to explore the challenge of designing and implementing my own symbolic engine and architecture.&lt;/p&gt;
&lt;p&gt;Building a CAS involves many fascinating areas of computer science, including:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Mathematical parsing&lt;/li&gt;
&lt;li&gt;Compiler-like tokenization and lexing&lt;/li&gt;
&lt;li&gt;Expression trees (ASTs)&lt;/li&gt;
&lt;li&gt;Symbolic algebra&lt;/li&gt;
&lt;li&gt;Equation solving&lt;/li&gt;
&lt;li&gt;Formula simplification&lt;/li&gt;
&lt;li&gt;Polynomial manipulation&lt;/li&gt;
&lt;li&gt;Exact arithmetic&lt;/li&gt;
&lt;li&gt;Algorithm design&lt;/li&gt;
&lt;li&gt;Performance optimization&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Rather than relying on an existing symbolic engine, Algenix is planned as a fresh implementation with its own design.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&quot;-the-vision&quot;&gt;🎯 The Vision&lt;/h2&gt;
&lt;p&gt;Algenix aims to become a modern mathematics platform featuring:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;⚡ High-performance C++ core&lt;/li&gt;
&lt;li&gt;🐍 Clean Python bindings&lt;/li&gt;
&lt;li&gt;🌍 Cross-platform support&lt;/li&gt;
&lt;li&gt;📖 Extensive documentation&lt;/li&gt;
&lt;li&gt;🧪 Comprehensive testing&lt;/li&gt;
&lt;li&gt;💻 Interactive command-line interface&lt;/li&gt;
&lt;li&gt;🧮 Natural mathematical syntax&lt;/li&gt;
&lt;li&gt;📦 Easy installation via pip&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;One of the long-term goals is to allow mathematical expressions to be written naturally.&lt;/p&gt;
&lt;p&gt;For example:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-text&quot;&gt;2x + 5 = 17
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;instead of requiring programming-style syntax.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&quot;-planned-features&quot;&gt;🧠 Planned Features&lt;/h2&gt;
&lt;p&gt;The roadmap is divided into major releases, with each version introducing a new area of mathematics.&lt;/p&gt;
&lt;p&gt;Some planned capabilities include:&lt;/p&gt;
&lt;h3 id=&quot;core-algebra&quot;&gt;Core Algebra&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;Expression simplification&lt;/li&gt;
&lt;li&gt;Expansion&lt;/li&gt;
&lt;li&gt;Factorization&lt;/li&gt;
&lt;li&gt;Polynomial operations&lt;/li&gt;
&lt;li&gt;Collecting like terms&lt;/li&gt;
&lt;li&gt;Symbolic substitution&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id=&quot;equation-solving&quot;&gt;Equation Solving&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;Linear equations&lt;/li&gt;
&lt;li&gt;Quadratic equations&lt;/li&gt;
&lt;li&gt;Simultaneous equations&lt;/li&gt;
&lt;li&gt;Integer solution generation&lt;/li&gt;
&lt;li&gt;Constraint-based solving&lt;/li&gt;
&lt;li&gt;Step-by-step solutions&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id=&quot;symbolic-mathematics&quot;&gt;Symbolic Mathematics&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;Symbolic variables&lt;/li&gt;
&lt;li&gt;Exact fractions&lt;/li&gt;
&lt;li&gt;Radical expressions&lt;/li&gt;
&lt;li&gt;Expression rewriting&lt;/li&gt;
&lt;li&gt;Formula manipulation&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id=&quot;calculus&quot;&gt;Calculus&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;Limits&lt;/li&gt;
&lt;li&gt;Derivatives&lt;/li&gt;
&lt;li&gt;Integrals&lt;/li&gt;
&lt;li&gt;Taylor series&lt;/li&gt;
&lt;li&gt;Differential equations&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id=&quot;linear-algebra&quot;&gt;Linear Algebra&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;Matrices&lt;/li&gt;
&lt;li&gt;Determinants&lt;/li&gt;
&lt;li&gt;Eigenvalues&lt;/li&gt;
&lt;li&gt;Eigenvectors&lt;/li&gt;
&lt;li&gt;Matrix decompositions&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id=&quot;geometry&quot;&gt;Geometry&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;Coordinate geometry&lt;/li&gt;
&lt;li&gt;2D and 3D geometry&lt;/li&gt;
&lt;li&gt;Transformations&lt;/li&gt;
&lt;li&gt;Distance calculations&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id=&quot;statistics-amp-probability&quot;&gt;Statistics &amp;amp; Probability&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;Mean&lt;/li&gt;
&lt;li&gt;Median&lt;/li&gt;
&lt;li&gt;Variance&lt;/li&gt;
&lt;li&gt;Probability&lt;/li&gt;
&lt;li&gt;Regression&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id=&quot;number-theory&quot;&gt;Number Theory&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;Prime numbers&lt;/li&gt;
&lt;li&gt;Modular arithmetic&lt;/li&gt;
&lt;li&gt;Diophantine equations&lt;/li&gt;
&lt;li&gt;Number properties&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id=&quot;developer-features&quot;&gt;Developer Features&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;Python API&lt;/li&gt;
&lt;li&gt;C++ API&lt;/li&gt;
&lt;li&gt;Command-line interface&lt;/li&gt;
&lt;li&gt;Plugin support&lt;/li&gt;
&lt;li&gt;Project file format&lt;/li&gt;
&lt;li&gt;Extensive examples&lt;/li&gt;
&lt;/ul&gt;
&lt;hr&gt;
&lt;h2 id=&quot;-a-long-term-roadmap&quot;&gt;📈 A Long-Term Roadmap&lt;/h2&gt;
&lt;p&gt;Rather than trying to build everything in a single release, Algenix will grow through carefully planned versions.&lt;/p&gt;
&lt;p&gt;Each version will focus on a specific mathematical domain while keeping the project stable and maintainable.&lt;/p&gt;
&lt;p&gt;This approach allows the project to improve continuously while providing useful releases along the way.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&quot;-designed-for-everyone&quot;&gt;📚 Designed for Everyone&lt;/h2&gt;
&lt;p&gt;Algenix is intended for:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;👨🎓 Students&lt;/li&gt;
&lt;li&gt;👩🏫 Teachers&lt;/li&gt;
&lt;li&gt;👨💻 Developers&lt;/li&gt;
&lt;li&gt;🤖 Robotics enthusiasts&lt;/li&gt;
&lt;li&gt;🔬 Researchers&lt;/li&gt;
&lt;li&gt;⚙️ Engineers&lt;/li&gt;
&lt;li&gt;📊 Scientific programmers&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Whether you're solving equations, experimenting with symbolic algebra, or building mathematical software, the goal is to make Algenix a useful tool.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&quot;-open-source-from-day-one&quot;&gt;❤️ Open Source from Day One&lt;/h2&gt;
&lt;p&gt;Algenix is planned as an open-source project.&lt;/p&gt;
&lt;p&gt;The repository will include:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Complete source code&lt;/li&gt;
&lt;li&gt;Extensive documentation&lt;/li&gt;
&lt;li&gt;Example programs&lt;/li&gt;
&lt;li&gt;Unit tests&lt;/li&gt;
&lt;li&gt;Continuous Integration&lt;/li&gt;
&lt;li&gt;Version history&lt;/li&gt;
&lt;li&gt;Roadmaps&lt;/li&gt;
&lt;li&gt;Contribution guides&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The project will evolve publicly, allowing others to follow its progress and contribute ideas.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&quot;-looking-ahead&quot;&gt;🚀 Looking Ahead&lt;/h2&gt;
&lt;p&gt;Building a Computer Algebra System from scratch is a significant challenge, but it's also an opportunity to learn more about mathematics, algorithms, parsing, language design, and software engineering.&lt;/p&gt;
&lt;p&gt;Algenix is a long-term project, and every version will represent another step toward a complete symbolic mathematics platform.&lt;/p&gt;
&lt;p&gt;I hope developers, students, and mathematics enthusiasts will find the journey interesting.&lt;/p&gt;
&lt;p&gt;Thank you for reading, and stay tuned for the first release of &lt;strong&gt;Algenix&lt;/strong&gt;.&lt;/p&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/23401/introducing-algenix-building-an-open-source-computer-algebra-system-from-scratch-modern</guid>
<pubDate>Fri, 24 Jul 2026 14:33:53 +0000</pubDate>
</item>
<item>
<title>Sequence contains no elements</title>
<link>https://coderlegion.com/21746/sequence-contains-no-elements</link>
<description>&lt;p&gt;&lt;strong style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;
    Today, we're going to fix a LINQ Error: &lt;span style=&quot;color: rgb(185, 106, 217);&quot;&gt;&lt;em&gt;Sequence contains no elements&lt;/em&gt;&lt;/span&gt; which the programmers encounter in daily life. It usually happens when we're using the &lt;em style=&quot;background-color: rgb(206, 212, 217); color: rgb(0, 0, 0);&quot;&gt;Single()&lt;/em&gt; or &lt;em style=&quot;background-color: rgb(206, 212, 217); color: rgb(0, 0, 0);&quot;&gt;First()&lt;/em&gt; method to retrieve a value from a dataset. In this study blog, we'll explore why it happens and how to resolve it.
  &lt;/strong&gt;&lt;/p&gt;
&lt;div&gt;
  &lt;h4&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt; Table of Contents: &lt;a class=&quot;open&quot;&gt;&lt;/a&gt;&lt;/strong&gt;&lt;/span&gt;&lt;/h4&gt;
  &lt;div&gt;
    &lt;ol&gt;
      &lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;#_Toc123774610&quot;&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;What is &quot;Sequence contains no elements&quot;&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;#_Toc123774611&quot;&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;Causes&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;#_Toc123774612&quot;&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;Solution&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;#_Toc123774613&quot;&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;The Conclusion&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;#_Toc123774614&quot;&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;The Reference&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
    &lt;/ol&gt;
  &lt;/div&gt;
&lt;/div&gt;
&lt;section&gt;
  &lt;h2&gt;&lt;a class=&quot;custom_anchor&quot; name=&quot;_Toc123774610&quot; id=&quot;_Toc123774610&quot;&gt;&lt;/a&gt;&lt;strong&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;What is &quot;Sequence contains no elements&quot;&lt;/span&gt; &lt;a id=&quot;TypeError-str-object&quot; style=&quot;color: blue;&quot; rel=&quot;nofollow&quot; href=&quot;#_Toc123774610&quot;&gt;#&lt;/a&gt;&lt;/strong&gt;&lt;/h2&gt;
  &lt;p&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;
      This error happens we use &lt;em style=&quot;background-color: rgb(206, 212, 217); color: rgb(0, 0, 0);&quot;&gt;Single()&lt;/em&gt; or &lt;em style=&quot;background-color: rgb(206, 212, 217); color: rgb(0, 0, 0);&quot;&gt;First()&lt;/em&gt; to retrieve a value but the value doesn't exist in the dataset. Let's look an example:
    &lt;/span&gt;&lt;/p&gt;
  &lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;
internal class Student
    {
        private string name;
        private int age;
        private string gender;
        private string hobby;

        public Student(string name, int age, string gender, string hobby)
        {
            this.name = name;
            this.age = age;
            this.gender = gender;
            this.hobby = hobby;
        }

        public string Name
        {
            get { return name; }
            set { name = value; }
        }

        public int Age
        {
            get { return age; }
            set { age = value; }
        }
        public string Gender
        {
            get { return gender; }
            set { gender = value; }
        }
        public string Hobby
        {
            get { return hobby; }
            set { hobby = value; }
        }
    }
  &lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
  &lt;p&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;
      First, I create a &lt;em style=&quot;background-color: rgb(206, 212, 217); color: rgb(0, 0, 0);&quot;&gt;Student&lt;/em&gt; class with some properties.
    &lt;/span&gt;&lt;/p&gt;
  &lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;
List students = new List()
{
      new Student(&quot;Alex&quot;, 22, &quot;Male&quot;, &quot;Basketball&quot;),
      new Student(&quot;Cindy&quot;, 20, &quot;Female&quot;, &quot;Badminton&quot;),
      new Student(&quot;Joshua&quot;, 20, &quot;Male&quot;, &quot;Swimming&quot;),
      new Student(&quot;Emily&quot;, 21, &quot;Female&quot;, &quot;Basketball&quot;),
      new Student(&quot;Josely&quot;, 22, &quot;Female&quot;, &quot;Jogging&quot;),
};

var result = students.Where(student =&amp;gt; student.Name == &quot;Alex&quot;).Single();
Console.WriteLine($&quot;Here is the result:\n {Newtonsoft.Json.JsonConvert.SerializeObject(result)}&quot;);
  &lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
  &lt;p&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;
      Then, I create a list of &lt;em style=&quot;background-color: rgb(206, 212, 217); color: rgb(0, 0, 0);&quot;&gt;Student&lt;/em&gt; objects in my &lt;em style=&quot;background-color: rgb(206, 212, 217); color: rgb(0, 0, 0);&quot;&gt;program.cs&lt;/em&gt; and use the &lt;em style=&quot;background-color: rgb(206, 212, 217); color: rgb(0, 0, 0);&quot;&gt;Single()&lt;/em&gt; to get the only &lt;em&gt;Student&lt;/em&gt; with name &lt;em&gt;Alex&lt;/em&gt;.
    &lt;/span&gt;&lt;/p&gt;
  &lt;div style=&quot;margin-top: 15px&quot; class=&quot;div-purple&quot;&gt;
    &lt;span class=&quot;alert-header&quot;&gt;Note&lt;/span&gt;
    &lt;span class=&quot;alert-body&quot;&gt;We need to install &lt;em&gt;Newtonsoft&lt;/em&gt; library in the &lt;em&gt;Nuget Package&lt;/em&gt; so that we can use it to print out the &lt;em&gt;JSON string&lt;/em&gt; of our &lt;em&gt;Student&lt;/em&gt; object result.&lt;/span&gt;
  &lt;/div&gt;
  &lt;p&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;
      This is the result:
    &lt;/span&gt;&lt;/p&gt;
  &lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;
Here is the result:
 {&quot;Name&quot;:&quot;Alex&quot;,&quot;Age&quot;:22,&quot;Gender&quot;:&quot;Male&quot;,&quot;Hobby&quot;:&quot;Basketball&quot;}
  &lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
  &lt;p&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;
      Look, now we didn't get any errow because there's one &lt;em&gt;Student&lt;/em&gt; with name &lt;em&gt;Alex&lt;/em&gt;. Let's see another example:
    &lt;/span&gt;&lt;/p&gt;
  &lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;
List students = new List()
{
      new Student(&quot;Alex&quot;, 22, &quot;Male&quot;, &quot;Basketball&quot;),
      new Student(&quot;Cindy&quot;, 20, &quot;Female&quot;, &quot;Badminton&quot;),
      new Student(&quot;Joshua&quot;, 20, &quot;Male&quot;, &quot;Swimming&quot;),
      new Student(&quot;Emily&quot;, 21, &quot;Female&quot;, &quot;Basketball&quot;),
      new Student(&quot;Josely&quot;, 22, &quot;Female&quot;, &quot;Jogging&quot;),
};

var result = students.Where(student =&amp;gt; student.Name == &quot;Clarence&quot;).Single();
Console.WriteLine($&quot;Here is the result:\n {Newtonsoft.Json.JsonConvert.SerializeObject(result)}&quot;);
  &lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
  &lt;p&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;
      This is the result:
    &lt;/span&gt;&lt;/p&gt;
  &lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;
System.InvalidOperationException: 'Sequence contains no elements'
  &lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
  &lt;p&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;
      Now, the &lt;span style=&quot;color: rgb(185, 106, 217);&quot;&gt;&lt;em&gt;Sequence contains no elements&lt;/em&gt;&lt;/span&gt; error occurs. Let's look at another example using &lt;em style=&quot;background-color: rgb(206, 212, 217); color: rgb(0, 0, 0);&quot;&gt;First()&lt;/em&gt; method:
    &lt;/span&gt;&lt;/p&gt;
  &lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;
List students = new List()
{
      new Student(&quot;Alex&quot;, 22, &quot;Male&quot;, &quot;Basketball&quot;),
      new Student(&quot;Cindy&quot;, 20, &quot;Female&quot;, &quot;Badminton&quot;),
      new Student(&quot;Joshua&quot;, 20, &quot;Male&quot;, &quot;Swimming&quot;),
      new Student(&quot;Emily&quot;, 21, &quot;Female&quot;, &quot;Basketball&quot;),
      new Student(&quot;Josely&quot;, 22, &quot;Female&quot;, &quot;Jogging&quot;),
};

var result = students.Where(student =&amp;gt; student.Name == &quot;Clarence&quot;).First();
Console.WriteLine($&quot;Here is the result:\n {Newtonsoft.Json.JsonConvert.SerializeObject(result)}&quot;);
  &lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
  &lt;p&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;
      This is the result:
    &lt;/span&gt;&lt;/p&gt;
  &lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;
System.InvalidOperationException: 'Sequence contains no elements'
  &lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
  &lt;p&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;
      Same error occurs. Why? we'll see that next.
    &lt;/span&gt;&lt;/p&gt;
&lt;/section&gt;
&lt;section&gt;
  &lt;h2&gt;&lt;a class=&quot;custom_anchor&quot; name=&quot;_Toc123774611&quot; id=&quot;_Toc123774611&quot;&gt;&lt;/a&gt;&lt;strong&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;Causes&lt;/span&gt; &lt;a style=&quot;color: blue;&quot; rel=&quot;nofollow&quot; href=&quot;#_Toc123774611&quot;&gt;#&lt;/a&gt;&lt;/strong&gt;&lt;/h2&gt;
  &lt;p&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;
      Let's see the different types of errors that will be thrown while using &lt;em style=&quot;background-color: rgb(206, 212, 217); color: rgb(0, 0, 0);&quot;&gt;Single()&lt;/em&gt; or &lt;em style=&quot;background-color: rgb(206, 212, 217); color: rgb(0, 0, 0);&quot;&gt;First()&lt;/em&gt; method:
    &lt;/span&gt;&lt;/p&gt;
  &lt;h3&gt;&lt;em&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;Single():&lt;/span&gt;&lt;/em&gt;&lt;/h3&gt;
  &lt;ul&gt;
    &lt;li&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;&lt;strong&gt;&lt;em&gt;ArgumentNullException: &lt;/em&gt;&lt;/strong&gt;Thrown when the source sequence is &lt;em&gt;null&lt;/em&gt;.&lt;/span&gt;&lt;/li&gt;
    &lt;li&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;&lt;strong&gt;&lt;em&gt;InvalidOperationException: &lt;/em&gt;&lt;/strong&gt;Thrown when the no element satisfies the condition &lt;strong&gt;OR&lt;/strong&gt; more than one element satisfies the condition &lt;strong&gt;OR&lt;/strong&gt; the source sequence is empty.&lt;/span&gt;&lt;/li&gt;
  &lt;/ul&gt;
  &lt;h3&gt;&lt;em&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;First():&lt;/span&gt;&lt;/em&gt;&lt;/h3&gt;
  &lt;ul&gt;
    &lt;li&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;&lt;strong&gt;&lt;em&gt;ArgumentNullException: &lt;/em&gt;&lt;/strong&gt;Thrown when the source sequence is &lt;em&gt;null&lt;/em&gt;.&lt;/span&gt;&lt;/li&gt;
    &lt;li&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;&lt;strong&gt;&lt;em&gt;InvalidOperationException: &lt;/em&gt;&lt;/strong&gt;Thrown when no element satisfies the condition &lt;strong&gt;OR&lt;/strong&gt; the source sequence is empty.&lt;/span&gt;&lt;/li&gt;
  &lt;/ul&gt;
  &lt;p&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;
      According to the example on previous section, both &lt;em style=&quot;background-color: rgb(206, 212, 217); color: rgb(0, 0, 0);&quot;&gt;Single()&lt;/em&gt; and &lt;em style=&quot;background-color: rgb(206, 212, 217); color: rgb(0, 0, 0);&quot;&gt;First()&lt;/em&gt; method are getting the same error, that's &lt;span style=&quot;color: rgb(185, 106, 217);&quot;&gt;&lt;em&gt;System.InvalidOperationException: 'Sequence contains no elements'&lt;/em&gt;&lt;/span&gt;. This is because both of them can't find a value that meets the condition stated in the statement! So, how can we allow our program to run while this error is catched without being thrown at the output? Let's go to the next section.
    &lt;/span&gt;&lt;/p&gt;
&lt;/section&gt;
&lt;section&gt;
  &lt;h2&gt;&lt;a class=&quot;custom_anchor&quot; name=&quot;_Toc123774612&quot; id=&quot;_Toc123774612&quot;&gt;&lt;/a&gt;&lt;strong&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;Solution&lt;/span&gt; &lt;a style=&quot;color: blue;&quot; rel=&quot;nofollow&quot; href=&quot;#_Toc123774612&quot;&gt;#&lt;/a&gt;&lt;/strong&gt;&lt;/h2&gt;
  &lt;p&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;
      The solution is pretty simple, that's: instead of &lt;em style=&quot;background-color: rgb(206, 212, 217); color: rgb(0, 0, 0);&quot;&gt;Single()&lt;/em&gt; or &lt;em style=&quot;background-color: rgb(206, 212, 217); color: rgb(0, 0, 0);&quot;&gt;First()&lt;/em&gt;, use &lt;em style=&quot;background-color: rgb(206, 212, 217); color: rgb(0, 0, 0);&quot;&gt;SingleOrDefault()&lt;/em&gt; or &lt;em style=&quot;background-color: rgb(206, 212, 217); color: rgb(0, 0, 0);&quot;&gt;FirstOrDefault()&lt;/em&gt;. Instead of throwing the error &quot;&lt;span style=&quot;color: rgb(185, 106, 217);&quot;&gt;&lt;em&gt;Sequence contains no elements&lt;/em&gt;&lt;/span&gt;&quot;, they will return a &lt;em style=&quot;background-color: rgb(206, 212, 217); color: rgb(0, 0, 0);&quot;&gt;null&lt;/em&gt; value if no result found. Let's say:
    &lt;/span&gt;&lt;/p&gt;
  &lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;
List students = new List()
{
      new Student(&quot;Alex&quot;, 22, &quot;Male&quot;, &quot;Basketball&quot;),
      new Student(&quot;Cindy&quot;, 20, &quot;Female&quot;, &quot;Badminton&quot;),
      new Student(&quot;Joshua&quot;, 20, &quot;Male&quot;, &quot;Swimming&quot;),
      new Student(&quot;Emily&quot;, 21, &quot;Female&quot;, &quot;Basketball&quot;),
      new Student(&quot;Josely&quot;, 22, &quot;Female&quot;, &quot;Jogging&quot;),
};

var result = students.Where(student =&amp;gt; student.Name == &quot;Clarence&quot;).SingleOrDefault();
Console.WriteLine($&quot;Here is the result:\n {Newtonsoft.Json.JsonConvert.SerializeObject(result)}&quot;);
  &lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
  &lt;p&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;
      This is the result:
    &lt;/span&gt;&lt;/p&gt;
  &lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;
Here is the result:
 null
  &lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
  &lt;p&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;
      and for &lt;em style=&quot;background-color: rgb(206, 212, 217); color: rgb(0, 0, 0);&quot;&gt;FirstOrDefault()&lt;/em&gt;:
    &lt;/span&gt;&lt;/p&gt;
  &lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;
List students = new List()
{
      new Student(&quot;Alex&quot;, 22, &quot;Male&quot;, &quot;Basketball&quot;),
      new Student(&quot;Cindy&quot;, 20, &quot;Female&quot;, &quot;Badminton&quot;),
      new Student(&quot;Joshua&quot;, 20, &quot;Male&quot;, &quot;Swimming&quot;),
      new Student(&quot;Emily&quot;, 21, &quot;Female&quot;, &quot;Basketball&quot;),
      new Student(&quot;Josely&quot;, 22, &quot;Female&quot;, &quot;Jogging&quot;),
};

var result = students.Where(student =&amp;gt; student.Name == &quot;Clarence&quot;).FirstOrDefault();
Console.WriteLine($&quot;Here is the result:\n {Newtonsoft.Json.JsonConvert.SerializeObject(result)}&quot;);
  &lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
  &lt;p&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;
      This is the result:
    &lt;/span&gt;&lt;/p&gt;
  &lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;
Here is the result:
 null
  &lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
  &lt;p&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;
      Now, we can run our program without the error: &lt;span style=&quot;color: rgb(185, 106, 217);&quot;&gt;&lt;em&gt;Sequence contains no elements&lt;/em&gt;&lt;/span&gt; in the output. Although the condition is not met, we still can get a default object, which is &lt;em style=&quot;background-color: rgb(206, 212, 217); color: rgb(0, 0, 0);&quot;&gt;null&lt;/em&gt;. Looks, the solution is pretty simple right?
    &lt;/span&gt;&lt;/p&gt;
  &lt;div style=&quot;margin-top: 15px&quot; class=&quot;div-green&quot;&gt;
    &lt;span class=&quot;alert-header&quot;&gt;Tip&lt;/span&gt;
    &lt;span class=&quot;alert-body&quot;&gt;You can also execute some codes based on the object returned or return &lt;em style=&quot;background-color: rgb(206, 212, 217); color: rgb(0, 0, 0);&quot;&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.controllerbase.notfound?view=aspnetcore-7.0&quot; target=&quot;_blank&quot;&gt;NotFound()&lt;/a&gt;&lt;/em&gt; if you're using &lt;em style=&quot;background-color: rgb(206, 212, 217); color: rgb(0, 0, 0);&quot;&gt;ControllerBase&lt;/em&gt;.&lt;/span&gt;
  &lt;/div&gt;
  &lt;p&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;
      For instance:
    &lt;/span&gt;&lt;/p&gt;
  &lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;
List students = new List()
{
      new Student(&quot;Alex&quot;, 22, &quot;Male&quot;, &quot;Basketball&quot;),
      new Student(&quot;Cindy&quot;, 20, &quot;Female&quot;, &quot;Badminton&quot;),
      new Student(&quot;Joshua&quot;, 20, &quot;Male&quot;, &quot;Swimming&quot;),
      new Student(&quot;Emily&quot;, 21, &quot;Female&quot;, &quot;Basketball&quot;),
      new Student(&quot;Josely&quot;, 22, &quot;Female&quot;, &quot;Jogging&quot;),
};

var result = students.Where(student =&amp;gt; student.Name == &quot;Clarence&quot;).FirstOrDefault();
if(result != null)
{
    Console.WriteLine($&quot;Here is the result:\n {Newtonsoft.Json.JsonConvert.SerializeObject(result)}&quot;);
}
else
{
    Console.WriteLine(&quot;The student is not found in the record!&quot;);
}
  &lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
  &lt;p&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;
      This is the result:
    &lt;/span&gt;&lt;/p&gt;
  &lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;
The student is not found in the record!
  &lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;/section&gt;
&lt;section&gt;
  &lt;h2&gt;&lt;a class=&quot;custom_anchor&quot; name=&quot;_Toc123774613&quot; id=&quot;_Toc123774613&quot;&gt;&lt;/a&gt;&lt;strong&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;The Conclusion&lt;/span&gt; &lt;a style=&quot;color: blue;&quot; rel=&quot;nofollow&quot; href=&quot;#_Toc123774613&quot;&gt;#&lt;/a&gt;&lt;/strong&gt;&lt;/h2&gt;
  &lt;p&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;
      In this study blog, we've learned what is &lt;span style=&quot;color: rgb(185, 106, 217);&quot;&gt;&lt;em&gt;Sequence contains no elements&lt;/em&gt;&lt;/span&gt; in LINQ, why it happens and how to resolve it. Note that using &lt;em style=&quot;background-color: rgb(206, 212, 217); color: rgb(0, 0, 0);&quot;&gt;SingleOrDefault()&lt;/em&gt; or &lt;em style=&quot;background-color: rgb(206, 212, 217); color: rgb(0, 0, 0);&quot;&gt;FirstOrDefault()&lt;/em&gt; is always better as they will not throw exception and terminate the program. Instead, they can help the programmers to check the output while executing the statement. Thank you and enjoy your day! :)
    &lt;/span&gt;&lt;/p&gt;
&lt;/section&gt;
&lt;section&gt;
  &lt;h2&gt;&lt;a class=&quot;custom_anchor&quot; name=&quot;_Toc123774614&quot; id=&quot;_Toc123774614&quot;&gt;&lt;/a&gt;&lt;strong&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;The Reference&lt;/span&gt; &lt;a style=&quot;color: blue;&quot; rel=&quot;nofollow&quot; href=&quot;#_Toc123774614&quot;&gt;#&lt;/a&gt;&lt;/strong&gt;&lt;/h2&gt;
  &lt;p&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;
      For further information, please visit:
    &lt;/span&gt;&lt;/p&gt;
  &lt;ol&gt;
    &lt;li&gt;&lt;em&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;Serialization: &lt;/span&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/serialization/&quot; target=&quot;_blank&quot;&gt;https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/serialization/&lt;/a&gt;&lt;/em&gt;&lt;/li&gt;
    &lt;li&gt;&lt;em&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;Single() in LINQ: &lt;/span&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.single?view=net-7.0&quot; target=&quot;_blank&quot;&gt;https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.single?view=net-7.0&lt;/a&gt;&lt;/em&gt;&lt;/li&gt;
    &lt;li&gt;&lt;em&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;First() in LINQ: &lt;/span&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.first?view=net-7.0&quot; target=&quot;_blank&quot;&gt;https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.first?view=net-7.0&lt;/a&gt;&lt;/em&gt;&lt;/li&gt;
    &lt;li&gt;&lt;em&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;SingleOrDefault() in LINQ: &lt;/span&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.singleordefault?view=net-7.0&quot; target=&quot;_blank&quot;&gt;https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.singleordefault?view=net-7.0&lt;/a&gt;&lt;/em&gt;&lt;/li&gt;
    &lt;li&gt;&lt;em&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;FirstOrDefault() in LINQ: &lt;/span&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.firstordefault?view=net-7.0&quot; target=&quot;_blank&quot;&gt;https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.firstordefault?view=net-7.0&lt;/a&gt;&lt;/em&gt;&lt;/li&gt;
  &lt;/ol&gt;
&lt;/section&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/21746/sequence-contains-no-elements</guid>
<pubDate>Thu, 02 Jul 2026 06:40:00 +0000</pubDate>
</item>
<item>
<title>Convert the string into Camel case and remove special characters from string in C, C++</title>
<link>https://coderlegion.com/18847/convert-the-string-into-camel-case-and-remove-special-characters-from-string-in-c-c</link>
<description>&lt;p&gt;&lt;strong&gt;You might have encountered situation that's required to &lt;b&gt;Convert the string into Camel case and remove special characters from string&lt;/b&gt; in C or C++. To solve this problem, we can simply converting the string to camel case, then eliminating all special characters. In this article, we will also go over details with examples.&lt;/strong&gt;&lt;/p&gt;
&lt;div id=&quot;tc-div&quot;&gt;
&lt;h4&gt;&lt;span style=&quot;font-family:arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;Table of Contents &lt;a id=&quot;tc-toogle&quot; class=&quot;open&quot;&gt;&lt;/a&gt;&lt;/strong&gt;&lt;/span&gt;&lt;/h4&gt;
&lt;div id=&quot;tc-list&quot;&gt;
&lt;ol&gt;
&lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;#idt&quot;&gt;&lt;span style=&quot;font-family:arial,helvetica,sans-serif;&quot;&gt;Identify the problem&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;#sol&quot;&gt;&lt;span style=&quot;font-family:arial,helvetica,sans-serif;&quot;&gt;Solution&lt;/span&gt;&lt;/a&gt;
&lt;ol&gt;
&lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;#sol1&quot;&gt;&lt;span style=&quot;font-family:arial,helvetica,sans-serif;&quot;&gt;Solution in C++&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;#sol2&quot;&gt;&lt;span style=&quot;font-family:arial,helvetica,sans-serif;&quot;&gt;Solution in C&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;#con&quot;&gt;&lt;span style=&quot;font-family:arial,helvetica,sans-serif;&quot;&gt;Conclusion&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;#ref&quot;&gt;&lt;span style=&quot;font-family:arial,helvetica,sans-serif;&quot;&gt;Reference&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;&lt;/div&gt;&lt;/div&gt;
&lt;section&gt;
&lt;a id=&quot;idt&quot; class=&quot;custom_anchor&quot;&gt;&lt;/a&gt; &lt;h2&gt;&lt;span style=&quot;font-family:arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;1. Identify the problem&lt;/strong&gt;&lt;/span&gt;&lt;a id=&quot;identify-the-problem&quot; rel=&quot;nofollow&quot; href=&quot;#idt&quot; style=&quot;color: blue&quot;&gt;#&lt;/a&gt;&lt;/h2&gt;

&lt;p&gt;&lt;span style=&quot;font-family:arial,helvetica,sans-serif;&quot;&gt;An usual string, such as this sentence &lt;strong&gt;&quot;Hello World! How are you today?&quot;&lt;/strong&gt;, is not only contain word seperated by space. It's also has some &lt;span style=&quot;color: #ff04fc;&quot;&gt;special characters&lt;/span&gt; like the question mark &lt;b&gt;'?'&lt;/b&gt; or the exclamation mark &lt;b&gt;'!'&lt;/b&gt;. We only need the words and digits to remain, and erase the rest.  &lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Input&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;How old are you? I'm 15 years old&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Output&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;HowOldAreYouIm15YearsOld&lt;/code&gt;&lt;/pre&gt;
&lt;/section&gt;
&lt;section&gt;
&lt;a id=&quot;sol&quot; class=&quot;custom_anchor&quot;&gt;&lt;/a&gt; &lt;h2&gt;&lt;span style=&quot;font-family:arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;2. Solution&lt;/strong&gt;&lt;/span&gt; &lt;a id=&quot;solution&quot; rel=&quot;nofollow&quot; href=&quot;#sol&quot; style=&quot;color: blue&quot;&gt;#&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;Take the first example:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Hello World! How are you today?&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;It'll be easier to consider this problem as 2 smaller sub-problem: Converting a string to camel case, and removing all &lt;span style=&quot;color: #ff04fc;&quot;&gt;special characters&lt;/span&gt; from a string. We will go into the details of the solution with both C and C++, as well as things to keep in mind for each method.&lt;/p&gt;

&lt;a id=&quot;sol1&quot; class=&quot;custom_anchor&quot;&gt;&lt;/a&gt; &lt;h3&gt;&lt;span style=&quot;font-family:arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;1. Solution in C++&lt;/strong&gt;&lt;/span&gt;&lt;/h3&gt;

&lt;p&gt;We first create a function &lt;code&gt;'toCamelCase(string str)'&lt;/code&gt; which takes a string as an input and converts it to camel case. &lt;/p&gt;
&lt;pre&gt;&lt;code&gt;
&lt;span style=&quot;font-family:arial,helvetica,sans-serif;&quot;&gt;void to_camel_case(std::string &amp;amp;s) {
  if (s.empty()) return;
  for (int i = 0; i &amp;lt; s.length(); i++) {
    if (s[i] == ' ' || s[i] == '_') {
      int j = i + 1;
      if (j &amp;lt; s.length()) {
        s[j] = toupper(s[j]);
      }
    }
  }
}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Then, we design a function called &lt;code&gt;'removeSpecialChars(string str)'&lt;/code&gt; to return the input string after removing all special characters.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;
&lt;span style=&quot;font-family:arial,helvetica,sans-serif;&quot;&gt;void remove_special_characters(std::string &amp;amp;s) {
  if (s.empty()) return;
  for (int i = 0; i &amp;lt; s.length(); i++) {
    if (!isalnum(s[i])) {
      s.erase(i, 1);
      i--;
    }
  }
}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;a id=&quot;sol2&quot; class=&quot;custom_anchor&quot;&gt;&lt;/a&gt; &lt;h3&gt;&lt;span style=&quot;font-family:arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;2. Solution in C&lt;/strong&gt;&lt;/span&gt;&lt;/h3&gt;
&lt;p&gt;There seemes no obvious different when comparing to the solution in C++. First we convert string to camel case, then remove special characters.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;
&lt;span style=&quot;font-family:arial,helvetica,sans-serif;&quot;&gt;void to_camel_case(char *s) {
  if (s == NULL) return;
  int len = strlen(s);
  if (len == 0) return;
  for (int i = 0; i &amp;lt; len; i++) {
    if (s[i] == ' ' || s[i] == '_') {
      int j = i + 1;
      if (j &amp;lt; len) {
        s[j] = toupper(s[j]);
      }
    }
  }
}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;


&lt;pre&gt;&lt;code&gt;
&lt;span style=&quot;font-family:arial,helvetica,sans-serif;&quot;&gt;void remove_special_characters(char *s) {
  if (s == NULL) return;
  int len = strlen(s);
  if (len == 0) return;
  for (int i = 0; i &amp;lt; len; i++) {
    if (!isalnum(s[i])) {
      for (int j = i; j &amp;lt; len; j++) {
        s[j] = s[j + 1];
      }
      len--;
      i--;
    }
  }
}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;But we need to pay attention to the type of &lt;code&gt;&lt;strong&gt;string&lt;/strong&gt;&lt;/code&gt; in C.&lt;/p&gt;
&lt;div class=&quot;div-pink&quot;&gt;
&lt;span class=&quot;alert-header&quot;&gt;Caution&lt;/span&gt;
&lt;span class=&quot;alert-body&quot;&gt;In C++, we use the std::string class to handle strings, which provides a lot of helpful methods for manipulating strings, such as erase and empty. In C, we have to use arrays of characters, and manually manage memory allocation and deallocation.&lt;/span&gt;
&lt;/div&gt;

&lt;p&gt;The C++ implementation provides a more convenient and easier-to-use interface for string manipulation, while the C implementation provides a lower-level interface that gives you more control over memory and performance.&lt;/p&gt;

&lt;p&gt;Finally, after execute 2 functions, we will be able to receive the desired result&lt;/p&gt;
&lt;strong&gt;Output&lt;/strong&gt;
&lt;pre&gt;&lt;code&gt;HelloWorldHowAreYouToday&lt;/code&gt;&lt;/pre&gt;&lt;/section&gt;
&lt;section&gt;
&lt;a id=&quot;con&quot; class=&quot;custom_anchor&quot;&gt;&lt;/a&gt; &lt;h2&gt;&lt;span style=&quot;font-family:arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;3. Conclusion&lt;/strong&gt;&lt;/span&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;#con&quot; style=&quot;color: blue&quot;&gt;#&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;Going through this article, we've discussed about how to &lt;b&gt;Convert the string into Camel case and remove special characters from string&lt;/b&gt; in C and C++ , by raising the first letters from each word to uppercase first, after that removing the special characters. I recommend reading in details to understand better how it works and knows the different between 2 cases. Have a nice day!&lt;/p&gt;&lt;/section&gt;
&lt;section&gt;
&lt;a id=&quot;ref&quot; class=&quot;custom_anchor&quot;&gt;&lt;/a&gt; &lt;h2&gt;&lt;span style=&quot;font-family:arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;4. Reference&lt;/strong&gt;&lt;/span&gt;&lt;a id=&quot;reference&quot; rel=&quot;nofollow&quot; href=&quot;#ref&quot; style=&quot;color: blue&quot;&gt;#&lt;/a&gt;&lt;/h2&gt;
&lt;p&gt;For further information, please visit:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;i&gt;toupper()&lt;/i&gt;:&lt;a rel=&quot;nofollow&quot; href=&quot;https://cplusplus.com/reference/cctype/toupper/&quot;&gt; cplusplus.com/reference/cctype/toupper&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;b&gt;string&lt;/b&gt;:&lt;a rel=&quot;nofollow&quot; href=&quot;https://devdocs.io/c/string/byte&quot;&gt; https://devdocs.io/c/string/byte&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;/section&gt;</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/18847/convert-the-string-into-camel-case-and-remove-special-characters-from-string-in-c-c</guid>
<pubDate>Mon, 25 May 2026 04:00:43 +0000</pubDate>
</item>
<item>
<title>Index was outside the bounds of the array</title>
<link>https://coderlegion.com/18567/index-was-outside-the-bounds-of-the-array</link>
<description>&lt;p&gt;&lt;strong style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;Today, we're going to fix a C# Error: &lt;span style=&quot;color: rgb(185, 106, 217);&quot;&gt;&lt;em&gt;Index was outside the bounds of the array&lt;/em&gt;&lt;/span&gt; that usually occurs when we try to access the &lt;em&gt;index less than 0&lt;/em&gt; or &lt;em&gt;greater than or equal to the array length - 1&lt;/em&gt;. In this study blog, we'll explore why it happens and how to resolve it.&lt;/strong&gt;&lt;/p&gt;
&lt;div&gt;
  &lt;h4&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt; Table of Contents: &lt;a class=&quot;open&quot;&gt;&lt;/a&gt;&lt;/strong&gt;&lt;/span&gt;&lt;/h4&gt;
  &lt;div&gt;
    &lt;ol&gt;
      &lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;#_Toc123774610&quot;&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;What is &quot;Index was outside the bounds of the array&quot;&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;#_Toc123774611&quot;&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;Causes&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;#_Toc123774612&quot;&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;Solution&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;#_Toc123774613&quot;&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;The Conclusion&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;#_Toc123774614&quot;&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;The Reference&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
    &lt;/ol&gt;
  &lt;/div&gt;
&lt;/div&gt;
&lt;section&gt;
  &lt;h2&gt;&lt;a class=&quot;custom_anchor&quot; name=&quot;_Toc123774610&quot;&gt;&lt;/a&gt;&lt;strong&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;What is &quot;Index was outside the bounds of the array&quot;&lt;/span&gt; &lt;a style=&quot;color: blue;&quot; rel=&quot;nofollow&quot; href=&quot;#_Toc123774610&quot;&gt;#&lt;/a&gt;&lt;/strong&gt;&lt;/h2&gt;
  &lt;p&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;
      This error happens when we try to access the elements in the array using &lt;em&gt;&lt;strong&gt;invalid index&lt;/strong&gt;&lt;/em&gt;. Let's see an example:
    &lt;/span&gt;&lt;/p&gt;

  &lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;
int[] numbers = new int[] { 1,2,3,4,5,6,7,8,9 };
for(int i = 0; i &amp;lt;= numbers.Length; i++)
{
    Console.WriteLine(numbers[i]);
}
  &amp;lt;/span&amp;gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
  &lt;p&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;
      This is the output:
    &lt;/span&gt;&lt;/p&gt;
  &lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;
1
2
3
4
5
6
7
8
9
System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'
  &lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
  &lt;p&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;
      Why? Because the &lt;em style=&quot;background-color: rgb(206, 212, 217); color: rgb(0, 0, 0);&quot;&gt;numbers&lt;/em&gt; array has 9 elements, and thus its length is 9. However, in programming, each collection like array has indices in the range of &lt;em&gt;&lt;strong&gt;[0 - N-1], where N = array.length&lt;/strong&gt;&lt;/em&gt; and we can access each element in the array within that range. In the above example, after accessing &lt;em style=&quot;background-color: rgb(206, 212, 217); color: rgb(0, 0, 0);&quot;&gt;index 8 with element 9&lt;/em&gt; in &lt;em style=&quot;background-color: rgb(206, 212, 217); color: rgb(0, 0, 0);&quot;&gt;numbers&lt;/em&gt; array, we tend to access element at index &lt;em style=&quot;background-color: rgb(206, 212, 217); color: rgb(0, 0, 0);&quot;&gt;9&lt;/em&gt;, which is an &lt;em&gt;invalid index&lt;/em&gt; for &lt;em style=&quot;background-color: rgb(206, 212, 217); color: rgb(0, 0, 0);&quot;&gt;numbers&lt;/em&gt; array. That's why this error occur.
    &lt;/span&gt;&lt;/p&gt;
  &lt;p&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;
      Let's look at another example:
    &lt;/span&gt;&lt;/p&gt;
  &lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;
int[] numbers = new int[] { 1,2,3,4,5,6,7,8,9 };
numbers[-1] = 10;
  &lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
  &lt;p&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;
      This is the output:
    &lt;/span&gt;&lt;/p&gt;
  &lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;
System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'
  &lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
  &lt;p&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;
      Why? we're trying to assign value to the element of &lt;em style=&quot;background-color: rgb(206, 212, 217); color: rgb(0, 0, 0);&quot;&gt;numbers&lt;/em&gt; array at index &lt;em style=&quot;background-color: rgb(206, 212, 217); color: rgb(0, 0, 0);&quot;&gt;-1&lt;/em&gt;, which is also an &lt;em&gt;invalid index&lt;/em&gt; for &lt;em style=&quot;background-color: rgb(206, 212, 217); color: rgb(0, 0, 0);&quot;&gt;numbers&lt;/em&gt; array. Hence, the error will also occur.
    &lt;/span&gt;&lt;/p&gt;
&lt;/section&gt;
&lt;section&gt;
  &lt;h2&gt;&lt;a class=&quot;custom_anchor&quot; name=&quot;_Toc123774611&quot;&gt;&lt;/a&gt;&lt;strong&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;Causes&lt;/span&gt; &lt;a style=&quot;color: blue;&quot; rel=&quot;nofollow&quot; href=&quot;#_Toc123774611&quot;&gt;#&lt;/a&gt;&lt;/strong&gt;&lt;/h2&gt;
  &lt;p&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;
      The error, &lt;span style=&quot;color: rgb(185, 106, 217);&quot;&gt;&lt;em&gt;Index was outside the bounds of the array&lt;/em&gt;&lt;/span&gt; is actually under &lt;em style=&quot;background-color: rgb(206, 212, 217); color: rgb(0, 0, 0);&quot;&gt;IndexOutOfRangeException&lt;/em&gt; Class in C#. &lt;em style=&quot;background-color: rgb(206, 212, 217); color: rgb(0, 0, 0);&quot;&gt;IndexOutOfRangeException: The exception is thrown when the attempt to access the element of a collection or an array using the index outside its bounds is made.&lt;/em&gt; Hence, &lt;span style=&quot;color: rgb(185, 106, 217);&quot;&gt;&lt;em&gt;System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'&lt;/em&gt;&lt;/span&gt; occurs when we're trying to access the element of an array using &lt;em&gt;&lt;strong&gt;invalid index&lt;/strong&gt;&lt;/em&gt;. Don't fret; it can be simply resolved.
    &lt;/span&gt;&lt;/p&gt;
  &lt;div style=&quot;margin-top: 15px&quot; class=&quot;div-purple&quot;&gt;
    &lt;span class=&quot;alert-header&quot;&gt;Note&lt;/span&gt;
    &lt;span class=&quot;alert-body&quot;&gt;Every collection such as list, array or the other has only indices in the range of &lt;em&gt;[0, N-1]&lt;/em&gt;, where &lt;em&gt;N is the length of the array&lt;/em&gt; itself.&lt;/span&gt;
  &lt;/div&gt;
&lt;/section&gt;
&lt;section&gt;
  &lt;h2&gt;&lt;a class=&quot;custom_anchor&quot; name=&quot;_Toc123774612&quot;&gt;&lt;/a&gt;&lt;strong&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;Solution&lt;/span&gt; &lt;a style=&quot;color: blue;&quot; rel=&quot;nofollow&quot; href=&quot;#_Toc123774612&quot;&gt;#&lt;/a&gt;&lt;/strong&gt;&lt;/h2&gt;
  &lt;p&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;
      The solution is pretty simple, we just need to ensure we're accessing the elements of the array using the indices within its bounds. Let's say:
    &lt;/span&gt;&lt;/p&gt;
  &lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;
int[] numbers = new int[] { 1,2,3,4,5,6,7,8,9 };
for(int i = 0; i &amp;lt; numbers.Length; i++)
{
    Console.WriteLine(numbers[i]);
}
  &lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
  &lt;p&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;
      This is the output:
    &lt;/span&gt;&lt;/p&gt;
  &lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;
1
2
3
4
5
6
7
8
9
  &lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
  &lt;p&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;
      or you may also do like this:
    &lt;/span&gt;&lt;/p&gt;
  &lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;
int[] numbers = new int[] { 1,2,3,4,5,6,7,8,9 };
for(int i = 0; i &amp;lt;= numbers.Length-1; i++)
{
    Console.WriteLine(numbers[i]);
}
  &amp;lt;/span&amp;gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
  &lt;p&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;
      This is the output:
    &lt;/span&gt;&lt;/p&gt;
  &lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;
1
2
3
4
5
6
7
8
9
  &lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
  &lt;p&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;
      Both examples above are having the same output. What we do is to ensure that the iteration will only be in the range of &lt;em&gt;&lt;strong&gt;[0 - N-1], where N = array.length&lt;/strong&gt;&lt;/em&gt;. The &lt;em style=&quot;background-color: rgb(206, 212, 217); color: rgb(0, 0, 0);&quot;&gt;numbers&lt;/em&gt; array has the length of 9, and thus can only iterate from 0 to 8. These are the &lt;em&gt;&lt;strong&gt;valid indices&lt;/strong&gt;&lt;/em&gt; for the &lt;em style=&quot;background-color: rgb(206, 212, 217); color: rgb(0, 0, 0);&quot;&gt;numbers&lt;/em&gt; array.
    &lt;/span&gt;&lt;/p&gt;
  &lt;div style=&quot;margin-top: 15px&quot; class=&quot;div-green&quot;&gt;
    &lt;span class=&quot;alert-header&quot;&gt;Tip&lt;/span&gt;
    &lt;span class=&quot;alert-body&quot;&gt;You may also use &lt;em style=&quot;background-color: rgb(206, 212, 217); color: rgb(0, 0, 0);&quot;&gt;GetLowerBound(Int32)&lt;/em&gt; and &lt;em style=&quot;background-color: rgb(206, 212, 217); color: rgb(0, 0, 0);&quot;&gt;GetUpperBound(Int32)&lt;/em&gt; to avoid this error.&lt;/span&gt;
  &lt;/div&gt;
  &lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;
int[] numbers = new int[] { 1,2,3,4,5,6,7,8,9 };
for(int i = numbers.GetLowerBound(0); i &amp;lt;= numbers.GetUpperBound(0); i++)
{
    Console.WriteLine(numbers[i]);
}
  &amp;lt;/span&amp;gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
  &lt;p&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;
      This is the output:
    &lt;/span&gt;&lt;/p&gt;
  &lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;
1
2
3
4
5
6
7
8
9
  &lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
  &lt;p&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;
      For the case above, &lt;em style=&quot;background-color: rgb(206, 212, 217); color: rgb(0, 0, 0);&quot;&gt;GetLowerBound(0)&lt;/em&gt; is used to get the &lt;em&gt;&lt;strong&gt;index of the first element&lt;/strong&gt;&lt;/em&gt;, which is &lt;em&gt;0&lt;/em&gt; while &lt;em style=&quot;background-color: rgb(206, 212, 217); color: rgb(0, 0, 0);&quot;&gt;GetUpperBound(0)&lt;/em&gt; is used to get the &lt;em&gt;&lt;strong&gt;index of last element&lt;/strong&gt;&lt;/em&gt;. Hence, we can omit the error by using these two functions together.
    &lt;/span&gt;&lt;/p&gt;
  &lt;div style=&quot;margin-top: 15px&quot; class=&quot;div-purple&quot;&gt;
    &lt;span class=&quot;alert-header&quot;&gt;Note&lt;/span&gt;
    &lt;span class=&quot;alert-body&quot;&gt;The &lt;em&gt;dimension&lt;/em&gt; for both &lt;em style=&quot;background-color: rgb(206, 212, 217); color: rgb(0, 0, 0);&quot;&gt;GetLowerBound(int dimension)&lt;/em&gt; and &lt;em style=&quot;background-color: rgb(206, 212, 217); color: rgb(0, 0, 0);&quot;&gt;GetUpperBound(int dimension)&lt;/em&gt; is determined by the array type, whether it is &lt;em&gt;one-dimensional array&lt;/em&gt; or &lt;em&gt;two-dimensional array&lt;/em&gt; as they have the different &lt;a rel=&quot;nofollow&quot; href=&quot;https://learn.microsoft.com/en-us/dotnet/api/system.array.rank?view=net-7.0#system-array-rank&quot; target=&quot;_blank&quot;&gt;Rank&lt;/a&gt;. Make sure the dimension has the value of &lt;strong&gt;&lt;em&gt;greater than 0&lt;/em&gt;&lt;/strong&gt; or &lt;strong&gt;&lt;em&gt;Rank - 1&lt;/em&gt;&lt;/strong&gt;.&lt;/span&gt;
  &lt;/div&gt;
&lt;/section&gt;
&lt;section&gt;
  &lt;h2&gt;&lt;a class=&quot;custom_anchor&quot; name=&quot;_Toc123774613&quot;&gt;&lt;/a&gt;&lt;strong&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;The Conclusion&lt;/span&gt; &lt;a style=&quot;color: blue;&quot; rel=&quot;nofollow&quot; href=&quot;#_Toc123774613&quot;&gt;#&lt;/a&gt;&lt;/strong&gt;&lt;/h2&gt;
  &lt;p&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;
      In this study blog, we've explore what is &lt;span style=&quot;color: rgb(185, 106, 217);&quot;&gt;&lt;em&gt;Index was outside the bounds of the array&lt;/em&gt;&lt;/span&gt; in C#, why it happens and how to resolve it. You should always be aware with the indices of the array when you want to access its element. Make sure not to access index outside of its bound, which is the range &lt;em&gt;&lt;strong&gt;[0 - N - 1], where N = length of the array&lt;/strong&gt;&lt;/em&gt;. Thanks!
    &lt;/span&gt;&lt;/p&gt;
&lt;/section&gt;
&lt;section&gt;
  &lt;h2&gt;&lt;a class=&quot;custom_anchor&quot; name=&quot;_Toc123774614&quot;&gt;&lt;/a&gt;&lt;strong&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;The Reference&lt;/span&gt; &lt;a style=&quot;color: blue;&quot; rel=&quot;nofollow&quot; href=&quot;#_Toc123774614&quot;&gt;#&lt;/a&gt;&lt;/strong&gt;&lt;/h2&gt;
  &lt;p&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;
      For further information, please visit:
    &lt;/span&gt;&lt;/p&gt;
  &lt;ol&gt;
    &lt;li&gt;&lt;em&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;IndexOutOfRangeException: &lt;/span&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://learn.microsoft.com/en-us/dotnet/api/system.indexoutofrangeexception?view=net-7.0&quot; target=&quot;_blank&quot;&gt;https://learn.microsoft.com/en-us/dotnet/api/system.indexoutofrangeexception?view=net-7.0&lt;/a&gt;&lt;/em&gt;&lt;/li&gt;
    &lt;li&gt;&lt;em&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;GetLowerBound(Int32) in LINQ: &lt;/span&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://learn.microsoft.com/en-us/dotnet/api/system.array.getlowerbound?view=net-7.0#system-array-getlowerbound(system-int32)&quot; target=&quot;_blank&quot;&gt;https://learn.microsoft.com/en-us/dotnet/api/system.array.getlowerbound?view=net-7.0#system-array-getlowerbound(system-int32)&lt;/a&gt;&lt;/em&gt;&lt;/li&gt;
    &lt;li&gt;&lt;em&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;GetUpperBound(Int32): &lt;/span&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://learn.microsoft.com/en-us/dotnet/api/system.array.getupperbound?view=net-7.0#system-array-getupperbound(system-int32)&quot; target=&quot;_blank&quot;&gt;https://learn.microsoft.com/en-us/dotnet/api/system.array.getupperbound?view=net-7.0#system-array-getupperbound(system-int32)&lt;/a&gt;&lt;/em&gt;&lt;/li&gt;
  &lt;/ol&gt;
&lt;/section&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/18567/index-was-outside-the-bounds-of-the-array</guid>
<pubDate>Thu, 21 May 2026 12:28:19 +0000</pubDate>
</item>
<item>
<title>py_cpp_pair</title>
<link>https://coderlegion.com/17513/pycpppair</link>
<description>&lt;h2 id=&quot;py-cpp-pair&quot;&gt;py_cpp_pair&lt;/h2&gt;
&lt;p&gt;Write C++ directly inside Python strings, auto-generate &lt;code&gt;pybind11&lt;/code&gt; bindings, compile on-demand, dynamically load the extension, and inject exported symbols into your Python globals.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Version:&lt;/strong&gt; &lt;code&gt;1.0.0&lt;/code&gt;&lt;/p&gt;
&lt;h3 id=&quot;badges&quot;&gt;Badges&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;PyPI: &lt;code&gt;py_cpp_pair 1.0.0&lt;/code&gt; (import name: &lt;code&gt;py_cpp&lt;/code&gt;)&lt;/li&gt;
&lt;li&gt;Python: 3.10–3.13&lt;/li&gt;
&lt;li&gt;Platforms: Windows / Linux / macOS&lt;/li&gt;
&lt;li&gt;CI: GitHub Actions&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id=&quot;install&quot;&gt;Install&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;pip install py-cpp-pair
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Import name stays:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;import py_cpp as pcp
&lt;/code&gt;&lt;/pre&gt;
&lt;h3 id=&quot;quickstart&quot;&gt;Quickstart&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;import py_cpp as pcp

pcp.cpp(&quot;&quot;&quot;
int add(int a, int b) {
    return a + b;
}
&quot;&quot;&quot;)

print(add(5, 7))  # 12
&lt;/code&gt;&lt;/pre&gt;
&lt;h3 id=&quot;class-support&quot;&gt;Class support&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;import py_cpp as pcp

pcp.cpp(r&quot;&quot;&quot;
class Robot {
public:
    int power = 100;
    Robot() {}
    int attack() { return power * 2; }
};
&quot;&quot;&quot;)

r = Robot()
print(r.attack())  # 200
&lt;/code&gt;&lt;/pre&gt;
&lt;h3 id=&quot;public-api&quot;&gt;Public API&lt;/h3&gt;
&lt;p&gt;Only these are intended as public:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;pcp.cpp(code: str) -&amp;gt; module&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;pcp.install(package: str) -&amp;gt; bool&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;pcp.clear_cache() -&amp;gt; None&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;pcp.version() -&amp;gt; str&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id=&quot;cross-platform-support&quot;&gt;Cross-platform support&lt;/h3&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;&lt;th&gt;OS &lt;/th&gt;&lt;th&gt;Compiler used &lt;/th&gt;&lt;th&gt;Notes&lt;/th&gt;&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;&lt;td&gt;Windows &lt;/td&gt;&lt;td&gt;MinGW-w64 &lt;code&gt;g++&lt;/code&gt; (preferred) &lt;/td&gt;&lt;td&gt;Requires &lt;code&gt;g++&lt;/code&gt; on &lt;code&gt;PATH&lt;/code&gt;.&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;Linux &lt;/td&gt;&lt;td&gt;&lt;code&gt;g++&lt;/code&gt; &lt;/td&gt;&lt;td&gt;Requires build tools installed.&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;macOS &lt;/td&gt;&lt;td&gt;&lt;code&gt;clang++&lt;/code&gt; &lt;/td&gt;&lt;td&gt;Requires Xcode Command Line Tools.&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;Override the compiler via:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;# Windows (PowerShell)
$env:PY_CPP_CXX = &quot;g++&quot;

# Windows (cmd.exe)
set PY_CPP_CXX=g++

# Linux/macOS (bash/zsh)
export PY_CPP_CXX=clang++
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Optional best-effort auto-install (opt-in):&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;# Enable by setting an environment variable in your shell.
# The installer logic is OS-aware (Linux/macOS/Windows) and picks the best available path.

# Windows (PowerShell)
$env:PY_CPP_AUTO_INSTALL_COMPILER = &quot;1&quot;

# Windows (cmd.exe)
set PY_CPP_AUTO_INSTALL_COMPILER=1

# Linux/macOS (bash/zsh)
export PY_CPP_AUTO_INSTALL_COMPILER=1
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;One-shot (only for a single command):&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;# Windows (PowerShell)
$env:PY_CPP_AUTO_INSTALL_COMPILER=&quot;1&quot;; python -c &quot;import py_cpp.toolchain as t; t.ensure_compiler_available(); print('compiler ok')&quot;

# Linux/macOS (bash/zsh)
PY_CPP_AUTO_INSTALL_COMPILER=1 python -c &quot;import py_cpp.toolchain as t; t.ensure_compiler_available(); print('compiler ok')&quot;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Note: after an installer runs, you may need to open a new terminal so &lt;code&gt;PATH&lt;/code&gt; updates are visible.&lt;/p&gt;
&lt;h3 id=&quot;vcpkg-package-management&quot;&gt;vcpkg package management&lt;/h3&gt;
&lt;p&gt;Install a C++ library with:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;import py_cpp as pcp
pcp.install(&quot;fmt&quot;)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If the port does not exist:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-text&quot;&gt;Sorry, library not found.
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;py_cpp_pair&lt;/code&gt; detects &lt;code&gt;vcpkg&lt;/code&gt; via &lt;code&gt;VCPKG_ROOT&lt;/code&gt; or &lt;code&gt;PATH&lt;/code&gt;. If missing, it can auto-bootstrap by cloning vcpkg (requires Git).&lt;/p&gt;
&lt;h3 id=&quot;caching-and-build-layout&quot;&gt;Caching and build layout&lt;/h3&gt;
&lt;p&gt;&lt;code&gt;py_cpp_pair&lt;/code&gt; caches builds by SHA256 hash of the C++ source. Reusing identical code reuses the compiled extension.&lt;/p&gt;
&lt;p&gt;Per-user state is stored under &lt;code&gt;PY_CPP_HOME&lt;/code&gt; if set, otherwise the OS-default data directory:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Windows: &lt;code&gt;%LOCALAPPDATA%\\py_cpp&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;macOS: &lt;code&gt;~/Library/Application Support/py_cpp&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;Linux: &lt;code&gt;$XDG_DATA_HOME/py_cpp&lt;/code&gt; or &lt;code&gt;~/.local/share/py_cpp&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Subfolders:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;builds/&lt;/code&gt;: compiled extensions per hash&lt;/li&gt;
&lt;li&gt;&lt;code&gt;cache/&lt;/code&gt;: toolchain artifacts (Windows Python import libs)&lt;/li&gt;
&lt;li&gt;&lt;code&gt;logs/&lt;/code&gt;: optional logs (enable with &lt;code&gt;PY_CPP_LOG_FILE=1&lt;/code&gt;)&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id=&quot;troubleshooting&quot;&gt;Troubleshooting&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;ImportError: DLL load failed (Windows)&lt;/strong&gt;: ensure MinGW runtime DLLs are visible. &lt;code&gt;py_cpp_pair&lt;/code&gt; adds common DLL dirs automatically, but the compiler &lt;code&gt;bin&lt;/code&gt; directory must be on &lt;code&gt;PATH&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;No compiler found&lt;/strong&gt;: install &lt;code&gt;g++&lt;/code&gt;/&lt;code&gt;clang++&lt;/code&gt; and ensure it is on &lt;code&gt;PATH&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;vcpkg bootstrap fails&lt;/strong&gt;: install Git and retry, or set &lt;code&gt;VCPKG_ROOT&lt;/code&gt; to an existing vcpkg checkout.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id=&quot;performance-notes&quot;&gt;Performance notes&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;Compilation is cached by source hash; repeated calls are fast after the first build.&lt;/li&gt;
&lt;li&gt;For larger projects, prefer fewer, bigger &lt;code&gt;cpp()&lt;/code&gt; calls (each call creates a module).&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id=&quot;documentation&quot;&gt;Documentation&lt;/h3&gt;
&lt;p&gt;See &lt;code&gt;docs/&lt;/code&gt;:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;docs/installation.md&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;docs/architecture.md&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;docs/api.md&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;docs/package_manager.md&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;docs/troubleshooting.md&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;docs/examples.md&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id=&quot;roadmap&quot;&gt;Roadmap&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;Better symbol detection (still regex-based by design)&lt;/li&gt;
&lt;li&gt;Multiple translation units / headers&lt;/li&gt;
&lt;li&gt;Better vcpkg library auto-linking&lt;/li&gt;
&lt;li&gt;Optional clang-based parsing for richer bindings&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id=&quot;contributing&quot;&gt;Contributing&lt;/h3&gt;
&lt;p&gt;See &lt;code&gt;CONTRIBUTING.md&lt;/code&gt;.&lt;/p&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/17513/pycpppair</guid>
<pubDate>Tue, 12 May 2026 05:28:32 +0000</pubDate>
</item>
<item>
<title>POSIX Shared Memory</title>
<link>https://coderlegion.com/14234/posix-shared-memory</link>
<description>&lt;p&gt;POSIX shared memory allows to us to share a mapped region between unrelated processes without needing to create a corresponding  file.&lt;/p&gt;
&lt;p&gt;Linux uses a dedicated &lt;code&gt;tmpfs&lt;/code&gt; file system mounted under the directory &lt;code&gt;/dev/shm&lt;/code&gt;. This file system has kernel persistance - the shared memory objects that it contains will persists even if no process currently has them open, but they will be lost if the system is shut down.&lt;/p&gt;
&lt;p&gt;To use a POSIX shared memory object, we perform two steps:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Use the &lt;code&gt;shm_open()&lt;/code&gt; function to open an object with a specified name. The &lt;code&gt;shm_open()&lt;/code&gt; function is analogous to the &lt;code&gt;open()&lt;/code&gt; system call. It either creates a new shared memory object or opens an existing object. As its function result, &lt;code&gt;shm_open()&lt;/code&gt; returns a file descriptor referring to the object.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Pass the file descriptor obtained in the previous step in a call to &lt;code&gt;mmap()&lt;/code&gt; that specifies &lt;code&gt;MAP_SHARED&lt;/code&gt; in the flags argument. This maps the shared memory object into the process's virtual address space.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;pre&gt;&lt;code class=&quot;language-c&quot;&gt; #include &amp;lt;sys/mman.h&amp;gt;
 #include &amp;lt;sys/stat.h&amp;gt;        /* For mode constants */
 #include &amp;lt;fcntl.h&amp;gt;           /* For O_* constants */

int shm_open(const char *name, int oflag, mode_t mode);
int shm_unlink(const char *name);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;code&gt;name&lt;/code&gt; argument identifies the shared memory object to be created or opened. The &lt;code&gt;oflags&lt;/code&gt; argument is a mask of bits of O_* as being in &lt;code&gt;open()&lt;/code&gt; system call.&lt;/p&gt;
&lt;p&gt;At any point, we can apply &lt;code&gt;fstat()&lt;/code&gt; to the file descriptor returned by &lt;code&gt;shm_open()&lt;/code&gt; in order to obtain a &lt;code&gt;stat&lt;/code&gt; structure whose contain information about the shared memory object.&lt;/p&gt;
&lt;p&gt;Example of creating a POSIX shared memory is &lt;a rel=&quot;nofollow&quot; href=&quot;https://github.com/CanGulmez/Linux-Programming-Interface/blob/main/pshm/pshm_create.c&quot;&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;After created the memory object, we of course want to read and write the data into that. Data reading program is &lt;a rel=&quot;nofollow&quot; href=&quot;https://github.com/CanGulmez/Linux-Programming-Interface/blob/main/pshm/pshm_write.c&quot;&gt;here&lt;/a&gt; and writing program is &lt;a rel=&quot;nofollow&quot; href=&quot;https://github.com/CanGulmez/Linux-Programming-Interface/blob/main/pshm/pshm_read.c&quot;&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;SUSv3 requires that POSIX shared memory objects have at least kernel persistence; that is, they continue to exist until they are explicitly removed or the system is rebooted. When a shared memory object is no longer required, it should be removed using &lt;code&gt;shm_unlink()&lt;/code&gt;. The example program of its usage is &lt;a rel=&quot;nofollow&quot; href=&quot;https://github.com/CanGulmez/Linux-Programming-Interface/blob/main/pshm/pshm_unlink.c&quot;&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;In summary, a POSIX shared memory object is used to share a region of memory between unrelated processes without creating an underlying disk file. To do this, we replace the call to &lt;code&gt;open()&lt;/code&gt; that normally precedes &lt;code&gt;mmap()&lt;/code&gt; with a call to &lt;code&gt;shm_open()&lt;/code&gt;. The &lt;code&gt;shm_open()&lt;/code&gt; call creates a file in a memory-based file system, and we can employ traditional file descriptor system calls to perform various operations on this virtual file. In particular, &lt;code&gt;ftruncate()&lt;/code&gt; must be used to set the size of the shared memory object, since initially it has a length of zero.&lt;/p&gt;
</description>
<category>Tutorials</category>
<guid isPermaLink="true">https://coderlegion.com/14234/posix-shared-memory</guid>
<pubDate>Wed, 08 Apr 2026 12:50:12 +0000</pubDate>
</item>
<item>
<title>The Linux Programming Interface - Memory Mappings</title>
<link>https://coderlegion.com/14233/the-linux-programming-interface-memory-mappings</link>
<description>&lt;p&gt;Let's continue discussing the Linux programming with &lt;em&gt;mmap()&lt;/em&gt; system call.&lt;/p&gt;
&lt;p&gt;The mmap() system call creates a new &lt;em&gt;memory mapping&lt;/em&gt; in the calling process's virtual address space. There are two types of mapping:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;em&gt;File mapping&lt;/em&gt;: A file mapping maps a region of a file directly into the calling process's virtual memory.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;em&gt;Anonymous mapping&lt;/em&gt;: An anonymous mapping doesn't have a corresponding file. Instead, the pages of the mapping are initialized to 0.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The memory in one process's mapping may be shared with mappings in other processes (MAP_SHARED). This can occur in two ways:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;p&gt;When two processes map the same region of a file, they share the same pages of physical memory.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;A child process created by &lt;em&gt;fork()&lt;/em&gt; inherits copies of its parent's mappings, and these mappings refer to the same pages of physical memory as the corresponding mappings in the parent.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;We also set the memory mapping as private (MAP_PRIVATE) so that other processes cannot see the content of the memory mapping.&lt;/p&gt;
&lt;p&gt;In total, we can use mmap() in four situations:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;em&gt;Private file mapping&lt;/em&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;em&gt;Private anonymous mapping&lt;/em&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;em&gt;Shared file mapping&lt;/em&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;em&gt;Shared anonymous mapping&lt;/em&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;And don't forget &lt;em&gt;exec()&lt;/em&gt; family erase and rebuild the process virtual memory so that memory mapping is lost.&lt;/p&gt;
&lt;p&gt;If you type the &lt;code&gt;man 2 mmap&lt;/code&gt; and see the its signatures:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;void *mmap(void *addr, size_t length, int prot, int flags, int fd, off_t offset);
int munmap(void *addr, size_t length);
int msync(void *addr, size_t length, int flags);
void *mremap(void *oldaddr, size_t oldsize, size_t newsize, int flags, ... /* void *newaddr */)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In here:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;p&gt;The &lt;em&gt;addr&lt;/em&gt; argument indicates the virtual address at which the mapping is to be located. You should put the &lt;em&gt;NULL&lt;/em&gt; so that kernel selects the proper address.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The &lt;em&gt;length&lt;/em&gt; argument specifies the size of the mapping in bytes.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The &lt;em&gt;prot&lt;/em&gt; argument is a bit mask specifying the protection to be placed on the mapping and can take PROT_NONE, PROT_READ, PROT_WRITE, PROT_EXEC. For example, PROT_READ | PROT_WRITE means that mapping can be read and written but not executed.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The &lt;em&gt;flags&lt;/em&gt; argument is a bit mask of options controlling various aspects and can be MAP_PRIVATE and MAP_SHARED.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The &lt;em&gt;fd&lt;/em&gt; and &lt;em&gt;offset&lt;/em&gt; arguments are just for file mapping. But, in case of anonymous mapping, it is good practice to set &lt;em&gt;fd&lt;/em&gt; as -1.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Below is the simple anonymous file mapping program:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt; #include &quot;../linux.h&quot;

void main(int argc, char *argv[])
{
   char *addr;
   int fd;
   struct stat sb;

   if (argc != 2 || strcmp(argv[1], &quot;--help&quot;) == 0)
      usage_error(&quot;Wrong command-line usage&quot;);

   fd = open(argv[1], O_RDONLY);
   if (fd == -1)
      syscall_error();

   if (fstat(fd, &amp;amp;sb) == -1)
      syscall_error();

   addr = mmap(NULL, sb.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
   if (addr == MAP_FAILED)
      syscall_error();

   if (write(STDOUT_FILENO, addr, sb.st_size) == -1);
      syscall_error();

   exit(EXIT_SUCCESS);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As can be seen above, for file mapping (private or shared), the following steps are applied:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Obtain the file descriptor that is mapped, typically via a call to &lt;em&gt;open()&lt;/em&gt;.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Use &lt;em&gt;stat()&lt;/em&gt; system call to get the file length in bytes.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Pass these variables to mmap() system call call with NULL as start address of mapping.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Below is the another example about shared file mapping:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt; #include &quot;../linux.h&quot;

 #define MEM_SIZE 10

void main(int argc, char *argv[])
{
   char *addr;
   int fd;

   if (argc &amp;lt; 2 || strcmp(argv[1], &quot;--help&quot;) == 0)
      usage_error(&quot;Wrong command-line usage&quot;);

   fd = open(argv[1], O_RDWR);
   if (fd == -1)
      syscall_error();

   addr = mmap(NULL, MEM_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
   if (addr == MAP_FAILED)
      syscall_error();

   if (close(fd) == -1)       /* No longer need 'fd' */
      syscall_error();

   printf(&quot;Current string=%.*s\n&quot;, MEM_SIZE, addr);

   if (argc &amp;gt; 2) {            /* Update contents of region */
      if (strlen(argv[2]) &amp;gt;= MEM_SIZE)
         usage_error(&quot;String too long&quot;);
      
      memset(addr, 0, MEM_SIZE); /* Zero out region */
      strncpy(addr, argv[2], MEM_SIZE - 1);
      if (msync(addr, MEM_SIZE, MS_SYNC) == -1)
         syscall_error();

      printf(&quot;Copied \&quot;%s\&quot; to shared memory\n&quot;, argv[2]);
   }
   exit(EXIT_SUCCESS);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In this example, we see the writing 10 bytes to shared memory mapping after the zeroing a partition of file mapping. In addition, we see the &lt;em&gt;msync()&lt;/em&gt; system call. It is actually optional but good practice when writing to disk. It ensures that the 10 bytes are written to disk. &lt;/p&gt;
&lt;p&gt;In addition to MAP_PRIVATE and MAP_SHARED, Linux allows a number of other values to be included in the mmap() flags argument:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;p&gt;MAP_ANONYMOUS&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;MAP_FIXED&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;MAP_LOCKED&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;MAP_HUGETLB&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;MAP_NORESERVE&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;MAP_PRIVATE&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;MAP_POPULATE&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;MAP_SHARED&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;MAP_UNINITIALIZED&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Please read the manual page (&lt;code&gt;man 2 mmap&lt;/code&gt;) to learn these flags.&lt;/p&gt;
&lt;p&gt;When talking about memory mapping and virtual memory layout, I wanna give you some virtual memory operations. There are four main system call:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;p&gt;The &lt;em&gt;mprotect()&lt;/em&gt; system call changes the protection on a region of virtual memory.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The &lt;em&gt;mlock()&lt;/em&gt; and &lt;em&gt;mlockall()&lt;/em&gt; system calls lock a region of virtual memory into physical memory.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The &lt;em&gt;mincore()&lt;/em&gt; system call allows a process to determine whether the pages in a region of virtual memory are resident in physical memory.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The &lt;em&gt;madvise()&lt;/em&gt; system call allows a process to advise the kernel about its future patterns of usage of a virtual memory region.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Signatures of these system calls:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;int mprotect(void *addr, size_t len, int prot);
int mlock(const void *addr, size_t len);
int mlockall(int flags);
int munlock(const void *addr, size_t len);
int munlockall(void);
int mincore(void *addr, size_t length, unsigned char *vec);
int madvise(void *addr, size_t length, int advice);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Below is the simple program about changing the memory protection mapped by mmap() system call.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt; #include &quot;../linux.h&quot;

 #define LEN          (1024 * 1024)
 #define SHELL_FMT    &quot;cat /proc/%ld/maps | grep zero&quot;
 #define CMD_SIZE     (sizeof(SHELL_FMT) + 20)

void main(int argc, char *argv[])
{
   char cmd[CMD_SIZE];
   char *addr;
 
   addr = mmap(NULL, LEN, PROT_NONE, MAP_SHARED | 
               MAP_ANONYMOUS, -1, 0);
   if (addr == MAP_FAILED)
      syscall_error();
 
   /* Display line from /proc/self/maps corresponding to mapping */
 
   printf(&quot;Before mprotect()\n&quot;);
   snprintf(cmd, CMD_SIZE, SHELL_FMT, (long) getpid());
   system(cmd);
 
   /* Change protection on memory to allow read and write access */
 
   if (mprotect(addr, LEN, PROT_READ | PROT_WRITE) == -1)
      syscall_error();

   printf(&quot;After mprotect()\n&quot;);
   system(cmd);

   exit(EXIT_SUCCESS);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In here, firstly I've mapped a shared anonymous memory. mprotect() changes the memory mapping's from none to read and write protections. To see the this change, we can inspect the &lt;em&gt;/proc/PID/maps&lt;/em&gt; file.&lt;/p&gt;
&lt;p&gt;Until here, I gave you the overall memory mapping techniques. I'll explain the &lt;em&gt;shared memory&lt;/em&gt; which is the most effective data transmission IPC mechanism of Linux in further article.&lt;/p&gt;
&lt;p&gt;Resource:&lt;/p&gt;
&lt;p&gt;Kerrisk M., The Linux Programming Interface, no starch press, 2010&lt;/p&gt;
</description>
<category>Tutorials</category>
<guid isPermaLink="true">https://coderlegion.com/14233/the-linux-programming-interface-memory-mappings</guid>
<pubDate>Wed, 08 Apr 2026 11:50:41 +0000</pubDate>
</item>
<item>
<title>Simple Code Injection into ELF Executable</title>
<link>https://coderlegion.com/14091/simple-code-injection-into-elf-executable</link>
<description>&lt;p&gt;In this tutorial, I will explain an code injection technique into ELF executable.&lt;/p&gt;
&lt;p&gt;Firstly, you need to understand the ELF executable, its contents, sections, symbol table or so on. I've written a dedicated article previously. So if you don't have any information about ELF, please read it firstly and then come here again.&lt;/p&gt;
&lt;p&gt;Let's say we have the following source file:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;/**
  * Simple Code Injection
  */

 #include &amp;lt;stdio.h&amp;gt;
 #include &amp;lt;stdlib.h&amp;gt;
 #include &amp;lt;unistd.h&amp;gt;

int main(int argc, char *argv[])
{
int i, num;

        num = 10;

        for (i = 0; i &amp;lt; num; i++)
        {
              printf(&quot;#%d\n&quot;, i);
        }
        return EXIT_SUCCESS;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Compile this source file and then run it:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-shell&quot;&gt;$ gcc main.c -o main ; ./main
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;After that, you will see:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-console&quot;&gt; #0
 #1
 #2
 #3
 #4
 #5
 #6
 #7
 #8
 #9
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In here, I will change the &lt;em&gt;num = 10&lt;/em&gt; to &lt;em&gt;num = 5&lt;/em&gt; so that the output will be #0 to #4. &lt;/p&gt;
&lt;p&gt;To accomplish this, I need to find the corresponding machine instruction/s. According to your background, you need to know that &lt;em&gt;num&lt;/em&gt; variable will be in the &lt;em&gt;.text&lt;/em&gt; section of ELF executable. Because it is the local variable. To display the .text section of the program, &lt;em&gt;objdump&lt;/em&gt; is the primarily tool:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-shell&quot;&gt;$ objdump -j .text -d main
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The output will be as following:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-console&quot;&gt;(...)

0000000000001149 &amp;lt;main&amp;gt;:
    1149:f3 0f 1e fa          endbr64
    114d:55                   push   %rbp
    114e:48 89 e5             mov    %rsp,%rbp
    1151:48 83 ec 20          sub    $0x20,%rsp
    1155:89 7d ec             mov    %edi,-0x14(%rbp)
    1158:48 89 75 e0          mov    %rsi,-0x20(%rbp)
    115c:c7 45 fc 0a 00 00 00 movl   $0xa,-0x4(%rbp)
    1163:c7 45 f8 00 00 00 00 movl   $0x0,-0x8(%rbp)
    116a:eb 1d                jmp    1189 &amp;lt;main+0x40&amp;gt;
    116c:8b 45 f8             mov    -0x8(%rbp),%eax
    116f:89 c6                mov    %eax,%esi
    1171:48 8d 05 8c 0e 00 00 lea    0xe8c(%rip),%rax        # 2004 &amp;lt;_IO_stdin_used+0x4&amp;gt;
    1178:48 89 c7             mov    %rax,%rdi
    117b:b8 00 00 00 00       mov    $0x0,%eax
    1180:e8 cb fe ff ff       call   1050 &amp;lt;printf@plt&amp;gt;
    1185:83 45 f8 01          addl   $0x1,-0x8(%rbp)
    1189:8b 45 f8             mov    -0x8(%rbp),%eax
    118c:3b 45 fc             cmp    -0x4(%rbp),%eax
    118f:7c db                jl     116c &amp;lt;main+0x23&amp;gt;
    1191:b8 00 00 00 00       mov    $0x0,%eax
    1196:c9                   leave
    1197:c3                   ret
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Which machine instruction/s corresponds to &lt;em&gt;num = 10&lt;/em&gt;? You need to know reading the assembly instructions in here. The answer is the &lt;strong&gt;movl   $0xa,-0x4(%rbp)&lt;/strong&gt; assembly instruction. Because the stack pointer of the program was enlarged by 4 bytes (&lt;em&gt;int&lt;/em&gt; holds 4 bytes of memory) to lower address and put the immediate 0xA value. So that I need to change the 0xA value to 0x5. &lt;/p&gt;
&lt;p&gt;After the found required assembly instruction, I need to determine the memory address of it. If you look at center column, the machine instruction is &lt;strong&gt;c7 45 fc 0a 00 00 00&lt;/strong&gt;. In here:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;c7: the opcode of &lt;em&gt;movl&lt;/em&gt; register&lt;/li&gt;
&lt;li&gt;45 fc: the displacement of -0x4(%rbp)&lt;/li&gt;
&lt;li&gt;0a 00 00 00: the immediate value, 0xA (little-endian)&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;c7 byte resides at 0x115c address so that 0a byte at 0x115f.&lt;/p&gt;
&lt;p&gt;To change that byte, I'm gonna use &lt;em&gt;hexedit&lt;/em&gt; program:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-shell&quot;&gt;$ hexedit ./main
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;You will see:&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6xykdj3162c4xy1fq0pv.png&quot; alt=&quot;Image description&quot;&gt;&lt;/p&gt;
&lt;p&gt;After that, you move to 0x115F address and change the 0x0A value to 0x05. Save the changes and then run the program again. You will see:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-console&quot;&gt; #0
 #1
 #2
 #3
 #4
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;That's it. You injected the new code in the ELF executable . &lt;/p&gt;
&lt;p&gt;This technique is simple and powerful. But there are some limitations. The most important one is that you should not shift the byte addresses, just replace it. If you wanna change the entire ELF executable addresses, you need the other techniques. That's the next article's topic.&lt;/p&gt;
</description>
<category>Tutorials</category>
<guid isPermaLink="true">https://coderlegion.com/14091/simple-code-injection-into-elf-executable</guid>
<pubDate>Mon, 06 Apr 2026 20:12:17 +0000</pubDate>
</item>
<item>
<title>Interrupt Management in ARM Cortex-M</title>
<link>https://coderlegion.com/14090/interrupt-management-in-arm-cortex-m</link>
<description>&lt;p&gt;Interrupts is the must-known concept in embedded programming. So I wanna explain the interrupt management in ARM Cortex-M in this tutorial.&lt;/p&gt;
&lt;p&gt;ARM architecture distinguishes between the two types: &lt;em&gt;interrupt&lt;/em&gt; and &lt;em&gt;system exception&lt;/em&gt;. Interrupts are primarily sourced by external hardware like UART that warns about arrival of data. System exceptions are more software-related and caused by ARM Cortex internal.&lt;/p&gt;
&lt;p&gt;Interrupts and system exceptions are exchangeably used. But even if both of these do same thing (especially in programming), the differences are important for us, engineers!&lt;/p&gt;
&lt;p&gt;I'll use &quot;interrupt&quot; word for both terms further, if otherwise declared.&lt;/p&gt;
&lt;p&gt;Before diving into interrupts, you need to understand the general execution workflow of ARM Cortex. There are two types of &lt;em&gt;execution&lt;/em&gt; modes: &lt;em&gt;thread&lt;/em&gt; and &lt;em&gt;interrupt&lt;/em&gt;. After resetting the microcontroller, execution flow starts in thread mode so that if you want to use interrupts, you need to enter the interrupt mode. But how?&lt;/p&gt;
&lt;p&gt;When you flash your firmware into microcontroller (base address of 0x08000000, in case), ARM Cortex starts to execute the firmware's machine instructions in thread mode. If you want to use any interrupt, you have to explicitly say it to ARM Cortex by using &lt;em&gt;Interrupt Service Routines (ISRs)&lt;/em&gt;. ISRs are actually standard C functions, but have the special signatures. I'm gonna explain it later.&lt;/p&gt;
&lt;p&gt;The most important question about interrupts is that why do we need interrupts?&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;The answer: Interrupts are the source of multiprogramming!&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Interrupts give us &lt;em&gt;second&lt;/em&gt; execution flow besides the main flow (executed in thread mode by default). It also gives the &lt;em&gt;context switch&lt;/em&gt; mechanism for RTOS. I will explain it lastly. &lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5dvmqafsj7ilkcameuq1.png&quot; alt=&quot;Image description&quot;&gt;&lt;/p&gt;
&lt;p&gt;ARM Cortex has a special hardware called &lt;em&gt;Nested Vectored Interrupt Controller (NVIC)&lt;/em&gt;. It handles and manages the all interrupt usage. Below is the its simple schematic:&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ifm0nlj1u3zt5ujigevn.png&quot; alt=&quot;Image description&quot;&gt;&lt;/p&gt;
&lt;p&gt;Another important dedicated hardware is the &lt;em&gt;EXTI Controller&lt;/em&gt;. The peripheral interrupts in the microcontroller directly are connected to NVIC. But If you want to use interrupts over microcontroller pins (like detecting rising or falling edge of a button), you have to use EXTI lines. Microcontroller pins are grouped and tied to specific EXTI lines. Please look at the reference manual to find it.&lt;/p&gt;
&lt;p&gt;We have many different types of interrupts. For now, let's look at these:&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oxuqk3xcz9kjg3zxrjgh.png&quot; alt=&quot;Image description&quot;&gt;&lt;/p&gt;
&lt;p&gt;ARM Cortex has defined 15 fixed system exceptions (coming from internal of Cortex). But microcontroller vendors specify also variable-length interrupts (coming from external of Cortex). For example, STM32 series microcontrollers allow up to 256 interrupts.&lt;/p&gt;
&lt;p&gt;But where are located these interrupts? The answer is the &lt;em&gt;at vector table&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;The vector table is an array of word data inside the system&lt;br&gt;
memory, each representing the starting address of one exception type [1].&lt;/p&gt;
&lt;p&gt;If you've flashed any firmware into microcontroller over OpenOCD + GDB, you've seen probably the this vector table. If you've not, let's see it exactly. &lt;/p&gt;
&lt;p&gt;I have STM32F446RE microcontroller and ST-LINK connection. I've compiled a firmware (&lt;em&gt;firmware.elf&lt;/em&gt;) to flash it. Open a terminal and type:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;$ openocd -f interface/stlink.cfg -f target/stm32f4x.cfg
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;And open the second terminal and type:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;$ arm-none-eabi-gdb firmware.elf
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Lastly, type these into GDB session:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;(gdb) target remote localhost:3333
(gdb) monitor reset halt
(gdb) load
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;After flashed the firmware into microcontroller, you will see:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Loading section .isr_vector, size 0x1c4 lma 0x8000000
Loading section .text, size 0x1080 lma 0x80001d0
Loading section .rodata, size 0x10 lma 0x8001250
Loading section .init_array, size 0x4 lma 0x8001260
Loading section .fini_array, size 0x4 lma 0x8001264
Loading section .data, size 0x10 lma 0x8001268
Start address 0x80011d0, load size 4716
Transfer rate: 9 KB/sec, 786 bytes/write.
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Yeah! You see the interrupt vector table (_.isr_vector_) section was flashed at the base address of flash memory and other sections after the vector table. If you use any type of interrupt, the ARM Cortex gets the corresponding ISR handler from there so that ARM Cortex exactly knows the ISR handler addresses. You just need to select the required ISR handler function!&lt;/p&gt;
&lt;p&gt;As I said before, ISR handlers are special type of C functions. But why? Because the handlers have predefined function prototypes. You have to use these function prototypes. Otherwise, ARM Cortex cannot find it and treated as normal C functions, not the ISR handlers. &lt;/p&gt;
&lt;p&gt;These predefined handler prototypes are stored in the &lt;em&gt;startup code&lt;/em&gt;. For STM32F446RE, it is _startup_stm32f446xx.S_ file. Below is a part of this startup code:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;(...)

  .word  Reset_Handler
  .word  NMI_Handler
  .word  HardFault_Handler
  .word  MemManage_Handler
  .word  BusFault_Handler

(...)

  .word     CAN1_TX_IRQHandler                /* CAN1 TX                      */                         
  .word     CAN1_RX0_IRQHandler               /* CAN1 RX0                     */                          
  .word     CAN1_RX1_IRQHandler               /* CAN1 RX1                     */                          
  .word     CAN1_SCE_IRQHandler               /* CAN1 SCE                     */                          
  .word     EXTI9_5_IRQHandler                /* External Line[9:5]s          */                          
  .word     TIM1_BRK_TIM9_IRQHandler          /* TIM1 Break and TIM9          */         
  .word     TIM1_UP_TIM10_IRQHandler          /* TIM1 Update and TIM10        */         
  .word     TIM1_TRG_COM_TIM11_IRQHandler     /* TIM1 Trigger and Commutation and TIM11 */
  .word     TIM1_CC_IRQHandler                /* TIM1 Capture Compare         */                          
  .word     TIM2_IRQHandler                   /* TIM2                         */                   
  .word     TIM3_IRQHandler                   /* TIM3                         */                   
  .word     TIM4_IRQHandler                   /* TIM4                         */                   
  .word     I2C1_EV_IRQHandler                /* I2C1 Event                   */                          
  .word     I2C1_ER_IRQHandler                /* I2C1 Error                   */                          
  .word     I2C2_EV_IRQHandler                /* I2C2 Event                   */                          
  .word     I2C2_ER_IRQHandler                /* I2C2 Error                   */          

(...)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;At the beginning, I've stated that interrupts are the source of multiprogramming. This is core logic behind the RTOS!&lt;/p&gt;
&lt;p&gt;RTOSes use the interrupts to create many &lt;em&gt;tasks&lt;/em&gt;. In classic firmware written with RTOS, there are many tasks that the RTOS kernel have to handle and manage. You can think that task in the firmware corresponds to process in the computers. &lt;/p&gt;
&lt;p&gt;The RTOS kernel needs to execute these tasks in order and with same time-slice so that the kernel cuts the one task execution and passes to the next task execution using &lt;em&gt;context switches&lt;/em&gt;. This is done by using interrupts. For example, FreeRTOS kernel uses &lt;em&gt;SVC&lt;/em&gt; and &lt;em&gt;PendSV&lt;/em&gt; interrupts specificly to make the contex switch. Apart from that, the RTOS kernel uses also the &lt;em&gt;SysTick&lt;/em&gt; interrupt to give the equal execution time to each task. &lt;/p&gt;
&lt;p&gt;Got it. I've explain the interrupt management in ARM Cortex-M in general. I put the some references below. You can look at the interrupts and similar topics in there.&lt;/p&gt;
&lt;p&gt;References:&lt;/p&gt;
&lt;p&gt;[1]. Yiu J., The Definitive Guide to The ARM Cortex-M3, Second Edition, Newnes, page 36.&lt;br&gt;
Noviello C., Mastering STM32, 0.26 Release, Leanpub&lt;/p&gt;
</description>
<category>Tutorials</category>
<guid isPermaLink="true">https://coderlegion.com/14090/interrupt-management-in-arm-cortex-m</guid>
<pubDate>Mon, 06 Apr 2026 15:15:30 +0000</pubDate>
</item>
<item>
<title>How to build a firmware using Makefile?</title>
<link>https://coderlegion.com/14088/how-to-build-a-firmware-using-makefile</link>
<description>&lt;p&gt;In embedded programming, we trust IDEs like STM32CubeIDE, Keil or so on. These IDEs give us just some buttons and UIs to build, flash, and debug the source code that we've written for a MCU. But, I think that every engineer that works on this field have to know that how these steps are made by hand.&lt;/p&gt;
&lt;p&gt;In this tutorial, I will show building a firmware written for STM32F446RE MCU with just using a single Makefile.&lt;/p&gt;
&lt;p&gt;Below is the project directory:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;$ tree
.
├── bin/
├── drivers/
│   ├── CMSIS/
│   ├── STM32F446RETX_FLASH.ld
│   └── STM32F4xx_HAL_Driver/
├── lib/
├── Makefile
└── src/
    ├── it.c
    ├── main.c
    ├── main.h
    └── peripheral.c
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Firstly, which libraries do we need to have?&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;p&gt;HAL library&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;CMSIS library&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Linker script&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Startup/system code&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;arm-none-eabi-* tools&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;I've put the all required libraries/scripts into &lt;strong&gt;/drivers&lt;/strong&gt; directory. Please download these using:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;$ git clone --recurse-submodules https://github.com/STMicroelectronics/STM32CubeF4.git
$ sudo apt install gcc-arm-none-eabi
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In here, HAL library is used to program the peripherals and CMSIS for ARM-Cortex itself. These are the most important libraries that we have to get. &lt;/p&gt;
&lt;p&gt;Apart from that, we also need some special files. First is the &lt;strong&gt;linker script&lt;/strong&gt;. It includes the memory layout of microcontroller. Sometimes, it comes from above command. But if you cannot find it there, please install it externally. Another file is the &lt;strong&gt;startup code&lt;/strong&gt;. It's written in Assembly language. As its name suggests, it's the first code that runs in microcontroller. Basically, it includes the &lt;strong&gt;Reset_Handler&lt;/strong&gt; and a branch that jumps into &lt;strong&gt;main()&lt;/strong&gt; function in your source code. Also &lt;strong&gt;system code&lt;/strong&gt; includes the some generic and general definitions.&lt;/p&gt;
&lt;p&gt;After downloaded and explained the required ones, Let's write the &lt;strong&gt;Makefile&lt;/strong&gt; step by step:&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;1. Toolchain definitions&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;CC        := arm-none-eabi-gcc
OBJCOPY:= arm-none-eabi-objcopy
SIZE:= arm-none-eabi-size
RM        := rm -f
FILE:= file
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;2. MCU-specific definitions&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;DEVICE_FAMILY     := STM32F4xx
DEVICE_MODEL     := STM32F446xx
DEVICE_VARIANT     := STM32F446RETx
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;3. Compiler and linker flags&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;CORTEX_FLAGS     := -mthumb -mcpu=cortex-m4 -mfpu=fpv4-sp-d16 -mfloat-abi=hard
COMMON_FLAGS     := -g3 -Os -ffunction-sections -fdata-sections -Wall
AS_FLAGS             := -x assembler-with-cpp
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In here, we've defined some flags:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;-mthumb&lt;/strong&gt; means that the firmware uses thumb (16-bit) instruction set.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;-mcpu=cortex-m4&lt;/strong&gt; means the ARM-Cortex series itself.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;-mfpu=fpv4-sp-d16&lt;/strong&gt; and &lt;strong&gt;-mfloat-abi=hard&lt;/strong&gt; means that floating-point operations can be done in the firmware.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;4. Include paths&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;MAIN_INC:= ./src
CMSIS_INC:= ./drivers/CMSIS/Include
CMSIS_DEV_INC:= ./drivers/CMSIS/Device/ST/STM32F4xx/Include
HAL_INC:= ./drivers/STM32F4xx_HAL_Driver/Inc
CMSIS_DSP_INC:= ./drivers/CMSIS/DSP/Include
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In here, we specified the header files that are used in the source code.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;5. Source and special files&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;MAIN_SRC:= $(wildcard ./src/*.c)
HAL_SRC:= $(wildcard ./drivers/STM32F4xx_HAL_Driver/Src/*.c)
SYSTEM_SRC:= ./drivers/CMSIS/Device/ST/STM32F4xx/Source/Templates/system_stm32f4xx.c
STARTUP_CODE:= ./drivers/CMSIS/Device/ST/STM32F4xx/Source/Templates/gcc/startup_stm32f446xx.S
LINKER_SCRIPT:= ./drivers/STM32F446RETX_FLASH.ld
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;6. Sorthands and build definitions&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;DEFINES:= -D$(DEVICE_FAMILY) -D$(DEVICE_MODEL) -D$(DEVICE_VARIANT) \
-DUSE_HAL_DRIVER

SOURCES:= $(MAIN_SRC) $(HAL_SRC) $(SYSTEM_SRC)
OBJECTS:= $(notdir $(patsubst %.c,%.o,$(SOURCES))) startup_stm32f446xx.o
INCLUDES:= -I$(MAIN_INC) -I$(CMSIS_DEV_INC) -I$(CMSIS_INC) -I$(HAL_INC) \
-I$(CMSIS_DSP_INC)

CFLAGS:= $(CORTEX_FLAGS) $(COMMON_FLAGS) $(DEFINES) $(INCLUDES)
AFLAGS:= $(CORTEX_FLAGS) $(AS_FLAGS) $(DEFINES) $(INCLUDES)
LDFLAGS:= $(CORTEX_FLAGS) -T $(LINKER_SCRIPT) \
-Wl,--gc-sections,--relax --specs=nano.specs --specs=nosys.specs \
   -Wl,--start-group -lc -lm -lnosys -Wl,--end-group
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In here, I mostly did the string operations and manipulations. But some points are interesting and need some explanations:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Firstly, I've grouped the sources and libraries and converted the source file suffixes into object file formats.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Also, I've created three total flags that will be used for compiling, assembling, and linking phases.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;In linker flags, I put the linker script. As you noticed, this step will be done after the compiling the source files. I also linked the some libraries. &lt;strong&gt;-lc&lt;/strong&gt; is the standard C library. In firmware, we use often string manipulation functions (&lt;strong&gt;strlen()&lt;/strong&gt;, &lt;strong&gt;strcat()&lt;/strong&gt;, &lt;strong&gt;strcpy()&lt;/strong&gt; or so on), &lt;strong&gt;snprint()&lt;/strong&gt;, &lt;strong&gt;memset()&lt;/strong&gt;, or similar ones. &lt;strong&gt;-lm&lt;/strong&gt; is the math library as you know. &lt;strong&gt;-lnosys&lt;/strong&gt; means that I'm just implementing the bare-metal firmware, there is no such as kernel or fully OS.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;7. Output files&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;FIRMWARE_ELF:= firmware.elf
FIRMWARE_BIN:= firmware.bin
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Generally, we use the ELF file when flashing and debugging. ELF executable includes the both machine code, metadata, debug information, symbol table or similar stuffs. In contrast, BIN executable just includes the machine code. If you look at the size of both, you will use the ELF executable is much bigger! &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;8. The recipe&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;.PHONY: all

all:
@echo &quot;-------------------------------------&quot;
@echo &quot;----- Building the source files -----&quot;
@echo &quot;-------------------------------------&quot;
@$(CC) $(AFLAGS) -c $(STARTUP_CODE)
@$(CC) $(CFLAGS) -c $(SOURCES)

@echo &quot;\n------------------------------------&quot;
@echo &quot;----- Linking the object files -----&quot;
@echo &quot;------------------------------------&quot;
@$(CC) $(LDFLAGS) $(OBJECTS) -o $(FIRMWARE_ELF)
@$(OBJCOPY) -O binary $(FIRMWARE_ELF) $(FIRMWARE_BIN)
@$(RM) $(OBJECTS)

@echo &quot;\n-------------------------------------&quot;
@echo &quot;----- The firmware memory usage -----&quot;
@echo &quot;-------------------------------------&quot;
@$(SIZE) $(FIRMWARE_ELF)

@echo &quot;\n-------------------------------------&quot;
@echo &quot;----- The firmware binary format ----&quot;
@echo &quot;-------------------------------------&quot;
@$(FILE) $(FIRMWARE_ELF)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Lastly, run the Makefile:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;$ make
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;That's it . You've built the both &lt;strong&gt;firmware.elf&lt;/strong&gt; and &lt;strong&gt;firmware.bin&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;You are ready to flash the built firmware into microcontroller with this or similar command (over ST-Link connection):&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;$ openocd -f interface/stlink.cfg -f target/stm32f4x.cfg -c &quot;program firmware.elf verify reset exit&quot;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;I've also published a repository for that. You can look at it from here: &lt;a rel=&quot;nofollow&quot; href=&quot;https://github.com/CanGulmez/Embedded-Firmware-with-Makefile&quot;&gt;https://github.com/CanGulmez/Embedded-Firmware-with-Makefile&lt;/a&gt;&lt;/p&gt;
</description>
<category>Tutorials</category>
<guid isPermaLink="true">https://coderlegion.com/14088/how-to-build-a-firmware-using-makefile</guid>
<pubDate>Mon, 06 Apr 2026 15:13:09 +0000</pubDate>
</item>
<item>
<title>Flashing and Debugging A Firmware in Detail</title>
<link>https://coderlegion.com/14087/flashing-and-debugging-a-firmware-in-detail</link>
<description>&lt;p&gt;In this tutorial, I will inspect, flash and debug a firmware written for STM32F446RE microcontroller. To accomplish this, we need some dedicated tools:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;openocd&lt;/li&gt;
&lt;li&gt;arm-none-eabi-*&lt;/li&gt;
&lt;li&gt;gdb-multiarch&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;openocd is the primarily tool that we have to get. It's used as bridge between your host machine and debugger hardware. (I'm using use ST-Link hardware in this time). I will use it to connect to the debugger hardware. arm-none-eabi-* tools are the ARM toolchain   used in development of the firmware. gdb-multiarch is the debugger too.&lt;/p&gt;
&lt;p&gt;You can get these tools:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-shell&quot;&gt;$ sudo apt install openocd gcc-arm-none-eabi gdb-multiarch
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;em&gt;Note: I'm on Ubuntu 24.04, gcc-arm-none-eabi tools don't include the gdb debugger like arm-none-eabi-gdb. So that gdb-multiarch is being installed externally. On some distribution, the gdb debugger comes with gcc-arm-none-eabi.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;Suppose that I have a firmware called &quot;firmware.elf&quot; and wanna inspect it as first step. &lt;/p&gt;
&lt;p&gt;The first thing that you should do probably is to determine the firmware itself:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-console&quot;&gt;$ file firmware.elf
firmware.elf: ELF 32-bit LSB executable, ARM, EABI5 version 1 (SYSV), statically linked, with debug_info, not stripped
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;em&gt;file&lt;/em&gt; command simply outputs the firmware properties like the endiannes, architecture, or so on. You can see easily that this firmware was written for 32-bit ARM Cortex.&lt;/p&gt;
&lt;p&gt;We can see also the section sizes (in bytes) of the firmware with &lt;em&gt;arm-none-eabi-size&lt;/em&gt; command:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-console&quot;&gt;$ arm-none-eabi-size firmware.elf
   text   data    bss    dec    hexfilename
   5252     20   1732   7004   1b5cfirmware.elf
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If you are not familiar with sections of the executables, I've wrote many tutorials that explains the ELF executable. You can look at there.&lt;/p&gt;
&lt;p&gt;If you exactly wanna see the contents of the firmware, &lt;em&gt;arm-none-eabi-objdump&lt;/em&gt; is the primarily tool for that:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-console&quot;&gt;$ arm-none-eabi-objdump -j .text -d firmware.elf

firmware.elf:     file format elf32-littlearm


Disassembly of section .text:

(...)

0800079c &amp;lt;main&amp;gt;:
 800079c:b500      push{lr}
 800079e:b091      subsp, #68@ 0x44
 80007a0:f000 f8ac bl80008fc &amp;lt;HAL_Init&amp;gt;
 80007a4:f000 f82c bl8000800 &amp;lt;configOscClk&amp;gt;
 80007a8:f000 f844 bl8000834 &amp;lt;configDebugPort&amp;gt;
 80007ac:4911      ldrr1, [pc, #68]@ (80007f4 &amp;lt;main+0x58&amp;gt;)
 80007ae:4d12      ldrr5, [pc, #72]@ (80007f8 &amp;lt;main+0x5c&amp;gt;)
 80007b0:4c12      ldrr4, [pc, #72]@ (80007fc &amp;lt;main+0x60&amp;gt;)
 80007b2:4668      movr0, sp
 80007b4:f7ff ff08 bl80005c8 &amp;lt;strcpy&amp;gt;
 80007b8:4668      movr0, sp
 80007ba:f7ff ff81 bl80006c0 &amp;lt;strlen&amp;gt;
 80007be:f04f 33ff mov.wr3, #4294967295@ 0xffffffff
 80007c2:b282      uxthr2, r0
 80007c4:4669      movr1, sp
 80007c6:480d      ldrr0, [pc, #52]@ (80007fc &amp;lt;main+0x60&amp;gt;)
 80007c8:f000 fdc2 bl8001350 &amp;lt;HAL_UART_Transmit&amp;gt;
 80007cc:4629      movr1, r5
 80007ce:4668      movr0, sp
 80007d0:f7ff fefa bl80005c8 &amp;lt;strcpy&amp;gt;
 80007d4:4668      movr0, sp
 80007d6:f7ff ff73 bl80006c0 &amp;lt;strlen&amp;gt;
 80007da:f04f 33ff mov.wr3, #4294967295@ 0xffffffff
 80007de:b282      uxthr2, r0
 80007e0:4669      movr1, sp
 80007e2:4620      movr0, r4
 80007e4:f000 fdb4 bl8001350 &amp;lt;HAL_UART_Transmit&amp;gt;
 80007e8:f44f 707a mov.wr0, #1000@ 0x3e8
 80007ec:f000 f8b2 bl8000954 &amp;lt;HAL_Delay&amp;gt;
 80007f0:e7ec      b.n80007cc &amp;lt;main+0x30&amp;gt;
 80007f2:bf00      nop
 80007f4:0800146c .word0x0800146c
 80007f8:08001489 .word0x08001489
 80007fc:20000084 .word0x20000084

(...)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;For example, you see the &lt;em&gt;main()&lt;/em&gt; function in &lt;em&gt;.text&lt;/em&gt; section of the firmware. At left, the address of the machine code were being displayed. At center, you see the machine code corresponding to assembly instructions that is at right side.&lt;/p&gt;
&lt;p&gt;Inspecting the contents of ELF executable is huge topic. It has many variants and view-of-points in there.&lt;/p&gt;
&lt;p&gt;&quot;Flashing&quot; term means writing the dedicated sections of the firmware into the flash memory area of the microcontroller. It's done with many different ways. But I will show you openocd tool.&lt;/p&gt;
&lt;p&gt;In here, I have to define that how exactly does openocd work. It actually creates a server into the host machine with given configuration files. After starting the server session, you need to connect to that server over telnet or gdb. &lt;/p&gt;
&lt;p&gt;Let's do it. Firstly, connect the microcontroller to the host machine. Then open a terminal session and type this command:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-shell&quot;&gt;$ openocd -f interface/stlink.cfg -f target/stm32f4x.cfg
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In here, I gave the two configuration files. First is the interface. As I said, I use the ST-Link connection. Second is the target file. It defines the target architecture. The openocd comes a bunch of configuration files. So search it and find the appropriate configuration files.&lt;/p&gt;
&lt;p&gt;You will see something like this:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-console&quot;&gt;Open On-Chip Debugger 0.12.0
Licensed under GNU GPL v2
For bug reports, read
http://openocd.org/doc/doxygen/bugs.html
Info : auto-selecting first available session transport &quot;hla_swd&quot;. To override use 'transport select &amp;lt;transport&amp;gt;'.
Info : The selected transport took over low-level target control. The results might differ compared to plain JTAG/SWD
Info : Listening on port 6666 for tcl connections
Info : Listening on port 4444 for telnet connections
Info : clock speed 2000 kHz
Info : STLINK V2J33M25 (API v2) VID:PID 0483:374B
Info : Target voltage: 3.224656
Info : [stm32f4x.cpu] Cortex-M4 r0p1 processor detected
Info : [stm32f4x.cpu] target has 6 breakpoints, 4 watchpoints
Info : starting gdb server for stm32f4x.cpu on 3333
Info : Listening on port 3333 for gdb connections
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The openocd attached the 4444 port to telnet and 3333 port to gdb. So that I will bind the 3333 port in the gdb session.&lt;/p&gt;
&lt;p&gt;Secondly, open the second terminal and type:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-shell&quot;&gt;$ gdb-multiarch firmware.elf
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;At the moment, you are in the gdb session. In here, bind to the 3333 port:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-console&quot;&gt;(gdb) target remote localhost:3333
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;For now, you are in the control and responsible for the all flashing and debugging operations.&lt;/p&gt;
&lt;p&gt;To flash the firmware, use these commands:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-console&quot;&gt;(gdb) monitor reset halt
(gdb) load
(gdb) monitor reset halt
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;There are tons of commands you can type in the gdb session. We can split these commands in two categories. &lt;em&gt;monitor &amp;lt;command-name&amp;gt;&lt;/em&gt; commands directly are run by the openocd command. Other commands are run by the gdb itself.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;load&lt;/em&gt; is the main command to flash the firmware. Before and after that command, resetting and halting the CPU execution is good practice. Output will be like:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-plaintext&quot;&gt;Loading section .isr_vector, size 0x1c4 lma 0x8000000
Loading section .text, size 0x126c lma 0x8000200
Loading section .rodata, size 0x4c lma 0x800146c
Loading section .ARM, size 0x8 lma 0x80014b8
Loading section .init_array, size 0x4 lma 0x80014c0
Loading section .fini_array, size 0x4 lma 0x80014c4
Loading section .data, size 0xc lma 0x80014c8
Start address 0x08001400, load size 5272
Transfer rate: 9 KB/sec, 753 bytes/write.
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;That means that the firmware successfully was flashed .&lt;/p&gt;
&lt;p&gt;If you just wanna flash the firmware and not debugging, this following command is enough:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-shell&quot;&gt;$ openocd -f interface/stlink.cfg -f target/stm32f4x.cfg -c &quot;program firmware.elf verify reset exit&quot;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Instead of dealing with two terminal sessions, above command is just the one-step operation.&lt;/p&gt;
&lt;p&gt;The main reason opening the second gdb session is to make the debugging. If you did the debugging previously, you will be familiar with these commands:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-console&quot;&gt;(gdb) break main
(gdb) continue
(gdb) next
(gdb) finish
(gdb) print var
(gdb) x/16wx *ptr
(gdb) set var
(gdb) list
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The debugging operations are huge and will not fit into a single tutorial as you guest. So that I don't wanna dive into the these and other operations. But I wanna give you a good reference: &lt;em&gt;The Art of Debugging with GDB, DDD, and Eclipse&lt;/em&gt; written by Norman Matloff and Peter Jay Salzman.&lt;/p&gt;
&lt;p&gt;Until here, I gave a overall explanation the end-to-end pipeline. I'll explain the other stuffs in further. &lt;/p&gt;
</description>
<category>Tutorials</category>
<guid isPermaLink="true">https://coderlegion.com/14087/flashing-and-debugging-a-firmware-in-detail</guid>
<pubDate>Mon, 06 Apr 2026 14:53:30 +0000</pubDate>
</item>
<item>
<title>ERROR (expected nested-name-specifier before ‘namespace’)-Fixed</title>
<link>https://coderlegion.com/13667/error-expected-nested-name-specifier-before-namespace-fixed</link>
<description>&lt;p&gt;The &lt;strong&gt;'ERROR (expected nested-name-specifier before ‘namespace’)`&lt;/strong&gt; error you may get while compiling your &lt;strong&gt;C++&lt;/strong&gt; code with a C++ compiler, this kind of issue might frustrate one, here we will discuss in the depth about the &lt;strong&gt;issue&lt;/strong&gt;. &lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://kodlogs.net/?qa=blob&amp;amp;qa_blobid=1477928991728469158&quot; alt=&quot;&quot; width=&quot;539&quot; height=&quot;359&quot;&gt;&lt;/p&gt;
&lt;h5 class=&quot;pk-title pk-toc-title pk-font-block&quot;&gt;Photo by &lt;a href=&quot;https://www.pexels.com/photo/people-standing-on-top-of-mountain-2114206/&quot; rel=&quot;nofollow&quot;&gt;Rachel Vine&lt;/a&gt;&lt;/h5&gt;
&lt;h5 class=&quot;pk-title pk-toc-title pk-font-block&quot;&gt;TABLE OF CONTENTS&lt;/h5&gt;
&lt;ol&gt;
&lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;#what-is-attributeerror-module-object-has-no-attribute-strptime&quot;&gt;What is &quot;ERROR (expected nested-name-specifier before ‘namespace’)&quot;?&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;#Why-does-blocked-a-frame-with-origin-null-from-accessing-a-cross-origin-frame-happens&quot;&gt;Why &quot;&lt;/a&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;#what-is-attributeerror-module-object-has-no-attribute-strptime&quot;&gt;ERROR (expected nested-name-specifier before ‘namespace’)&lt;/a&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;#Why-does-blocked-a-frame-with-origin-null-from-accessing-a-cross-origin-frame-happens&quot;&gt;&quot; happens?&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;#how-to-resolve&quot;&gt;How to resolve &quot;&lt;/a&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;#what-is-attributeerror-module-object-has-no-attribute-strptime&quot;&gt;ERROR (expected nested-name-specifier before ‘namespace’)&lt;/a&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;#how-to-resolve&quot;&gt;&lt;strong&gt;&quot;&lt;/strong&gt;:&lt;/a&gt;
&lt;ol&gt;
&lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;#solution-use-local-web-server&quot;&gt;Solution:&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;#conclusion&quot;&gt;Conclusion&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;h2 id=&quot;what-is-attributeerror-module-object-has-no-attribute-strptime&quot;&gt;&lt;strong&gt;What is  “ERROR (expected nested-name-specifier before ‘namespace’)&lt;/strong&gt;&lt;strong&gt;”?&lt;/strong&gt;&lt;/h2&gt;
&lt;p&gt;Before discussing the error, we should know, what is a &lt;strong&gt;&lt;code&gt;nested name specifier&lt;/code&gt;&lt;/strong&gt;?&lt;/p&gt;
&lt;p&gt;C++ nested name specifiers are the &lt;strong&gt;prefixes &lt;/strong&gt;to qualified names. For example,&lt;code&gt; “foo::” in “foo::x”&lt;/code&gt; is a nested name specifier. Nested name specifiers are made up of a sequence of specifiers, each of which can be namespace, type, identifier (for dependent names), &lt;strong&gt;decltype specifier&lt;/strong&gt;, or the &lt;strong&gt;global specifier (‘::’)&lt;/strong&gt;. The last two specifiers can only appear at the start of a nested-namespace-specifier.&lt;/p&gt;
&lt;p&gt;&lt;code&gt;#include &lt;/code&gt;&lt;br&gt;&lt;code&gt;#include &lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;code&gt;template&lt;/code&gt;&lt;br&gt;&lt;code&gt;class ListPtr;&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;code&gt;template&lt;/code&gt;&lt;br&gt;&lt;code&gt;class ListPtrIterator {&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;code&gt;public:&lt;/code&gt;&lt;br&gt;&lt;code&gt;ListPtrIterator( ListPtr* _user ):&lt;/code&gt;&lt;br&gt;&lt;code&gt;M_user( _user ),&lt;/code&gt;&lt;br&gt;&lt;code&gt;M_cur( M_user-&amp;gt;begin() ) {}&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;code&gt;bool&lt;/code&gt;&lt;br&gt;&lt;code&gt;cur( T*&amp;amp; );&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;code&gt;bool&lt;/code&gt;&lt;br&gt;&lt;code&gt;reset( void ) {&lt;/code&gt;&lt;br&gt;&lt;code&gt;M_cur =M_user-&amp;gt;begin();&lt;/code&gt;&lt;br&gt;&lt;code&gt;return M_cur!=M_user-&amp;gt;end();&lt;/code&gt;&lt;br&gt;&lt;code&gt;}&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;code&gt;private:&lt;/code&gt;&lt;br&gt;&lt;code&gt;ListPtr* M_user;&lt;/code&gt;&lt;br&gt;&lt;code&gt;typename list::iterator M_cur;&lt;/code&gt;&lt;br&gt;&lt;code&gt;^^^^&lt;/code&gt;&lt;br&gt;&lt;code&gt;ERROR: expected nested-name-specifier before 'list'&lt;/code&gt;&lt;br&gt;&lt;code&gt;};&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Output&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;new.cpp:28:46: warning: multi-character character constant [-Wmultichar]

 ERROR: expected nested-name-specifier before 'list'&lt;/code&gt;&lt;/pre&gt;
&lt;h2 id=&quot;Why-does-blocked-a-frame-with-origin-null-from-accessing-a-cross-origin-frame-happens&quot;&gt;&lt;strong&gt;Why does “ERROR (expected nested-name-specifier before ‘namespace’)&lt;/strong&gt;&lt;strong&gt;“ happens?&lt;/strong&gt;&lt;/h2&gt;
&lt;p&gt;As the compiler suggests that there is an with the list. &lt;strong&gt;Here the compiler does not accept the list as it is&lt;/strong&gt;. Compiler accepts it as std::list.&lt;/p&gt;
&lt;p&gt;As we know if we do not use the using namespace std in our program then we will face an error saying may be like that cout was not declared in this scope. But we know that in the past we did not need to define the using namespace std in the program. But now we have to use it or we have to use cout as std::cout. &lt;/p&gt;
&lt;p&gt;In the program given above the cause is pretty similar to this reason.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Following is the error message you get:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;code&gt;` main.cpp online 2:7: error: expected nested-name-specifier before ‘namespace’&lt;br&gt; using namespace std;&lt;br&gt;       ^~~~~~~~~`&lt;/code&gt;&lt;/p&gt;
&lt;p&gt; &lt;/p&gt;
&lt;h2&gt;&lt;strong&gt;How to resolve “ERROR (expected nested-name-specifier before ‘namespace’)&lt;/strong&gt;&lt;strong&gt;”?&lt;/strong&gt;&lt;/h2&gt;
&lt;h2 id=&quot;solution-1-use-local-web-server&quot; style=&quot;line-height: 1;&quot;&gt;&lt;strong&gt;Solution :&lt;/strong&gt;&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;As I mentioned earlier, in the program given above the cause is pretty similar to this reason.&lt;/strong&gt; So we have to use std::list to resolve the error since compilers do not accept containers without nested-name-specifier.&lt;/p&gt;
&lt;p&gt; &lt;/p&gt;
&lt;p style=&quot;line-height: 1;&quot;&gt;⚠️ Remember to use C++11 (otherwise you'll receive an error saying that extended initializer lists are only available with -std=c++11 or -std=gnu++11)..&lt;/p&gt;
&lt;p style=&quot;line-height: 1;&quot;&gt; &lt;/p&gt;
&lt;p&gt;ℹ   Ensure that the relevant header files are included.&lt;/p&gt;
&lt;h3 style=&quot;text-align: left;&quot;&gt;&lt;strong&gt;Conclusion:&lt;/strong&gt;&lt;/h3&gt;
&lt;p style=&quot;text-align: left;&quot;&gt; We discussed in this article about &lt;strong&gt;ERROR (expected nested-name-specifier before ‘namespace’) discussed &lt;/strong&gt;and a number of &lt;strong&gt;solutions &lt;/strong&gt;to get around it, one final way out may be be to upgrade to a more recent compiler version &lt;/p&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/13667/error-expected-nested-name-specifier-before-namespace-fixed</guid>
<pubDate>Mon, 30 Mar 2026 03:20:18 +0000</pubDate>
</item>
<item>
<title>Error does not name a type C++</title>
<link>https://coderlegion.com/13363/error-does-not-name-a-type-c</link>
<description>&lt;h1&gt; Error does not name a type in C++
&lt;/h1&gt;
&lt;p&gt;The &quot;error does not name a type&quot; in C/C++ is defined as the when user declares outside of the function or does not include it properly in the main file this error will through.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://i.postimg.cc/dtVS0znp/image.png&quot; alt=&quot;&quot; width=&quot;639&quot; height=&quot;359&quot;&gt;&lt;/p&gt;
&lt;h5 class=&quot;pk-title pk-toc-title pk-font-block&quot;&gt;TABLE OF CONTENTS&lt;/h5&gt;
&lt;ol&gt;
&lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;#what-is-attributeerror-module-object-has-no-attribute-strptime&quot;&gt;Why this error occurs?&lt;/a&gt;&lt;/li&gt;

&lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;#how-to-resolve&quot;&gt;How to resolve:&lt;/a&gt;
&lt;ol&gt;
&lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;#solution-1-use-local-web-server&quot;&gt;Solution 1:&lt;/a&gt;


&lt;/li&gt;&lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;#solution-1-use-local-web-server1&quot;&gt;Solution 2:&lt;/a&gt;

&lt;/li&gt;&lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;#solution-3-use-local-web-server1&quot;&gt;Solution 3:&lt;/a&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;/li&gt;&lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;#conclusion&quot;&gt;Conclusion&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;h2&gt;&lt;strong&gt;Why this error occurs?&lt;/strong&gt;&lt;/h2&gt;
&lt;pre&gt;&lt;code&gt;File: sample.h  
 #ifndef SAMPLE_H__&amp;lt;br /&amp;gt;#define SAMPLE_H__
   namespace Sampletest {
    class CP_M_ReferenceCounted&amp;lt;br /&amp;gt;{&amp;lt;br /&amp;gt;};
    }
    #endif
    &amp;lt;br /&amp;gt;File : test.cpp
#include &quot;sample.h&quot;
    typedef CP_M_ReferenceCounted FxRC;
   &amp;lt;br /&amp;gt;int main(int argc, char **argv)&amp;lt;br /&amp;gt;{
    &amp;lt;p&amp;gt;return 0;&amp;lt;br /&amp;gt;}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;br&gt;If you run the above code you will get the error &quot;...error: CP_M_ReferenceCounted does not name a type&quot;&lt;/p&gt;
&lt;p&gt; &lt;/p&gt;
&lt;h2 id=&quot;how-to-resolve&quot;&gt;&lt;strong&gt;How to resolve :&lt;/strong&gt;&lt;/h2&gt;
&lt;p&gt;To overcome this error follow this two methods of solutions&lt;/p&gt;
&lt;h2 style=&quot;line-height: 1;&quot;&gt;&lt;strong&gt;Solution 1:&lt;/strong&gt;&lt;/h2&gt;
&lt;p&gt;To avoid this error, we have to add the &quot;using namespace Sampletest&quot; at the start of the program in C++.&lt;/p&gt;
&lt;p&gt;To avoid this error, we have to add the &quot;using namespace Sampletest&quot; at the start of the program in C++.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;p&amp;gt;File : test.cpp&amp;lt;/p&amp;gt;
&amp;lt;p&amp;gt;&amp;lt;code&amp;gt;#include &quot;sample.h&quot;&amp;lt;/p&amp;gt;
&amp;lt;p&amp;gt;//Add the following to your code&amp;lt;/p&amp;gt;
&amp;lt;p&amp;gt;using namespace Sampletest&amp;lt;/p&amp;gt;
&amp;lt;p&amp;gt;typedef CP_M_ReferenceCounted FxRC;&amp;lt;/p&amp;gt;
&amp;lt;p&amp;gt;&amp;lt;br /&amp;gt;int main(int argc, char **argv)&amp;lt;br /&amp;gt;{&amp;lt;/p&amp;gt;
&amp;lt;p&amp;gt;return 0;&amp;lt;br /&amp;gt;}&amp;lt;/code&amp;gt;&amp;lt;/p&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;h2 id=&quot;solution-1-use-local-web-server1&quot; style=&quot;line-height: 1;&quot;&gt;&lt;strong&gt;Solution 2:&lt;/strong&gt;&lt;/h2&gt;
&lt;p&gt;To avoid this kind of error we need to add the header &quot;#include sample.h&quot; at the starting of the program in C++.&lt;/p&gt;
&lt;p&gt;Same Problem while declaring outside of the function&lt;/p&gt;
&lt;p&gt;These kinds of errors are also acquired while printing outside of any function.&lt;br&gt;A statement which isn't declaration in C++ need to be printed inside of the function&lt;/p&gt;
&lt;p&gt;&lt;br&gt;&lt;b&gt;File test.cpp&lt;/b&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;p&amp;gt;#include &amp;lt;iostream&amp;gt;&amp;lt;br /&amp;gt;#include &amp;lt;cstring&amp;gt;&amp;lt;br /&amp;gt;using namespace std;&amp;lt;/p&amp;gt;
&amp;lt;p&amp;gt;struct Node{&amp;lt;br /&amp;gt;char *name;&amp;lt;br /&amp;gt;int age;&amp;lt;br /&amp;gt;Node(char *nc = &quot;&quot;, int ax = 0){&amp;lt;br /&amp;gt;name = new char[strlen(nc) + 1];&amp;lt;br /&amp;gt;strcpy(name, n);&amp;lt;br /&amp;gt;age = ax;&amp;lt;br /&amp;gt;}&amp;lt;br /&amp;gt;};&amp;lt;/p&amp;gt;
&amp;lt;p&amp;gt;Node node1(&quot;Roger&quot;, 20), node2(node1);&amp;lt;br /&amp;gt;cout &amp;lt;&amp;lt; node1.name &amp;lt;&amp;lt; ' ' &amp;lt;&amp;lt; node1.age &amp;lt;&amp;lt; ' ' &amp;lt;&amp;lt; node2.name &amp;lt;&amp;lt; ' ' &amp;lt;&amp;lt; node2.age;&amp;lt;br /&amp;gt;strcpy(node2.name, &quot;Wendy&quot;);&amp;lt;br /&amp;gt;node2.name = 30;&amp;lt;br /&amp;gt;cout &amp;lt;&amp;lt; node1.name &amp;lt;&amp;lt; ' ' &amp;lt;&amp;lt; node1.age &amp;lt;&amp;lt; ' ' &amp;lt;&amp;lt; node2.name &amp;lt;&amp;lt; ' ' &amp;lt;&amp;lt; node2.age;&amp;lt;/p&amp;gt;
&amp;lt;p&amp;gt; &amp;lt;/p&amp;gt;
&amp;lt;p&amp;gt;&amp;lt;b&amp;gt;Output :&amp;lt;/b&amp;gt;&amp;lt;/p&amp;gt;
&amp;lt;p&amp;gt;error: ‘node2’ does not name a type&amp;lt;/p&amp;gt;
&amp;lt;br/&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;h2 id=&quot;solution-3-use-local-web-server1&quot; style=&quot;line-height: 1;&quot;&gt;&lt;strong&gt;Solution 3:&lt;/strong&gt;&lt;/h2&gt;
&lt;p&gt;To avoid these types of errors you need to add everything inside the function,&lt;br&gt;because a statement that isn't a declaration in C++ needs to be inside the function&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;p&amp;gt;&amp;lt;code&amp;gt;int main() {&amp;lt;br /&amp;gt;Node node1(&quot;Roger&quot;, 20), node2(node1);&amp;lt;br /&amp;gt;cout &amp;lt;&amp;lt; node1.name &amp;lt;&amp;lt; ' ' &amp;lt;&amp;lt; node1.age &amp;lt;&amp;lt; ' ' &amp;lt;&amp;lt; node2.name &amp;lt;&amp;lt; ' ' &amp;lt;&amp;lt; node2.age;&amp;lt;br /&amp;gt;strcpy(node2.name, &quot;Wendy&quot;);&amp;lt;br /&amp;gt;node2.name = 30;&amp;lt;br /&amp;gt;cout &amp;lt;&amp;lt; node1.name &amp;lt;&amp;lt; ' ' &amp;lt;&amp;lt; node1.age &amp;lt;&amp;lt; ' ' &amp;lt;&amp;lt; node2.name &amp;lt;&amp;lt; ' ' &amp;lt;&amp;lt; node2.age;&amp;lt;br /&amp;gt;}&amp;lt;/code&amp;gt;&amp;lt;/p&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;h3 style=&quot;text-align: left;&quot;&gt;&lt;strong&gt;Conclusion:&lt;/strong&gt;&lt;/h3&gt;
&lt;p&gt;In this article, we have seen why the undefined error occurs in C/C++ and discussed how to resolve these errors in various methods.&lt;/p&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/13363/error-does-not-name-a-type-c</guid>
<pubDate>Mon, 23 Mar 2026 09:40:17 +0000</pubDate>
</item>
<item>
<title>Porting Test Drive II from SNES to PC, Part 5: Making scanline validation repo-owned</title>
<link>https://coderlegion.com/13288/porting-test-drive-ii-from-snes-to-pc-part-5-making-scanline-validation-repo-owned</link>
<description>&lt;h2 id=&quot;porting-test-drive-ii-from-snes-to-pc-part-5-making-scanline-validation-repo-owned&quot;&gt;Porting Test Drive II from SNES to PC, Part 5: Making scanline validation repo-owned&lt;/h2&gt;
&lt;p&gt;The cleanup thread in this repo is still product work.&lt;/p&gt;
&lt;p&gt;That point is easy to miss when a change is small. The commit I closed today, &lt;code&gt;224057d&lt;/code&gt; on 2026-03-19, does not add a new renderer, a new extractor, or a new visible gameplay result. What it does is remove another place where the archaeology loop could silently lean on mutable shared emulator output.&lt;/p&gt;
&lt;p&gt;That matters more than it sounds.&lt;/p&gt;
&lt;h3 id=&quot;the-last-cleanup-checkpoint-was-only-half-the-job&quot;&gt;The last cleanup checkpoint was only half the job&lt;/h3&gt;
&lt;p&gt;The previous cleanup commit, &lt;code&gt;d06ac64&lt;/code&gt;, moved the boot-probe path onto repo-owned outputs by default.&lt;/p&gt;
&lt;p&gt;That was a good checkpoint, but it did not close the whole class of problem.&lt;/p&gt;
&lt;p&gt;There was still a committed scanline-validation path that defaulted to Mesen's shared &lt;code&gt;LuaScriptData&lt;/code&gt; area:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;validation/mesen_scanline_step_test.lua&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;tools/capture_visible_mode7_range.py&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;That meant a helper could still read from a mutable emulator-owned location unless the caller was careful.&lt;/p&gt;
&lt;p&gt;In a repo like this, that is a real risk:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;the same script can be run many times across different frame windows&lt;/li&gt;
&lt;li&gt;multiple archaeology lanes can be active in parallel&lt;/li&gt;
&lt;li&gt;old probe JSON can look plausible enough to reuse by mistake&lt;/li&gt;
&lt;li&gt;automation becomes harder to reason about when &quot;latest file wins&quot;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The whole point of the cleanup track is to make that kind of accidental ambiguity harder.&lt;/p&gt;
&lt;h3 id=&quot;what-changed-in-this-checkpoint&quot;&gt;What changed in this checkpoint&lt;/h3&gt;
&lt;p&gt;This iteration was intentionally narrow.&lt;/p&gt;
&lt;p&gt;The generic Mesen launcher, &lt;code&gt;validation/run_mesen_capture.sh&lt;/code&gt;, now prepares the parent directory for &lt;code&gt;TD2_SCANLINE_TEST_OUTPUT_PREFIX&lt;/code&gt; before launching the emulator.&lt;/p&gt;
&lt;p&gt;That means the scanline probe can be given a repo-owned destination without relying on the caller to pre-create the directory tree.&lt;/p&gt;
&lt;p&gt;Then the committed visible-range helper, &lt;code&gt;tools/capture_visible_mode7_range.py&lt;/code&gt;, was updated so that it no longer defaults to shared &lt;code&gt;LuaScriptData&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Instead, when you run something like:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-sh&quot;&gt;python3 tools/capture_visible_mode7_range.py \
  1094 1101 \
  --output tools/out/visible_mode7_1094_1101.json
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;the helper now derives a repo-owned raw probe prefix beside the aggregate output:&lt;/p&gt;
&lt;p&gt;&lt;code&gt;tools/out/visible_mode7_1094_1101_scanline_probe/td2_scanline_step_test.json&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;It also records that raw probe path in the aggregate JSON payload, so the run is easier to trace later.&lt;/p&gt;
&lt;p&gt;That is the important pattern:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;one command&lt;/li&gt;
&lt;li&gt;one explicit aggregate output&lt;/li&gt;
&lt;li&gt;one repo-owned raw probe surface attached to that run&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;No silent dependence on whatever happened to be left in &lt;code&gt;.mesen-config/Mesen2/LuaScriptData&lt;/code&gt;.&lt;/p&gt;
&lt;h3 id=&quot;why-this-matters-for-archaeology&quot;&gt;Why this matters for archaeology&lt;/h3&gt;
&lt;p&gt;This project is already juggling several different kinds of evidence:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;emulator captures&lt;/li&gt;
&lt;li&gt;bridge extracts&lt;/li&gt;
&lt;li&gt;direct ROM-derived builders&lt;/li&gt;
&lt;li&gt;runtime manifests&lt;/li&gt;
&lt;li&gt;scanline probes&lt;/li&gt;
&lt;li&gt;contract checks&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;That is healthy, but only if the repo keeps a strong boundary between:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;authoritative artifacts&lt;/li&gt;
&lt;li&gt;scratch intermediates&lt;/li&gt;
&lt;li&gt;stale leftovers from old experiments&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Shared emulator output blurs that boundary.&lt;/p&gt;
&lt;p&gt;Repo-owned per-run output sharpens it again.&lt;/p&gt;
&lt;p&gt;That pays off immediately in a few ways:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;validation commands become easier to rerun without cleanup guesswork&lt;/li&gt;
&lt;li&gt;aggregate JSON can point back to the exact raw probe surface it used&lt;/li&gt;
&lt;li&gt;it becomes clearer which artifacts belong to the repo's evidence chain&lt;/li&gt;
&lt;li&gt;future automation can assume less hidden global state&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;None of that is glamorous, but it is exactly the kind of work that keeps a reverse-engineering-heavy port from becoming fragile.&lt;/p&gt;
&lt;h3 id=&quot;what-this-checkpoint-does-not-solve&quot;&gt;What this checkpoint does not solve&lt;/h3&gt;
&lt;p&gt;It is important not to oversell this.&lt;/p&gt;
&lt;p&gt;This commit does not finish the validation-output cleanup track.&lt;/p&gt;
&lt;p&gt;In particular, it does not yet absorb the newer gameplay-oriented scanline wrapper that is currently sitting in the dirty worktree. That helper is part of active lane work and should be closed as its own checkpoint instead of being folded into a cleanup commit by accident.&lt;/p&gt;
&lt;p&gt;So the state after &lt;code&gt;224057d&lt;/code&gt; is:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;boot-probe output defaults are repo-owned&lt;/li&gt;
&lt;li&gt;the committed visible-range scanline helper now follows the same policy&lt;/li&gt;
&lt;li&gt;the broader scanline/gameplay cleanup surface is still open&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;That is the right level of scope for one iteration.&lt;/p&gt;
&lt;h3 id=&quot;where-the-project-stands-now&quot;&gt;Where the project stands now&lt;/h3&gt;
&lt;p&gt;The repo's overall posture is still the same:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Lane 1 bank30 unresolved queue closure remains the official top gate&lt;/li&gt;
&lt;li&gt;Lane 2 tilemap provenance has solid contiguous coverage through &lt;code&gt;1086..1117&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;Lane 3 gameplay archaeology is active and currently lives deep in visible-phase scanline work&lt;/li&gt;
&lt;li&gt;the cleanup/refocus track is still running in parallel so those archaeology lanes stay trustworthy&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;This checkpoint belongs to that last category.&lt;/p&gt;
&lt;p&gt;It is small, but it makes the validation surface more deterministic, and that gives the later archaeology results a better floor to stand on.&lt;/p&gt;
&lt;h3 id=&quot;next-step&quot;&gt;Next step&lt;/h3&gt;
&lt;p&gt;The next cleanup-side step is straightforward:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;push the same repo-owned/per-run policy through the remaining scanline and gameplay wrappers&lt;/li&gt;
&lt;li&gt;keep trimming lingering doc examples that still assume shared emulator output&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;After that, the project can keep pressing the more interesting blockers:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;the &lt;code&gt;958..977&lt;/code&gt; bootstrap gap&lt;/li&gt;
&lt;li&gt;the &lt;code&gt;986+&lt;/code&gt; final-screen composition gap&lt;/li&gt;
&lt;li&gt;the callback-family replacement work beyond the current intro coverage&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;That is the shape of progress here.&lt;/p&gt;
&lt;p&gt;Not every useful checkpoint produces a new frame.&lt;/p&gt;
&lt;p&gt;Some of them make sure the next frame result is actually believable.&lt;/p&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/13288/porting-test-drive-ii-from-snes-to-pc-part-5-making-scanline-validation-repo-owned</guid>
<pubDate>Sat, 21 Mar 2026 13:48:21 +0000</pubDate>
</item>
<item>
<title>Porting Test Drive II from SNES to PC, Part 3: Provenance instead of screenshots</title>
<link>https://coderlegion.com/13286/porting-test-drive-ii-from-snes-to-pc-part-3-provenance-instead-of-screenshots</link>
<description>&lt;h2 id=&quot;porting-test-drive-ii-from-snes-to-pc-part-3-provenance-instead-of-screenshots&quot;&gt;Porting Test Drive II from SNES to PC, Part 3: Provenance instead of screenshots&lt;/h2&gt;
&lt;p&gt;Once the SDL runtime could play a real intro path, the next bottleneck was not rendering. It was evidence.&lt;/p&gt;
&lt;p&gt;If a frame looked close, that was no longer enough. The project needed to answer harder questions:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Which ROM chunk produced the visible tilemap?&lt;/li&gt;
&lt;li&gt;Which callback path was active when that chunk was used?&lt;/li&gt;
&lt;li&gt;Is this frame a stable source window, or just a screenshot that happens to match today?&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;That is the phase that starts on March 5 and dominates the repo through March 17.&lt;/p&gt;
&lt;h3 id=&quot;the-repo-grew-a-dedicated-archaeology-workspace&quot;&gt;The repo grew a dedicated archaeology workspace&lt;/h3&gt;
&lt;p&gt;Commit &lt;code&gt;6a12991&lt;/code&gt; on 2026-03-05 added the &lt;code&gt;rom_analysis/&lt;/code&gt; workspace and a lot of the tooling that now defines the back half of the project:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;build_bank30_chunk_registry.py&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;build_mesen_design_pack.py&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;build_mesen_design_pack_range.py&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;extract_compression_header_manifest.py&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;validate_td2_chunks.py&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;summarize_l001210_trace.py&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;new roadmap and checkpoint docs under &lt;code&gt;rom_analysis/docs/&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;This was a useful structural move for two reasons.&lt;/p&gt;
&lt;p&gt;First, it separated &quot;runtime code that has to ship frames&quot; from &quot;analysis code that has to explain frames.&quot; Those concerns overlap, but they are not the same job.&lt;/p&gt;
&lt;p&gt;Second, it made the archaeology lane explicit. The repo stopped treating bank 10, bank 11, and bank 30 as vague future work. It started giving them artifacts, checkpoints, and pass or fail surfaces.&lt;/p&gt;
&lt;h3 id=&quot;l001210-became-the-main-provenance-hook&quot;&gt;&lt;code&gt;L001210&lt;/code&gt; became the main provenance hook&lt;/h3&gt;
&lt;p&gt;The core trace target in this phase is &lt;code&gt;L001210&lt;/code&gt;, the dispatcher at &lt;code&gt;00:9210&lt;/code&gt; that is tied to chunk usage. The project added probe-side tracing and summary tooling so it could move from static bank scanning to runtime-backed provenance.&lt;/p&gt;
&lt;p&gt;That flow looks like this:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-sh&quot;&gt;make -C tools l001210-probe L001210_PROBE_TOTAL_FRAMES=3600 MESEN_TIMEOUT_SECONDS=90
make -C tools l001210-trace-summary
make -C tools bank30-registry
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;By itself, a bank scan tells you where candidate compressed blocks exist. It does not tell you which ones matter in a live frame window. The &lt;code&gt;L001210&lt;/code&gt; trace changed that.&lt;/p&gt;
&lt;p&gt;The bank-30 registry could now classify candidates by both decode status and runtime visibility. As of the current snapshot, the unresolved queue is still concrete:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;1E:E91F&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;1E:EE7F&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;1E:DA96&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;1E:9681&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;That is better than a hand-wavy &quot;some bank 30 work remains.&quot; It is a small list of named unresolved producers with evidence attached.&lt;/p&gt;
&lt;h3 id=&quot;design-packs-made-the-frame-data-usable-outside-the-emulator&quot;&gt;Design packs made the frame data usable outside the emulator&lt;/h3&gt;
&lt;p&gt;The project also stopped treating raw Mesen dumps as the final output format.&lt;/p&gt;
&lt;p&gt;&lt;code&gt;mesen_ppu_extract&lt;/code&gt; and the design-pack builders turned frame windows into bundles that can be inspected like assets instead of debugger state:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;per-layer visible renders&lt;/li&gt;
&lt;li&gt;decoded tilemaps&lt;/li&gt;
&lt;li&gt;tile sheets&lt;/li&gt;
&lt;li&gt;sprite analysis&lt;/li&gt;
&lt;li&gt;raw VRAM/CGRAM/OAM&lt;/li&gt;
&lt;li&gt;stable manifests for a frame or a frame range&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;That gave the repo a middle layer between emulator internals and runtime playback. The port could still consume raw scene files, but the engineer could now inspect the same frame as:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;raw SNES memory&lt;/li&gt;
&lt;li&gt;decoded tilemap entries&lt;/li&gt;
&lt;li&gt;sprite metadata&lt;/li&gt;
&lt;li&gt;a runtime sequence window&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;That is why later provenance work stays readable. The project has actual frame packages, not just screenshots and prose.&lt;/p&gt;
&lt;h3 id=&quot;provenance-windows-got-promoted-one-range-at-a-time&quot;&gt;Provenance windows got promoted one range at a time&lt;/h3&gt;
&lt;p&gt;The best example is the tilemap-to-ROM provenance chain around the late attract path.&lt;/p&gt;
&lt;p&gt;Commit &lt;code&gt;bd239a0&lt;/code&gt; on 2026-03-13 promoted provenance windows through &lt;code&gt;1101&lt;/code&gt;. The next commit, &lt;code&gt;7614c8f&lt;/code&gt;, pushed that contiguous reading through &lt;code&gt;1117&lt;/code&gt;. Those windows are not just captured frames. They carry a source argument.&lt;/p&gt;
&lt;p&gt;The current reading in the roadmap is very specific:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;bg1&lt;/code&gt; is the visible main-screen layer across the promoted window&lt;/li&gt;
&lt;li&gt;&lt;code&gt;chrBaseWords = 0x2000&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;runtime provenance steps through three chunk anchors:&lt;ul&gt;
&lt;li&gt;&lt;code&gt;1094..1095 -&amp;gt; 0D:C4DC&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;1096..1100 -&amp;gt; 07:BF49&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;1101..1117 -&amp;gt; 07:C112&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;That is the kind of statement that changes implementation strategy. Once a port effort knows which visible block comes from which chunk family, asset conversion and runtime replacement can be targeted. Without that, every new frame range looks like a one-off.&lt;/p&gt;
&lt;p&gt;The repo is careful here in a way I like: it does not overclaim continuity. It explicitly treats &lt;code&gt;1117&lt;/code&gt; as the current confidence edge and avoids pretending that later frames are solved by carry-over alone.&lt;/p&gt;
&lt;h3 id=&quot;the-same-tooling-started-reaching-gameplay&quot;&gt;The same tooling started reaching gameplay&lt;/h3&gt;
&lt;p&gt;This archaeology phase is not limited to front-end cleanup.&lt;/p&gt;
&lt;p&gt;Commit &lt;code&gt;36767ce&lt;/code&gt; captured the first deterministic track-1 seed window for frames &lt;code&gt;86..93&lt;/code&gt;. Commit &lt;code&gt;207d8f6&lt;/code&gt; followed with a bounded sweep. The current roadmap now says:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;.mesen-config/Mesen2/SaveStates/game_11.mss&lt;/code&gt; is a usable deterministic seed&lt;/li&gt;
&lt;li&gt;&lt;code&gt;b_hold&lt;/code&gt; is the first nontrivial dynamic lane&lt;/li&gt;
&lt;li&gt;the queue cursor equalization path is directly observed through frames &lt;code&gt;90..92&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;That is exactly the right style of progress for gameplay-era reverse engineering. It is not &quot;bank 10 is understood.&quot; It is &quot;this input schedule on this savestate produces this specific observable state transition window.&quot;&lt;/p&gt;
&lt;p&gt;The later timed-input extraction work in &lt;code&gt;802f804&lt;/code&gt; extends the same method to a different provenance problem. The repo recovered a later direct-hit cluster around:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;7051 -&amp;gt; 0D:C4DC&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;7059 -&amp;gt; 07:BF49&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;7064 -&amp;gt; 07:C112&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Again, the useful part is not just that those frames were found. It is that they were found under a deterministic scripted-input lane and packaged with provenance outputs.&lt;/p&gt;
&lt;h3 id=&quot;what-changed-in-practice&quot;&gt;What changed in practice&lt;/h3&gt;
&lt;p&gt;Before this phase, the repo could say:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;this frame range matches the emulator closely&lt;/li&gt;
&lt;li&gt;this runtime path seems to work&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;After this phase, the repo could say:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;this frame range belongs to callback family &lt;code&gt;01:9FE5&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;this visible tile block maps to specific chunk producers&lt;/li&gt;
&lt;li&gt;this gameplay seed window is reproducible from a known savestate and input schedule&lt;/li&gt;
&lt;li&gt;these bank-30 candidates remain unresolved even after matrix sweeps&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;That is a different level of engineering maturity.&lt;/p&gt;
&lt;p&gt;It also changes what &quot;port progress&quot; means. A project like this does not move linearly from renderer to gameplay. It moves by reducing uncertainty in the places where rendering, content, and control flow meet.&lt;/p&gt;
&lt;p&gt;By mid-March, &lt;code&gt;asmdump&lt;/code&gt; had become good at that:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;deterministic capture&lt;/li&gt;
&lt;li&gt;design-ready frame bundles&lt;/li&gt;
&lt;li&gt;trace-backed chunk provenance&lt;/li&gt;
&lt;li&gt;promoted source windows with explicit confidence edges&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;That set up the next phase cleanly. Once the repo could explain its frame windows, the next pressure point was obvious: the validation surface had to become stricter, and the repo itself had to get cleaner so generated output did not drown the actual evidence.&lt;/p&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/13286/porting-test-drive-ii-from-snes-to-pc-part-3-provenance-instead-of-screenshots</guid>
<pubDate>Sat, 21 Mar 2026 13:29:08 +0000</pubDate>
</item>
<item>
<title>Porting Test Drive II from SNES to PC, Part 2: The first native intro slice</title>
<link>https://coderlegion.com/13285/porting-test-drive-ii-from-snes-to-pc-part-2-the-first-native-intro-slice</link>
<description>&lt;h2 id=&quot;porting-test-drive-ii-from-snes-to-pc-part-2-the-first-native-intro-slice&quot;&gt;Porting Test Drive II from SNES to PC, Part 2: The first native intro slice&lt;/h2&gt;
&lt;p&gt;The first two days in &lt;code&gt;asmdump&lt;/code&gt; were about measurability. The next phase, from February 28 through March 2, was about replacing a narrow front-end slice with native code.&lt;/p&gt;
&lt;p&gt;That is the point where the project stopped proving that it could extract data and started proving that it could replay behavior.&lt;/p&gt;
&lt;h3 id=&quot;the-runtime-target-was-small-on-purpose&quot;&gt;The runtime target was small on purpose&lt;/h3&gt;
&lt;p&gt;The &lt;code&gt;port/&lt;/code&gt; runtime was never meant to be a full game engine in week one. It was a controlled execution environment for known assets and known frame windows.&lt;/p&gt;
&lt;p&gt;By this stage, &lt;code&gt;port/README.md&lt;/code&gt; already described a focused runtime:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;SDL2 window and renderer&lt;/li&gt;
&lt;li&gt;fixed 60 Hz loop&lt;/li&gt;
&lt;li&gt;256x224 framebuffer&lt;/li&gt;
&lt;li&gt;direct SNES BG rendering from extracted &lt;code&gt;VRAM + CGRAM + PPU state&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;optional OBJ composition from extracted OAM&lt;/li&gt;
&lt;li&gt;sequence playback for extracted scene windows&lt;/li&gt;
&lt;li&gt;indexed palette-animation playback for compact native clips&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;That last distinction mattered immediately. Some intro segments are better represented as sampled frame sequences. Others are better represented as a native state machine driven by extracted data.&lt;/p&gt;
&lt;p&gt;The project did not try to answer that in the abstract. It answered it on one scene.&lt;/p&gt;
&lt;h3 id=&quot;why-the-ballistic-splash-was-the-right-first-target&quot;&gt;Why the Ballistic splash was the right first target&lt;/h3&gt;
&lt;p&gt;The Ballistic intro window is anchored cleanly at frame &lt;code&gt;654&lt;/code&gt;. It is also a good engineering target:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;it is deterministic under no input&lt;/li&gt;
&lt;li&gt;it is presentation-heavy but structurally simple&lt;/li&gt;
&lt;li&gt;it is mostly a palette-driven BG scene, not a sprite-heavy gameplay state&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The repo ended up carrying three versions of the same clip:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;a measured reference clip from deterministic screenshots&lt;/li&gt;
&lt;li&gt;a ROM-derived clip generated from helper-scene CGRAM plus the &lt;code&gt;A39C&lt;/code&gt; palette ramp&lt;/li&gt;
&lt;li&gt;a compact callback asset for direct runtime playback via &lt;code&gt;ballistic_a39c&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;That progression matters. The measured clip proves what the frame window should look like. The ROM-derived clip proves that the asset path can reconstruct it from source data. The callback asset proves that the runtime can execute a compact native representation instead of replaying a bag of screenshots.&lt;/p&gt;
&lt;p&gt;By the time commit &lt;code&gt;aa67d27&lt;/code&gt; landed on 2026-02-28, the repo had already marked the milestone directly: &quot;reproduce intro animation natively.&quot;&lt;/p&gt;
&lt;h3 id=&quot;hybrid-playback-was-a-feature-not-a-compromise&quot;&gt;Hybrid playback was a feature, not a compromise&lt;/h3&gt;
&lt;p&gt;One of the best early decisions in this project was to allow hybrid manifests instead of forcing every frame range into the same representation.&lt;/p&gt;
&lt;p&gt;That produced several useful runtime artifacts:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;tools/out/ballistic_native_sequence.txt&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;tools/out/ballistic_rom_sequence.txt&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;tools/out/ballistic_callback_sequence.txt&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;tools/out/intro_loop_hybrid_sequence.txt&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;tools/out/intro_loop_hybrid_bridge_visible_sequence.txt&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The project used those manifests to keep progress moving while specific windows remained unresolved.&lt;/p&gt;
&lt;p&gt;The no-input intro loop is the clearest example:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;direct runtime &lt;code&gt;ballistic_a39c&lt;/code&gt; playback covers the Ballistic segment&lt;/li&gt;
&lt;li&gt;sampled bootstrap playback bridges the unstable &lt;code&gt;958..977&lt;/code&gt; window&lt;/li&gt;
&lt;li&gt;queue-driven &lt;code&gt;snes_bg&lt;/code&gt; replacements cover frames &lt;code&gt;978&lt;/code&gt; and &lt;code&gt;982&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;later attract states can be swapped between sampled and native bridge-visible windows as coverage improves&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;This is a better engineering shape than an all-or-nothing rewrite. Every new native window can replace a sampled window when it is good enough, without destabilizing the rest of the loop.&lt;/p&gt;
&lt;h3 id=&quot;the-bootstrap-and-bridge-work-forced-more-precise-tooling&quot;&gt;The bootstrap and bridge work forced more precise tooling&lt;/h3&gt;
&lt;p&gt;The easy story would have been &quot;render the Ballistic clip and move on.&quot; The real story is that getting beyond it forced the repo to model the transition frames precisely.&lt;/p&gt;
&lt;p&gt;The project added:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;repeatable &lt;code&gt;L00A00C&lt;/code&gt; scene building&lt;/li&gt;
&lt;li&gt;decoded WRAM queue summaries for the bootstrap window&lt;/li&gt;
&lt;li&gt;queue-driven scene builders for post-Ballistic frames&lt;/li&gt;
&lt;li&gt;OAM-aware &lt;code&gt;snes_bg&lt;/code&gt; playback&lt;/li&gt;
&lt;li&gt;bridge-visible Mode 7 scene models for the late attract path&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;That is how the repo got to statements that are actually useful:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;frame &lt;code&gt;978&lt;/code&gt; and frame &lt;code&gt;982&lt;/code&gt; can be reconstructed from the queued VRAM/OAM path&lt;/li&gt;
&lt;li&gt;frame &lt;code&gt;986&lt;/code&gt; is close on the BG side but still wrong in OBJ composition&lt;/li&gt;
&lt;li&gt;late bridge-visible frames through &lt;code&gt;1093&lt;/code&gt; can run natively in the SDL runtime, even when screenshot parity is still open for some of them&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The runtime command surface reflects that evolution:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-sh&quot;&gt;make -C port

./port/build/td2_port --sequence ./tools/out/ballistic_callback_sequence.txt
./port/build/td2_port --sequence ./tools/out/intro_loop_hybrid_sequence.txt
./port/build/td2_port --sequence ./tools/out/intro_loop_hybrid_bridge_visible_sequence.txt
./port/build/td2_port --headless --sequence ./tools/out/intro_loop_hybrid_bridge_visible_sequence.txt --sequence-no-loop --frames 1418 --dump-prefix ./port/build/intro_loop_hybrid_bridge_visible
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;At this point the port is no longer just &quot;an SDL viewer for extracted images.&quot; It is executing multiple representations of front-end state:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;pure extracted scene windows&lt;/li&gt;
&lt;li&gt;compact callback assets&lt;/li&gt;
&lt;li&gt;palette-driven indexed animations&lt;/li&gt;
&lt;li&gt;queue-derived bridge scenes&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;That is the real milestone.&lt;/p&gt;
&lt;h3 id=&quot;the-code-had-to-be-reorganized-early&quot;&gt;The code had to be reorganized early&lt;/h3&gt;
&lt;p&gt;Commit &lt;code&gt;8858823&lt;/code&gt; on 2026-03-01 is one of the most practical commits in the whole history. It split a &lt;code&gt;3083&lt;/code&gt;-line &lt;code&gt;main.c&lt;/code&gt; into:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;td2_types.h&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;td2_io.c/.h&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;td2_ppu.c/.h&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;a much smaller &lt;code&gt;main.c&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;That same commit also added:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;docs/bootstrap_9D69_analysis.md&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;docs/bank10_11_30_notes.md&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;port/test_regression.sh&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;This is not incidental cleanup. It is the point where the runtime stopped being a prototype and started becoming an environment that other port work could live inside.&lt;/p&gt;
&lt;p&gt;There are two reasons that matters:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;The PPU and scene-loading path were already complicated enough to deserve their own modules.&lt;/li&gt;
&lt;li&gt;The reverse-engineering notes and the runtime code had started to depend on each other in both directions.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Once the project reached hybrid intro playback, runtime work and archaeology work were no longer separate lanes. The runtime needed more exact hardware facts. The archaeology needed a runtime that could replay extracted states and make errors visible.&lt;/p&gt;
&lt;h3 id=&quot;first-native-launch-means-more-than-the-window-opened-&quot;&gt;First native launch means more than &quot;the window opened&quot;&lt;/h3&gt;
&lt;p&gt;Commit &lt;code&gt;87a3f67&lt;/code&gt; on 2026-03-02 is named &quot;first native launch running intro anim.&quot; The important part of that message is not &quot;launch.&quot; It is &quot;running intro anim.&quot;&lt;/p&gt;
&lt;p&gt;At that point, the project had already moved from:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;raw ROM and disassembly&lt;/li&gt;
&lt;li&gt;to deterministic captures and extraction&lt;/li&gt;
&lt;li&gt;to a PC runtime capable of replaying a real front-end path with native logic in the loop&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;That is the point where the questions get more expensive and more interesting.&lt;/p&gt;
&lt;p&gt;You are no longer asking:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Can I decode this chunk?&lt;/li&gt;
&lt;li&gt;Can I render this tilemap?&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;You are asking:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Which frames still need sampled playback?&lt;/li&gt;
&lt;li&gt;Which callbacks can be promoted to native code?&lt;/li&gt;
&lt;li&gt;Where does the remaining mismatch come from: BG state, OAM state, queue timing, Mode 7 math, or presentation order?&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;That is why the next phase in the repo turns hard toward provenance, callback tracing, and window-by-window archaeology. Once the renderer can play the intro, the bottleneck is no longer drawing. The bottleneck is explaining exactly where each visible window comes from.&lt;/p&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/13285/porting-test-drive-ii-from-snes-to-pc-part-2-the-first-native-intro-slice</guid>
<pubDate>Sat, 21 Mar 2026 13:28:35 +0000</pubDate>
</item>
<item>
<title>Porting Test Drive II from SNES to PC, Part 1: Day 0 to a measurable ROM</title>
<link>https://coderlegion.com/13284/porting-test-drive-ii-from-snes-to-pc-part-1-day-0-to-a-measurable-rom</link>
<description>&lt;h2 id=&quot;porting-test-drive-ii-from-snes-to-pc-part-1-day-0-to-a-measurable-rom&quot;&gt;Porting Test Drive II from SNES to PC, Part 1: Day 0 to a measurable ROM&lt;/h2&gt;
&lt;p&gt;Between February 26 and March 19, 2026, the &lt;code&gt;asmdump&lt;/code&gt; repo moved through 45 commits. It started as a raw reverse-engineering dump and ended this stretch with a C/SDL runtime, deterministic emulator probes, tilemap provenance tooling, and regression gates.&lt;/p&gt;
&lt;p&gt;This first part covers the first two days: what was in the repo on day 0, why the project did not start with gameplay code, and how the initial extraction and validation toolchain changed the shape of the problem.&lt;/p&gt;
&lt;h3 id=&quot;day-0-the-repo-was-a-reverse-engineering-base&quot;&gt;Day 0: the repo was a reverse-engineering base&lt;/h3&gt;
&lt;p&gt;Commit &lt;code&gt;a683c61&lt;/code&gt; on 2026-02-26 is the real starting point. It imported:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;bank0.asm&lt;/code&gt; through &lt;code&gt;bank31.asm&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;game.smc&lt;/code&gt; and &lt;code&gt;game.sym&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;ROM build files like &lt;code&gt;Makefile&lt;/code&gt;, &lt;code&gt;linkfile&lt;/code&gt;, &lt;code&gt;main.s&lt;/code&gt;, &lt;code&gt;snes.asm&lt;/code&gt;, and &lt;code&gt;spc700.asm&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;That is enough to rebuild and inspect the ROM. It is not enough to port it.&lt;/p&gt;
&lt;p&gt;There was no extraction pipeline. There was no deterministic capture harness. There was no stable asset format that a PC runtime could load. The repo knew a lot about addresses, but very little about contracts.&lt;/p&gt;
&lt;p&gt;The absence of a direct decompilation path matters here. &lt;code&gt;bank0.asm&lt;/code&gt; already exposed recognizable reset, NMI, IRQ, and callback scheduling logic, but the gameplay-facing banks were not in a state where a straight assembly-to-C pass would be a good use of time:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;bank10.asm&lt;/code&gt; and &lt;code&gt;bank11.asm&lt;/code&gt; still mixed code and data heavily&lt;/li&gt;
&lt;li&gt;&lt;code&gt;bank30.asm&lt;/code&gt; looked more like structured tables and dispatcher data than a clean list of callable functions&lt;/li&gt;
&lt;li&gt;&lt;code&gt;game.sym&lt;/code&gt; exposed labels and coverage, not behavior&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;So the early plan was not &quot;translate bank 0, then bank 1, then bank 10&quot;. The early plan was:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Make the original ROM measurable.&lt;/li&gt;
&lt;li&gt;Extract typed data from it.&lt;/li&gt;
&lt;li&gt;Rebuild systems on the PC side against those measured outputs.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;That decision is still the right one. A reliable port needs a reference harness before it needs more C files.&lt;/p&gt;
&lt;h3 id=&quot;the-first-burst-of-tooling&quot;&gt;The first burst of tooling&lt;/h3&gt;
&lt;p&gt;February 27 has nine commits. That entire day is the actual day-1 port effort.&lt;/p&gt;
&lt;p&gt;The important commits are:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;c867efd&lt;/code&gt; - SNES asset extraction toolchain scaffolding&lt;/li&gt;
&lt;li&gt;&lt;code&gt;fcc30b5&lt;/code&gt; - scene, sprite, and road visualization tooling&lt;/li&gt;
&lt;li&gt;&lt;code&gt;f8785b9&lt;/code&gt; - fully integrated Qt asset viewer UI&lt;/li&gt;
&lt;li&gt;&lt;code&gt;2bc9dc2&lt;/code&gt; - initial scripts, sprite translation, capture data, and the first runtime skeleton&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The repo stopped treating the ROM as a monolith and started turning it into inspectable outputs:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;palette dumps as JSON&lt;/li&gt;
&lt;li&gt;VRAM reconstruction and boot-screen manifests&lt;/li&gt;
&lt;li&gt;decompressed chunk outputs&lt;/li&gt;
&lt;li&gt;tile sheets rendered to neutral image formats&lt;/li&gt;
&lt;li&gt;Mesen-based screenshot and state capture&lt;/li&gt;
&lt;li&gt;scene visualizers that could be driven outside the emulator&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Representative commands from that stage still describe the approach well:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-sh&quot;&gt;./validation/run_mesen_capture.sh

python3 tools/extract_bank3_palettes.py game.smc tools/out/bank3_palettes.json
python3 tools/extract_boot_screen_manifest.py game.smc tools/out/bank1_boot_screen.json
python3 tools/build_boot_vram.py game.smc tools/out/bank1_boot_screen.json tools/out/bank1_boot_vram_variant0.bin --json-out tools/out/bank1_boot_vram_variant0.json
python3 tools/decompress_td2_chunk.py game.smc tools/out/bank7_42fb_8000.bin --bank 7 --addr 0x8000 --json-out tools/out/bank7_42fb_8000.json
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;None of that is glamorous. All of it is necessary.&lt;/p&gt;
&lt;p&gt;The early &lt;code&gt;validation/&lt;/code&gt; scripts mattered because they made the emulator part of the build surface instead of a manual debugging tool. &lt;code&gt;mesen_capture.lua&lt;/code&gt; gave the project deterministic frame dumps and input logs. &lt;code&gt;mesen_probe_boot.lua&lt;/code&gt; started recording boot and title-state selectors frame by frame. Once those existed, &quot;what does the ROM do here?&quot; stopped being a memory question and became a file question.&lt;/p&gt;
&lt;h3 id=&quot;typed-outputs-changed-the-project&quot;&gt;Typed outputs changed the project&lt;/h3&gt;
&lt;p&gt;The most important change in those first two days was not the number of tools. It was the move toward typed outputs.&lt;/p&gt;
&lt;p&gt;There is a real difference between:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&quot;I have a PNG of the title screen&quot;&lt;/li&gt;
&lt;li&gt;and &quot;I have VRAM, CGRAM, OAM, PPU state, decompressed source chunks, and the command sequence that built this screen&quot;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The first is useful for discussion. The second is useful for engineering.&lt;/p&gt;
&lt;p&gt;By the end of the initial toolchain burst, the repo already had examples of that second category:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;tools/out/bank3_palettes.json&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;tools/out/bank1_boot_screen.json&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;tools/out/bank1_boot_vram_variant0.json&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;tools/out/bank7_42fb_8000.json&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;deterministic Mesen capture logs under &lt;code&gt;.mesen-config/Mesen2/LuaScriptData/&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;That gave the project a clean boundary between &quot;ROM-side fact&quot; and &quot;PC-side implementation&quot;. It also made later runtime work much less fragile. The SDL renderer could target stable files instead of scraping live emulator output or hard-coding one-off frame knowledge.&lt;/p&gt;
&lt;h3 id=&quot;why-the-visualizers-mattered&quot;&gt;Why the visualizers mattered&lt;/h3&gt;
&lt;p&gt;&lt;code&gt;fcc30b5&lt;/code&gt; and &lt;code&gt;f8785b9&lt;/code&gt; are easy to dismiss as UI work, but they are part of the core engineering story.&lt;/p&gt;
&lt;p&gt;The early scene, sprite, road, and Qt viewer tools turned opaque ROM state into something an engineer could inspect without rebuilding the entire mental model every session. That is not polish. That is throughput.&lt;/p&gt;
&lt;p&gt;On a project like this, the fast path is rarely &quot;write more code&quot;. The fast path is usually:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;expose the data&lt;/li&gt;
&lt;li&gt;make it inspectable&lt;/li&gt;
&lt;li&gt;reduce the number of manual emulator steps between a hypothesis and a rendered result&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;That principle shows up all over the repo after day 1. The later design packs, provenance windows, regression gates, and scanline samplers are all extensions of the same idea.&lt;/p&gt;
&lt;h3 id=&quot;what-the-repo-looked-like-after-the-first-real-day&quot;&gt;What the repo looked like after the first real day&lt;/h3&gt;
&lt;p&gt;By the end of &lt;code&gt;2bc9dc2&lt;/code&gt;, the repo had crossed a line:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;it still was not a gameplay port&lt;/li&gt;
&lt;li&gt;it still was not a decompilation&lt;/li&gt;
&lt;li&gt;but it was no longer just a disassembly dump&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;It had become a measurable workbench:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;deterministic captures&lt;/li&gt;
&lt;li&gt;extraction scripts&lt;/li&gt;
&lt;li&gt;decompression tooling&lt;/li&gt;
&lt;li&gt;typed manifests&lt;/li&gt;
&lt;li&gt;visual inspection tools&lt;/li&gt;
&lt;li&gt;the first C/SDL runtime skeleton under &lt;code&gt;port/&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;That last item is where the next part starts. Once the reference side was strong enough, the obvious next step was not more extraction. It was to take one narrow front-end slice and get it running natively.&lt;/p&gt;
&lt;p&gt;That slice ended up being the Ballistic intro path, and it forced the project to answer a harder question than &quot;can I decode this asset?&quot;:&lt;/p&gt;
&lt;p&gt;&quot;Which parts of the intro are best represented as raw extracted state, and which parts need a native callback-driven implementation?&quot;&lt;/p&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/13284/porting-test-drive-ii-from-snes-to-pc-part-1-day-0-to-a-measurable-rom</guid>
<pubDate>Sat, 21 Mar 2026 13:28:13 +0000</pubDate>
</item>
<item>
<title>Enhanced TENEX C shell</title>
<link>https://coderlegion.com/11226/enhanced-tenex-c-shell</link>
<description>&lt;p&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://github.com/Krush206/etcsh&quot;&gt;etcsh&lt;/a&gt; is an enhanced version of the original tcsh, which is a version of the original Berkeley C shell implementing file name completion and command line editing.&lt;/p&gt;
&lt;p&gt;etcsh features the following enhancements and fixes over the original tcsh.&lt;/p&gt;
&lt;p&gt;• Function declarations;&lt;/p&gt;
&lt;p&gt;• read to variables from pipes and redirections;&lt;/p&gt;
&lt;p&gt;• comments on interactive sessions;&lt;/p&gt;
&lt;p&gt;• tell whether &lt;code&gt;stdin&lt;/code&gt; is empty or not;&lt;/p&gt;
&lt;p&gt;• variable expansion on expressions corrected;&lt;/p&gt;
&lt;p&gt;• piped built-ins are forked;&lt;/p&gt;
&lt;p&gt;• missing &lt;code&gt;test&lt;/code&gt; built-in implemented;&lt;/p&gt;
&lt;p&gt;• read-write variable flag;&lt;/p&gt;
&lt;p&gt;• &lt;code&gt;exit&lt;/code&gt; shall cancel lists.&lt;/p&gt;
&lt;p&gt;More is to come. Feedbacks and contributions are much appreciated.&lt;/p&gt;
</description>
<category>Launches</category>
<guid isPermaLink="true">https://coderlegion.com/11226/enhanced-tenex-c-shell</guid>
<pubDate>Sun, 08 Feb 2026 04:27:16 +0000</pubDate>
</item>
<item>
<title>Integrating TON blockchain into Trust Wallet: a case study</title>
<link>https://coderlegion.com/9966/integrating-ton-blockchain-into-trust-wallet-a-case-study</link>
<description>&lt;p&gt;I had &lt;strong&gt;TON&lt;/strong&gt; cryptocurrency. I had &lt;strong&gt;Trust Wallet&lt;/strong&gt;. But I couldn't use them together — TON simply wasn't supported.&lt;/p&gt;
&lt;p&gt;I could have waited. Instead, I decided to build it myself.&lt;/p&gt;
&lt;p&gt;A month later, TON was live in a wallet with 130 million users.&lt;/p&gt;
&lt;hr&gt;
&lt;h3 id=&quot;the-grant-that-almost-fell-through&quot;&gt;The Grant That Almost Fell Through&lt;/h3&gt;
&lt;p&gt;I noticed that TON Foundation was offering &lt;strong&gt;development grants&lt;/strong&gt;. I applied. Almost immediately, they reached out — we hopped on a call and talked it through.&lt;/p&gt;
&lt;p&gt;At the same time, I messaged a friend who worked at Trust Wallet. Together, we set up a &lt;strong&gt;group chat&lt;/strong&gt;: Wallet Core developers, the TON team, my engineer friend, and me.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Then things got complicated.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Trust Wallet&lt;/em&gt; has &lt;strong&gt;two parts&lt;/strong&gt;. &lt;em&gt;Wallet Core&lt;/em&gt; is open-source and handles transaction signing. After discussing it in our chat, I realized we could contribute there. But there's a second part — app interaction (fetching balances, broadcasting transactions). That's &lt;strong&gt;closed-source&lt;/strong&gt;. Only Trust Wallet's internal team can build it.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;And that means:&lt;/strong&gt; management approval, allocated engineering time, accountability. &lt;em&gt;Trust Wallet&lt;/em&gt; can't just say &quot;sure, we'll ship it next month.&quot;&lt;/p&gt;
&lt;p&gt;&lt;em&gt;TON Foundation&lt;/em&gt; had doubts: &lt;/p&gt;
&lt;blockquote&gt;&lt;p&gt;What if Trust Wallet never adds it to the app? Why fund the grant?&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Eventually, both teams &lt;strong&gt;met in the middle&lt;/strong&gt;. TON approved the grant; &lt;em&gt;Trust Wallet&lt;/em&gt; committed to prioritizing the integration. Win-win: a new blockchain and users for Trust Wallet, a new wallet and users for TON.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;We started coding&lt;/strong&gt;. My friend did most of the development — I reviewed and refined. We merged the PR in about a month.&lt;/p&gt;
&lt;hr&gt;
&lt;p&gt;&lt;img src=&quot;https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p6uc8zjloe2rbfhwsv3o.jpg&quot; alt=&quot;Integrating TON to Trust Wallet&quot;&gt;&lt;/p&gt;
&lt;h3 id=&quot;how-trust-wallet-works-under-the-hood&quot;&gt;How Trust Wallet Works Under the Hood&lt;/h3&gt;
&lt;p&gt;Trust Wallet runs on three platforms: Android, iOS, and a browser extension.&lt;/p&gt;
&lt;p&gt;At its core is &lt;strong&gt;Wallet Core&lt;/strong&gt; — an open-source library supporting &lt;strong&gt;over 130 blockchains&lt;/strong&gt;. Written in C++ and Rust. It's not just used by Trust Wallet; other major wallets like Crypto.com rely on it too. The library handles:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Private key generation&lt;/li&gt;
&lt;li&gt;Address creation and validation&lt;/li&gt;
&lt;li&gt;Transaction signing&lt;/li&gt;
&lt;li&gt;Smart contract interactions&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;This is where we added TON.&lt;/p&gt;
&lt;hr&gt;
&lt;h3 id=&quot;an-unexpected-bonus-code-from-everscale&quot;&gt;An Unexpected Bonus: Code from Everscale&lt;/h3&gt;
&lt;p&gt;Few people know the full story.&lt;/p&gt;
&lt;p&gt;Originally, Durov launched TON, with &lt;em&gt;TON Labs&lt;/em&gt; handling part of the development. After US sanctions, Durov stepped away — but &lt;strong&gt;&lt;em&gt;TON Labs&lt;/em&gt;&lt;/strong&gt; didn't. They continued building a fork called &lt;em&gt;Free TON&lt;/em&gt;, which later became Everscale.&lt;/p&gt;
&lt;p&gt;Then a new &lt;strong&gt;&lt;em&gt;TON Foundation&lt;/em&gt;&lt;/strong&gt; emerged, endorsed by Durov. It's now integrated into Telegram and has taken off, becoming a leading TON blockchain.&lt;/p&gt;
&lt;p&gt;Here's the thing: &lt;em&gt;TON Labs&lt;/em&gt; did a lot of impressive technical work. Everscale was already in Wallet Core. We extracted the shared code into a module called &lt;strong&gt;CommonTON&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;That code now powers both &lt;em&gt;Everscale&lt;/em&gt; and &lt;em&gt;TON&lt;/em&gt;.&lt;/p&gt;
&lt;hr&gt;
&lt;h3 id=&quot;what-makes-ton-unique&quot;&gt;What Makes TON Unique&lt;/h3&gt;
&lt;h4 id=&quot;your-wallet-is-a-smart-contract&quot;&gt;Your Wallet Is a Smart Contract&lt;/h4&gt;
&lt;p&gt;In TON, a wallet isn't just an address — it's a full-fledged smart contract. Everscale uses the older V3 wallet; for TON, we implemented V4R2.&lt;/p&gt;
&lt;h4 id=&quot;transaction-structure&quot;&gt;Transaction Structure&lt;/h4&gt;
&lt;p&gt;In order to create a transaction from wallet, you have to send a message to the wallet smart contract: &lt;/p&gt;
&lt;pre&gt;&lt;code&gt;External Message (from user to their contract)
├── header: sender's contract address
├── stateInit: code and data (first transaction only)
└── body:
    ├── signature: Ed25519 signature
    └── signing_message:
        ├── wallet_id, expire_at, seqno
        └── Internal Message (to recipient)
            ├── header: &quot;send Y nanotons to address Z&quot;
            └── body: transfer comment
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;I won't go too deep here. You can read more about the V4 wallet &lt;a rel=&quot;nofollow&quot; href=&quot;https://docs.ton.org/standard/wallets/v4&quot;&gt;in the docs&lt;/a&gt; — including the source code.&lt;/p&gt;
&lt;h4 id=&quot;cells-and-boc-a-unique-data-model&quot;&gt;Cells and BOC — A Unique Data Model&lt;/h4&gt;
&lt;p&gt;All data in TON is represented as a tree of cells (Bag of Cells). Each cell holds up to 1023 bits of data and up to 4 references to other cells.&lt;/p&gt;
&lt;p&gt;Here's how we create a cell with V4R2 wallet data:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-cpp&quot;&gt;Cell::Ref WalletV4R2::createDataCell() const {
    CellBuilder builder;

    builder.appendU32(0);                       // sequence_number
    builder.appendU32(walletId);                // wallet_id
    builder.appendRaw(publicKey.bytes, 256);   // public key
    builder.appendBitZero();                   // &quot;no plugins&quot; flag

    return builder.intoCell();  // Total: 321 bits
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;To build a transaction, you assemble these cells correctly: recipient address, amount, comment — all packed into a BOC. Luckily, the BOC serializer was already implemented.&lt;/p&gt;
&lt;h4 id=&quot;address-formats&quot;&gt;Address Formats&lt;/h4&gt;
&lt;p&gt;Everscale only has raw addresses:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;0:4f6bbb5de550f01a5b73792ceca77d8c933ab396a1e300eb0ab5a5f49a430986
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;TON also supports a user-friendly format:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;EQBPa7td5VDwGltzeSzsp32MkzqzlqHjAOsKtaX0mkMJhq_B
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This is a base64 string that includes address type information and a checksum. The checksum helps catch typos in seed phrases.&lt;/p&gt;
&lt;hr&gt;
&lt;h3 id=&quot;why-tonkeeper-and-trust-wallet-are-incompatible&quot;&gt;Why Tonkeeper and Trust Wallet Are Incompatible&lt;/h3&gt;
&lt;h4 id=&quot;the-mnemonic-problem&quot;&gt;The Mnemonic Problem&lt;/h4&gt;
&lt;p&gt;Standards rule the blockchain world. Much of what originated in Bitcoin is still used today. BIP39 (Bitcoin Improvement Proposal) describes how to derive a private key from a seed phrase. The formula: &lt;code&gt;seed = hash(mnemonic + salt)&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;By standard, salt = &lt;code&gt;&quot;mnemonic&quot; + password&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;In TON, salt = &lt;code&gt;&quot;TON default seed&quot;&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;The result: &lt;strong&gt;the same seed phrase produces different keys&lt;/strong&gt; in Tonkeeper vs. Trust Wallet. You cannot transfer a wallet between them.&lt;/p&gt;
&lt;p&gt;This isn't unique to TON — the same issue exists with Waves, Qtum, and Polkadot (sr25519).&lt;/p&gt;
&lt;h4 id=&quot;checksum-validation&quot;&gt;Checksum Validation&lt;/h4&gt;
&lt;p&gt;TON addresses include a checksum. If a user mistypes a word in their seed phrase and the checksum doesn't match, the wallet warns them immediately. This is another reason Tonkeeper and Trust Wallet wallets aren't interchangeable.&lt;/p&gt;
&lt;h4 id=&quot;beyond-wallet-core&quot;&gt;Beyond Wallet Core&lt;/h4&gt;
&lt;p&gt;In addition to the Wallet Core implementation, I provided Trust Wallet's team with &lt;strong&gt;code examples&lt;/strong&gt;: how to fetch transaction data, query wallet state, and more. I also &lt;strong&gt;consulted&lt;/strong&gt; on app integration questions related to TON. Also added blockchain info and the logo to the &lt;a rel=&quot;nofollow&quot; href=&quot;https://github.com/trustwallet/assets&quot;&gt;assets repository&lt;/a&gt;.&lt;/p&gt;
&lt;hr&gt;
&lt;h3 id=&quot;the-result&quot;&gt;The Result&lt;/h3&gt;
&lt;p&gt;I connected with the TON and Trust Wallet teams. My friend and I built the integration. The code now runs in Trust Wallet across all platforms.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;January 2023&lt;/strong&gt; — the PR was merged into Wallet Core.&lt;/p&gt;
&lt;p&gt;Numbers:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;130 million Trust Wallet users gained access to TON&lt;/li&gt;
&lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://github.com/ton-society/grants-and-bounties/issues/81&quot;&gt;Grant&lt;/a&gt; for blockchain integration: $4,250&lt;/li&gt;
&lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://github.com/ton-society/grants-and-bounties/issues/255&quot;&gt;Grant&lt;/a&gt; for adding Jettons: $4,000&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Code:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://github.com/trustwallet/wallet-core/pull/2813&quot;&gt;TON in Wallet Core&lt;/a&gt; — main integration&lt;/li&gt;
&lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://github.com/trustwallet/wallet-core/pull/3331&quot;&gt;Jettons (TON tokens)&lt;/a&gt; — added later&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;A few months later, I added Jettons, then moved on to other projects for TON and NEAR. But that's a story for another time.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Occasionally I share notes on development and more on &lt;a rel=&quot;nofollow&quot; href=&quot;https://x.com/polyprogrammist&quot;&gt;Twitter&lt;/a&gt;&lt;/strong&gt;&lt;/p&gt;
&lt;hr&gt;
&lt;p&gt;&lt;strong&gt;I would also like to say thank you to:&lt;/strong&gt;&lt;br&gt;
&lt;a rel=&quot;nofollow&quot; href=&quot;https://x.com/hewigovens&quot;&gt;Tao Xu&lt;/a&gt;, &lt;a rel=&quot;nofollow&quot; href=&quot;https://x.com/mileriesime&quot;&gt;Sztergbaum Roman&lt;/a&gt;, &lt;a rel=&quot;nofollow&quot; href=&quot;https://github.com/optout21&quot;&gt;optout&lt;/a&gt;, &lt;a rel=&quot;nofollow&quot; href=&quot;https://www.linkedin.com/in/sergey-boyko-0791/&quot;&gt;Sergei&lt;/a&gt;, &lt;a rel=&quot;nofollow&quot; href=&quot;https://github.com/vcoolish&quot;&gt;Viacheslav&lt;/a&gt; from Trust Wallet team - for organisation and code review&lt;/p&gt;
&lt;p&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://x.com/playittodeath&quot;&gt;Kirill&lt;/a&gt; from TON Foundation - for helping me manage all of that, &lt;a rel=&quot;nofollow&quot; href=&quot;linkedin.com/in/narek-abovyan-25347418b?originalSubdomain=ae&quot;&gt;Narek&lt;/a&gt; - for tech support from TON, &lt;a rel=&quot;nofollow&quot; href=&quot;https://x.com/steveyun_ton&quot;&gt;Steve Yun&lt;/a&gt; - for grant and support&lt;/p&gt;
&lt;p&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://www.linkedin.com/in/vbushev/&quot;&gt;Viacheslav&lt;/a&gt; - for implementing the main integration&lt;/p&gt;
&lt;p&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://www.linkedin.com/in/milosvova/&quot;&gt;Vladimir&lt;/a&gt; from Trust Wallet - for making it possible and for code review&lt;/p&gt;
&lt;p&gt;And to everyone, who contributed to this project&lt;/p&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/9966/integrating-ton-blockchain-into-trust-wallet-a-case-study</guid>
<pubDate>Mon, 19 Jan 2026 03:18:04 +0000</pubDate>
</item>
<item>
<title>How to round off double value to 2 decimal places in C++</title>
<link>https://coderlegion.com/9697/how-to-round-off-double-value-to-2-decimal-places-in-c</link>
<description>&lt;p&gt;Preciseness is crucial in programming, particularly when working with &lt;strong&gt;numerical quantities&lt;/strong&gt;. It's common to need to&lt;strong&gt; round a double to a certain number of decimal places&lt;/strong&gt; in a variety of fields, from &lt;strong&gt;scientific calculation to banking&lt;/strong&gt;. We will look into C++ and examine several techniques to round a double to two decimal places in this article. Whether you're an experienced programmer or a novice to the field, knowing this basic function is essential to &lt;strong&gt;producing precise and well-rounded programs&lt;/strong&gt;. Come along as we explore different approaches and practices to help you understand details of C++ rounding.&lt;/p&gt;
&lt;div&gt;
&lt;h4&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;Table of Contents: &lt;a class=&quot;open&quot;&gt;&lt;/a&gt;&lt;/strong&gt;&lt;/span&gt;&lt;/h4&gt;
&lt;div&gt;
&lt;ol&gt;
&lt;li&gt;&lt;a href=&quot;#what&quot; rel=&quot;nofollow&quot;&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;Rounding a Double Value to 2 Decimal Places in C++&lt;/span&gt;&lt;/a&gt;
&lt;ol&gt;
&lt;li&gt;&lt;a href=&quot;#why&quot; rel=&quot;nofollow&quot;&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;Using round()&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#why1&quot; rel=&quot;nofollow&quot;&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;Using std::setprecision()&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#when&quot; rel=&quot;nofollow&quot;&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;Some Alternative Approaches&lt;/span&gt;&lt;/a&gt;
&lt;ol&gt;
&lt;li&gt;&lt;a href=&quot;#when3&quot; rel=&quot;nofollow&quot;&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;Using printf()&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#when4&quot; rel=&quot;nofollow&quot;&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;Using floor and ceil&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#when5&quot; rel=&quot;nofollow&quot;&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;Using Boost Library&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;/li&gt;
&lt;li&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;a href=&quot;#con&quot; rel=&quot;nofollow&quot;&gt;References&lt;/a&gt;&lt;/span&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;section&gt;&lt;a id=&quot;what&quot; class=&quot;custom_anchor&quot;&gt;&lt;/a&gt;
&lt;h2&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;Rounding a Double Value to 2 Decimal Places in C++&lt;/strong&gt;&lt;/span&gt;&lt;/h2&gt;
&lt;section&gt;&lt;a id=&quot;why&quot; class=&quot;custom_anchor&quot;&gt;&lt;/a&gt;
&lt;h3&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;1. Using round()&lt;/strong&gt;&lt;/span&gt;&lt;/h3&gt;
&lt;p&gt;Programming frequently involves rounding a double to two decimal places, particularly in mathematical or financial applications. We'll look at a simple C++ technique to do this.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;STEP 1&lt;/strong&gt;: Create a double variable that holds the value you want to round.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;STEP 2&lt;/strong&gt;: Multiply the double by 100 to shift the decimal two places to the right.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;STEP 3&lt;/strong&gt;: Round the result using the &lt;code&gt;'round()'&lt;/code&gt; function from the&lt;code&gt;''&lt;/code&gt; library.&lt;/li&gt;
&lt;/ol&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;#include &lt;br&gt;
#include &lt;br&gt;
int main() {&lt;br&gt;
    // Example value to be rounded&lt;br&gt;
    double value = 12.345;&lt;br&gt;
    // Step 1: Multiply by 100&lt;br&gt;
    double multipliedValue = value * 100;&lt;br&gt;
    // Step 2: Round the result&lt;br&gt;
    double roundedValue = round(multipliedValue);&lt;br&gt;
    // Step 3: Divide by 100 to get the final rounded value&lt;br&gt;
    roundedValue /= 100;&lt;br&gt;
    // Display the result&lt;br&gt;
    std::cout &amp;lt;&amp;lt; &quot;Original Value: &quot; &amp;lt;&amp;lt; value &amp;lt;&amp;lt; std::endl;&amp;lt;br&amp;gt;
    std::cout &amp;lt;&amp;lt; &quot;Rounded Value: &quot; &amp;lt;&amp;lt; roundedValue &amp;lt;&amp;lt; std::endl;&amp;lt;br&amp;gt;
    return 0;&lt;br&gt;
}&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;ul&gt;
&lt;li&gt;The original number is first multiplied by 100 to shift the decimal two places to the right.&lt;/li&gt;
&lt;li&gt;After that, the result is rounded to the nearest integer using the &lt;code&gt;'round()'&lt;/code&gt; method.&lt;/li&gt;
&lt;li&gt;In order to return the decimal to its initial location and essentially round to two decimal places, we divide the result by 100.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Output:&lt;/p&gt;
&lt;p&gt;&lt;a title=&quot;&quot;&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=9192105920901753504&quot; alt=&quot;&quot; width=&quot;580&quot; height=&quot;200&quot;&gt;&lt;/a&gt;&lt;/p&gt;
&lt;/section&gt;
&lt;section&gt;&lt;a id=&quot;why1&quot; class=&quot;custom_anchor&quot;&gt;&lt;/a&gt;
&lt;h3&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;2. Using 'std::setprecision'&lt;/strong&gt;&lt;/span&gt;&lt;/h3&gt;
&lt;p&gt;Another way to round a double to two decimal places is to use the &lt;code&gt;''&lt;/code&gt; library's &lt;code&gt;'std::setprecision'&lt;/code&gt;function.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;STEP 1:&lt;/strong&gt; Include the necessary header files.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;STEP 2: &lt;/strong&gt;Use &lt;code&gt;'std::setprecision'&lt;/code&gt; to set the precision to two decimal places.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;STEP 3:&lt;/strong&gt; Use &lt;code&gt;'std::fixed'&lt;/code&gt; to ensure that the precision is applied to the decimal part.&lt;/li&gt;
&lt;/ol&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;#include &lt;br&gt;
#include &lt;br&gt;
int main() {&lt;br&gt;
    // Example value to be rounded&lt;br&gt;
    double value = 12.345;&lt;br&gt;
    std::cout &amp;lt;&amp;lt; &quot;Original Value: &quot; &amp;lt;&amp;lt; value &amp;lt;&amp;lt; std::endl;&amp;lt;br&amp;gt;
    // Step 1: Set precision to two decimal places&lt;br&gt;
    std::cout &amp;lt;&amp;lt; std::fixed &amp;lt;&amp;lt; std::setprecision(2);&amp;lt;br&amp;gt;
    // Step 2: Display the rounded value&lt;br&gt;
    std::cout &amp;lt;&amp;lt; &quot;Rounded Value: &quot; &amp;lt;&amp;lt; value &amp;lt;&amp;lt; std::endl;&amp;lt;br&amp;gt;
    return 0;&lt;br&gt;
}&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;ul&gt;
&lt;li&gt;By using &lt;code&gt;'std::setprecision(2)'&lt;/code&gt;, we specify that we want two digits after the decimal point.&lt;/li&gt;
&lt;li&gt;Even in cases where trailing zeros are present, &lt;code&gt;'std::fixed'&lt;/code&gt; makes sure that the accuracy is applied to the decimal portion.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Output:&lt;/p&gt;
&lt;a title=&quot;&quot;&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=18393475123241651668&quot; alt=&quot;&quot; width=&quot;580&quot; height=&quot;200&quot;&gt;&lt;/a&gt;
&lt;div class=&quot;div-faq&quot;&gt;&lt;span class=&quot;faq-header&quot;&gt;FAQ&lt;/span&gt; Q:How do these methods handle edge cases, such as extremely large or small double values?&lt;br&gt;A: The methods provided are generally robust for a wide range of double values. However, extreme values may lead to precision issues. It's advisable to test and adapt the methods based on your specific application's requirement.&lt;/div&gt;
&lt;section&gt;&lt;a id=&quot;when&quot; class=&quot;custom_anchor&quot;&gt;&lt;/a&gt;
&lt;h2&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;Some Alternative Approches&lt;/strong&gt;&lt;/span&gt;&lt;/h2&gt;
&lt;p&gt;Some alternative method used to round off the decimal values as followed:&lt;/p&gt;
&lt;section&gt;&lt;a id=&quot;when3&quot; class=&quot;custom_anchor&quot;&gt;&lt;/a&gt;
&lt;h3&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;1. Using printf()&lt;/strong&gt;&lt;/span&gt;&lt;/h3&gt;
&lt;p&gt;An alternate method is to round to two decimal places by using the &lt;code&gt;'printf' &lt;/code&gt;function and the format specifier &lt;strong&gt;&quot;%.2f&quot;&lt;/strong&gt;.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;STEP 1&lt;/strong&gt;: Include the necessary header file.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;STEP 2&lt;/strong&gt;: Use printf with the &quot;%.2f&quot; format specifier&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;STEP 3&lt;/strong&gt;: Pass the double value as an argument to printf.&lt;/li&gt;
&lt;/ul&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;#include &lt;br&gt;
int main() {&lt;br&gt;
    // Example value to be rounded&lt;br&gt;
    double value = 12.345;&lt;br&gt;
    // Step 1: Display the rounded value using printf&lt;br&gt;
    printf(&quot;Original Value: %.3f\n&quot;, value);&lt;br&gt;
    printf(&quot;Rounded Value: %.2f\n&quot;, value);&lt;br&gt;
    return 0;&lt;br&gt;
}&lt;br&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The &quot;%.2f&quot; format specifier in &lt;code&gt;'printf'&lt;/code&gt; indicates that we want two digits after the decimal point.&lt;/p&gt;
&lt;p&gt;Output:&lt;/p&gt;
&lt;a title=&quot;&quot;&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=1739889786105833586&quot; alt=&quot;&quot; width=&quot;580&quot; height=&quot;200&quot;&gt;&lt;/a&gt;
&lt;div class=&quot;div-faq&quot;&gt;&lt;span class=&quot;faq-header&quot;&gt;FAQ&lt;/span&gt; Q: Can I round to a different number of decimal places?&lt;br&gt;A: Yes, you can. Adjust the multiplier or precision value accordingly.&lt;/div&gt;
&lt;/section&gt;
&lt;section&gt;&lt;a id=&quot;when4&quot; class=&quot;custom_anchor&quot;&gt;&lt;/a&gt;
&lt;h3&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;2. Using floor and ceil&lt;/strong&gt;&lt;/span&gt;&lt;/h3&gt;
&lt;p&gt;This method utilizes the floor and ceil functions from &lt;code&gt;''&lt;/code&gt; to round the double to two decimal places.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;STEP 1&lt;/strong&gt;: Include the necessary header files.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;STEP 2&lt;/strong&gt;: Use &lt;code&gt;'floor'&lt;/code&gt; to round down and &lt;code&gt;'ceil'&lt;/code&gt; to round up.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;STEP 3&lt;/strong&gt;: Choose the rounded value based on proximity to the original.&lt;/li&gt;
&lt;/ul&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;#include &lt;br&gt;
#include &lt;br&gt;
int main() {&lt;br&gt;
    // Example value to be rounded&lt;br&gt;
    double value = 12.345;&lt;br&gt;
    // Step 1: Round down and round up&lt;br&gt;
    double roundedDown = floor(value * 100) / 100;&lt;br&gt;
    double roundedUp = ceil(value * 100) / 100;&lt;br&gt;
    // Step 2: Choose the rounded value based on proximity&lt;br&gt;
    double roundedValue = (value - roundedDown &amp;lt; roundedUp - value) ? roundedDown : roundedUp;&lt;br&gt;
    // Step 3: Display the result&lt;br&gt;
    std::cout &amp;lt;&amp;lt; &quot;Original Value: &quot; &amp;lt;&amp;lt; value &amp;lt;&amp;lt; std::endl;&amp;lt;br&amp;gt;
    std::cout &amp;lt;&amp;lt; &quot;Rounded Value: &quot; &amp;lt;&amp;lt; roundedValue &amp;lt;&amp;lt; std::endl;&amp;lt;br&amp;gt;
    return 0;&lt;br&gt;
}&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;'floor'&lt;/code&gt; and &lt;code&gt;'ceil'&lt;/code&gt; are used to round down and round up, respectively.The choice between the rounded down and rounded up values is made based on proximity to the original value.&lt;/p&gt;
&lt;p&gt;Output:&lt;/p&gt;
&lt;p&gt;&lt;a title=&quot;&quot;&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=1519064916921088579&quot; alt=&quot;&quot; width=&quot;580&quot; height=&quot;200&quot;&gt;&lt;/a&gt;&lt;/p&gt;
&lt;/section&gt;
&lt;/section&gt;
&lt;section&gt;&lt;a id=&quot;when5&quot; class=&quot;custom_anchor&quot;&gt;&lt;/a&gt;
&lt;h3&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;3. Using Boost Library&lt;/strong&gt;&lt;/span&gt;&lt;/h3&gt;
&lt;p&gt;For C++ programming, Boost offers a versatile collection of libraries. The &lt;code&gt;'numeric_cast'&lt;/code&gt; function from the Boost Numeric Conversion library will be used in this example to round a double to two decimal places.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;STEP 1&lt;/strong&gt;: Include the necessary header file.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;STEP 2&lt;/strong&gt;: Use boost::numeric_cast to round the double.&lt;/li&gt;
&lt;/ul&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;#include  &lt;br&gt;
#include &lt;br&gt;
int main() {&lt;br&gt;
    // Example value to be rounded&lt;br&gt;
    double value = 12.345;&lt;br&gt;
    // Step 1: Round the double using boost::numeric_cast&lt;br&gt;
    try {&lt;br&gt;
        double roundedValue = boost::numeric_cast(static_cast(value * 100 + 0.5)) / 100.0;&lt;br&gt;
        // Step 2: Display the result&lt;br&gt;
        std::cout &amp;lt;&amp;lt; &quot;Original Value: &quot; &amp;lt;&amp;lt; value &amp;lt;&amp;lt; std::endl;&amp;lt;br&amp;gt;
        std::cout &amp;lt;&amp;lt; &quot;Rounded Value: &quot; &amp;lt;&amp;lt; roundedValue &amp;lt;&amp;lt; std::endl;&amp;lt;br&amp;gt;
    } catch (const boost::numeric::bad_numeric_cast&amp;amp; e) {&lt;br&gt;
        std::cerr &amp;lt;&amp;lt; &quot;Error: &quot; &amp;lt;&amp;lt; e.what() &amp;lt;&amp;lt; std::endl;&amp;lt;br&amp;gt;
    }&lt;br&gt;
    return 0;&lt;br&gt;
}&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;'boost::numeric_cast'&lt;/code&gt; is used to perform the casting with rounding.&lt;br&gt;The try-catch block is used to catch any exceptions that may occur during the rounding process.&lt;br&gt;The formula static_cast(value * 100 + 0.5) / 100.0 effectively rounds the double to two decimal places using the numeric_cast mechanism.&lt;/p&gt;
&lt;p&gt;Make sure you have Boost installed properly and that your compiler can find the Boost headers. If you still encounter issues, consider checking your Boost installation or consult the Boost documentation for the correct header and library settings.&lt;/p&gt;
&lt;/section&gt;
&lt;div class=&quot;div-faq&quot;&gt;&lt;span class=&quot;faq-header&quot;&gt;FAQ&lt;/span&gt; Q: In Practical, why we are rounding a number to 2 decimal places? Where it is applied?&lt;br&gt;A: Numerous real-world applications frequently need rounding values to two decimal places, especially in areas where accuracy and clarity are critical. In the context of financial computations, consider the following real-world example:
&lt;ol&gt;
&lt;li&gt;Rounding to two decimal places provides a clear and standardized way to represent currency values. It aligns with common currency formatting conventions and makes it easier for users to understand.&lt;/li&gt;
&lt;li&gt;Floating-point arithmetic can sometimes introduce small precision errors. Rounding to two decimal places helps mitigate these issues, especially in scenarios where exact precision is not critical.&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
&lt;section&gt;&lt;a class=&quot;custom_anchor&quot;&gt;&lt;/a&gt;
&lt;h2&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;References&lt;/strong&gt;&lt;/span&gt;&lt;/h2&gt;
&lt;p&gt;Here are some reference links that can help you with rounding off double values:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;C++ Reference (cppreference.com)&lt;br&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://en.cppreference.com/w/&quot;&gt;cppreference.com&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;C++ Standard - ISO/IEC 14882:&lt;br&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://www.iso.org/standard/79358.html&quot;&gt;ISO/IEC 14882:2020 - International Standard for C++&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/section&gt;
&lt;/section&gt;
&lt;/section&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/9697/how-to-round-off-double-value-to-2-decimal-places-in-c</guid>
<pubDate>Wed, 14 Jan 2026 13:24:47 +0000</pubDate>
</item>
<item>
<title>[SOLVED] A project with an output type of class library cannot be started directly</title>
<link>https://coderlegion.com/9695/solved-a-project-with-an-output-type-of-class-library-cannot-be-started-directly</link>
<description>&lt;p&gt;Errors are frequently encountered in software development, and recognizing them is essential for debugging and developing one's coding abilities. Especially in Visual Studio or other comparable IDEs, one such problem that developers frequently run across is the error message &quot;&lt;strong&gt;A project with an output type of class library cannot be started directly&lt;/strong&gt;.&quot; This error occurs due to different reasons likewise, using &lt;strong&gt;incorrect project configuration &lt;/strong&gt;or if we &lt;strong&gt;misunderstand the class functionality&lt;/strong&gt;. You can resolve this error using &lt;strong&gt;correct project configuraing &lt;/strong&gt;and &lt;strong&gt;understand class functionality&lt;/strong&gt; before coding.&lt;/p&gt;
&lt;p&gt;In this article, we'll look into the error message &quot;&lt;strong&gt;A project with an output type of class library cannot be started directly&lt;/strong&gt;&quot;, why it occurs, provide examples, and explain how to resolve it like you need to &lt;strong&gt;change the initial project to a web application or console application with an executable output type&lt;/strong&gt;. As an alternative, you can &lt;strong&gt;create a new project (like a console programme) and include a reference to the class library project&lt;/strong&gt; in it to test the functionality of the library. The error message is as shown:&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=13039658087062102150&quot; alt=&quot;&quot; width=&quot;600&quot; height=&quot;260&quot;&gt;&lt;/p&gt;
&lt;div&gt;
&lt;h4&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;Table of Contents: &lt;a class=&quot;open&quot;&gt;&lt;/a&gt;&lt;/strong&gt;&lt;/span&gt;&lt;/h4&gt;
&lt;div&gt;
&lt;ol&gt;
&lt;li&gt;&lt;a href=&quot;#what&quot; rel=&quot;nofollow&quot;&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span data-sheets-value=&quot;{&quot; data-sheets-userformat=&quot;{&quot;&gt;What is the error?&lt;/span&gt;&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#why&quot; rel=&quot;nofollow&quot;&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;Why does this error occur?&lt;/span&gt;&lt;/a&gt;
&lt;ol&gt;
&lt;li&gt;&lt;a href=&quot;#why1&quot; rel=&quot;nofollow&quot;&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;Incorrect Project Configuration&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#why2&quot; rel=&quot;nofollow&quot;&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;Misunderstanding of Class Library Functionality&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#sol&quot; rel=&quot;nofollow&quot;&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;How can you solve the error?&lt;/span&gt;&lt;/a&gt;
&lt;ol&gt;
&lt;li&gt;&lt;a href=&quot;#sol1&quot; rel=&quot;nofollow&quot;&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;Correct Output Type Configuration&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#sol2&quot; rel=&quot;nofollow&quot;&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;Create Separate Executable Project&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#prac&quot; rel=&quot;nofollow&quot;&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;Best Methods to Avoid Mistakes in the Future&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#con&quot; rel=&quot;nofollow&quot;&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;Wrapping up&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;a href=&quot;#ref&quot; rel=&quot;nofollow&quot;&gt;References&lt;/a&gt;&lt;/span&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;section&gt;&lt;a class=&quot;custom_anchor&quot;&gt;&lt;/a&gt;
&lt;h2&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;What is the error?&lt;/strong&gt;&lt;/span&gt;&lt;/h2&gt;
&lt;p&gt;This error message indicates that an attempt was made to run a project that was set up as a class library directly, but it was missing the necessary executable code to run on its own as an application. Class libraries are &lt;strong&gt;collections of reusable code&lt;/strong&gt; that are meant to be used by different projects in the same software solution. Class libraries, in contrast to independently apps, without a central point of execution and so cannot be launched directly. Because there are &lt;strong&gt;no executable instructions in a class library project&lt;/strong&gt;, trying to run the project &lt;strong&gt;will result in this error&lt;/strong&gt;.&lt;/p&gt;
&lt;/section&gt;
&lt;section&gt;&lt;a class=&quot;custom_anchor&quot;&gt;&lt;/a&gt;
&lt;h2&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;Why does this error occur?&lt;/strong&gt;&lt;/span&gt;&lt;/h2&gt;
&lt;section&gt;&lt;a class=&quot;custom_anchor&quot;&gt;&lt;/a&gt;
&lt;h3&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;1. Incorrect Project Configuration&lt;br&gt;&lt;/strong&gt;&lt;/span&gt;&lt;/h3&gt;
&lt;p&gt;The incorrect configuration of the project causes this problem; usually, the output type is set to &quot;&lt;strong&gt;Class Library&lt;/strong&gt;&quot; rather than an executable output type like &quot;&lt;strong&gt;Console Application&lt;/strong&gt;&quot; or &quot;&lt;strong&gt;Windows Application&lt;/strong&gt;.&quot; This error occurs when you try to run class libraries directly since they are not designed to be run that way. The code is as followed:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;&lt;span class=&quot;hljs-type&quot;&gt;&lt;span class=&quot;hljs-meta&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;// MyClassLibrary.cs&lt;br&gt;
using System;&lt;br&gt;
namespace MyClassLibrary&lt;br&gt;
{&lt;br&gt;
    public class MyClass&lt;br&gt;
    {&lt;br&gt;
        public void MyMethod()&lt;br&gt;
        {&lt;br&gt;
            Console.WriteLine(&quot;Hello from MyClass!&quot;);&lt;br&gt;
        }&lt;br&gt;
    }&lt;br&gt;
}&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The error message is as followed:&lt;/p&gt;
&lt;pre&gt;&lt;/pre&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=8081957910511307198&quot; alt=&quot;&quot; width=&quot;1170&quot; height=&quot;650&quot;&gt;
&lt;div class=&quot;div-green&quot;&gt;&lt;span class=&quot;alert-header&quot;&gt;Tip:&lt;/span&gt; Double-check the start-up project settings in your solution to avoid running non-executable projects directly.&lt;/div&gt;
&lt;/section&gt;
&lt;section&gt;&lt;a id=&quot;why2&quot; class=&quot;custom_anchor&quot;&gt;&lt;/a&gt;
&lt;h3&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;2. Misunderstanding of Class Library Functionality&lt;br&gt;&lt;/span&gt;&lt;/h3&gt;
&lt;p&gt;Class libraries are collections of reusable code components meant to be used by other projects, not executed directly. This error occurs when attempting to run a class library project that lacks a main entry point for execution, such as a main() function in C++ or a &lt;code&gt;'Main()'&lt;/code&gt; method in C#. The error code is as followed:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;&lt;span class=&quot;hljs-type&quot;&gt;&lt;span class=&quot;hljs-meta&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;// MyClassLibrary.h&lt;br&gt;
#pragma once&lt;br&gt;
#include &lt;br&gt;
class MyClass {&lt;br&gt;
public:&lt;br&gt;
    void MyMethod() {&lt;br&gt;
        std::cout &amp;lt;&amp;lt; &quot;Hello from MyClass!&quot; &amp;lt;&amp;lt; std::endl;&amp;lt;br&amp;gt;
    }&lt;br&gt;
};&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The error message is as followed:&lt;/p&gt;
&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=11318152968477822388&quot; alt=&quot;&quot; width=&quot;1170&quot; height=&quot;650&quot;&gt;&lt;/section&gt;
&lt;/section&gt;
&lt;section&gt;&lt;/section&gt;
&lt;section&gt;&lt;a class=&quot;custom_anchor&quot;&gt;&lt;/a&gt;
&lt;h2&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;How can you solve the error?&lt;/strong&gt;&lt;/span&gt;&lt;/h2&gt;
&lt;p&gt;You can follow the following methods to resolve your error:&lt;/p&gt;
&lt;section&gt;&lt;a class=&quot;custom_anchor&quot;&gt;&lt;/a&gt;
&lt;h3&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;1. Correct Output Type Configuration&lt;br&gt;&lt;/span&gt;&lt;/h3&gt;
&lt;p&gt;Steps for correcting output type configuration in Visual Studio&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Open Project Properties
&lt;ul&gt;
&lt;li&gt;In Visual Studio, right-click on the project in Solution Explorer.&lt;/li&gt;
&lt;li&gt;Select &quot;&lt;strong&gt;Properties&lt;/strong&gt;&quot; from the context menu.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;Navigate to Application Settings
&lt;ul&gt;
&lt;li&gt;Go to the &quot;&lt;strong&gt;Application&lt;/strong&gt;&quot; tab in the project properties window.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;Change your Output Type 
&lt;ul&gt;
&lt;li&gt;Under &quot;&lt;strong&gt;Output Type&lt;/strong&gt;&quot;, ensure that it is set to an appropriate executable type such as &quot;&lt;strong&gt;Console Application&lt;/strong&gt;&quot; or &quot;&lt;strong&gt;Windows Application&lt;/strong&gt;&quot;.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;Apply Changes
&lt;ul&gt;
&lt;li&gt;Click &quot;&lt;strong&gt;OK&lt;/strong&gt;&quot; after &quot;&lt;strong&gt;Applying&lt;/strong&gt;&quot; required modifications.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;/section&gt;
&lt;section&gt;&lt;a class=&quot;custom_anchor&quot;&gt;&lt;/a&gt;
&lt;h3&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;2. Create Separate Executable Project&lt;br&gt;&lt;/span&gt;&lt;/h3&gt;
&lt;p&gt;Steps for creating separate executable project.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Step 1: Create MyClassLibrary (Class Library) Project&lt;/strong&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Open Visual Studio.&lt;/li&gt;
&lt;li&gt;Click on &quot;&lt;strong&gt;File&lt;/strong&gt;&quot; at the top left corner.&lt;/li&gt;
&lt;li&gt;Choose &quot;&lt;strong&gt;New&lt;/strong&gt;&quot; and then &quot;Project&quot;.&lt;/li&gt;
&lt;li&gt;Select the option &quot;&lt;strong&gt;Class Library (.NET Core)&lt;/strong&gt;&quot;. &lt;/li&gt;
&lt;li&gt;Give your project a name like &quot;&lt;strong&gt;MyClassLibrary&lt;/strong&gt;&quot; and click &quot;&lt;strong&gt;Create&lt;/strong&gt;&quot;.&lt;/li&gt;
&lt;li&gt;Now, you can write your reusable code in this project.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;strong&gt;Step 2: Create MyConsoleApp (Console Application) Project&lt;/strong&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Again, click on &quot;&lt;strong&gt;File&lt;/strong&gt;&quot; at the top left corner.&lt;/li&gt;
&lt;li&gt;Choose &quot;&lt;strong&gt;New&lt;/strong&gt;&quot; and then &quot;&lt;strong&gt;Project&lt;/strong&gt;&quot;.&lt;/li&gt;
&lt;li&gt;But this time, select &quot;&lt;strong&gt;Console App (.NET Core)&lt;/strong&gt;&quot;.&lt;/li&gt;
&lt;li&gt;Name your project, maybe &quot;MyConsoleApp&quot;, and click &quot;Create&quot;.&lt;/li&gt;
&lt;li&gt;Now, let's connect it to the class library.&lt;/li&gt;
&lt;li&gt;Right-click on &quot;&lt;strong&gt;Dependencies&lt;/strong&gt;&quot; in the Solution Explorer (on the right).&lt;/li&gt;
&lt;li&gt;Select &quot;&lt;strong&gt;Add Reference&lt;/strong&gt;&quot;.&lt;/li&gt;
&lt;li&gt;In the window that pops up, go to the &quot;Projects&quot; tab and check &quot;&lt;em&gt;MyClassLibrary&lt;/em&gt;&quot;.&lt;/li&gt;
&lt;li&gt;Click &quot;OK&quot; to connect the projects.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;strong&gt;Step 3: Use MyClassLibrary in MyConsoleApp&lt;/strong&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Open the file named &quot;&lt;strong&gt;Program.cs&lt;/strong&gt;&quot; in the MyConsoleApp project.&lt;/li&gt;
&lt;li&gt;At the top of the file, add a line like &lt;em&gt;&quot;using MyClassLibrary;&quot;&lt;/em&gt; (for C#) or &lt;em&gt;#include&lt;/em&gt; &quot;&lt;strong&gt;MyClassLibrary.h&lt;/strong&gt;&quot; (for C++).&lt;/li&gt;
&lt;li&gt;Now, you can use the classes and methods from your class library in your console application! Just write the code to call those methods inside the Main function.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;strong&gt;Step 4: Set MyConsoleApp as the Starting Point&lt;br&gt;&lt;/strong&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;In the Solution Explorer, find your MyConsoleApp project.&lt;/li&gt;
&lt;li&gt;Select &quot;&lt;em&gt;Set as Start-up Project&lt;/em&gt;&quot; with a right-click on it. &lt;/li&gt;
&lt;li&gt;This tells Visual Studio to start running your console application when you press the &quot;play&quot; button.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;strong&gt;Step 5: Run Your Console Application&lt;/strong&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Press the &quot;debug&quot; button (or press F5) to run your console application.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;strong&gt;In MyClassLibrary (Class Library) Project&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;&lt;span class=&quot;hljs-type&quot;&gt;&lt;span class=&quot;hljs-meta&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;// MyClass.cs&lt;br&gt;
using System;&lt;br&gt;
namespace MyClassLibrary&lt;br&gt;
{&lt;br&gt;
    public class MyClass&lt;br&gt;
    {&lt;br&gt;
        public void MyMethod()&lt;br&gt;
        {&lt;br&gt;
            Console.WriteLine(&quot;Hello from MyClass!&quot;);&lt;br&gt;
        }&lt;br&gt;
    }&lt;br&gt;
}&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;In MyConsoleApp (Console Application) Project&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;&lt;span class=&quot;hljs-type&quot;&gt;&lt;span class=&quot;hljs-meta&quot;&gt;&lt;span class=&quot;hljs-keyword&quot;&gt;using MyClassLibrary;&lt;br&gt;
using System;&lt;br&gt;
namespace MyConsoleApp&lt;br&gt;
{&lt;br&gt;
    class Program&lt;br&gt;
    {&lt;br&gt;
        static void Main(string[] args)&lt;br&gt;
        {&lt;br&gt;
            MyClass myClass = new MyClass();&lt;br&gt;
            myClass.MyMethod();&lt;br&gt;
        }&lt;br&gt;
    }&lt;br&gt;
}&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The output is as shown&lt;/p&gt;
&lt;/section&gt;
&lt;section&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=12622164166243280959&quot; alt=&quot;&quot; width=&quot;750&quot; height=&quot;170&quot;&gt;&lt;/section&gt;
&lt;/section&gt;
&lt;section&gt;&lt;a id=&quot;prac&quot; class=&quot;custom_anchor&quot;&gt;&lt;/a&gt;
&lt;h2&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;Best Methods to Avoid Mistakes in the Future&lt;/strong&gt;&lt;/span&gt;&lt;/h2&gt;
&lt;p&gt;You can follow the following preventive measures to avoid error in the future:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;To identify configuration mistakes early on, implement automated build and test procedures.&lt;/li&gt;
&lt;li&gt;Identify the different project types and their objectives to ensure their proper use.&lt;/li&gt;
&lt;li&gt;Regularly review and verify project properties, including output type and target framework.&lt;/li&gt;
&lt;/ol&gt;
&lt;/section&gt;
&lt;div class=&quot;div-faq&quot;&gt;&lt;span class=&quot;faq-header&quot;&gt;FAQ&lt;/span&gt; Q: What is the main cause of the error &quot;A project with an output type of class library cannot be started directly&quot;?&lt;br&gt;A: The main cause is misconfiguring a project as a class library instead of an executable application.&lt;br&gt;&lt;br&gt;Q: Can automated processes help prevent this error?&lt;br&gt;A: Yes, implementing automated build and test processes can catch configuration errors early in the development cycle.&lt;/div&gt;
&lt;section&gt;&lt;a class=&quot;custom_anchor&quot;&gt;&lt;/a&gt;
&lt;h2&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;Wrapping Up&lt;/strong&gt;&lt;/span&gt;&lt;/h2&gt;
&lt;p&gt;In conclusion, misconfigurations or errors during development are frequently the cause of the problem &quot;A project with an output type of class library cannot be started directly&quot;. It happens when you try to run a class library project that doesn't have an execution entry point. Developers should be aware of project kinds, &lt;strong&gt;choose the right starter project&lt;/strong&gt;, and &lt;strong&gt;routinely check properties &lt;/strong&gt;in order to avoid making mistakes like this one. &lt;strong&gt;Code reviews&lt;/strong&gt; and &lt;strong&gt;automated procedures&lt;/strong&gt; can help reduce the danger even more. By following best practices, one may able to reduce mistakes and keep a productive growth process. &lt;strong&gt;Continued productivity&lt;/strong&gt; and &lt;strong&gt;efficiency &lt;/strong&gt;are ensured by quick resolutions achieved through &lt;strong&gt;configuration verification&lt;/strong&gt;.&lt;/p&gt;
&lt;/section&gt;
&lt;section&gt;&lt;a class=&quot;custom_anchor&quot;&gt;&lt;/a&gt;
&lt;h2&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;References&lt;/strong&gt;&lt;/span&gt;&lt;/h2&gt;
&lt;p&gt;Here are some reference links related to above error:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;Microsoft Visual Studio Documentation&lt;br&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://learn.microsoft.com/en-us/dotnet/fundamentals/&quot;&gt;Visual Studio .NET Documentation&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/section&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/9695/solved-a-project-with-an-output-type-of-class-library-cannot-be-started-directly</guid>
<pubDate>Wed, 14 Jan 2026 12:11:33 +0000</pubDate>
</item>
<item>
<title>How to Generate Random Numbers from 1 to 6 in C++</title>
<link>https://coderlegion.com/7695/how-to-generate-random-numbers-from-1-to-6-in-c</link>
<description>&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt;To &quot;generate random numbers from 1 to 6 in C++&quot;:&lt;/p&gt;
&lt;ul&gt;
&lt;li style=&quot;text-align: justify; margin: 1;&quot;&gt;Use the C++ built-in library &lt;strong&gt;stdlib.h&lt;/strong&gt; in the header.&lt;/li&gt;
&lt;li style=&quot;text-align: justify; margin: 1;&quot;&gt;Use the &lt;strong&gt;rand() function&lt;/strong&gt; to generate random numbers.&lt;/li&gt;
&lt;li style=&quot;text-align: justify; margin: 1;&quot;&gt;Use the &lt;strong&gt;srand() function&lt;/strong&gt; to generate a different number at each execution.&lt;/li&gt;
&lt;li style=&quot;text-align: justify; margin: 1;&quot;&gt;Use the &lt;strong&gt;time.h library&lt;/strong&gt; in the header with the srand() function to get different values at each execution, as the value will change relative to the time, which is a better option compared to just using srand().&lt;/li&gt;
&lt;li style=&quot;text-align: justify; margin: 1;&quot;&gt;Use &lt;strong&gt;For-loop&lt;/strong&gt; to check that numbers are generated randomly from 1 to 6 at each iteration.&lt;/li&gt;
&lt;li style=&quot;text-align: justify; margin: 1;&quot;&gt;Check if random numbers are generated upon each execution from 1 to 6.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 style=&quot;margin: 0.5;&quot;&gt;Code to Generate Random Number &lt;/h2&gt;
&lt;h3 style=&quot;margin: 0.5;&quot;&gt; Step 1: Code Editor: Open Your Code Editor &lt;/h3&gt;
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt; To get started with code writing, you need to open your favorite code editor. I prefer to use the&lt;a rel=&quot;nofollow&quot; href=&quot;denied:“https://www.onlinegdb.com/online_c++_compiler”&quot;&gt; OnlineGDB &lt;/a&gt;compiler.&lt;/p&gt;
&lt;h3 style=&quot;margin: 0.5;&quot;&gt; Step 2: Write Code: Start Writing Code in C++&lt;/h3&gt;
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt;Let's code in the code editor step by step.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Write Necessary Headers&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt; //this library is used to handle input and output
#include &amp;lt;stdlib.h&amp;gt; //library for random number generator a mandatory library
#include &amp;lt;time.h&amp;gt; //used for generating random value relative to time 
using namespace std;
&lt;/code&gt;&lt;/pre&gt;
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt;Begin with defining all the libraries that are required throughout the function implementation. I used the &lt;strong&gt;stdlib.h&lt;/strong&gt; library to &lt;strong&gt;generate the random numbers&lt;/strong&gt;. &lt;strong&gt;time.h&lt;/strong&gt; is used for all the &lt;strong&gt;time-related functions&lt;/strong&gt;, and it is required to state the current time so that randomness is ensured. You also have to define other basic libraries including &lt;strong&gt;iostream and std&lt;/strong&gt; to deal with all the input-output related operations in C++.&lt;/p&gt;
&lt;div class=&quot;div-green&quot;&gt;
&lt;span class=&quot;alert-header&quot;&gt;Tip:&lt;/span&gt;
&lt;span class=&quot;alert-body&quot;&gt;You can also use &lt;strong&gt;cstdlib&lt;/strong&gt; and &lt;strong&gt;ctime&lt;/strong&gt; library instead of &lt;strong&gt;stdlib.h&lt;/strong&gt; &lt;strong&gt;time.h&lt;/strong&gt;, as it is more specific to C++.&lt;/span&gt;
&lt;/div&gt;
&lt;p&gt;&lt;strong&gt;Create diceRoll() Function&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;int diceRoll()
{
    srand(time(0)); //this built-in function ensures that upon each execution a random number is generated
    cout&amp;lt;&amp;lt;&quot;Roll a Dice&quot;&amp;lt;&amp;lt;endl;
    //loop for generation number from 1 to 6
    for(int i=0; i&amp;lt;6; i++)
    {
    int numbers = (rand() % 6) + 1; // this function ensures that the reminder should be displayed and will be from within the range
    cout&amp;lt;&amp;lt;&quot; &quot;;
    cout &amp;lt;&amp;lt; numbers;
    }
    cout&amp;lt;&amp;lt;endl;
    return 0;
} 
&lt;/code&gt;&lt;/pre&gt;
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt;Now, moving towards the creation of the diceRoll() function, here, I have defined the function return type int to pass the random values to the main function. The first thing is to &lt;strong&gt;initialize the srand() function&lt;/strong&gt; that ensures that on each execution different values are generated, but for the surety, the &lt;strong&gt;better approach is to use the time(0) function&lt;/strong&gt; from time.h library that saves the current time relative to starting value i.e. seeding value and passes it as an argument to the srand(time(0)) function. It will surely give a sequence of random values upon each execution.&lt;br&gt;
Then, I create a for-loop to iterate the dice faces within the range of 1 to 6. In each iteration, whenever a random number is generated, the number will take &lt;strong&gt;modules&lt;/strong&gt; with 6 to &lt;strong&gt;not exceed the range&lt;/strong&gt; and should start with the number 1 and then store the values in the numbers variable. These sequences of numbers will be returned to the Main function.&lt;/p&gt;
&lt;div class=&quot;div-blue&quot;&gt; 
&lt;span class=&quot;alert-header&quot;&gt;Note:&lt;/span&gt; 
&lt;span class=&quot;alert-body&quot;&gt;Make sure to use modules (%) as it will help to generate the number within your defined range.&lt;/span&gt;&lt;/div&gt;
&lt;p&gt;&lt;strong&gt;Create the Main Function&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;int main(){
    cout &amp;lt;&amp;lt;&quot;The Random numbers Generated from 1 to 6&quot;&amp;lt;&amp;lt;endl;
    cout&amp;lt;&amp;lt;diceRoll(); // call the diceroll function
    return 0;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt;In the end, the &lt;strong&gt;Main function&lt;/strong&gt; is defined to print the sequence of random numbers by calling the diceRoll() function.&lt;/p&gt;
&lt;h3 style=&quot;margin: 0.5;&quot;&gt; Step 3: Code Compilation: Compile the code of Step 2 &lt;/h3&gt;
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt;After writing the code, you must compile the code so that the results will display. If you are with me, just click the &lt;strong&gt;run&lt;/strong&gt; button in the OnlineGDB compiler to start the compilation.&lt;/p&gt;
&lt;h3 style=&quot;margin: 0.5;&quot;&gt; Step 4: Random Number Generated: Output &lt;/h3&gt;
&lt;p&gt;&lt;img src=&quot;https://live.staticflickr.com/65535/53545756797_b612bb7e94_h.jpg&quot; alt=&quot;image&quot;&gt;&lt;/p&gt;
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt;Congratulations! You have created a simple diceroll game by using the built-in function. Is not this easy? Yes, that is why the use of built-in libraries makes the problem easy for developers.&lt;/p&gt;
&lt;h2 style=&quot;margin: 0.5;&quot;&gt;Alternative Approach: Using Random Library&lt;/h2&gt;
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt;Curious, &lt;strong&gt;is there any other method&lt;/strong&gt; to generate random numbers in C++? &lt;strong&gt;Yes&lt;/strong&gt;, In C++ 11, there is &lt;strong&gt;one more library&lt;/strong&gt; introduced that is also used to generate random numbers. As rand() library is the default choice of many developers who have been using C++ for decades, but there are some limitations, as it is bound to some specific range using &lt;strong&gt;rand_max&lt;/strong&gt;. Therefore, the &lt;strong&gt;random&lt;/strong&gt; library overcomes this limitation by providing a vast range of distribution with better quality of randomness.&lt;/p&gt;
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt;To &quot;generate random numbers from 1 to 6 using Random library in C++&quot;:&lt;/p&gt;
&lt;ul&gt;
&lt;li style=&quot;text-align: justify; margin: 1;&quot;&gt;Use the C++ built-in library &lt;strong&gt;random&lt;/strong&gt; in the header.&lt;/li&gt;
&lt;li style=&quot;text-align: justify; margin: 1;&quot;&gt;Use the &lt;strong&gt;random_device&lt;/strong&gt; defined in the library to get the start number i.e. seed value for generating a random number.&lt;/li&gt;
&lt;li style=&quot;text-align: justify; margin: 1;&quot;&gt;Use the &lt;strong&gt;mt19937&lt;/strong&gt; engine to generate a random number using a uniform distribution.&lt;/li&gt;
&lt;li style=&quot;text-align: justify; margin: 1;&quot;&gt;Use the &lt;strong&gt;uniform_int_distribution&lt;/strong&gt; to generate numbers uniformly  and define the range from 1 to 6. &lt;/li&gt;
&lt;li style=&quot;text-align: justify; margin: 1;&quot;&gt;Return the generated values to the Main function to display the Random number.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 style=&quot;margin: 0.5;&quot;&gt; Code Demonstration using Random Library &lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;#include &amp;lt;iostream&amp;gt; //this library is used to handle input and output
#include &amp;lt;random&amp;gt; //library is needed to generate a random number
using namespace std;
//the function in which a random number is generated for a simple dice roll game
int dicerolled()
{
   random_device rd; //this random_device is used to obtain the seed random system
   mt19937 gen(rd()); //this is the distribution which is used for generating number
   uniform_int_distribution&amp;lt;int&amp;gt; dist(1,6); //this piece of code defines the distribution range from 1 to 6 using a uniform distribution
   return dist(gen); 
} 
int main(){
    cout &amp;lt;&amp;lt;&quot;The Random numbers Generated from 1 to 6&quot;&amp;lt;&amp;lt;endl;
    cout&amp;lt;&amp;lt;&quot;This is the results after using Random Library &quot;&amp;lt;&amp;lt;endl;
    cout&amp;lt;&amp;lt;dicerolled();
    return 0;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt;In the above code of the diceRoll() function, I first create the &lt;strong&gt;random_device&lt;/strong&gt; with the name &quot;rd&quot; that is used to obtain the starting seed to initialize the random system. After that I used the &lt;strong&gt;mt19937 algorithm&lt;/strong&gt; to generate the number by using &lt;strong&gt;uniform_int_distribution&lt;/strong&gt; range from 1 to 6 this will generate the random number and return it to the main function.&lt;/p&gt;
&lt;div class=&quot;div-blue&quot;&gt; 
&lt;span class=&quot;alert-header&quot;&gt;Note:&lt;/span&gt; 
&lt;span class=&quot;alert-body&quot;&gt;random_device is the standard generator defined by the library &lt;/span&gt;
&lt;/div&gt;
&lt;div class=&quot;div-blue&quot;&gt; 
&lt;span class=&quot;alert-header&quot;&gt;Note:&lt;/span&gt; 
&lt;span class=&quot;alert-body&quot;&gt;There are many other algorithms instead of mt19937 if you want to use other engines for number generator you can go through the reference at the end of the page.&lt;/span&gt;
&lt;/div&gt;
&lt;h3 style=&quot;margin: 0.5;&quot;&gt;Output: Using Random Library&lt;/h3&gt;
&lt;p&gt;&lt;img src=&quot;https://live.staticflickr.com/65535/53546963559_598e68733e_h.jpg&quot; alt=&quot;image&quot;&gt;&lt;/p&gt;
&lt;div class=&quot;div-faq&quot; style=&quot;margin-bottom: 15px;&quot;&gt; 
&lt;span class=&quot;faq-header&quot; style=&quot;font-weight: bold; color: dark-gray;&quot;&gt;FAQs&lt;/span&gt; 
&lt;span class=&quot;faq-body&quot; style=&quot;margin-top: 3px; margin-bottom: 20px;&quot;&gt; Q: What is the difference between rand() and srand() function? &lt;br&gt;A: The rand() stands for a random number whereas the srand() stands for a seeding random number both are the function of the same library that is used to generate random values but the srand() is used for stating the initial value for the sequence and to make sure that different value is generated when the program runs.&lt;/span&gt; 
&lt;span class=&quot;faq-body&quot; style=&quot;margin-top: 3px; margin-bottom: 20px;&quot;&gt;Q: Can I use the same library in C language instead of C++? &lt;br&gt; A: Yes, there is not much difference in both the language only the slight syntax difference otherwise you can use the library in the C program as well.&lt;/span&gt; 
&lt;span class=&quot;faq-body&quot; style=&quot;margin-top: 3px;&quot;&gt; Q: Can I find the maximum and minimum range of random numbers using the rand() library?&lt;br&gt;A: Yes, you can find the maximum range by using the function RAND_MAX which provides the maximum value range that is exactly the range for int datatype but for minimum, the range always starts from 0.0.&lt;/span&gt;
&lt;/div&gt;
&lt;h2 style=&quot;margin: 0.5;&quot;&gt;Wrapping Up&lt;/h2&gt;
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt;In the end, you got to know how easily you can generate random numbers, whether to use the &lt;strong&gt;rand()&lt;/strong&gt; function or an updated library i.e. &lt;strong&gt;random&lt;/strong&gt;. However, there are some reasons for using each library. The rand() function can used if you are making a &lt;strong&gt;small-scale application&lt;/strong&gt; because of its range limitation but, if you are making a &lt;strong&gt;large-scale application&lt;/strong&gt; where the &lt;em&gt;quality cannot neglect&lt;/em&gt;, then random is the best option because the random library provides a robust and flexible way to generate the number. C++ developer needs to understand the use case of each library to create a more &lt;strong&gt;robust simulation&lt;/strong&gt; application. Thanks for reading the guide. Happy Coding!&lt;/p&gt;
&lt;hr&gt; 
&lt;h2 style=&quot;margin: 0.5;&quot;&gt; Reference&lt;/h2&gt; 
&lt;ul&gt;
&lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://cplusplus.com/reference/random/&quot; title=&quot;random&quot;&gt;Random library in C++&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://cplusplus.com/reference/cstdlib/rand/&quot; title=&quot;rand&quot;&gt;Rand library in C++&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/7695/how-to-generate-random-numbers-from-1-to-6-in-c</guid>
<pubDate>Mon, 24 Nov 2025 00:21:36 +0000</pubDate>
</item>
<item>
<title>How to solve &quot;Undefined reference to 'sqrt' Error</title>
<link>https://coderlegion.com/7690/how-to-solve-undefined-reference-to-sqrt-error</link>
<description>&lt;h2 id=&quot;introduction-&quot;&gt;Introduction :&lt;/h2&gt;
&lt;p&gt;If you are a newbie to C or C++ and are working with a math library, then you might get this error  &lt;strong&gt;Undefined reference to `sqrt' .&lt;/strong&gt; This error indicates that the compiler or linker couldn't find the definition for the sqrt function, which is used to calculate the square root of a number. To resolve this, &lt;strong&gt;you need to link your program with the math library.&lt;/strong&gt; In your terminal, if you're using the GCC compiler for example, you can do this by adding &lt;strong&gt;-lm&lt;/strong&gt; at the end of your command line. This ensures that the math library is correctly linked and the sqrt function is recognized. In this blog post, I will guide you in detail on how can you resolve this error.&lt;/p&gt;
&lt;div class=&quot;div-green&quot;&gt;
&lt;span class=&quot;alert-header&quot;&gt;Tip:&lt;/span&gt;
&lt;span class=&quot;alert-body&quot;&gt;Always ensure that you link your program to the math library by adding
-lm at the end of your command line when you compile your program.  E.g. when you compile your C program run a command like this in the
terminal.  here Main.c is the program that you want to compile and
main is the program that you will get after compilation.

    gcc -o main Main.c -lm

&lt;/span&gt;
&lt;/div&gt;
&lt;h2 id=&quot;why-did-this-error-happen-&quot;&gt;Why did this error happen?&lt;/h2&gt;
&lt;p&gt;This error generally occurs when the math library, which contains the definition of the sqrt function, is not correctly linked to your program. (&lt;em&gt;This error message indicates that when compiling or linking your code, the system couldn't find the necessary instructions for the sqrt function, which is commonly used for calculating square roots. This usually happens when the program is unable to locate the library or source code where sqrt is defined.&lt;/em&gt;) Without this link, your program doesn't know how to execute the sqrt function, hence the &quot;&lt;strong&gt;undefined reference&lt;/strong&gt;&quot; error.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;&lt;em&gt;Here is a code block that might produce this error:&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;#include &amp;lt;stdio.h&amp;gt;

int main() {
   double num = 9.0;
   double root = sqrt(num);
   printf(&quot;square root of %.2f is %.2f&quot;, num, root);
   return 0;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;&lt;em&gt;Error by Compiler:&lt;/em&gt;&lt;/strong&gt; &lt;br&gt;
&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=12321165294849246736&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;h2 id=&quot;causes-for-the-undefined-reference-to-sqrt-error&quot;&gt;Causes for the &quot;Undefined reference to `sqrt'&quot; Error&lt;/h2&gt;
&lt;h3 id=&quot;1-lack-of-proper-linkage-to-the-math-library&quot;&gt;1. Lack of Proper Linkage to the Math Library&lt;/h3&gt;
&lt;p&gt;The math library houses the 'sqrt' function definition. If your program is not properly linked to this library, it will not know how to execute the 'sqrt' function, hence the &quot;&lt;strong&gt;undefined reference&lt;/strong&gt;&quot; error. For example, the following code snippet will produce an error because it does not link to the math library:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;    #include&amp;lt;math.h&amp;gt;
    #include&amp;lt;stdio.h&amp;gt;
    
    int main() {
       double num = 9.0;
       double root = sqrt(num);
       printf(&quot;square root of %.2f is %.2f&quot;, num, root);
       return 0;
    }
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;To fix this, add &lt;code&gt;-lm&lt;/code&gt; at the end of your command line when you compile your program. This ensures that your program is linked to the math library.&lt;/p&gt;
&lt;h3 id=&quot;2-syntax-error-or-incorrect-usage-of-the-sqrt-function&quot;&gt;2. Syntax Error or Incorrect Usage of the 'sqrt' Function&lt;/h3&gt;
&lt;p&gt;Even if your program is properly linked to the math library, it can still produce an &quot;&lt;strong&gt;undefined reference&quot;&lt;/strong&gt; error if there's a syntax error or incorrect usage of the '&lt;strong&gt;sqrt&lt;/strong&gt;' function. For example, forgetting to include the &lt;strong&gt;math library&lt;/strong&gt; before using the 'sqrt' function will produce an error:&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Error code:&lt;/strong&gt; &lt;/p&gt;
&lt;pre&gt;&lt;code&gt;#include &amp;lt;stdio.h&amp;gt;

int main() {
   double num = 9.0;
   double root = sqrt(num);
   printf(&quot;square root of %.2f is %.2f&quot;, num, root);
   return 0;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;div class=&quot;div-red&quot;&gt;
&lt;span class=&quot;alert-header&quot;&gt;Caution:&lt;/span&gt;
&lt;span class=&quot;alert-body&quot;&gt;Don't miss to add &quot; math library &quot; at the header. &lt;/span&gt;
&lt;/div&gt;
&lt;p&gt;To fix this, ensure that you include the math library at the start of your program by adding &lt;strong&gt;&lt;code&gt;#include &amp;lt;math.h&amp;gt;&lt;/code&gt;&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Corrected code:&lt;/strong&gt; &lt;/p&gt;
&lt;pre&gt;&lt;code&gt;#include &amp;lt;stdio.h&amp;gt;
#include &amp;lt;math.h&amp;gt;

int main() {
   double num = 9.0;
   double root = sqrt(num);
   printf(&quot;square root of %.2f is %.2f&quot;, num, root);
   return 0;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h3 id=&quot;3-using-an-outdated-or-incompatible-compiler&quot;&gt;3. Using an Outdated or Incompatible Compiler&lt;/h3&gt;
&lt;p&gt;Using an outdated or incompatible compiler might trigger this error. Different compilers might have different methods for linking libraries or different requirements for syntax. Make sure you're using a compiler that's compatible with your code and with the libraries you're using.&lt;/p&gt;
&lt;h2 id=&quot;solution-for-undefined-reference-to-sqrt-error&quot;&gt;Solution for  &quot;Undefined reference to `sqrt'&quot; Error&lt;/h2&gt;
&lt;h3 id=&quot;1-properly-link-your-program-to-the-math-library&quot;&gt;1. Properly Link Your Program to the Math Library&lt;/h3&gt;
&lt;p&gt;The most common cause of this error is not linking the math library correctly. You need to link your program to the math library in your code. This can be done by adding &lt;code&gt;-lm&lt;/code&gt; at the end of your command when compiling your program. Here is how you can do it:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;gcc -o program program.c -lm
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In this command, program.c is the file you want to compile, and program is the name of the output file. The -lm flag ensures that the math library is linked properly.&lt;/p&gt;
&lt;h3 id=&quot;2-check-your-syntax-and-usage-of-sqrt-function&quot;&gt;2. Check Your Syntax and Usage of 'sqrt' Function&lt;/h3&gt;
&lt;p&gt;The 'sqrt' function is defined in the math library, so you need to ensure that you're including this library in your program. If you forget to do so, you'll get an &quot;undefined reference&quot; error. Here's how you can include the math library:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;#include &amp;lt;math.h&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Here's an example of a program that correctly includes the math library and uses the 'sqrt' function:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;#include &amp;lt;stdio.h&amp;gt;
#include &amp;lt;math.h&amp;gt;

int main() {
   double num = 16.0;
   double root = sqrt(num);
   printf(&quot;square root of %.2f is %.2f&quot;, num, root);
   return 0;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h3 id=&quot;3-use-a-compatible-compiler&quot;&gt;3. Use a Compatible Compiler&lt;/h3&gt;
&lt;p&gt;Different compilers might have different ways of linking libraries and different requirements for syntax. If you're still encountering the &quot;undefined reference&quot; error, you might want to try using a different compiler. For example, if you're currently using &lt;strong&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://gcc.gnu.org/onlinedocs/&quot;&gt;gcc&lt;/a&gt;&lt;/strong&gt;, you might want to try using &lt;strong&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://clang.llvm.org/docs/UsersManual.html&quot;&gt;clang&lt;/a&gt;&lt;/strong&gt; instead. Here's how you can do that:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;clang -o program program.c -lm
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In this command, &lt;code&gt;**program.c**&lt;/code&gt; is the file you want to compile, and &lt;code&gt;**program**&lt;/code&gt; is the name of the output file. The &lt;code&gt;-lm&lt;/code&gt; flag ensures that the math library is linked properly.&lt;/p&gt;
&lt;p&gt;Remember, the key is to ensure that your program is correctly linked to the math library, and to check your usage of the 'sqrt' function. If you keep these points in mind, you should be able to avoid the &quot;undefined reference to `sqrt'&quot; error.&lt;/p&gt;
&lt;h2 id=&quot;frequently-asked-questions&quot;&gt;&lt;em&gt;Frequently Asked Questions&lt;/em&gt;&lt;/h2&gt;
&lt;div class=&quot;div-faq&quot;&gt;
&lt;span class=&quot;faq-header&quot;&gt;1. What does the &quot;Undefined reference to `sqrt'&quot; error mean?&lt;/span&gt;
&lt;span class=&quot;faq-body&quot;&gt;Ans.  This error means that the compiler or linker couldn't find the definition for the sqrt function, which is used to calculate the square root of a number.&lt;/span&gt;
&lt;/div&gt;
&lt;div class=&quot;div-faq&quot;&gt;
&lt;span class=&quot;faq-header&quot;&gt;2. Why does the &quot;Undefined reference to `sqrt'&quot; error occur?&lt;/span&gt;
&lt;span class=&quot;faq-body&quot;&gt;
Ans.  This error generally occurs when the math library, which contains the definition of the sqrt function, is not correctly linked to your program. Without this link, your program doesn't know how to execute the sqrt function, hence the &quot;undefined reference&quot; error.&lt;/span&gt;
&lt;/div&gt;
&lt;div class=&quot;div-faq&quot;&gt;
&lt;span class=&quot;faq-header&quot;&gt;3. How do I fix the &quot;Undefined reference to `sqrt'&quot; error?
&lt;/span&gt;
&lt;span class=&quot;faq-body&quot;&gt;Ans.  You just need to link your program to the math library in your code. You can do this by adding lm at the end of your command line when you compile your program.&lt;/span&gt;
&lt;/div&gt;
&lt;div class=&quot;div-faq&quot;&gt;
&lt;span class=&quot;faq-header&quot;&gt;4. Why do I still get the &quot;Undefined reference to `sqrt'&quot; error even after linking to the math library?
&lt;/span&gt;
&lt;span class=&quot;faq-body&quot;&gt;Ans.  Even if your program is properly linked to the math library, it can still produce an &quot;undefined reference&quot; error if there's a syntax error or incorrect usage of the 'sqrt' function. Make sure to include the math library at the start of your program and check your usage of the 'sqrt' function.&lt;/span&gt;
&lt;/div&gt;
&lt;div class=&quot;div-faq&quot;&gt;
&lt;span class=&quot;faq-header&quot;&gt;5. Can using an outdated or incompatible compiler cause the &quot;Undefined reference to `sqrt'&quot; error?
&lt;/span&gt;
&lt;span class=&quot;faq-body&quot;&gt;Ans.  Yes, using an outdated or incompatible compiler might trigger this error. Different compilers might have different methods for linking libraries or different requirements for syntax. Make sure you're using a compiler that's compatible with your code and with the libraries you're using&lt;/span&gt;
&lt;/div&gt;
&lt;h2 id=&quot;conclusion-&quot;&gt;Conclusion :&lt;/h2&gt;
&lt;p&gt;In conclusion, the &quot;&lt;strong&gt;Undefined reference to 'sqrt&lt;/strong&gt;'&quot; error is a common issue faced by beginners in C or C++ programming. Understanding the causes and knowing how to resolve this error is crucial. Properly linking your program to the math library, checking your syntax and usage of the 'sqrt' function, and using a compatible compiler are the key steps to solving this error. Always remember to include the math library at the start of your program and check your usage of the 'sqrt' function. By following these steps, you should be able to compile and run your programs successfully without encountering this error. Happy coding!&lt;/p&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/7690/how-to-solve-undefined-reference-to-sqrt-error</guid>
<pubDate>Mon, 24 Nov 2025 00:11:55 +0000</pubDate>
</item>
<item>
<title>How to Write a program to find the sum of the following series 1^1+2^2+3^3... in Python,Java and C</title>
<link>https://coderlegion.com/7688/how-to-write-a-program-to-find-the-sum-of-the-following-series-1-1-2-2-3-3-in-python-java-and-c</link>
<description>&lt;h2 id=&quot;introduction--1&quot;&gt;Introduction :&lt;/h2&gt;
&lt;p&gt;In this tutorial, we will learn how to write a program to calculate the sum of the series &lt;strong&gt;1^1+2^2+3^3...&lt;/strong&gt; in three popular programming languages: &lt;strong&gt;Python, Java, and C&lt;/strong&gt;. This series is a mathematical sequence where each term is the number raised to the power of itself. The intriguing pattern of numbers is not only fascinating but also presents a good programming challenge. The quick solution to this problem involves &lt;strong&gt;writing a loop that iterates over a specified range of terms, raising each term to its own power, and then adding the result to a running total.&lt;/strong&gt;&lt;/p&gt;
&lt;div class=&quot;div-green&quot;&gt;
&lt;span class=&quot;alert-header&quot;&gt;Tip:&lt;/span&gt;
&lt;span class=&quot;alert-body&quot;&gt;As we dive into the specifics of each language, remember that the logic remains consistent across languages. However, the syntax and specific functions used may differ.&lt;/span&gt;
&lt;/div&gt;
&lt;h2 id=&quot;the-significance-of-series-1-1-2-2-3-3-&quot;&gt;The significance of series 1^1+2^2+3^3...?&lt;/h2&gt;
&lt;p&gt;The series 1^1+2^2+3^3... is significant in various mathematical and computational contexts. It is an example of a &lt;a rel=&quot;nofollow&quot; href=&quot;https://en.wikipedia.org/wiki/Power_series&quot;&gt;power series&lt;/a&gt;, where each term is a number raised to the power of itself. This kind of series has unique properties and patterns that make it an interesting subject for mathematical analysis. It can be seen in different mathematical conundrums and has relevance in the fields of number theory and calculus, among others.&lt;/p&gt;
&lt;p&gt;From a computational perspective, implementing a program to calculate the sum of this series is a useful exercise in programming and algorithm design. Not only does it provide a practical application for loops and conditional statements, but it also allows for an exploration of efficiency and optimization. As the series grows, the computation can become quite complex, and writing a program to handle this efficiently is a valuable skill for any programmer.&lt;/p&gt;
&lt;h2 id=&quot;approach-to-solving-the-series&quot;&gt;Approach to Solving the Series&lt;/h2&gt;
&lt;p&gt;To find the sum of this series, we will follow a specific approach using loops and exponents.&lt;/p&gt;
&lt;h3 id=&quot;basic-logic-&quot;&gt;Basic Logic:&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;Initialize a variable to keep track of the sum.&lt;/li&gt;
&lt;li&gt;Create a loop that will iterate over the range of terms we want to calculate. This range should start from 1 because the first term of our series is 1^1.&lt;/li&gt;
&lt;li&gt;For each iteration, calculate the current term by raising the current number to its own power. In Python, this can be done using the &lt;strong&gt; operator; in Java, we use &lt;/strong&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html&quot;&gt;Math.pow()&lt;/a&gt;&lt;strong&gt;, and in C, we can use the &lt;/strong&gt;pow()&lt;strong&gt; function from the &lt;/strong&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://www.ibm.com/docs/ro/zos/2.1.0?topic=files-mathh&quot;&gt;math.h library&lt;/a&gt;**.&lt;/li&gt;
&lt;li&gt;Add the calculated term to our sum.&lt;/li&gt;
&lt;li&gt;Repeat steps 3 and 4 for each term in the series.&lt;/li&gt;
&lt;li&gt;After the loop ends, the variable will hold the sum of the series.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id=&quot;example-&quot;&gt;Example:&lt;/h3&gt;
&lt;p&gt;Let's say we want to calculate the sum of the first three terms of the series.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Initialize the sum to 0.&lt;/li&gt;
&lt;li&gt;The loop will iterate over the range 1 to 3.&lt;/li&gt;
&lt;li&gt;For the first iteration, we calculate 1^1 (which equals 1) and add it to our sum. The sum is now 1.&lt;/li&gt;
&lt;li&gt;For the second iteration, we calculate 2^2 (which equals 4) and add it to our sum. The sum is now 5.&lt;/li&gt;
&lt;li&gt;For the third iteration, we calculate 3^3 (which equals 27) and add it to our sum. The sum is now 32.&lt;/li&gt;
&lt;li&gt;The loop ends, and our sum (32) is the sum of the first three terms of the series.&lt;/li&gt;
&lt;/ol&gt;
&lt;div class=&quot;div-red&quot;&gt;
&lt;span class=&quot;alert-header&quot;&gt;Caution:&lt;/span&gt;
&lt;span class=&quot;alert-body&quot;&gt;Make sure you correctly implement the logic for raising each term to its own power. This is a crucial step, and mistakes here could lead to incorrect results.&lt;/span&gt;
&lt;/div&gt;
&lt;h2 id=&quot;program-in-the-python-language-&quot;&gt;Program in the Python language : &lt;/h2&gt;
&lt;p&gt;Here is a Python code snippet that calculates the sum of the series 1^1+2^2+3^3... up to n terms:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;def sum_of_series(n):
    sum = 0
    for i in range(1, n+1):
        sum += i**i
    return sum

print(sum_of_series(5))  # Output: 3413
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Output :&lt;/strong&gt; &lt;br&gt;
&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=12214821274097320090&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;p&gt;In this code, we first define a function called &lt;code&gt;sum_of_series&lt;/code&gt; which will do the job of adding up the numbers in our series. The &lt;code&gt;n&lt;/code&gt; in the brackets is a placeholder for the number of terms we want to add up in the series.&lt;/p&gt;
&lt;p&gt;Inside the function, we create a variable &lt;code&gt;sum&lt;/code&gt; and set its initial value to 0. This variable will hold the running total of the sum as we add each term of the series.&lt;/p&gt;
&lt;p&gt;We then start a loop with &lt;code&gt;for i in range(1, n+1):&lt;/code&gt;. This loop will repeat a set of actions for each number in the series, starting from 1 and going up to &lt;code&gt;n&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;In the loop, we have &lt;code&gt;sum += i**i&lt;/code&gt;. This line takes each number &lt;code&gt;i&lt;/code&gt; in our series, raises &lt;code&gt;i&lt;/code&gt; to the power of &lt;code&gt;i&lt;/code&gt; (which is what &lt;code&gt;i**i&lt;/code&gt; means), and adds the result to our running total &lt;code&gt;sum&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;After the loop has added up all the terms in the series, &lt;code&gt;return sum&lt;/code&gt; gives us back the final total sum.&lt;/p&gt;
&lt;p&gt;Finally, &lt;code&gt;print(sum_of_series(5))&lt;/code&gt; uses our &lt;code&gt;sum_of_series&lt;/code&gt; function to calculate the sum of the first 5 terms of the series. The result, which is 3413, is then printed out.&lt;/p&gt;
&lt;div class=&quot;div-green&quot;&gt;
&lt;span class=&quot;alert-header&quot;&gt;Tip:&lt;/span&gt;
&lt;span class=&quot;alert-body&quot;&gt;Remember that the sum starts at zero, and each term in the series is added to this running total. This is a common pattern in many programming problems.&lt;/span&gt;
&lt;/div&gt;
&lt;h2 id=&quot;program-in-the-java-language-&quot;&gt;Program in the Java language :&lt;/h2&gt;
&lt;p&gt;Here is a Java code snippet that calculates the sum of the series 1^1+2^2+3^3... up to n terms:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class Main {
    public static void main(String[] args) {
        System.out.println(sumOfSeries(4));  // Output: 288
    }

    public static int sumOfSeries(int n) {
        int sum = 0;
        for (int i = 1; i &amp;lt;= n; i++) {
            sum += Math.pow(i, i);
        }
        return sum;
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Output:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt; &lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=6848809132910968099&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;p&gt;In this code, we create a &lt;code&gt;sumOfSeries&lt;/code&gt; function that takes an integer &lt;code&gt;n&lt;/code&gt; as an argument and returns the sum of the series up to &lt;code&gt;n&lt;/code&gt; terms. Inside the function, we initialize a &lt;code&gt;sum&lt;/code&gt; variable to 0. Then, we create a &lt;strong&gt;for loop&lt;/strong&gt; that iterates from &lt;strong&gt;1&lt;/strong&gt; to &lt;strong&gt;n&lt;/strong&gt;. On each iteration, we add the ith term of the series (calculated as &lt;strong&gt;i&lt;/strong&gt; raised to the power of i using &lt;code&gt;Math.pow(i, i)&lt;/code&gt;) to sum. After the loop ends, we return the &lt;strong&gt;sum&lt;/strong&gt;. In the main method, we call &lt;code&gt;sumOfSeries(4)&lt;/code&gt; to calculate the sum of the first 4 terms of the series and print the result, which is 288.&lt;/p&gt;
&lt;h2 id=&quot;program-in-the-c-language-&quot;&gt;Program in the C language :&lt;/h2&gt;
&lt;p&gt;Here is a C code snippet that does the same:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;#include &amp;lt;stdio.h&amp;gt;
#include &amp;lt;math.h&amp;gt;

int sumOfSeries(int n) {
    int sum = 0;
    for (int i = 1; i &amp;lt;= n; i++) {
        sum += pow(i, i);
    }
    return sum;
}

int main() {
    printf(&quot;%d\\n&quot;, sumOfSeries(3));  // Output: 32
    return 0;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Output :&lt;/strong&gt; &lt;br&gt;
&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=6103199279474117884&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;p&gt;In this C code, we define a function &lt;code&gt;sumOfSeries&lt;/code&gt; just like in the Java example. The &lt;code&gt;pow&lt;/code&gt; function from the &lt;code&gt;math.h&lt;/code&gt; library is used to calculate each term of the series. The &lt;code&gt;printf&lt;/code&gt; function is used in the &lt;code&gt;main&lt;/code&gt; function to print the result of &lt;code&gt;sumOfSeries(3)&lt;/code&gt;, which calculates the sum of the first 3 terms of the series and gives the output 32.&lt;/p&gt;
&lt;div class=&quot;div-green&quot;&gt;
&lt;span class=&quot;alert-header&quot;&gt;Tip:&lt;/span&gt;
&lt;span class=&quot;alert-body&quot;&gt;When implementing the logic for the series in your chosen programming language, remember to start your loop from 1, not 0 because the first term of the series is 1^1. Also, ensure that your loop runs up to and includes n, the number of terms you want to calculate, as the last term is also part of the series.&lt;/span&gt;
&lt;/div&gt;
&lt;div class=&quot;div-blue&quot;&gt;
&lt;span class=&quot;alert-header&quot;&gt;Note:&lt;/span&gt;
&lt;span class=&quot;alert-body&quot;&gt;The program is designed to calculate the sum of the series 1^1+2^2+3^3... for positive integer values of `n`. If a negative number is given as input, the program's behavior is undefined and it may not function as expected.

Additionally, as `n` increases, each term in the series (which is raised to the power of itself) can become very large. This can lead to overflow errors, meaning the calculated value is too large to be represented by the data type being used. For handling large values of `n`, you might need to use a data type that can store very large numbers, or implement an algorithm that can handle such computations without causing overflow.&lt;/span&gt;
&lt;/div&gt;
&lt;div class=&quot;div-faq&quot;&gt;
&lt;span class=&quot;faq-header&quot;&gt;FAQ&lt;/span&gt;
&lt;span class=&quot;faq-body&quot;&gt;&lt;br&gt;1. What are some real-world applications of this series?&lt;br&gt;
Ans. While this series is primarily of mathematical interest, understanding how to compute series like this one can have practical applications in fields such as computer science, engineering, and physics. They can help in understanding algorithms, solving differential equations, or analyzing complex systems.
&lt;/span&gt;&lt;br&gt;

&lt;span class=&quot;faq-body&quot;&gt;&lt;br&gt;
2. Why does the series start at 1^1 and not 0^0?&lt;br&gt;
Ans. The series starts at 1^1 because 0^0 is an indeterminate form. That means it's not well-defined and could potentially take on any value, depending on the context. To keep things simple and avoid confusion, we start the series at 1^1.&lt;/span&gt;&lt;br&gt;

&lt;span class=&quot;faq-body&quot;&gt;&lt;br&gt;
3. What happens if I try to calculate the series for a very large number?&lt;br&gt;
Ans. If you try to calculate the series for a very large number, you might encounter overflow errors, meaning the calculated value is too large to be represented by the data type being used. This is because each term in the series is raised to the power of itself, which can lead to very large numbers even for relatively small terms. Therefore, when working with large numbers, it's important to consider using data types that can handle them.&lt;/span&gt;
&lt;/div&gt;
&lt;h2 id=&quot;conclusion--1&quot;&gt;Conclusion :&lt;/h2&gt;
&lt;p&gt;In conclusion, this tutorial has provided a comprehensive guide on how to write a program to calculate the &lt;strong&gt;sum of the series 1^1+2^2+3^3...&lt;/strong&gt; in Python, Java, and C. We've explored the significance of this series in mathematical and computational contexts and unpacked a step-by-step approach to solving it. We've also presented Python, Java, and C code snippets as practical examples. As we explored these solutions, we highlighted the importance of correctly implementing the logic for raising each term to its own power and the need to be cautious of the range of values your program can handle to prevent overflow errors. While this series is primarily of mathematical interest, the ability to compute series like this one has practical applications in various fields and helps us understand complex algorithms.&lt;/p&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/7688/how-to-write-a-program-to-find-the-sum-of-the-following-series-1-1-2-2-3-3-in-python-java-and-c</guid>
<pubDate>Mon, 24 Nov 2025 00:05:13 +0000</pubDate>
</item>
<item>
<title>Sbor - Project Manager for C</title>
<link>https://coderlegion.com/6984/sbor-project-manager-for-c</link>
<description>&lt;p&gt;Hi devs, &lt;/p&gt;
&lt;p&gt;Ever thought that writing CMake at 3am was tedious, you might have read about a project creating script in my &lt;a rel=&quot;nofollow&quot; href=&quot;https://coderlegion.com/6867/project-creation-script-for-multiple-languages&quot;&gt;previous blog&lt;/a&gt;. That script was for not just C, it was for multiple languages. &lt;/p&gt;
&lt;p&gt;&lt;code&gt;sbor&lt;/code&gt; is a project manager for C which is inspired by &lt;code&gt;cargo&lt;/code&gt;. It provides familiar commands like &lt;/p&gt;
&lt;p&gt;&lt;code&gt;sbor init&lt;/code&gt; to create a new C project which uses CMake to create the Makefile. &lt;/p&gt;
&lt;p&gt;&lt;code&gt;sbor build&lt;/code&gt;, builds th ebinary using CMake and &lt;code&gt;make&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;code&gt;sbor run&lt;/code&gt; builds and runs the binary.&lt;/p&gt;
&lt;p&gt;&lt;code&gt;sbor add &amp;lt;header&amp;gt;&lt;/code&gt; adds a system header like &lt;code&gt;string.h&lt;/code&gt; or &lt;code&gt;math.h&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;code&gt;sbor remove &amp;lt;header&lt;/code&gt; removes the header.&lt;/p&gt;
&lt;p&gt;I hope this helps create a better experience for eith Rust devs using C (Not gonna happen I know) and/or beginners to C.&lt;/p&gt;
&lt;p&gt;Here is the link&lt;/p&gt;
&lt;p&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://github.com/Vaishnav-Sabari-Girish/sbor&quot;&gt;Link&lt;/a&gt;&lt;/p&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/6984/sbor-project-manager-for-c</guid>
<pubDate>Fri, 31 Oct 2025 17:03:44 +0000</pubDate>
</item>
<item>
<title>Hello World! Welcome to the C/C++ Group!</title>
<link>https://coderlegion.com/5602/hello-world-welcome-to-the-c-c-group</link>
<description>&lt;h2 id=&quot;hello-world-welcome-to-the-c-c-group-&quot;&gt;Hello World! Welcome to the C/C++ Group!&lt;/h2&gt;
&lt;p&gt;We’re excited to have you here! This is a space where you can share, learn, and connect with other developers who love C/C++.&lt;/p&gt;
&lt;h3 id=&quot;start-by-saying-hi-&quot;&gt;Start by saying hi!&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;Introduce yourself in the comments below&lt;/strong&gt;—tell us your name, what you’re working on, or something fun about yourself. We’d love to get to know you!&lt;/p&gt;
&lt;p&gt;Once you’ve said hi, you can:&lt;/p&gt;
&lt;p&gt;Share your C/C++ tips or interesting projects.&lt;/p&gt;
&lt;p&gt;Ask questions and get feedback from the community.&lt;/p&gt;
&lt;p&gt;Comment on and support other members’ posts.&lt;/p&gt;
&lt;p&gt;We’re happy you joined the C/C++ Group and can’t wait to see your contributions. Let’s make this a friendly and helpful place to learn together!&lt;/p&gt;
</description>
<category>C++</category>
<guid isPermaLink="true">https://coderlegion.com/5602/hello-world-welcome-to-the-c-c-group</guid>
<pubDate>Fri, 26 Sep 2025 03:55:41 +0000</pubDate>
</item>
<item>
<title>PHardwareITK - Python Module (AkshuDev)</title>
<link>https://coderlegion.com/3908/phardwareitk-python-module-akshudev</link>
<description>&lt;h2 id=&quot;i-m-14-and-built-a-python-hardware-interface-toolkit-yes-it-works-&quot;&gt;I'm 14 and Built a Python Hardware Interface Toolkit (Yes, It Works)&lt;/h2&gt;
&lt;p&gt;Hi, I’m AkshuDev (Can't disclose my name)  — I’m 14 years old, and over the last 5 months, I built a full hardware interface, OS toolkit, and virtual BIOS in &lt;strong&gt;pure Python&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;No C. (Unless u like opengl, but I don't provide it in publishes)&lt;br&gt;
No &lt;code&gt;ctypes&lt;/code&gt;. (Okay a little bit)&lt;br&gt;
No dependencies (unless you want them).&lt;br&gt;
Just Python.&lt;/p&gt;
&lt;p&gt;And it’s live on GitHub and PyPI.&lt;/p&gt;
&lt;hr&gt;
&lt;h3 id=&quot;what-i-built&quot;&gt;What I Built&lt;/h3&gt;
&lt;h4 id=&quot;phardwareitk-phoenix-hardware-interface-toolkit&quot;&gt;PHardwareITK: Phoenix Hardware Interface Toolkit&lt;/h4&gt;
&lt;p&gt;This module is a &lt;strong&gt;complete system&lt;/strong&gt; for:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;File systems (PBFS: Phoenix Block File System)&lt;/li&gt;
&lt;li&gt;Virtual CPUs (PVCPU, runs &lt;code&gt;.vasm&lt;/code&gt; files)&lt;/li&gt;
&lt;li&gt;Memory simulation&lt;/li&gt;
&lt;li&gt;BIOS interrupts and booting logic&lt;/li&gt;
&lt;li&gt;️ GUI rendering using &lt;strong&gt;pure Python&lt;/strong&gt; (no SDL2 required)&lt;/li&gt;
&lt;li&gt;HGame: my own graphics engine inspired by &lt;code&gt;pygame&lt;/code&gt;, but written from scratch&lt;/li&gt;
&lt;li&gt;Permission management&lt;/li&gt;
&lt;li&gt;Tools for OS builders and experimenters&lt;/li&gt;
&lt;li&gt;C emulation in Python&lt;/li&gt;
&lt;li&gt;And way way more&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;And the best part, it has 0 required Dependencies, YEAH 0! There are 4 optional Dependencies but required are 0&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Here’s the GitHub repo:&lt;br&gt;
 &lt;a rel=&quot;nofollow&quot; href=&quot;https://github.com/AkshuDev/PHardwareITK&quot;&gt;PHardwareITK on GitHub&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;And it’s installable on PyPI:  &lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;pip install phardwareitk
&lt;/code&gt;&lt;/pre&gt;
&lt;h2 id=&quot;how-it-all-started&quot;&gt;How It All Started&lt;/h2&gt;
&lt;p&gt;My first module was PheonixAppAPI. It was a simple binary + cryptography module I built to support my app, Pheonix.&lt;/p&gt;
&lt;p&gt;Then I went to my hometown for a while and didn’t have my PC. I got bored.&lt;/p&gt;
&lt;p&gt;So I thought:&lt;br&gt;
“What if I make something that lets Python control hardware?”&lt;/p&gt;
&lt;p&gt;And that’s how PHardwareITK was born — from a simple idea to now a 12,000-download module.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&quot;how-it-works-1&quot;&gt;How It Works&lt;/h2&gt;
&lt;p&gt;I wrote my own:&lt;/p&gt;
&lt;p&gt;BIOS (in Python)&lt;/p&gt;
&lt;p&gt;File system (PBFS)&lt;/p&gt;
&lt;p&gt;Bootloader logic&lt;/p&gt;
&lt;p&gt;Virtual assembly (.vasm) file format (planned)&lt;/p&gt;
&lt;p&gt;Virtual CPU architecture (PVCPU) (in development)&lt;/p&gt;
&lt;p&gt;Permission tables, RAM cache, and direct drive access &lt;/p&gt;
&lt;p&gt;GUI toolkit using just Python (or optional SDL2 if devs want it)&lt;/p&gt;
&lt;p&gt;And a million more things (not really million btw)&lt;/p&gt;
&lt;p&gt;Note: PBFS was first made in python and is also called Python Based File System but the official (again by me) is called Pheonix-Block-File-System and I am currently updating that so my current PBFS in this module has outdated layout and will be updated, here check it out -&lt;/p&gt;
&lt;p&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://github.com/AkshuDev/Pheonix-Block-File-System&quot;&gt;https://github.com/AkshuDev/Pheonix-Block-File-System&lt;/a&gt;&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&quot;i-even-made-a-youtube-video&quot;&gt;I Even Made a YouTube Video&lt;/h2&gt;
&lt;p&gt;I created a 4K video showing how PhoenixAppAPI works, including deep binary mapping and encryption tools. You can watch it on this channel-&amp;gt; AkshobhyaEverything&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&quot;i-m-looking-for-contributors&quot;&gt;I'm Looking for Contributors&lt;/h2&gt;
&lt;p&gt;This is a HUGE project — I lost count of how many files it has &lt;/p&gt;
&lt;p&gt;I’m currently working on docs, and I’ve tagged some help wanted issues on GitHub. I’d love if you could:&lt;/p&gt;
&lt;p&gt;Try it out&lt;/p&gt;
&lt;p&gt;Star the repo if you like it ⭐&lt;/p&gt;
&lt;p&gt;Help with documentation or examples&lt;/p&gt;
&lt;p&gt;Share feedback&lt;/p&gt;
&lt;p&gt;It’s open source and 100% Python!&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&quot;final-thoughts&quot;&gt;Final Thoughts&lt;/h2&gt;
&lt;p&gt;If you’re:&lt;/p&gt;
&lt;p&gt;An OS dev&lt;/p&gt;
&lt;p&gt;A retro computing fan&lt;/p&gt;
&lt;p&gt;A Python developer who wants more control&lt;/p&gt;
&lt;p&gt;Or just someone curious how a 14-year-old built an entire OS environment in Python...&lt;/p&gt;
&lt;p&gt;Come check it out!&lt;/p&gt;
&lt;p&gt;Thanks for reading,&lt;br&gt;
— AkshuDev&lt;/p&gt;
</description>
<category>IoT &amp; Hardware</category>
<guid isPermaLink="true">https://coderlegion.com/3908/phardwareitk-python-module-akshudev</guid>
<pubDate>Fri, 11 Jul 2025 19:37:45 +0000</pubDate>
</item>
<item>
<title>PHardwareITK - Python Module</title>
<link>https://coderlegion.com/3889/phardwareitk-python-module</link>
<description>&lt;h2 id=&quot;i-m-14-and-built-a-python-hardware-interface-toolkit-yes-it-works--1&quot;&gt;I'm 14 and Built a Python Hardware Interface Toolkit (Yes, It Works)&lt;/h2&gt;
&lt;p&gt;Hi, I’m AkshuDev (Can't disclose my name)  — I’m 14 years old, and over the last 5 months, I built a full hardware interface, OS toolkit, and virtual BIOS in &lt;strong&gt;pure Python&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;No C. (Unless u like opengl, but I don't provide it in publishes)&lt;br&gt;
No &lt;code&gt;ctypes&lt;/code&gt;. (Okay a little bit)&lt;br&gt;
No dependencies (unless you want them).&lt;br&gt;
Just Python.&lt;/p&gt;
&lt;p&gt;And it’s live on GitHub and PyPI.&lt;/p&gt;
&lt;hr&gt;
&lt;h3 id=&quot;what-i-built-1&quot;&gt;What I Built&lt;/h3&gt;
&lt;h4 id=&quot;phardwareitk-phoenix-hardware-interface-toolkit-1&quot;&gt;PHardwareITK: Phoenix Hardware Interface Toolkit&lt;/h4&gt;
&lt;p&gt;This module is a &lt;strong&gt;complete system&lt;/strong&gt; for:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;File systems (PBFS: Phoenix Block File System)&lt;/li&gt;
&lt;li&gt;Virtual CPUs (PVCPU, runs &lt;code&gt;.vasm&lt;/code&gt; files)&lt;/li&gt;
&lt;li&gt;Memory simulation&lt;/li&gt;
&lt;li&gt;BIOS interrupts and booting logic&lt;/li&gt;
&lt;li&gt;️ GUI rendering using &lt;strong&gt;pure Python&lt;/strong&gt; (no SDL2 required)&lt;/li&gt;
&lt;li&gt;HGame: my own graphics engine inspired by &lt;code&gt;pygame&lt;/code&gt;, but written from scratch&lt;/li&gt;
&lt;li&gt;Permission management&lt;/li&gt;
&lt;li&gt;Tools for OS builders and experimenters&lt;/li&gt;
&lt;li&gt;And way way more&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Here’s the GitHub repo:&lt;br&gt;
 &lt;a rel=&quot;nofollow&quot; href=&quot;https://github.com/AkshuDev/PHardwareITK&quot;&gt;PHardwareITK on GitHub&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;And it’s installable on PyPI:  &lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;pip install phardwareitk
&lt;/code&gt;&lt;/pre&gt;
&lt;h2 id=&quot;how-it-all-started-1&quot;&gt;How It All Started&lt;/h2&gt;
&lt;p&gt;My first module was PheonixAppAPI. It was a simple binary + cryptography module I built to support my app, Pheonix.&lt;/p&gt;
&lt;p&gt;Then I went to my hometown for a while and didn’t have my PC. I got bored.&lt;/p&gt;
&lt;p&gt;So I thought:&lt;br&gt;
“What if I make something that lets Python control hardware?”&lt;/p&gt;
&lt;p&gt;And that’s how PHardwareITK was born — from a simple idea to now a 12,000-download module.&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&quot;how-it-works-2&quot;&gt;How It Works&lt;/h2&gt;
&lt;p&gt;I wrote my own:&lt;/p&gt;
&lt;p&gt;BIOS (in Python)&lt;/p&gt;
&lt;p&gt;File system (PBFS)&lt;/p&gt;
&lt;p&gt;Bootloader logic&lt;/p&gt;
&lt;p&gt;Virtual assembly (.vasm) file format (planned)&lt;/p&gt;
&lt;p&gt;Virtual CPU architecture (PVCPU) (in development)&lt;/p&gt;
&lt;p&gt;Permission tables, RAM cache, and direct drive access &lt;/p&gt;
&lt;p&gt;GUI toolkit using just Python (or optional SDL2 if devs want it)&lt;/p&gt;
&lt;p&gt;And a million more things (not really million btw)&lt;/p&gt;
&lt;p&gt;Note: PBFS was first made in python and is also called Python Based File System but the official (again by me) is called Pheonix-Block-File-System and I am currently updating that so my current PBFS in this module has outdated layout and will be updated, here check it out -&lt;/p&gt;
&lt;p&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://github.com/AkshuDev/Pheonix-Block-File-System&quot;&gt;https://github.com/AkshuDev/Pheonix-Block-File-System&lt;/a&gt;&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&quot;i-even-made-a-youtube-video-1&quot;&gt;I Even Made a YouTube Video&lt;/h2&gt;
&lt;p&gt;I created a 4K video showing how PhoenixAppAPI works, including deep binary mapping and encryption tools. You can watch it on this channel-&amp;gt; AkshobhyaEverything&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&quot;i-m-looking-for-contributors-1&quot;&gt;I'm Looking for Contributors&lt;/h2&gt;
&lt;p&gt;This is a HUGE project — I lost count of how many files it has &lt;/p&gt;
&lt;p&gt;I’m currently working on docs, and I’ve tagged some help wanted issues on GitHub. I’d love if you could:&lt;/p&gt;
&lt;p&gt;Try it out&lt;/p&gt;
&lt;p&gt;Star the repo if you like it ⭐&lt;/p&gt;
&lt;p&gt;Help with documentation or examples&lt;/p&gt;
&lt;p&gt;Share feedback&lt;/p&gt;
&lt;p&gt;It’s open source and 100% Python!&lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&quot;final-thoughts-1&quot;&gt;Final Thoughts&lt;/h2&gt;
&lt;p&gt;If you’re:&lt;/p&gt;
&lt;p&gt;An OS dev&lt;/p&gt;
&lt;p&gt;A retro computing fan&lt;/p&gt;
&lt;p&gt;A Python developer who wants more control&lt;/p&gt;
&lt;p&gt;Or just someone curious how a 14-year-old built an entire OS environment in Python...&lt;/p&gt;
&lt;p&gt;Come check it out!&lt;/p&gt;
&lt;p&gt;Thanks for reading,&lt;br&gt;
— AkshuDev&lt;/p&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/3889/phardwareitk-python-module</guid>
<pubDate>Thu, 10 Jul 2025 15:06:58 +0000</pubDate>
</item>
<item>
<title>Transitioning from Assembly to C: Challenges and Solutions for Programmers Effectively</title>
<link>https://coderlegion.com/3394/transitioning-from-assembly-to-c-challenges-and-solutions-for-programmers-effectively</link>
<description>&lt;h4 id=&quot;the-evolution-of-programming-from-assembly-to-c&quot;&gt;The Evolution of Programming: From Assembly to C&lt;/h4&gt;
&lt;p&gt;The history of programming is marked by significant milestones, one of which is the transition from assembly language to C. This shift revolutionized the way programmers wrote code, enabling them to create more portable, maintainable, and efficient software. However, this transition was not without its challenges. Programmers had to adapt to a new language, syntax, and programming paradigm, overcoming obstacles that arose from the differences between assembly language and C.&lt;/p&gt;
&lt;p&gt;The early days of programming were characterized by the use of assembly languages, which were symbolic representations of machine code. Assembly languages were closely tied to the hardware architecture, requiring programmers to manually manage registers, memory, and other hardware resources. This low-level programming paradigm demanded a deep understanding of the underlying hardware and its intricacies. Assembly language programming was tedious, time-consuming, and often resulted in code that was difficult to maintain and port.&lt;/p&gt;
&lt;p&gt;As programming evolved, the need for a higher-level language became apparent. C, developed by Dennis Ritchie in the early 1970s, marked a significant departure from assembly language. It introduced a higher-level abstraction, allowing programmers to write code that was more portable, efficient, and easier to maintain. C's syntax and semantics were designed to be more intuitive and expressive than assembly language, making it easier for programmers to write complex programs.&lt;/p&gt;
&lt;h4 id=&quot;assembly-language-a-low-level-programming-paradigm&quot;&gt;Assembly Language: A Low-Level Programming Paradigm&lt;/h4&gt;
&lt;p&gt;Assembly languages are low-level programming languages that are symbolic representations of machine code. They are closely tied to the hardware architecture, requiring programmers to manually manage registers, memory, and other hardware resources. This low-level programming paradigm demands a deep understanding of the underlying hardware and its intricacies.&lt;/p&gt;
&lt;p&gt;Programmers working with assembly language had to be familiar with the specific hardware architecture they were working with. They had to understand the instruction set, register layout, and memory organization of the target machine. This knowledge was essential to write efficient and correct assembly code.&lt;/p&gt;
&lt;p&gt;Assembly language programming was tedious and time-consuming. Programmers had to manually manage memory, registers, and other hardware resources, which made it prone to errors. The code was also difficult to maintain and port, as it was closely tied to the specific hardware architecture.&lt;/p&gt;
&lt;h4 id=&quot;the-advent-of-c-a-higher-level-abstraction&quot;&gt;The Advent of C: A Higher-Level Abstraction&lt;/h4&gt;
&lt;p&gt;C, developed by Dennis Ritchie in the early 1970s, marked a significant departure from assembly language. It introduced a higher-level abstraction, allowing programmers to write code that was more portable, efficient, and easier to maintain. C's syntax and semantics were designed to be more intuitive and expressive than assembly language, making it easier for programmers to write complex programs.&lt;/p&gt;
&lt;p&gt;C's higher-level abstraction was achieved through several key features. Firstly, C introduced a type system, which allowed programmers to define the type of variables and functions. This helped catch type-related errors at compile-time, making the code more robust and maintainable.&lt;/p&gt;
&lt;p&gt;Secondly, C provided a range of control structures, such as if-else statements, loops, and functions, which made it easier to write structured code. These control structures allowed programmers to write more modular and reusable code, reducing the complexity of large programs.&lt;/p&gt;
&lt;p&gt;Thirdly, C introduced pointers, which allowed programmers to manipulate memory addresses directly. Pointers were a powerful feature that enabled programmers to write efficient and flexible code. However, they also introduced new challenges, such as pointer arithmetic and type checking.&lt;/p&gt;
&lt;h4 id=&quot;challenges-when-transitioning-from-assembly-to-c&quot;&gt;Challenges When Transitioning from Assembly to C&lt;/h4&gt;
&lt;p&gt;When programmers transitioned from assembly language to C, they faced several challenges. One of the primary difficulties was adapting to C's syntax and semantics, which were significantly different from those of assembly language. C's use of pointers, in particular, proved to be a major hurdle for many programmers.&lt;/p&gt;
&lt;h5 id=&quot;understanding-pointer-syntax-and-semantics&quot;&gt;Understanding Pointer Syntax and Semantics&lt;/h5&gt;
&lt;p&gt;C's pointer syntax can be confusing, especially for those familiar with assembly language, where memory addresses are often manipulated using registers and explicit memory access instructions. In C, pointers are variables that hold memory addresses, and their syntax (e.g., &lt;code&gt;*&lt;/code&gt;, &lt;code&gt;&amp;amp;&lt;/code&gt;, &lt;code&gt;-&amp;gt;&lt;/code&gt;) requires a good understanding of the language's type system and operator precedence.&lt;/p&gt;
&lt;p&gt;Programmers had to learn how to declare, initialize, and use pointers correctly, avoiding common pitfalls like null pointer dereferences and pointer arithmetic errors. They had to understand the difference between pointer declaration and pointer dereferencing, as well as the implications of pointer arithmetic.&lt;/p&gt;
&lt;h5 id=&quot;pointer-arithmetic-and-array-indexing&quot;&gt;Pointer Arithmetic and Array Indexing&lt;/h5&gt;
&lt;p&gt;C's pointer arithmetic and array indexing rules can be tricky to grasp, especially for programmers accustomed to assembly language's direct memory access. Understanding how pointer arithmetic works, and how it relates to array indexing, required a significant mental adjustment.&lt;/p&gt;
&lt;p&gt;Programmers had to learn how to use pointer arithmetic to traverse arrays and manipulate data structures, while avoiding issues like buffer overflows and out-of-bounds access. They had to understand the relationship between pointers and arrays, as well as the implications of pointer arithmetic on array indexing.&lt;/p&gt;
&lt;h5 id=&quot;type-checking-and-casting&quot;&gt;Type Checking and Casting&lt;/h5&gt;
&lt;p&gt;C is a statically typed language, which means it checks the types of variables at compile-time. However, C's type system is not as strict as some other languages, and implicit casting can sometimes lead to issues. Programmers coming from assembly language, where type checking is typically not present, had to adapt to C's type system and learn when to use explicit casting.&lt;/p&gt;
&lt;p&gt;They had to understand the implications of implicit casting and how to avoid type-related errors. They also had to learn how to use explicit casting to convert between different types, while avoiding potential pitfalls like data loss or corruption.&lt;/p&gt;
&lt;h4 id=&quot;other-challenges-memory-management-and-portability&quot;&gt;Other Challenges: Memory Management and Portability&lt;/h4&gt;
&lt;p&gt;In addition to pointer-related challenges, programmers transitioning from assembly language to C faced other difficulties. One of the most significant was memory management. C provides some abstractions, but it still requires manual memory management using &lt;code&gt;malloc&lt;/code&gt;, &lt;code&gt;free&lt;/code&gt;, and other functions.&lt;/p&gt;
&lt;p&gt;Programmers had to learn how to manage memory effectively, avoiding issues like memory leaks and dangling pointers. They had to understand the implications of dynamic memory allocation and how to use it correctly.&lt;/p&gt;
&lt;p&gt;Another challenge was portability. C is a portable language, but different compilers and platforms can have varying implementations and quirks. Programmers had to learn how to write portable code and understand the implications of compiler-specific features and extensions.&lt;/p&gt;
&lt;h4 id=&quot;overcoming-the-challenges-practice-mentorship-and-resources&quot;&gt;Overcoming the Challenges: Practice, Mentorship, and Resources&lt;/h4&gt;
&lt;p&gt;To overcome the challenges associated with transitioning from assembly language to C, programmers relied on various resources and strategies. One of the most effective ways to learn C was through practice and experience. As programmers wrote more C code, they became more comfortable with the language and its subtleties.&lt;/p&gt;
&lt;p&gt;Mentorship and code review also played a crucial role in helping programmers adapt to C. Experienced C programmers helped newcomers learn best practices and avoid common pitfalls. Code review, in particular, was an effective way to identify and fix errors, improving overall code quality.&lt;/p&gt;
&lt;p&gt;C textbooks and documentation were another essential resource for programmers. Classics like Kernighan and Ritchie's &quot;The C Programming Language&quot; (1978) and compiler documentation helped programmers learn C and its idioms. Online resources, forums, and communities also provided a wealth of information and support for programmers transitioning to C.&lt;/p&gt;
&lt;h4 id=&quot;best-practices-for-transitioning-to-c&quot;&gt;Best Practices for Transitioning to C&lt;/h4&gt;
&lt;p&gt;To ensure a smooth transition from assembly language to C, programmers can follow several best practices:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Start with the basics&lt;/strong&gt;: Understand C's syntax, semantics, and type system before diving into complex programs.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Practice, practice, practice&lt;/strong&gt;: Write C code regularly to become comfortable with the language and its subtleties.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Use resources and documentation&lt;/strong&gt;: Leverage C textbooks, documentation, and online resources to learn C and stay up-to-date with best practices.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Join online communities&lt;/strong&gt;: Participate in online forums and communities to connect with other C programmers and learn from their experiences.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Code review and testing&lt;/strong&gt;: Regularly review and test code to identify and fix errors, improving overall code quality.&lt;/li&gt;
&lt;/ol&gt;
&lt;h4 id=&quot;advanced-topics-in-c-programming&quot;&gt;Advanced Topics in C Programming&lt;/h4&gt;
&lt;p&gt;Once programmers have a solid grasp of C's basics, they can move on to more advanced topics. These include:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Advanced pointer manipulation&lt;/strong&gt;: Understanding how to use pointers to manipulate complex data structures, such as linked lists and trees.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Dynamic memory allocation&lt;/strong&gt;: Learning how to use &lt;code&gt;malloc&lt;/code&gt;, &lt;code&gt;free&lt;/code&gt;, and other functions to manage memory dynamically.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Multi-threading and concurrency&lt;/strong&gt;: Understanding how to write concurrent programs using C's threading APIs.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Advanced data structures and algorithms&lt;/strong&gt;: Learning how to implement complex data structures, such as hash tables and graphs, and algorithms, such as sorting and searching.&lt;/li&gt;
&lt;/ol&gt;
&lt;h4 id=&quot;conclusion-1&quot;&gt;Conclusion&lt;/h4&gt;
&lt;p&gt;The transition from assembly language to C was a significant milestone in the history of programming. While challenging, this shift enabled programmers to write more portable, maintainable, and efficient code. By understanding the challenges associated with transitioning to C and following best practices, programmers can ensure a smooth transition and become proficient in this powerful and versatile language.&lt;/p&gt;
&lt;p&gt;As programming continues to evolve, the lessons learned from this transition remain relevant, informing the development of new languages and programming paradigms. The legacy of C continues to shape the programming landscape, influencing the design of modern languages and software systems.&lt;/p&gt;
&lt;h4 id=&quot;future-directions&quot;&gt;Future Directions&lt;/h4&gt;
&lt;p&gt;As programming continues to evolve, it is likely that new challenges and opportunities will arise. The development of new languages, frameworks, and tools will continue to shape the programming landscape. By understanding the history and challenges associated with transitioning to C, programmers can better navigate these changes and adapt to new technologies.&lt;/p&gt;
&lt;p&gt;The rise of new programming paradigms, such as functional programming and concurrency, will continue to influence the development of programming languages. Programmers will need to adapt to these new paradigms and learn how to apply them effectively in their work.&lt;/p&gt;
&lt;p&gt;In conclusion, the transition from assembly language to C was a pivotal moment in the history of programming. By understanding the challenges associated with this transition and following best practices, programmers can ensure a smooth transition to C and become proficient in this powerful and versatile language. As programming continues to evolve, the lessons learned from this transition will remain relevant, informing the development of new languages and programming paradigms.&lt;/p&gt;
&lt;h4 id=&quot;the-legacy-of-c&quot;&gt;The Legacy of C&lt;/h4&gt;
&lt;p&gt;C's impact on the programming world cannot be overstated. It has influenced the development of numerous other languages, including C++, Java, and Python. C's portability, efficiency, and flexibility have made it a popular choice for systems programming, embedded systems, and other applications where performance is critical.&lt;/p&gt;
&lt;p&gt;C's legacy continues to shape the programming landscape, influencing the design of modern languages and software systems. Its influence can be seen in the design of operating systems, compilers, and other low-level software.&lt;/p&gt;
&lt;p&gt;In conclusion, the transition from assembly language to C was a significant milestone in the history of programming. While challenging, this shift enabled programmers to write more portable, maintainable, and efficient code. By understanding the challenges associated with transitioning to C and following best practices, programmers can ensure a smooth transition and become proficient in this powerful and versatile language.&lt;/p&gt;
&lt;hr&gt;
</description>
<category>C</category>
<guid isPermaLink="true">https://coderlegion.com/3394/transitioning-from-assembly-to-c-challenges-and-solutions-for-programmers-effectively</guid>
<pubDate>Sun, 22 Jun 2025 05:46:57 +0000</pubDate>
</item>
<item>
<title>Zig Programming Language</title>
<link>https://coderlegion.com/811/zig-programming-language</link>
<description>&lt;p&gt;In the vast landscape of programming languages, where each claims to solve unique problems, Zig has emerged as a rising star in the systems programming domain. Created by Andrew Kelley in 2016, Zig is a general-purpose programming language that emphasises simplicity, performance, and reliability. For those seeking an alternative to C and C++ for systems-level development, Zig offers compelling features that make it worth exploring.&lt;/p&gt;
&lt;h3 id=&quot;what-is-zig-&quot;&gt;What is Zig?&lt;/h3&gt;
&lt;p&gt;Zig is a statically-typed programming language designed to be a better tool for building robust and efficient software. It is particularly suited for low-level programming, such as operating systems, game engines, and embedded systems. Zig’s design philosophy focuses on:&lt;/p&gt;
&lt;p&gt;Simplicity: Reducing developer overhead by offering a clean, minimalistic syntax.&lt;/p&gt;
&lt;p&gt;Performance: Compiling to highly optimised machine code with predictable execution.&lt;/p&gt;
&lt;p&gt;Reliability: Providing strong safety guarantees without sacrificing control over the hardware.&lt;/p&gt;
&lt;h3 id=&quot;key-features-of-zig&quot;&gt;Key Features of Zig&lt;/h3&gt;
&lt;ol&gt;
&lt;li&gt;&lt;p&gt;No Hidden Control Flow&lt;br&gt;
Unlike languages that abstract away control flow behind constructs like exceptions, Zig makes control flow explicit. This eliminates surprises and ensures that developers have full control over the program’s behaviour.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Manual Memory Management&lt;br&gt;
Zig gives developers full control over memory allocation and deallocation. While this requires more effort, it prevents the pitfalls of automatic garbage collection and allows precise tuning for performance-critical applications.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Error Handling Done Right&lt;br&gt;
Zig introduces a unique error handling model that replaces exceptions with error unions. Errors in Zig are treated as data, making it easier to reason about failure states and handle them predictably.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Cross-Compilation Made Easy&lt;br&gt;
Zig’s build system and cross-compilation support are second to none. By leveraging LLVM under the hood, Zig can target multiple architectures seamlessly. This makes it an ideal choice for projects requiring portability.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Interop with C&lt;br&gt;
Zig was designed to coexist with C code. Developers can call C functions directly and include C headers without additional bindings. This makes Zig a practical choice for gradually migrating legacy codebases.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Safety and Debugging Tools&lt;br&gt;
Zig offers various safety features like bounds checking, undefined behavior detection, and thread safety without compromising performance. These tools are invaluable for writing reliable software.&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;h3 id=&quot;why-choose-zig-&quot;&gt;Why Choose Zig?&lt;/h3&gt;
&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Modern Replacement for C&lt;br&gt;
C has been the go-to language for systems programming for decades, but its lack of modern features can hinder productivity and lead to subtle bugs. Zig retains the power of C while improving safety, readability, and developer experience.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Lightweight and Fast&lt;br&gt;
Zig’s compiler is lightweight and fast, making it easy to integrate into existing workflows. Unlike some languages that require extensive tooling, Zig priorities simplicity and speed.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Growing Ecosystem&lt;br&gt;
Though still relatively new, Zig’s ecosystem is expanding rapidly. Libraries, tools, and community contributions are steadily increasing, making it easier to adopt Zig for real-world projects.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Ideal for Learning Systems Programming&lt;br&gt;
Zig’s explicit nature and lack of hidden abstractions make it an excellent choice for developers who want to deepen their understanding of how computers work at a low level.&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;h3 id=&quot;use-cases-for-zig&quot;&gt;Use Cases for Zig&lt;/h3&gt;
&lt;p&gt;Zig is particularly well-suited for:&lt;/p&gt;
&lt;p&gt;Game Development: Its performance and control over memory make it ideal for building game engines and high-performance gaming applications.&lt;/p&gt;
&lt;p&gt;Embedded Systems: Zig’s lightweight nature and ability to cross-compile to various architectures make it a natural choice for embedded programming.&lt;/p&gt;
&lt;p&gt;Operating Systems: Zig’s low-level capabilities and explicit control over hardware resources enable the development of operating systems and kernels.&lt;/p&gt;
&lt;p&gt;Tooling and Compilers: The language’s simplicity and performance are perfect for creating tools like compilers, debuggers, and build systems.&lt;/p&gt;
&lt;h3 id=&quot;the-future-of-zig&quot;&gt;The Future of Zig&lt;/h3&gt;
&lt;p&gt;As Zig continues to mature, its potential to disrupt the systems programming space becomes increasingly apparent. With each release, new features and optimisations make it an even more attractive choice for developers. While it may not yet rival the popularity of C or Rust, Zig’s unique approach and growing community suggest that it has a bright future ahead.&lt;/p&gt;
&lt;h3 id=&quot;conclusion-2&quot;&gt;Conclusion&lt;/h3&gt;
&lt;p&gt;Zig represents a fresh perspective in systems programming, blending the best aspects of C with modern language features and tooling. Whether you’re building a high-performance application or exploring systems-level programming for the first time, Zig is worth considering. Its emphasis on simplicity, performance, and reliability positions it as a strong contender for the next generation of systems programming languages.&lt;/p&gt;
</description>
<category>Other</category>
<guid isPermaLink="true">https://coderlegion.com/811/zig-programming-language</guid>
<pubDate>Tue, 14 Jan 2025 20:06:06 +0000</pubDate>
</item>
<item>
<title>Munmap_chunk() invalid pointer Fixed</title>
<link>https://coderlegion.com/12/munmapchunk-invalid-pointer-fixed</link>
<description>&lt;p&gt;The &lt;strong&gt;&quot;Munmap_chunk(): Invalid Pointer&quot;&lt;/strong&gt; error typically appears during the &lt;strong&gt;runtime&lt;/strong&gt; of a program while executing it. It arises when a program tries to &lt;strong&gt;free&lt;/strong&gt; a particular memory portion that has either never been allocated or has already been freed. To resolve this error we need to be careful with &lt;strong&gt;memory management &lt;/strong&gt;, and in this article, we will discuss the error cases deeply and how to resolve them.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=337288044536260041&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;h2&gt;Understanding the Error&lt;/h2&gt;
&lt;p&gt;The &lt;strong&gt;&quot;munmap_chunk(): invalid pointer&quot;&lt;/strong&gt; error typically occurs when there's an attempt to &lt;strong&gt;free &lt;/strong&gt;a pointer that was not allocated through &lt;strong&gt;malloc&lt;/strong&gt;, &lt;strong&gt;calloc&lt;/strong&gt;, or &lt;strong&gt;realloc&lt;/strong&gt; functions, or if the pointer has already been &lt;strong&gt;freed&lt;/strong&gt;. In simpler terms, this error arises when you're trying to return memory that wasn't yours to begin with or no longer belongs to you.&lt;/p&gt;
&lt;p&gt;This error can also occur due to buffer &lt;strong&gt;overflow&lt;/strong&gt;, where your program writes more data into a buffer than it can hold, thus overwriting other information. Additionally, it can be caused by memory &lt;strong&gt;corruption&lt;/strong&gt;, where your program erroneously alters the metadata that the dynamic memory allocator uses to keep track of allocated blocks.&lt;/p&gt;
&lt;h2&gt;Error Triggering Cases&lt;/h2&gt;
&lt;h3&gt;Case 1: Invalid Pointer&lt;/h3&gt;
&lt;p&gt;In this case we are trying to &lt;strong&gt;free&lt;/strong&gt; a pointer that is not assigned to anything. We only &lt;strong&gt;delcared &lt;/strong&gt;the pointer but didn't &lt;strong&gt;define&lt;/strong&gt; it by &lt;strong&gt;intialzing&lt;/strong&gt; it or assigning a &lt;strong&gt;memory address&lt;/strong&gt; to it. Take a look at the following code:&lt;/p&gt;
&lt;pre&gt;
&lt;code class=&quot;language-cpp&quot;&gt;#include &amp;lt;stdlib.h&amp;gt;

int main(void)
{
        char *ptr; // this is the line that causes the error to happen
        int toallocate = 0;

        if (toallocate)
        {
                ptr = malloc(10);
                free(ptr);
        }
        free(ptr); //This is the line that raises the error

        return 0;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Here, we have &lt;strong&gt;declared&lt;/strong&gt; a pointer &lt;strong&gt;&quot;ptr&quot;&lt;/strong&gt;, then we are checking with an &lt;strong&gt;if&lt;/strong&gt; condition if it's the right situation to allocate memory and assign the address to &lt;strong&gt;&quot;ptr&quot;,&lt;/strong&gt; and after that we called the &lt;strong&gt;free&lt;/strong&gt; function to free the allocated memory&lt;/p&gt;
&lt;h3&gt;Case 2: Double Free&lt;/h3&gt;
&lt;p&gt;In this case, we are freeing a memory that we already have freed before and that happens more in complicated programs with a lot of files and modules, so let's check a simple snippet code:&lt;/p&gt;
&lt;pre&gt;
&lt;code class=&quot;language-cpp&quot;&gt;#include &amp;lt;stdlib.h&amp;gt;

int main(void)
{
    char *ptr = malloc(10);
    int isallocate = 0;

    // some code here

    free(ptr); // Correctly freeing the pointer.

    // some other code

    if (isallocate)
        ptr = malloc(15);

    free(ptr); // freeing the ptr again 

    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Of course, it won't be as simple as the above code, but I made it simple to understand it easier and I can assure you it will be the same &lt;strong&gt;flow&lt;/strong&gt; every time. So in the above code, we allocated a memory for some reason, We finished using it and we decided to free it, with no problems till now, but what if we tried it to free the same pointer again ?. That will trigger the error because we can't &lt;strong&gt;free&lt;/strong&gt; a pointer that is already freed.&lt;/p&gt;
&lt;h3&gt;Case 3: Freeing Part of Allocated Memory&lt;/h3&gt;
&lt;p&gt;We can't &lt;strong&gt;free&lt;/strong&gt; just a portion of a block of memory. It's all or nothing. So we &lt;strong&gt;shouldn't&lt;/strong&gt; &lt;strong&gt;pass&lt;/strong&gt; a pointer pointing at  a memory address other than the one that the &lt;strong&gt;memory&lt;/strong&gt; block &lt;strong&gt;starts&lt;/strong&gt; with. The following code demonstrate the case and where is the line that causes the error:&lt;/p&gt;
&lt;pre&gt;
&lt;code class=&quot;language-cpp&quot;&gt;#include &amp;lt;stdlib.h&amp;gt;

int main(void)
{
    char *ptr = malloc(50); // Allocate memory

    free(ptr + 10); // This line triggers the error
    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;So what's happening here? We're &lt;strong&gt;allocating&lt;/strong&gt; a block of memory for ptr using &lt;strong&gt;&lt;code&gt;malloc()&lt;/code&gt;&lt;/strong&gt;. Then, we're trying to &lt;strong&gt;&lt;code&gt;free()&lt;/code&gt;&lt;/strong&gt; a part of that memory block. Specifically, we are trying to &lt;strong&gt;free&lt;/strong&gt; the memory block after its &lt;strong&gt;strating&lt;/strong&gt; byte by &lt;strong&gt;10&lt;/strong&gt; &lt;strong&gt;more&lt;/strong&gt; bytes, but that won't work, because it's to free all the block code or nothing from it, so that will trigger the error.&lt;/p&gt;
&lt;h2&gt;Walking Through The Solutions&lt;/h2&gt;
&lt;h3&gt;Review Your Code&lt;/h3&gt;
&lt;p&gt;Start by thoroughly reviewing your code, especially areas where you're freeing memory. Ensure that every pointer you're attempting to free was indeed allocated using malloc, calloc, or realloc. Also, check to make sure you're not freeing the same pointer twice.&lt;/p&gt;
&lt;pre&gt;
&lt;code class=&quot;language-c language-cpp&quot;&gt;char* ptr = malloc(10);
// ... some code ..
free(ptr);
// ... some more code ...
free(ptr); // this will cause an error&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In the example above, the pointer &lt;code&gt;ptr&lt;/code&gt; is freed twice, which will lead to the &quot;munmap_chunk(): invalid pointer&quot; error.&lt;/p&gt;
&lt;h3&gt;Debug Your Code&lt;/h3&gt;
&lt;p&gt;Debugging your code can help identify problematic sections. Tools like Valgrind or GDB (GNU Debugger) are extremely helpful for this purpose.&lt;/p&gt;
&lt;p&gt;Valgrind is a programming tool that helps detect memory leaks and memory management issues. Running your program through Valgrind can help pinpoint the exact location of the error:&lt;/p&gt;
&lt;pre&gt;
&lt;code class=&quot;bash&quot;&gt;valgrind ./your_program
&lt;/code&gt;&lt;/pre&gt;
&lt;div class=&quot;div-green&quot;&gt;
&lt;span class=&quot;alert-header&quot;&gt;Tip:&lt;/span&gt;
&lt;span class=&quot;alert-body&quot;&gt;Use the &lt;strong&gt;-g&lt;/strong&gt; option when you compile the code to get useful info like which line that caused the error&lt;/span&gt;
&lt;/div&gt;
&lt;p&gt;GDB is another powerful debugging tool that allows you to see what is going on 'inside' your program while it executes.&lt;/p&gt;
&lt;pre&gt;
&lt;code class=&quot;bash&quot;&gt;gdb your_program
run
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Case 1: Solution: Invalid Pointer&lt;/h3&gt;
&lt;p&gt;In this case, we need to initialize the &lt;strong&gt;&quot;ptr&quot;&lt;/strong&gt; with &lt;strong&gt;NULL &lt;/strong&gt; and that will make it safe to pass it to the &lt;strong&gt;free()&lt;/strong&gt; function without raising any errors unless the program entered the &lt;strong&gt;if&lt;/strong&gt; block, allocated a memory block, and then calling the &lt;strong&gt;free&lt;/strong&gt; &lt;strong&gt;two&lt;/strong&gt; times with &lt;strong&gt;same&lt;/strong&gt; pointer, which will take us to next case and the solution for &lt;strong&gt;Double free&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;The &lt;strong&gt;invalid pointer &lt;/strong&gt;fix will be like the following code:&lt;/p&gt;
&lt;pre&gt;
&lt;code class=&quot;language-cpp&quot;&gt;#include &amp;lt;stdlib.h&amp;gt;

int main(void)
{
        char *ptr = NULL; // fixed line
        int allocate = 0;

        if (allocate)
        {
                ptr = malloc(10);
                free(ptr);
        }
        free(ptr);

        return 0;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Case 2: Solution: Double Free&lt;/h3&gt;
&lt;p&gt;In the case, we need to assign &lt;strong&gt;NULL&lt;/strong&gt; to &lt;strong&gt;&quot;ptr&quot;&lt;/strong&gt; after calling the &lt;strong&gt;free() &lt;/strong&gt;so if there is any additional attempt to &lt;strong&gt;free&lt;/strong&gt; &lt;strong&gt;&quot;ptr&quot;&lt;/strong&gt;, it will run safely without any problems. So the code after the fix will be like the following:&lt;/p&gt;
&lt;pre&gt;
&lt;code class=&quot;language-cpp&quot;&gt;#include &amp;lt;stdlib.h&amp;gt;

int main(void)
{
    char *ptr = malloc(10);
    int isallocate = 0;

    // some code here

    free(ptr); // Correctly freeing the pointer.
    ptr = NULL; // fixed line

    // some other code

    if (isallocate)
        ptr = malloc(15);

    free(ptr); // freeing the ptr again but safely this time

    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;div class=&quot;div-green&quot;&gt;
&lt;span class=&quot;alert-header&quot;&gt;Tip:&lt;/span&gt;
&lt;span class=&quot;alert-body&quot;&gt;Always after freeing a pointer, assign NULL to the pointer to avoid problems if there is any additional attempts to free the same pointer&lt;/span&gt;
&lt;/div&gt;
&lt;h3&gt;Case 3: Solution: Freeing Part of Allocated Memory&lt;/h3&gt;
&lt;p&gt;In this case, it's obvious that the solution is not to pass a random memory address of memory block or a pointer pointing at a random memory address of the memory block, but the &lt;strong&gt;correct&lt;/strong&gt; method is to pass the memory address that &lt;strong&gt;begins&lt;/strong&gt; the &lt;strong&gt;memory block&lt;/strong&gt; or the pointer that pointing at it, and we get it as the &lt;strong&gt;return&lt;/strong&gt; value of functions that allocate &lt;strong&gt;memory dynamiclly&lt;/strong&gt; like &lt;strong&gt;malloc&lt;/strong&gt;, &lt;strong&gt;alloc&lt;/strong&gt;, etc...the&lt;/p&gt;
&lt;p&gt;So the code after the fix should be like the following:&lt;/p&gt;
&lt;pre&gt;
&lt;code class=&quot;language-cpp&quot;&gt;#include &amp;lt;stdlib.h&amp;gt;
int main(void) {
    char *ptr = malloc(50); // Allocate memory

    free(ptr); // Fixed to pass the first of the block memory
    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Fix Buffer Overflows and Memory Corruption&lt;/h3&gt;
&lt;p&gt;If the error persists even after ensuring correct memory &lt;strong&gt;allocation &lt;/strong&gt;and &lt;strong&gt;deallocation&lt;/strong&gt;, you might be dealing with a &lt;strong&gt;buffer overflow&lt;/strong&gt; or &lt;strong&gt;memory corruption&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;In case of a &lt;strong&gt;buffer overflow&lt;/strong&gt;, ensure that you're not writing &lt;strong&gt;beyond&lt;/strong&gt; the memory you've allocated. For instance, if you've allocated an array of size 10, make sure you're not trying to access or modify the 11th element.&lt;/p&gt;
&lt;p&gt;For &lt;strong&gt;memory corruption&lt;/strong&gt;, the solution is trickier as it involves understanding how dynamic memory management works in C. However, tools like &lt;strong&gt;Valgrind&lt;/strong&gt; can help identify memory corruption issues as well.&lt;/p&gt;
&lt;p&gt;It's a good practice to always check the return value of the dynamic allocations functions, like &lt;strong&gt;malloc&lt;/strong&gt; before using it to handle the failure if you are out of memory, you should&lt;strong&gt;exit&lt;/strong&gt; the program with a user-friendly error message. better than continue running the program until it crashes, so instead of the following code:&lt;/p&gt;
&lt;pre&gt;
&lt;code class=&quot;language-cpp&quot;&gt;ptr = malloc(10);

// doing something with ptr&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We write it &lt;strong&gt;correctly&lt;/strong&gt; like:&lt;/p&gt;
&lt;pre&gt;
&lt;code class=&quot;language-cpp&quot;&gt;ptr = malloc(10);
if (ptr == NULL)
{
   fprintf(stderr, &quot;allocating failed: out of memory&quot;);
   exit(1);
}

// doing something with ptr&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In the above code, we checked if &lt;strong&gt;ptr&lt;/strong&gt; is &lt;strong&gt;NULL&lt;/strong&gt;. If that condition is true which means that &lt;strong&gt;malloc&lt;/strong&gt; &lt;strong&gt;failed&lt;/strong&gt; to allocate memory, then we print a message to the &lt;strong&gt;standard error&lt;/strong&gt; and &lt;strong&gt;exit&lt;/strong&gt; with &lt;strong&gt;1&lt;/strong&gt; which means&lt;strong&gt; &lt;/strong&gt;somethinng wrong happened caused to exit.&lt;/p&gt;
&lt;h2&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;In conclusion, while the &lt;strong&gt;&quot;munmap_chunk(): invalid pointer&quot;&lt;/strong&gt; error can initially seem daunting, understanding its root causes and knowing how to debug your code effectively can take you a long way in resolving it.&lt;/p&gt;
&lt;p&gt;We have discussed the importance &lt;strong&gt;of reviewing&lt;/strong&gt; the code and using tools to help us like &lt;strong&gt;Valgrind&lt;/strong&gt; and &lt;strong&gt;GDB&lt;/strong&gt;, how to &lt;strong&gt;nullish&lt;/strong&gt; the &lt;strong&gt;pointer&lt;/strong&gt; after &lt;strong&gt;freeing&lt;/strong&gt; it to avoid any potential errors, to pass to the &lt;strong&gt;free&lt;/strong&gt; function the &lt;strong&gt;start&lt;/strong&gt; of the memory block only, and the correct way to handle the &lt;strong&gt;failing&lt;/strong&gt; of allocating memory dynamically. Watch out for &lt;strong&gt;buffer overflows&lt;/strong&gt;, and use tools like &lt;strong&gt;Valgrind&lt;/strong&gt; and &lt;strong&gt;GDB&lt;/strong&gt; to help you along the way. Happy coding!&lt;/p&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/12/munmapchunk-invalid-pointer-fixed</guid>
<pubDate>Sat, 09 Sep 2023 00:41:08 +0000</pubDate>
</item>
<item>
<title>Assignment makes integer from pointer without a cast in c</title>
<link>https://coderlegion.com/1/assignment-makes-integer-from-pointer-without-a-cast-in-c</link>
<description>&lt;p&gt;Programming can be both rewarding and challenging. You work hard on your code, and just when it seems to be functioning perfectly, an error message pops up on your screen, leaving you frustrated and clueless about what went wrong. One common error that programmers encounter is the &lt;strong&gt;&quot;Assignment makes integer from pointer without a cast&quot; &lt;/strong&gt;error in C.&lt;/p&gt;
&lt;p&gt;This error occurs when you try to assign a value from a &lt;strong&gt;pointer&lt;/strong&gt; variable to an &lt;strong&gt;integer&lt;/strong&gt; variable without properly &lt;strong&gt;casting&lt;/strong&gt; it. To fix this error, you need to make sure that you cast the pointer value to the appropriate data type before assigning it to an integer variable. In this article, we will dive deeper into the causes of this error and provide you with solutions to overcome it.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=3374782502460835989&quot; alt=&quot;&quot;&gt;&lt;br&gt;
&lt;/p&gt;&lt;h2&gt;What makes this error occur?&lt;/h2&gt;
&lt;p&gt;I will present some cases that triggers that error to occur, and they are all have the same concept, so if you understanded why the failure happens, then you will figure out how to solve all the cases easily.&lt;/p&gt;
&lt;h3&gt;Case 1: Assignment of a pointer to an integer variable&lt;/h3&gt;
&lt;pre&gt;
&lt;code class=&quot;language-c language-cpp&quot;&gt;int main(void)
{
        int *ptr, n1, n2;

        n1 = 2;
        ptr = &amp;amp;n1;
        n2 = ptr; /* Failure in this line */
}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In this simple code we have three variables, an integer pointer &lt;strong&gt;&quot;ptr&quot;&lt;/strong&gt;, and two integers &lt;strong&gt;&quot;n1&quot;&lt;/strong&gt; and &lt;strong&gt;&quot;n2&quot;&lt;/strong&gt;. We assign &lt;strong&gt;2&lt;/strong&gt; to &lt;strong&gt;&quot;n1&quot;&lt;/strong&gt;, so far so good, then we assign the address of &lt;strong&gt;&quot;n2&quot;&lt;/strong&gt; to &lt;strong&gt;&quot;ptr&quot;&lt;/strong&gt; which is the suitable storing data type for a pointer, so no problems untill now, till we get to this line &lt;strong&gt;&quot;n2 = ptr&quot;&lt;/strong&gt; when we try to assign &lt;strong&gt;&quot;ptr&quot;&lt;/strong&gt; which is a &lt;strong&gt;memory address&lt;/strong&gt; to &lt;strong&gt;&quot;n2&quot;&lt;/strong&gt; that needs to store an integer data type because it's not a pointer.&lt;/p&gt;
&lt;h3&gt;Case 2: Returning a Pointer from a Function that Should Return an Integer&lt;/h3&gt;
&lt;pre&gt;
&lt;code class=&quot;language-cpp&quot;&gt;int* getinteger() {
    int *intp, myint = 10;

    intp = &amp;amp;myint;
    return intp;
}

int main(void)
{
        int result = getinteger(); /* this line causes the failure */

        return (0);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As you can see, it's another situation but it's the same idea which causes the compilation error.  We are trying here to assign the return of &lt;strong&gt;getinteger&lt;/strong&gt; function which is a &lt;strong&gt;pointer &lt;/strong&gt;that conatains a &lt;strong&gt;memory address&lt;/strong&gt; to the &lt;strong&gt;result &lt;/strong&gt;variable that is an &lt;strong&gt;int&lt;/strong&gt; type which needs an &lt;strong&gt;integer&lt;/strong&gt;&lt;/p&gt;
&lt;h3&gt;&lt;strong&gt;Case 3: Misusing Array Names as Pointers&lt;/strong&gt;&lt;/h3&gt;
&lt;pre&gt;
&lt;code class=&quot;language-cpp&quot;&gt;int main(void)
{
        int myarray[5] = {1, 2, 3, 4, 5};
        int myint;

        myint = myarray; /* this line will cause the failure */

        return (0);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As we might already know, that the &lt;strong&gt;identifier&lt;/strong&gt; (name) of the array is actually a &lt;strong&gt;pointer&lt;/strong&gt; to the array first element &lt;strong&gt;memory address&lt;/strong&gt;, so it's a pointer after all, and assigning a pointer type to int type causes the same compilation error.&lt;/p&gt;
&lt;h2&gt;The solutions&lt;/h2&gt;
&lt;p&gt;The key to avoiding the error is understanding that pointers and integers are different types of variables in C. Pointers hold memory addresses, while integers hold numeric values. We can use either &lt;strong&gt;casting&lt;/strong&gt;, &lt;strong&gt;dereferencing the pointer&lt;/strong&gt; or just redesign another solution for the problem we are working on that allows the two types to be the same. It all depending on the situation.&lt;/p&gt;
&lt;p&gt;Let's try to solve the above cases:&lt;/p&gt;
&lt;h3&gt;Case 1: Solution: Deferencing the pointer&lt;/h3&gt;
&lt;p&gt;We need in this case to asssign an &lt;strong&gt;int &lt;/strong&gt;type to &lt;strong&gt;&quot;n2&quot;&lt;/strong&gt; not a pointer or memory address, so how do we get the value of the variable that the pointer &quot;ptr&quot; pointing to? We get it by &lt;strong&gt;deferencing the pointer&lt;/strong&gt;, so the code after the fix will be like the following:&lt;/p&gt;
&lt;pre&gt;
&lt;code class=&quot;language-cpp&quot;&gt;int main(void)
{
        int *ptr, n1, n2;

        n1 = 2;
        ptr = &amp;amp;n1;
        n2 = *ptr; /* Line fixed */
}&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Case 2: Solution: Choosing the right data type&lt;/h3&gt;
&lt;p&gt;In this case we have two options, either we change the &lt;strong&gt;getinteger&lt;/strong&gt; returning type to &lt;strong&gt;int&lt;/strong&gt; or change the &lt;strong&gt;result&lt;/strong&gt; variable type to a &lt;strong&gt;pointer&lt;/strong&gt;. I will go with the latter option, because there are a lot of functions in the C standard library that returning a pointer, so what we can control is our variable that takes the function return. So the code after the fix will be like the following:&lt;/p&gt;
&lt;pre&gt;
&lt;code class=&quot;language-cpp&quot;&gt;int* getinteger() {
    int *intp, myint = 10;

    intp = &amp;amp;myint;
    return intp;
}

int main(void)
{
        int *result = getinteger(); /* Fixed line */

        return (0);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We here changed the &lt;strong&gt;result&lt;/strong&gt; variable from normal int to an int pointer by adding &lt;strong&gt;&quot;*&quot;&lt;/strong&gt;.&lt;/p&gt;
&lt;h3&gt;Case 3: Solution: Using the array subscript operator&lt;/h3&gt;
&lt;p&gt;In this case we can get the value of any number in the array  by using the &lt;strong&gt;subscript &lt;/strong&gt;opeartor ([]) on the array with the index number like: &lt;strong&gt;myarray[1]&lt;/strong&gt; for the second element which is &lt;strong&gt;2&lt;/strong&gt;. If we still remember that the array identifier is a pointer to the array first memory, then we can also get the value of the array first element by &lt;strong&gt;deferencing the array identifier &lt;/strong&gt;like: &lt;strong&gt;*myarray&lt;/strong&gt; which will get us &lt;strong&gt;1&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;But let's solve the case by using the &lt;strong&gt;subscript&lt;/strong&gt; opeartor which is the more obvious way. So the code will be like the following:&lt;/p&gt;
&lt;pre&gt;
&lt;code class=&quot;language-cpp&quot;&gt;int main(void)
{
        int myarray[5] = {1, 2, 3, 4, 5};
        int myint;

        myint = myarray[0]; /* Fixed line */

        return (0);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now the number &lt;strong&gt;1&lt;/strong&gt; is assigned to &lt;strong&gt;myint&lt;/strong&gt; without any compilation erros.&lt;/p&gt;
&lt;h2&gt;The conclusion&lt;/h2&gt;
&lt;p&gt;In conclusion, the error &lt;strong&gt;&quot;assignment to ‘int’ from ‘int *’ makes integer from pointer without a cast&quot;&lt;/strong&gt; arises in C programming when there is an attempt to assign a &lt;strong&gt;memory address&lt;/strong&gt; (held by a pointer) directly to an integer variable. This is a type mismatch as pointers and integers are fundamentally different types of variables in C.&lt;/p&gt;
&lt;p&gt;To avoid or correct this error, programmers need to ensure they are handling pointers and integers appropriately. If the intent is to assign the value pointed by a pointer to an integer, &lt;strong&gt;dereferencing&lt;/strong&gt; should be used. If a function is meant to return an integer, it should not return a pointer. When dealing with arrays, remember that the array &lt;strong&gt;name&lt;/strong&gt; behaves like a pointer to the first element, not an individual element of the array.&lt;/p&gt;
</description>
<category>C++</category>
<guid isPermaLink="true">https://coderlegion.com/1/assignment-makes-integer-from-pointer-without-a-cast-in-c</guid>
<pubDate>Mon, 21 Aug 2023 20:17:46 +0000</pubDate>
</item>
</channel>
</rss>