<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Suraj Kareppagol on Medium]]></title>
        <description><![CDATA[Stories by Suraj Kareppagol on Medium]]></description>
        <link>https://medium.com/@surajkareppagol.dev?source=rss-3503edd13a7b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*6Q6NJANswv2FJPjsdlbxJA.jpeg</url>
            <title>Stories by Suraj Kareppagol on Medium</title>
            <link>https://medium.com/@surajkareppagol.dev?source=rss-3503edd13a7b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 16:32:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@surajkareppagol.dev/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Write Safer Programs with std::optional<T>]]></title>
            <link>https://medium.com/@surajkareppagol.dev/write-safer-programs-with-std-optional-t-c0e12378b0a4?source=rss-3503edd13a7b------2</link>
            <guid isPermaLink="false">https://medium.com/p/c0e12378b0a4</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[cplusplus]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Suraj Kareppagol]]></dc:creator>
            <pubDate>Sun, 20 Sep 2026 07:52:56 GMT</pubDate>
            <atom:updated>2026-09-20T07:52:56.610Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/751/1*Gu7nJ42ySZFAkDHVvC0Mug.png" /></figure><h3>Motivation</h3><p>C++ traditionally uses NULL to indicate the absence of a value. If this case isn&#39;t handled correctly, programs can crash or exhibit undefined behavior. Because NULL is tightly coupled with raw pointers, developers must take great care when using it.</p><p>std::optional&lt;T&gt; (introduced in C++17) provides a type-safe alternative to raw pointers. It is a template that can hold almost any type. Its name makes it clear that the contained value is optional, it may or may not be present.</p><h3>std::optional&lt;T&gt; in Action</h3><p>The usage is straightforward. std::optional&lt;T&gt; is a class that offers several useful member functions. Below is a short example that demonstrates two functions:</p><ul><li><strong>get_even_number</strong> - Accepts a signed integer, checks whether it is negative, even, or odd, and always returns an even number (or nothing for a negative input).</li><li><strong>check_optional</strong> - Retrieves the optional result and prints it if a value is present.</li></ul><pre>#include &lt;cstdint&gt;<br>#include &lt;iostream&gt;<br>#include &lt;optional&gt;<br><br>std::optional&lt;uint64_t&gt; get_even_number(int64_t x) {<br>    if (x &lt; 0) {<br>        return std::nullopt;          /* No value for negative input */<br>    } else if (x % 2 == 0) {<br>        return x;                     /* Already even */<br>    } else {<br>        return x + 1;                 /* Make it even */<br>    }<br>}<br><br>void check_optional(int64_t num) {<br>   std::optional&lt;uint64_t&gt; number = get_even_number(num);<br>   if (number.has_value()) {<br>        std::cout &lt;&lt; *number &lt;&lt; &#39;\n&#39;; /* Safe dereference */<br>    } else {<br>        std::cout &lt;&lt; &quot;Doesn&#39;t contain a valid value.\n&quot;;<br>    }<br>}<br><br>int main() {<br>    check_optional(24);<br>    check_optional(55);<br>    check_optional(-12);<br>    check_optional(0);<br>    return 0;<br>}</pre><p>There are two ways to return a value:</p><ul><li><strong>Implicit conversion</strong> — return x + 1;</li><li><strong>Explicit construction</strong> — return std::optional&lt;uint64_t&gt;{x + 1};</li></ul><p>If there is no value to return, we use std::nullopt. This constant indicates &quot;no value&quot;.</p><h3>Common std::optional Operations</h3><h3>has_value()</h3><p>Returns a bool indicating whether the optional contains a value.</p><pre>if (number.has_value()) {<br>    /* Contains a value */<br>} else {<br>    /* Empty */<br>}</pre><h3>value()</h3><p>Provides access to the stored value. If the optional is empty, it throws std::bad_optional_access. This is safer than dereferencing (*) an empty optional.</p><pre>try {<br>    std::cout &lt;&lt; number.value() &lt;&lt; &#39;\n&#39;;<br>} catch (const std::bad_optional_access&amp;) {<br>    std::cout &lt;&lt; &quot;No value present.\n&quot;;<br>}</pre><h3>Dereference (*) and Member Access (-&gt;)</h3><p>These operators work like pointers but are <strong>unsafe</strong> on an empty optional. Prefer value() or value_or().</p><pre>if (number) {               /* Equivalent to has_value() */<br>    std::cout &lt;&lt; *number &lt;&lt; &#39;\n&#39;;<br>}</pre><h3>value_or()</h3><p>Returns the contained value if present; otherwise, it returns a supplied default.</p><pre>std::cout &lt;&lt; number.value_or(0) &lt;&lt; &#39;\n&#39;;</pre><h3>reset()</h3><p>Destroys the current value and makes the optional empty.</p><pre>number.reset();   /* Now number.has_value() == false */</pre><h3>Complete Example</h3><p>std::optional&lt;T&gt; stores the value of T directly inside the optional, avoiding dynamic allocation. When value() or the dereference operator is used, a reference (not a copy) is returned. Using value_or() on an empty optional copies the default value, which is negligible for primitive types but could matter for expensive objects.</p><p>One limitation: std::optional cannot hold references directly.</p><pre>#include &lt;iostream&gt;<br>#include &lt;optional&gt;<br>#include &lt;string&gt;<br><br>std::optional&lt;std::string&gt; get_string(const std::string&amp; str) {<br>    return (str.length() % 2 == 0)<br>               ? std::optional&lt;std::string&gt;{str}<br>               : std::nullopt;<br>}<br><br>void test_has_value() {<br>    std::cout &lt;&lt; &quot;---- has_value() ----\n&quot;;<br>    std::optional&lt;std::string&gt; s = get_string(&quot;aaa&quot;);<br>    if (s.has_value())<br>        std::cout &lt;&lt; &quot;s has value: &quot; &lt;&lt; *s &lt;&lt; &#39;\n&#39;;<br>    else<br>        std::cout &lt;&lt; &quot;s is empty.\n&quot;;<br>}<br><br>void test_value() {<br>    std::cout &lt;&lt; &quot;---- value() ----\n&quot;;<br>    std::optional&lt;std::string&gt; odd = get_string(&quot;aaa&quot;);<br>    try {<br>        std::cout &lt;&lt; odd.value() &lt;&lt; &#39;\n&#39;;<br>    } catch (const std::bad_optional_access&amp;) {<br>        std::cout &lt;&lt; &quot;Tried to access empty optional.\n&quot;;<br>    }<br><br>    std::optional&lt;std::string&gt; even = get_string(&quot;aaaa&quot;);<br>    std::cout &lt;&lt; even.value() &lt;&lt; &#39;\n&#39;;<br>}<br><br>void test_value_or() {<br>    std::cout &lt;&lt; &quot;---- value_or() ----\n&quot;;<br>    std::optional&lt;std::string&gt; s = get_string(&quot;aaa&quot;);<br>    std::cout &lt;&lt; s.value_or(&quot;default&quot;) &lt;&lt; &#39;\n&#39;;<br>}<br><br>int main() {<br>    test_has_value();<br>    test_value();<br>    test_value_or();<br>    return 0;<br>}</pre><h3>Conclusion</h3><p>If the types you work with are small and cheap to copy, std::optional is an excellent way to make the presence or absence of a value explicit and safe. It eliminates many classes of bugs associated with raw pointers and NULL.</p><p><em>If this article helped you, feel free to share it. For further discussion, please comment below or connect with me on </em><a href="https://www.linkedin.com/in/surajkareppagol/"><em>LinkedIn</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c0e12378b0a4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[container_of: Clever Macros #1]]></title>
            <link>https://medium.com/@surajkareppagol.dev/container-of-clever-macros-1-42e61f2aa3a8?source=rss-3503edd13a7b------2</link>
            <guid isPermaLink="false">https://medium.com/p/42e61f2aa3a8</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[cplusplus]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[c-programming]]></category>
            <dc:creator><![CDATA[Suraj Kareppagol]]></dc:creator>
            <pubDate>Thu, 17 Sep 2026 13:55:54 GMT</pubDate>
            <atom:updated>2026-09-17T13:55:54.618Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*AOfJSr2BWMwFEj8ccoPGTg.png" /></figure><p>container_of is a clever macro that helps you calculate the base address of a structure when you have a pointer to one of its member fields.</p><pre>#define container_of(ptr, type, member)                                        \<br>  ({                                                                           \<br>    const typeof(((type *)0)-&gt;member) *__mptr = (ptr);                         \<br>    (type *)((char *)__mptr - offsetof(type, member));                         \<br>  })</pre><p>At first glance, this code looks a bit alien, especially if you are not familiar with some of the extensions and techniques commonly used in low-level C programming. Let’s break it down.</p><ul><li><strong>(type *)0</strong>: Casts 0 to a pointer to type. This does not access address 0; it is used as a way for typeof to determine the type of the specified member.</li><li><strong>(char *)__mptr</strong>: Casts the member pointer to char *, allowing the subtraction to be performed in terms of bytes.</li><li><strong>offsetof(type, member)</strong>: Calculates the offset of member from the beginning of the structure. offsetof is available in the standard C header &lt;stddef.h&gt;.</li></ul><p>The macro takes three arguments:</p><ul><li><strong>ptr</strong>: A pointer to the member field.</li><li><strong>type</strong>: The type of the structure containing that member.</li><li><strong>member</strong>: The name of the member field that ptr points to.</li></ul><p>Consider the following structure:</p><pre>typedef struct find_my_address {<br>  int random;<br>  char *str;<br>  int boundary;<br>} fma_t;</pre><p>Suppose we have a pointer to the str member and want to find the address of the structure containing it:</p><pre>fma_t *fmap = container_of(&amp;fma.str, fma_t, str);</pre><p>Conceptually, the macro expands to something similar to:</p><pre>fma_t *fmap = ({<br>  const typeof(((fma_t *)0)-&gt;str) *__mptr = (&amp;fma.str);<br>  (fma_t *)((char *)__mptr - __builtin_offsetof(fma_t, str));<br>});</pre><p>The important part is this:</p><pre>(type *)((char *)__mptr - offsetof(type, member))</pre><p>If __mptr points to the str member, we know how far str is located from the beginning of fma_t. Therefore, subtracting that offset from the member&#39;s address gives us the address of the structure itself.</p><h3>How does offsetof work?</h3><p>offsetof calculates the offset of a member within a structure.</p><p>Conceptually, it uses an expression involving a null pointer:</p><pre>((type *)0)-&gt;member</pre><p>The idea is to treat the structure as if it starts at address 0 and determine where the specified member would be located relative to that starting point.</p><p>For example, imagine a simplified structure where the first member starts at offset 0 and the second member starts 4 bytes later:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/383/1*PmSwzgz0CxhKzxcCUykY5g.png" /></figure><p>If we have a pointer to the second member, its address is 1004. If offsetof(type, second_member) is 4, then container_of effectively performs:</p><pre>1004 - 4 = 1000</pre><p>And 1000 is the base address of the structure.</p><p>So, in simple terms:</p><pre>address of the structure<br>        =<br>address of member<br>        -<br>member&#39;s offset within the structure</pre><p>That is the core idea behind container_of.</p><h3>Why is container_of useful?</h3><p>container_of is particularly useful when working with <strong>embedded structures, generic data structures, callbacks, and intrusive data structures</strong>.</p><p>A common situation is that an API gives you a pointer to a member rather than a pointer to the entire structure. If you know the type of the containing structure and which member you have a pointer to, container_of lets you recover the structure&#39;s address.</p><p>This is especially common in systems programming and the Linux kernel, where structures frequently embed generic nodes such as linked-list entries.</p><p>For example:</p><pre>struct my_object {<br>  int data;<br>  struct list_node node;<br>};</pre><p>If a linked-list API gives you a pointer to node, you can use container_of to recover the corresponding struct my_object.</p><p>The major advantage is that it avoids storing an additional back-pointer inside every object. The relationship between the member and its containing structure is already known from the structure layout, so the compiler can calculate the containing object’s address.</p><p>That makes container_of a powerful example of how C&#39;s low-level control over memory layout can be used to build generic and efficient abstractions.</p><h3>Complete Example</h3><p>Here is a complete example that demonstrates the idea:</p><pre>#include &lt;stddef.h&gt;<br>#include &lt;stdio.h&gt;<br><br>#define container_of(ptr, type, member)                  \<br>  ({                                                     \<br>    const typeof(((type *)0)-&gt;member) *__mptr = (ptr);   \<br>    (type *)((char *)__mptr - offsetof(type, member));   \<br>  })<br><br>typedef struct find_my_address {<br>  int random;<br>  char *str;<br>  int boundary;<br>} fma_t;<br><br>int main(void) {<br>  fma_t fma = {0};<br>  printf(&quot;Direct: My address is (%p).\n&quot;, (void *)&amp;fma);<br>  fma_t *fmap = container_of(&amp;fma.str, fma_t, str);<br>  printf(&quot;Calculated: My address is (%p).\n&quot;, (void *)fmap);<br>  return 0;<br>}</pre><p>The output should show that both addresses are the same:</p><pre>Direct: My address is (0x0x7ffcc8f3c050)<br>Calculated: My address is (0x0x7ffcc8f3c050)</pre><p>The first address comes directly from the structure:</p><pre>&amp;fma</pre><p>The second address is calculated from the address of its member:</p><pre>container_of(&amp;fma.str, fma_t, str)</pre><p>Both point to the same location.</p><p>That is the clever part of container_of.</p><p><em>If you’d like to discuss this further, please feel free to comment below or connect with me on </em><a href="https://www.linkedin.com/in/surajkareppagol/"><em>LinkedIn</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=42e61f2aa3a8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding C++ Atomics: From Memory Ordering to a Lock-Free Queue]]></title>
            <link>https://medium.com/@surajkareppagol.dev/understanding-c-atomics-from-memory-ordering-to-a-lock-free-queue-227a25cc2490?source=rss-3503edd13a7b------2</link>
            <guid isPermaLink="false">https://medium.com/p/227a25cc2490</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[multithreading]]></category>
            <dc:creator><![CDATA[Suraj Kareppagol]]></dc:creator>
            <pubDate>Thu, 17 Sep 2026 13:48:34 GMT</pubDate>
            <atom:updated>2026-09-17T13:48:34.895Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*ezR7vQ8CEe8QqabJjadb0A.png" /></figure><h3>Motivation</h3><p>Concurrency is a programming paradigm that allows a program to handle multiple tasks and make progress during overlapping periods of time. Without concurrency, task A would run to completion before task B could start. With concurrency, task A can run, pause, give task B a chance to run, and then resume, allowing multiple tasks to make progress over overlapping periods.</p><p>Consider this: if concurrency didn’t exist, you wouldn’t be reading this article right now. A browser is a large binary that spawns multiple threads and handles multiple tasks during overlapping periods. On a single CPU core, the operating system can rapidly switch between these threads, giving the appearance of simultaneous execution. On a multicore system, however, multiple threads can execute <strong>in parallel</strong> on different CPU cores. This highlights the distinction between <strong>concurrency</strong>, which is about dealing with multiple tasks that make overlapping progress, and <strong>parallelism</strong>, which is about executing multiple tasks simultaneously.</p><p>However, making programs concurrent is difficult. Much of the complexity arises from data dependencies: how different tasks consume data, whether they depend on other tasks, and how those dependencies are synchronized. Some common issues include data races, race conditions, deadlocks, and more. Several mechanisms exist to address these issues, such as mutexes, semaphores, barriers, and spinlocks. These mechanisms are useful, but contention and blocking can introduce latency — something engineers try to minimize in high-performance systems.</p><p>One way to reduce synchronization overhead, where appropriate, is to avoid lock-based synchronization primitives and instead use <strong>atomic operations</strong>.</p><h3>Atomic Operations to the Rescue</h3><blockquote><em>The word </em><strong><em>atom</em></strong><em> is derived from the Greek word </em>atomos<em>, meaning “indivisible.”</em></blockquote><pre>int a = 3;<br>int b = 4;</pre><p>This code snippet creates two variables and assigns values to them. When compiled into machine code, it may span several instructions. Since these two lines don’t depend on each other, we generally don’t care about the order in which the CPU executes them. It might initialize variable b first, then a, or execute them in another order.</p><p>However, in concurrent programs, instruction reordering and interleaving can become problematic when operations have dependencies or when multiple threads access shared data.</p><p>But what if an operation could be performed as a single indivisible step? This is the idea behind atomic operations. An atomic operation appears indivisible to other threads with respect to the atomic object being accessed. Depending on the type and platform, atomic operations may be implemented using hardware-supported atomic instructions or other mechanisms.</p><p>Many languages, including C++, provide mechanisms for using atomic operations. std::atomic&lt;T&gt;, introduced in C++11, provides atomic access to an object and exposes a set of atomic operations.</p><p>Consider a task scheduler using a queue that multiple threads can access. Using lock-based primitives works well, but contention on the lock can introduce synchronization overhead. By introducing atomic operations to the queue, we can potentially reduce some of that overhead and make it more efficient.</p><p>Let’s get comfortable with std::atomic&lt;T&gt;, and then we&#39;ll build both a lock-based queue and a queue using atomic operations to compare their performance.</p><h3>Hands-On with std::atomic&lt;T&gt;</h3><p>std::atomic&lt;T&gt; is a template that provides atomic operations on a value of type T. Here, int is wrapped in std::atomic, allowing us to perform atomic operations on the variable.</p><pre>#include &lt;atomic&gt;</pre><pre>std::atomic&lt;int&gt; a_int{0};</pre><h3>store(value, order)</h3><p>The store() method atomically replaces the current stored value with value. The order parameter specifies the memory order, which we&#39;ll cover shortly.</p><pre>a_int.store(2);</pre><h3>load(order)</h3><p>The load() method atomically retrieves the current value.</p><pre>int a = a_int.load();</pre><h3>exchange(value, order)</h3><p>exchange() is similar to store(), but with a key difference: it replaces the current value with value and returns the old value. Think of it as an atomic swap.</p><h3>compare_exchange_*(expected, desired, success_order, failure_order)</h3><p>The compare_exchange_* methods are crucial. They compare the current value with expected. If they match, the method replaces the original value with desired and returns true. If they don&#39;t match, it updates expected with the current value and returns false.</p><p>There are two variants: compare_exchange_weak and compare_exchange_strong.</p><p>The weak variant may fail spuriously even when the comparison succeeds, so it is commonly used inside loops. The strong variant does not have these spurious failures.</p><h3>fetch_*(value, order)</h3><p>The fetch_* methods allow you to perform arithmetic and bitwise operations atomically. Available operations include add, sub, and, or, and xor.</p><h3>Memory Orders</h3><p>The order parameter in these methods is important. It specifies the memory-ordering constraints that apply to the atomic operation. Compilers and CPUs can reorder operations when doing so is permitted by the language and hardware memory model. In concurrent code, however, we often need specific ordering and visibility guarantees.</p><p>Memory orders allow us to control the ordering guarantees that matter for synchronization.</p><p>By default, memory_order_seq_cst is used.</p><h3>memory_order_relaxed</h3><p>memory_order_relaxed is the simplest option. It guarantees that the atomic operation itself is atomic, but it does not establish synchronization between that atomic operation and other memory operations.</p><p>Use it when you only need atomicity and don’t need the atomic variable to synchronize access to other data.</p><pre>int a = 0;<br>std::atomic&lt;int&gt; flag{0};<br>int b = 0;</pre><pre>a = 1;                                    /* Line A */<br>flag.store(1, std::memory_order_relaxed); /* Line B */<br>b = 1;                                    /* Line C */</pre><p>The store on Line B is atomic, but it does not establish a <em>happens-before</em> relationship with another thread merely because that thread observes the value 1. A relaxed operation provides no release or acquire synchronization with other memory accesses.</p><h3>memory_order_consume</h3><p>memory_order_consume provides ordering based on data dependencies. If a subsequent operation depends on a value loaded with memory_order_consume, that dependency is preserved.</p><p>For example:</p><pre>std::atomic&lt;int*&gt; box{nullptr};</pre><pre>/* The producer publishes a valid pointer here. */</pre><pre>int* current = box.load(std::memory_order_consume);<br>int value = *current;</pre><p>The operation that dereferences current depends on the value loaded from box.</p><p>In practice, memory_order_consume is rarely used because compiler support and implementation are complicated. Most code uses memory_order_acquire instead.</p><h3>memory_order_release</h3><p>memory_order_release is typically applied to store operations. Its important property is that memory operations <strong>before the release store cannot be reordered after it</strong> in a way that violates the C++ memory model.</p><p>A release operation is commonly used to publish data to another thread.</p><p>Using the same producer-consumer example:</p><pre>int data = 0;<br>std::atomic&lt;bool&gt; flag{false};</pre><pre>/* Producer thread */<br>data = 42;                                   /* Line A */<br>flag.store(true, std::memory_order_release); /* Line B */</pre><p>The release store ensures that the write to data is ordered before the publication of flag.</p><p>Another thread can then use an acquire load:</p><pre>/* Consumer thread */<br>if (flag.load(std::memory_order_acquire)) { /* Line C */<br>    std::cout &lt;&lt; data;                      /* Line D */<br>}</pre><p>If Line C observes the value stored by Line B, the write on Line A happens-before the read on Line D.</p><p>A simple way to remember release is:</p><blockquote><strong><em>Release prevents things before it from moving after it.</em></strong></blockquote><p>It is like saying: “Everything I did before this point must be published before I release this signal.”</p><h3>memory_order_acquire</h3><p>memory_order_acquire is typically applied to load operations. Its important property is that memory operations <strong>after the acquire operation cannot be reordered before it</strong> in a way that violates the C++ memory model.</p><p>More importantly, when an acquire load reads a value written by a release operation, the release and acquire operations establish a <strong>synchronizes-with</strong> relationship. This allows the acquiring thread to observe writes that happened before the release.</p><p>Consider this producer-consumer example:</p><pre>int data = 0;<br>std::atomic&lt;bool&gt; flag{false};</pre><pre>/* Producer thread */<br>data = 42;                                   /* Line A */<br>flag.store(true, std::memory_order_release); /* Line B */</pre><pre>/* Consumer thread */<br>if (flag.load(std::memory_order_acquire)) { /* Line C */<br>    std::cout &lt;&lt; data;                      /* Line D */<br>}</pre><p>Here is what happens:</p><ol><li>The producer writes 42 to data.</li><li>The producer performs the release store on flag.</li><li>The consumer performs an acquire load and observes true.</li><li>Because the acquire load reads the value stored by the release operation, the release store synchronizes with the acquire load.</li><li>The write to data happens-before the read of data.</li></ol><p>Therefore, the consumer can safely read data as 42.</p><p>A simple way to remember acquire is:</p><blockquote><strong><em>Acquire prevents things after it from moving before it.</em></strong></blockquote><p>It is like saying: “Once I have acquired this signal, I am allowed to see the work that was published before it.”</p><h3>memory_order_acq_rel</h3><p>memory_order_acq_rel is applied to read-modify-write operations such as fetch_* and compare_exchange_*. It combines both acquire and release semantics.</p><p>For example:</p><pre>std::atomic&lt;int&gt; count{0};</pre><pre>int old = count.fetch_add(1, std::memory_order_acq_rel);</pre><p>The acquire part applies to operations following the atomic operation, while the release part applies to operations preceding it.</p><p>It is useful when a read-modify-write operation both consumes previously published state and publishes new state.</p><h3>memory_order_seq_cst</h3><p>memory_order_seq_cst is the default memory order. It provides sequential consistency for sequentially consistent atomic operations. In addition to the acquire and release guarantees, all seq_cst atomic operations participate in a single global order that is consistent with the order of operations within each individual thread.</p><p>It is usually the easiest memory order to reason about, but it can impose stronger ordering constraints than necessary and may have a performance cost on some architectures.</p><pre>int a = 0;<br>std::atomic&lt;int&gt; flag{0};<br>int b = 0;</pre><pre>a = 1;                                   /* Line A */<br>flag.store(1, std::memory_order_seq_cst); /* Line B */<br>b = 1;                                   /* Line C */</pre><p>For this store, seq_cst provides release semantics, so operations before Line B cannot be reordered after it. It also participates in the global sequentially consistent order of seq_cst atomic operations.</p><h3>Building Thread-Safe Queues with Locks</h3><p>Before we try to build a queue using atomic operations, let’s start with the straightforward solution: a mutex and condition variables.</p><p>This gives us a correct and relatively simple thread-safe queue. More importantly, it gives us a <strong>baseline</strong>.</p><p>If we later replace the mutex with atomic operations, we can measure whether the additional complexity actually gives us a performance benefit.</p><p>The goal isn’t to prove that mutexes are slow or that atomics are always faster. The goal is to compare two synchronization approaches for the same problem and understand the trade-offs.</p><pre>#include &lt;chrono&gt;<br>#include &lt;condition_variable&gt;<br>#include &lt;iostream&gt;<br>#include &lt;mutex&gt;<br>#include &lt;thread&gt;<br>#include &lt;vector&gt;</pre><pre>#define QUEUE_SIZE 10</pre><pre>using namespace std;</pre><pre>class Queue {<br>private:<br>  int buffer[QUEUE_SIZE];<br>  int front = 0;<br>  int rear = 0;<br>  int count = 0;<br>  mutex m;<br>  condition_variable not_full;<br>  condition_variable not_empty;</pre><pre>public:<br>  Queue() {}</pre><pre>  void enqueue(int value, int id) {<br>    unique_lock&lt;mutex&gt; lock(m);</pre><pre>    /* Block if the queue is full until space becomes available */<br>    not_full.wait(lock, [this]() { return count &lt; QUEUE_SIZE; });</pre><pre>    buffer[front] = value;<br>    front = (front + 1) % QUEUE_SIZE;<br>    count++;</pre><pre>#if DEBUG<br>    cout &lt;&lt; &quot;[Thread &quot; &lt;&lt; id &lt;&lt; &quot;] [-&gt; Enqueue] &quot; &lt;&lt; value &lt;&lt; endl;<br>#endif</pre><pre>    /* Wake up a waiting consumer thread */<br>    not_empty.notify_one();<br>  }</pre><pre>  int dequeue(int id) {<br>    unique_lock&lt;mutex&gt; lock(m);</pre><pre>    /* Block if the queue is empty until an item is available */<br>    not_empty.wait(lock, [this]() { return count &gt; 0; });</pre><pre>    int value = buffer[rear];<br>    rear = (rear + 1) % QUEUE_SIZE;<br>    count--;</pre><pre>#if DEBUG<br>    cout &lt;&lt; &quot;[Thread &quot; &lt;&lt; id &lt;&lt; &quot;] [&lt;- Dequeue] &quot; &lt;&lt; value &lt;&lt; endl;<br>#endif</pre><pre>    /* Wake up a waiting producer thread */<br>    not_full.notify_one();<br>    return value;<br>  }<br>};</pre><pre>Queue queue;</pre><pre>void use_queue(int thread_id) {<br>  for (int i{0}; i &lt; 10000; i++) {<br>    queue.enqueue(i + 1, thread_id);<br>    int value = queue.dequeue(thread_id);<br>  }<br>}</pre><pre>void work() {<br>  vector&lt;thread&gt; tcontainer;</pre><pre>  for (int i{0}; i &lt; 10; i++) {<br>    tcontainer.emplace_back(thread(use_queue, i));<br>  }</pre><pre>  for (thread &amp;t : tcontainer) {<br>    t.join();<br>  }<br>}</pre><pre>int main() {<br>  cout &lt;&lt; &quot;--- Thread-safe queues with locks and condition variables ---\n&quot;;</pre><pre>  auto start = chrono::steady_clock::now();<br>  work();<br>  auto stop = chrono::steady_clock::now();</pre><pre>  chrono::milliseconds duration =<br>      chrono::duration_cast&lt;chrono::milliseconds&gt;(stop - start);</pre><pre>  cout &lt;&lt; &quot;It took &quot; &lt;&lt; duration.count() &lt;&lt; &quot; milliseconds.&quot; &lt;&lt; endl;</pre><pre>  return 0;<br>}</pre><p>This is a minimal thread-safe queue implementation that stores <strong>10 elements</strong>. We create <strong>10 threads</strong>, and each thread enqueues and dequeues <strong>10,000 elements</strong>. Let’s dissect the enqueue and dequeue functions.</p><h3>Enqueue</h3><pre>unique_lock&lt;mutex&gt; lock(m);</pre><p>Here, we create a unique lock on the mutex. unique_lock is useful because it can release the lock before its scope ends. More importantly, condition_variable::wait() requires a unique_lock because it temporarily releases the mutex while the thread is waiting and reacquires it before returning.</p><pre>/* Block if the queue is full until space becomes available */<br>not_full.wait(lock, [this]() { return count &lt; QUEUE_SIZE; });</pre><p>Here, we put the thread to sleep if the queue is full.</p><p>The predicate is important because condition variables can wake up even when the condition is not yet true. The predicate is checked again after the thread wakes up.</p><pre>buffer[front] = value;<br>front = (front + 1) % QUEUE_SIZE;<br>count++;</pre><p>We insert the value and advance front by 1, wrapping around when necessary to implement the circular queue.</p><pre>/* Wake up a waiting consumer thread */<br>not_empty.notify_one();</pre><p>Once we’ve pushed an element, we notify a waiting consumer thread that data may be available.</p><h3>Dequeue</h3><pre>unique_lock&lt;mutex&gt; lock(m);</pre><p>Here, we create a unique lock on the mutex.</p><pre>/* Block if the queue is empty until an item is available */<br>not_empty.wait(lock, [this]() { return count &gt; 0; });</pre><p>Here, we put the thread to sleep if the queue is empty.</p><pre>int value = buffer[rear];<br>rear = (rear + 1) % QUEUE_SIZE;<br>count--;</pre><p>We remove the value and advance rear by 1, wrapping around when necessary.</p><pre>/* Wake up a waiting producer thread */<br>not_full.notify_one();<br>return value;</pre><p>Once we’ve removed an element, we notify a waiting producer thread that space may now be available, and then return the value.</p><h3>Building Thread-Safe Queues with Atomic Operations</h3><p>Now that we’ve seen atomic operations and memory ordering, let’s put those concepts to work in a real concurrency problem.</p><p>Our mutex-based queue gives us a simple and correct solution, but every enqueue and dequeue operation has to acquire the same mutex. What if we could coordinate producers and consumers without using that mutex?</p><p>This is where the concepts we’ve just learned become useful.</p><p>Writing a lock-free version is difficult and complex. In the lock-based version, we protect the queue’s shared state with a mutex, making synchronization relatively straightforward. With atomic operations, careful design is required to ensure that multiple producers and consumers can safely operate on the queue without data races.</p><p>The following is a bounded MPMC (multiple-producer, multiple-consumer) queue based on <strong>Dmitry Vyukov’s bounded MPMC queue design</strong>.</p><p>A small terminology note: this design is commonly described as a “lock-free MPMC queue,” but it does not satisfy the formal lock-free progress guarantee in the strict sense. A producer can claim a position and then be delayed before publishing its result, which can prevent other operations from progressing past that point. Here, we’re primarily interested in the algorithm’s use of atomic operations and memory ordering.</p><pre>#include &lt;atomic&gt;<br>#include &lt;chrono&gt;<br>#include &lt;iostream&gt;<br>#include &lt;thread&gt;<br>#include &lt;vector&gt;</pre><pre>#define QUEUE_SIZE 10</pre><pre>using namespace std;</pre><pre>class Queue {<br>private:<br>  struct Cell {<br>    atomic&lt;size_t&gt; sequence;<br>    int data;<br>  };</pre><pre>  Cell buffer[QUEUE_SIZE];<br>  atomic&lt;size_t&gt; front{0};<br>  atomic&lt;size_t&gt; rear{0};</pre><pre>public:<br>  Queue() {<br>    for (size_t i = 0; i &lt; QUEUE_SIZE; ++i) {<br>      buffer[i].sequence.store(i, memory_order_relaxed);<br>    }<br>  }</pre><pre>  void enqueue(int value, int id) {<br>    Cell *cell;<br>    size_t pos = front.load(memory_order_relaxed);</pre><pre>    for (;;) {<br>      cell = &amp;buffer[pos % QUEUE_SIZE];<br>      size_t seq = cell-&gt;sequence.load(memory_order_acquire);<br>      intptr_t dif = (intptr_t)seq - (intptr_t)pos;</pre><pre>      if (dif == 0) {<br>        if (front.compare_exchange_weak(pos, pos + 1, memory_order_relaxed)) {<br>          break;<br>        }<br>      } else if (dif &lt; 0) {<br>        pos = front.load(memory_order_relaxed);<br>        this_thread::yield();<br>      } else {<br>        pos = front.load(memory_order_relaxed);<br>      }<br>    }</pre><pre>    cell-&gt;data = value;<br>    cell-&gt;sequence.store(pos + 1, memory_order_release);<br>  }</pre><pre>  int dequeue(int id) {<br>    Cell *cell;<br>    size_t pos = rear.load(memory_order_relaxed);</pre><pre>    for (;;) {<br>      cell = &amp;buffer[pos % QUEUE_SIZE];<br>      size_t seq = cell-&gt;sequence.load(memory_order_acquire);<br>      intptr_t dif = (intptr_t)seq - (intptr_t)(pos + 1);</pre><pre>      if (dif == 0) {<br>        if (rear.compare_exchange_weak(pos, pos + 1, memory_order_relaxed)) {<br>          break;<br>        }<br>      } else if (dif &lt; 0) {<br>        pos = rear.load(memory_order_relaxed);<br>        this_thread::yield();<br>      } else {<br>        pos = rear.load(memory_order_relaxed);<br>      }<br>    }</pre><pre>    int value = cell-&gt;data;<br>    cell-&gt;sequence.store(pos + QUEUE_SIZE, memory_order_release);</pre><pre>    return value;<br>  }<br>};</pre><pre>Queue queue;</pre><pre>void use_queue(int thread_id) {<br>  for (int i{0}; i &lt; 10000; i++) {<br>    queue.enqueue(i + 1, thread_id);<br>    int value = queue.dequeue(thread_id);<br>  }<br>}</pre><pre>void work() {<br>  vector&lt;thread&gt; tcontainer;</pre><pre>  for (int i{0}; i &lt; 10; i++) {<br>    tcontainer.emplace_back(thread(use_queue, i));<br>  }</pre><pre>  for (thread &amp;t : tcontainer) {<br>    t.join();<br>  }<br>}</pre><pre>int main() {<br>  cout &lt;&lt; &quot;--- Atomic bounded MPMC queue ---\n&quot;;</pre><pre>  auto start = chrono::steady_clock::now();<br>  work();<br>  auto stop = chrono::steady_clock::now();</pre><pre>  chrono::milliseconds duration =<br>      chrono::duration_cast&lt;chrono::milliseconds&gt;(stop - start);</pre><pre>  cout &lt;&lt; &quot;It took &quot; &lt;&lt; duration.count() &lt;&lt; &quot; milliseconds.&quot; &lt;&lt; endl;</pre><pre>  return 0;<br>}</pre><p>This implementation is similar to the lock-based version: we have one global queue and create 10 threads, each enqueuing and dequeuing 10,000 elements. However, instead of a simple array, we use an array of Cell structures, each holding a sequence number.</p><p>The sequence number is what allows producers and consumers to determine whether a slot is available, currently contains valid data, or is still being used by another operation.</p><p>Let’s dissect how this works.</p><h3>Constructor</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*W9XdMgX2DQ1ks0CIGXuNMQ.png" /></figure><pre>Queue() {<br>  for (size_t i = 0; i &lt; QUEUE_SIZE; ++i) {<br>    buffer[i].sequence.store(i, memory_order_relaxed);<br>  }<br>}</pre><p>Here, we initialize each cell by setting its sequence number. We use memory_order_relaxed because the queue has not yet been published to other threads, so no synchronization with other threads is required during construction.</p><h4>Trace</h4><ul><li>Every cell at index i starts with its sequence number set to i (Cell 0 has seq = 0, Cell 1 has seq = 1, and so on).</li><li>Both front and rear start at <strong>0</strong>.</li></ul><h3>Enqueue</h3><pre>void enqueue(int value, int id) {<br>  Cell *cell;<br>  size_t pos = front.load(memory_order_relaxed);</pre><pre>  for (;;) {<br>    cell = &amp;buffer[pos % QUEUE_SIZE];<br>    size_t seq = cell-&gt;sequence.load(memory_order_acquire);</pre><pre>    intptr_t dif = (intptr_t)seq - (intptr_t)pos;</pre><pre>    if (dif == 0) {<br>      if (front.compare_exchange_weak(pos, pos + 1, memory_order_relaxed)) {<br>        break;<br>      }<br>    } else if (dif &lt; 0) {<br>      pos = front.load(memory_order_relaxed);<br>      this_thread::yield();<br>    } else {<br>      pos = front.load(memory_order_relaxed);<br>    }<br>  }</pre><pre>  cell-&gt;data = value;<br>  cell-&gt;sequence.store(pos + 1, memory_order_release);<br>}</pre><ul><li>We initially load the current front index with memory_order_relaxed. This is a position hint indicating where the next item may be written.</li><li>We load the cell’s sequence number with memory_order_acquire. This allows us to safely observe the state published by the previous consumer.</li><li>We calculate the difference between the cell’s sequence number and our target position.</li><li>If the difference is <strong>zero</strong>, the cell is available for writing. We attempt to claim the position by advancing front with compare_exchange_weak.</li><li>If the difference is <strong>negative</strong>, the cell has not yet been released for this producer position, so we retry after yielding.</li><li>If the difference is <strong>positive</strong>, our position is stale, so we reload front.</li><li>Once the producer successfully claims the position, it writes the value into cell-&gt;data.</li><li>Finally, the producer stores the updated sequence number using memory_order_release. This publishes the data to a consumer that subsequently performs an acquire load of the sequence number.</li></ul><h4>Trace</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*BDNxmYX0utLCdzU1iLL8yA.png" /></figure><ul><li>A producer looks at front = 0, mapping to <strong>Index 0</strong> (0 % 10 = 0).</li><li>It checks the cell’s sequence. Since seq = 0 and the target pos = 0, the difference is dif = seq - pos = 0.</li><li>This <strong>0</strong> tells the producer: <em>“This slot is available for writing.”</em></li><li>The producer claims Index 0 by moving front to <strong>1</strong> using compare_exchange_weak.</li><li>It writes <strong>42</strong> into cell-&gt;data and updates the sequence number to pos + 1 (<strong>0 + 1 = 1</strong>).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*JOBsJV71B8GN3nhZcNRT1w.png" /></figure><ul><li><strong>Index 0 now holds </strong><strong>Seq: 1 and </strong><strong>Data: 42.</strong></li></ul><h3>Dequeue</h3><pre>int dequeue(int id) {<br>  Cell *cell;<br>  size_t pos = rear.load(memory_order_relaxed);</pre><pre>  for (;;) {<br>    cell = &amp;buffer[pos % QUEUE_SIZE];<br>    size_t seq = cell-&gt;sequence.load(memory_order_acquire);</pre><pre>    intptr_t dif = (intptr_t)seq - (intptr_t)(pos + 1);</pre><pre>    if (dif == 0) {<br>      if (rear.compare_exchange_weak(pos, pos + 1, memory_order_relaxed)) {<br>        break;<br>      }<br>    } else if (dif &lt; 0) {<br>      pos = rear.load(memory_order_relaxed);<br>      this_thread::yield();<br>    } else {<br>      pos = rear.load(memory_order_relaxed);<br>    }<br>  }</pre><pre>  int value = cell-&gt;data;<br>  cell-&gt;sequence.store(pos + QUEUE_SIZE, memory_order_release);</pre><pre>  return value;<br>}</pre><ul><li>We initially load the current rear index with memory_order_relaxed to find the next item to consume.</li><li>We load the cell’s sequence number with memory_order_acquire. This allows us to observe the producer&#39;s published data before reading cell-&gt;data.</li><li>We calculate the difference between the cell’s sequence number and the expected sequence for a consumer.</li><li>If the difference is <strong>zero</strong>, the cell contains valid data. We attempt to claim the position by advancing rear with compare_exchange_weak.</li><li>If the difference is <strong>negative</strong>, the cell is not yet ready for consumption, so we retry after yielding.</li><li>If the difference is <strong>positive</strong>, our position is stale, so we reload rear.</li><li>Once the consumer successfully claims the position, it reads cell-&gt;data.</li><li>Finally, it updates the sequence number using memory_order_release, publishing that the slot has been consumed and can eventually be reused by a producer.</li></ul><h4>Trace</h4><ul><li>A consumer looks at rear = 0, mapping to <strong>Index 0</strong>.</li><li>It checks the cell’s sequence and calculates dif = seq - (pos + 1).</li><li>Here, seq = 1 and pos + 1 = 1, resulting in dif = 0.</li><li>This <strong>0</strong> tells the consumer: <em>“A producer has finished writing valid data here.”</em></li><li>The consumer claims Index 0 by advancing rear to <strong>1</strong>, reads the data (<strong>42</strong>), and updates the sequence number to pos + QUEUE_SIZE (<strong>0 + 10 = 10</strong>).</li><li><strong>Index 0 now holds </strong><strong>Seq: 10.</strong></li><li>Eventually, producers and consumers loop all the way around the ring buffer. front and rear advance through the queue positions.</li><li>Suppose a producer reaches Index 0 again during cycle 1 (pos = 10).</li><li>It checks Index 0’s sequence number, which is now <strong>10</strong> because the consumer set it to pos + QUEUE_SIZE at the end of the previous cycle.</li><li>Since seq (10) == pos (10), the producer knows that the slot has been released and can proceed safely.</li><li>If the consumer had not finished reading yet, Index 0’s sequence would still be <strong>1</strong>. The producer would calculate dif = 1 - 10 = -9 (dif &lt; 0), recognizing that the slot is not yet available and retrying instead of overwriting active data.</li></ul><h3>Comparing Both Approaches</h3><p>The atomic queue appears more complicated at first glance, but it avoids mutex acquisition and blocking waits, which can reduce synchronization overhead in some workloads.</p><p>However, atomic does not automatically mean faster. Under different workloads, contention levels, thread counts, CPU architectures, and compiler optimizations, a well-designed lock-based queue can perform just as well or better.</p><p>The reason we built the lock-based queue first was to establish a baseline. Now we can compare the two approaches and see whether the additional complexity of the atomic implementation actually provides a benefit.</p><p>I ran both programs on my machine and obtained the following results:</p><pre># ./queue-lock-fixed &amp;&amp; ./queue-lock-free-fixed<br>--- Thread-safe queues with locks and condition variables ---<br>It took 37 milliseconds.<br>--- Atomic bounded MPMC queue ---<br>It took 16 milliseconds.</pre><p>The lock-based queue took approximately <strong>37 milliseconds</strong>, while the atomic queue took approximately <strong>16 milliseconds</strong>. This represents <strong>nearly a 2.3× difference in this particular benchmark</strong>, which is significant enough to make the additional complexity interesting.</p><p>However, this result should not be interpreted as “atomic queues are 2.3× faster than lock-based queues.”</p><p>The benchmark is only one workload, on one machine, under one set of conditions.</p><p>In particular, each thread immediately dequeues after enqueueing:</p><pre>queue.enqueue(i + 1, thread_id);<br>int value = queue.dequeue(thread_id);</pre><p>So the queue rarely becomes meaningfully full, and the benchmark does not represent every producer-consumer workload.</p><p>For a more meaningful comparison, it is worth running multiple iterations, discarding warm-up runs, reporting averages or distributions, and considering factors such as CPU frequency scaling, compiler optimizations, thread placement, CPU architecture, and system load.</p><p>It would also be useful to test different numbers of producers and consumers, different queue sizes, and workloads where producers and consumers operate independently.</p><p>The important point is that the benchmark gives us a reason to investigate atomic synchronization rather than simply assuming that it is faster.</p><h3>Conclusion</h3><p>The primary focus of this article was to provide an introduction to atomic operations and their support in C++. We started with basic operations such as load, store, exchange, and compare_exchange, then looked at memory ordering and finally put those concepts to work in a concurrent queue.</p><p>Looking back at the atomic queue implementation, we can appreciate how challenging it is to design such constructs correctly.</p><p>Despite the added complexity, atomic data structures can be worth the effort when profiling shows that synchronization overhead is a meaningful performance bottleneck.</p><p>That said, the standard best practice is to start with well-tested synchronization primitives, such as mutexes and condition variables, and only attempt more specialized atomic designs if profiling reveals that further optimization is necessary.</p><p>The goal isn’t to replace every mutex with an atomic operation. std::atomic gives us powerful building blocks, but using them correctly requires a good understanding of the C++ memory model and the algorithm built around them.</p><p>If you’d like to discuss this further, please feel free to comment below or connect with me on <a href="https://www.linkedin.com/in/surajkareppagol/">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=227a25cc2490" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The missing manual: Introduction to make]]></title>
            <link>https://medium.com/@surajkareppagol.dev/the-missing-manual-introduction-to-make-52f04a5ae776?source=rss-3503edd13a7b------2</link>
            <guid isPermaLink="false">https://medium.com/p/52f04a5ae776</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[gnu]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Suraj Kareppagol]]></dc:creator>
            <pubDate>Sat, 06 Jun 2026 16:44:50 GMT</pubDate>
            <atom:updated>2026-06-06T16:47:45.050Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OKeWsIjSvyGExqVAlOp1gQ.png" /><figcaption>Introduction to make</figcaption></figure><p>Make is a build tool. It is a program created to automate the build process. Note that it was not created only to use with C or C++. In this post I will explain how to use this tool.</p><p>Before we begin, create a directory and write a simple C program. Then create a file named as <strong>Makefile</strong>. Once this file is written run the make command.</p><h3>The rules and recipes</h3><p>The main building blocks of make are targets and rules to build them. Targets are the executable which needs to be built and rules are the instructions on how to build them.</p><p>Here is the example. Write the target and then put <strong>colon (:)</strong> right after that. Then put tab in the next line, then the command to build the executable. Tabs are necessary when adding the commands.</p><pre>main:<br>  gcc main.c -o main</pre><p>Lets expand this syntax. Here we have the target which is our executable, then dependencies. These are the source files or intermediate object which are needed to build the target. Then we have the recipes on the next line each prefixed with a tab.</p><pre>target: dependencies<br>  recipe</pre><p>The dependencies can be source files or other targets. Lets look at an example.</p><pre>main: a.o main.c<br>  gcc a.o main.c -o main<br><br>a.o:<br>  gcc -c a.c -o a.o</pre><p>Here we have the main rule main, which depends on a target and executable. Here we have another rule for building that target. Make will first check if there is recipe for building the target a.o, there is a recipe. Next it searches for the source file main.c, it is present. Then it builds the main executable.</p><blockquote>Please note that target name can be anything not necessarily the executable name.</blockquote><h3>Variables</h3><p>Variables are available in make which are containers to hold data. Here the variables only hold strings. Here CC and SRCS are two examples. Note that I have used the = operator to assign the values.</p><pre>CC = gcc<br>SRCS = main.c a.c</pre><p>The variables can be used directly in the recipes using the ${FOO} or $(FOO)syntax. Lets write a <strong>Makefile</strong> to create and print these variables to console.</p><pre>CC = gcc<br>SRCS = main.c<br><br>main: $(SRCS)<br>  echo $(CC) $(SRCS)<br>  gcc $(SRCS) -o main</pre><p>Here the recipes are simple console commands. The below is the console output for the above Makefile.</p><pre>echo main.c<br>main.c<br>gcc main.c -o main</pre><p>By default make prints the command which is being executed, this is really helpful while debugging. If this behavior is not needed then each command can be prefixed with a @ or just use -s, --slientor --quietoption with make command.</p><pre>main:<br>  @echo $(gcc) $(SRCS)</pre><pre>make -s</pre><p>Make by default provides some variables. There are a lot, but here are the two variables that we are going to use in later sections.</p><ul><li><strong>$@</strong>: Target file name</li><li><strong>$^</strong>: All prerequisites</li></ul><h3>Built-in Functions</h3><p>Make provides several built-in functions. We will just go through two basic functions which are wildcard and patsubst.</p><h4>Wildcard</h4><p>Suppose we have several source files and want to store the names in a variable. But writing each name is a hassle and if we delete or create a new file, each time we need to modify the variable. Instead of doing this we can use the wildcard function.</p><pre>SRCS = $(wildcard *.c)</pre><p>Lets unpack this.</p><ul><li><strong>SRCS</strong>: Variable name</li><li><strong>=</strong>: Assignment operator</li><li><strong>$()</strong>: Evaluate an expression</li><li><strong>wildcard</strong>: Wildcard function</li><li><strong>*\.c</strong>: Wildcard pattern, collect all the files that match this pattern</li></ul><p>This will populate the SRCS variable with all the source files which match the *.c wildcard pattern in the current directory. If the directory is different just prefix it, for example src/*.c.</p><h4>Pattern Substitution</h4><p>Pattern substitution makes life easier. Suppose we have several source files and these are the dependencies used to build the final executable. Now we don’t want keep writing *.o as files.</p><pre>main: a.o b.o c.o d.o e.o<br>  echo make</pre><p>Instead of doing this we can use the patsubst function. This will substitute a pattern in original source.</p><pre>$(patsubst pattern, replacement, text)</pre><p>Lets take a look at an example and unpack this.</p><pre>OBJS = $(patsubst %.c, %.o, $(SRCS))</pre><ul><li><strong>OBJS</strong>: Variable which will hold object file names</li><li><strong>patsubst</strong>: Function name</li><li><strong>%.c</strong>: Pattern to search and replace</li><li><strong>%.o</strong>: Substitution pattern</li><li><strong>$(SRCS)</strong>: Input to patsubst</li></ul><p>This function will fetch all the files which match %.c and keep the % as it is and replace the rest of the part with .o. Below is the output from the patsubst. Experiment with the parameters here to better understand it.</p><pre>a.c b.c main.c<br>a.o b.o main.o</pre><h3>Example</h3><p>Lets write a small <strong>Makefile</strong> that uses the concepts we just saw. I have 3 source files a.c, b.c and main.c. Now we need to compile these and build the final executable using make.</p><pre>SRCS = $(wildcard *.c)<br>OBJS = $(patsubst %.c, %.o, $(SRCS))<br><br>all: $(OBJS)<br>  gcc $^ -o main<br><br>%.o: %.c<br>  gcc -c $^<br><br>clean:<br>  rm *.o main</pre><p>We have two variables, we collect the source files and then we collect the object file names after using patsubst. The alltarget depends on $(OBJS), that is targets which match these dependencies.</p><p>We could write each of these target.</p><pre>a.o:<br>  gcc -c a.c<br><br>b.o:<br>  gcc -c b.c</pre><p>But these is tedious, we can again use the pattern matching here to create targets based on a specific pattern.</p><pre>%.o: %.c<br>  gcc -c $^</pre><p>Here these translates to all of the targets which match *.o pattern. Once we are done with this the all target will be created. Here we can have additional utility targets such as clean to clear the intermediate files.</p><h3>Conclusion</h3><p>These concepts are enough to get started. I will put more posts exploring more features of make. If you have any questions please leave a comment or connect with me on <a href="https://www.linkedin.com/in/surajkareppagol/">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52f04a5ae776" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Type-aware macros in C]]></title>
            <link>https://medium.com/@surajkareppagol.dev/type-aware-macros-in-c-2d08fc363d79?source=rss-3503edd13a7b------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d08fc363d79</guid>
            <category><![CDATA[c-programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[embedded-systems]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Suraj Kareppagol]]></dc:creator>
            <pubDate>Wed, 20 May 2026 14:19:05 GMT</pubDate>
            <atom:updated>2026-05-20T14:19:05.705Z</atom:updated>
            <content:encoded><![CDATA[<p>Apparently C has <em>type-aware macros</em>. Yes, you read it correctly. But what exactly are type-aware macros?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*777NmhclFlK9ZcQregqEvA.png" /><figcaption>Type-aware macros in C</figcaption></figure><blockquote>Type-aware macros in C are preprocessor macros that adapt their behavior based on the data type of their arguments.</blockquote><p>I had never used it before, didn’t even know this feature existed in C. When reading the C11 standard, I came across this feature. It is pretty powerful. Before C11 it was provided as a compiler extension, but now it is directly added into the standard itself.</p><pre>_Generic(expression, type1: result1, type2: result2, default: result3) (args)</pre><p>Here _Generic keyword is used to specify that we are going to use type-aware macro. It takes an expression to be type-checked. Then a list of type-value pairs. This type-value pair is important here we can specify what function call needs to be made based upon the type of expression. Then at the end the actual arguments these functions takes.</p><p>Note that here only one value can be type-checked not multiple values. During compilation based on the type appropriate function is substituted.</p><pre>#include &lt;stdio.h&gt;<br><br>#define ADD(x, y) _Generic((x), int: add_int, float: add_float)(x, y)<br><br>int add_int(int x, int y) { return x + y; }<br><br>float add_float(float x, float y) { return x + y; }<br><br>int main() {<br>  int a = 1, b = 1;<br>  float x = 1.0, y = 1.0;<br><br>  printf(&quot;The sum (int) is %d.\n&quot;, ADD(a, b));<br>  printf(&quot;The sum (float) is %.2f.\n&quot;, ADD(x, y));<br><br>  return 0;<br>}</pre><p>A more detailed example is given above. Here we have ADD macro and we have added two functions add_int() and add_float. Based on the arguments passed appropriate function call is made.</p><pre>The sum (int) is 2.<br>The sum (float) is 2.00.</pre><p>This is very similar to <em>templates</em> in C++ but again very limited in features. But since it is resolved during compile time this can be used in instances where we have multiple functions with same logic but with different arguments. Note that we are assuming that these are simple functions, because we need to write down all the functions and this is against the DRY (Don’t Repeat Yourself) principle.</p><p>I hope you enjoyed reading this blog. If you want to discuss further you can connect with me on <a href="https://www.linkedin.com/in/surajkareppagol/">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d08fc363d79" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Name mangling scheme in C++]]></title>
            <link>https://medium.com/@surajkareppagol.dev/name-mangling-scheme-in-c-0d86b6956eb9?source=rss-3503edd13a7b------2</link>
            <guid isPermaLink="false">https://medium.com/p/0d86b6956eb9</guid>
            <category><![CDATA[compilers]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[computer-science]]></category>
            <dc:creator><![CDATA[Suraj Kareppagol]]></dc:creator>
            <pubDate>Sat, 09 May 2026 17:28:13 GMT</pubDate>
            <atom:updated>2026-05-09T17:28:13.969Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently I explored the usage of extern &quot;C&quot; feature in C++. This allows us to tell the compiler not to mangle the names of symbols such that the program written in C++ can be used in programs written in C.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*o_CC45MkiR3Fibv7RQwLxg.png" /><figcaption>C++ Name Mangling Scheme</figcaption></figure><h3>Why name mangling is required?</h3><p>Name mangling is an essential requirement for C++ features to work as expected. Features such as <em>function overloading</em>, <em>templates</em>, <em>namespaces</em> and others. Let me explain it with an example.</p><pre>/* add is overloaded here */<br>int add(int a, int b) {<br>  return a + b;<br>}<br><br>double add(double a, double b) {<br>  return a + b;<br>}</pre><p>Here the function add is overloaded. Now if you use this function to add two numbers and then try to compile it without name mangling (via <strong>extern &quot;C&quot; </strong>feature) the<strong> linker</strong> will get confused and throw the below error.</p><pre>test.cpp:9:8: error: conflicting declaration of C function ‘double add(double, double)’<br>    9 | double add(double a, double b) { return a + b; }<br>      |        ^~~<br>test.cpp:7:5: note: previous declaration ‘int add(int, int)’<br>    7 | int add(int a, int b) { return a + b; }<br>      |     ^~~</pre><p>Now lets allow the compiler to use name mangling and see if it works. I just removed the extern &quot;C&quot; and it compiled without any issues. Now that we know the importance of name mangling, lets take a look at the scheme used to mangle C++ symbols.</p><pre>Adding two numbers (1, 2): 3</pre><blockquote>Name mangling is not used in C for Unix and Unix like systems. But this is not true for Windows as it has its own standard conventions for function calling hence it requires name mangling.</blockquote><h3>Name mangling scheme: Itanium C++ ABI</h3><p>On Unix and Unix like systems C++ follows the <strong><em>Itanium ABI</em></strong>. Now you might ask what is <strong><em>ABI (Application Binary Interface)</em></strong>? for now think of it as API equivalent for hardware. We will explore more about it in another post.</p><p>The name mangling scheme uses BNF (Backus–Naur form). BNF is a formal notation for describing <strong>context-free grammars</strong>, and the Itanium ABI specification uses it to define the mangling rules.</p><p>Let me explain BNF with an actual production. The below example here is bare minimum, the breakfast is one of the rule using which we can build up a production. Here we could replace the breakfast with the “bread” as it is one of the production. Then we replace protein with “eggs” and we got ourselves a complete sentence that somewhat makes sense.</p><p>If I could describe this in simpler terms here it is “you apply the grammar rules <strong>recursively</strong> until you reach <strong>terminal symbols</strong> (the actual characters), and that gives you the <strong>final production</strong>”, in our discussion the final production refers to the mangled name.</p><p>Please refer this <a href="https://en.wikipedia.org/wiki/Backus%E2%80%93Naur_form">link</a> to better understand this.</p><p>Here you need to know two terms <em>terminals</em> and <em>non-terminals</em>. The former refers to the rules which produce literal values, here protein and the latter refers to the rules which gives new rules. Think of this as nodes and leaves on a tree.</p><pre>breakfast -&gt; breakfast &quot;and&quot; protein;<br>breakfast -&gt; &quot;bread&quot;;<br><br>protein -&gt; &quot;eggs&quot;;</pre><p>I hope you understood that part. If yes then refer to this <a href="https://itanium-cxx-abi.github.io/cxx-abi/abi-mangling.html">table</a> here, which summarizes the encoding characters used as terminals. We will first take a look at some of the examples, then trace through an actual complex example from the <a href="https://itanium-cxx-abi.github.io/cxx-abi/abi.html"><em>Itanium ABI</em></a> documentation.</p><p>_Z1fv: lets unpack this.</p><ul><li>_Z — General prefix for all external C++ symbols</li><li>1f — Function f(), <em>&lt;number of characters&gt;&lt;function&gt;</em></li><li>v — Doesn’t take any arguments</li></ul><p>Lets look at another example, _Z3fooic .</p><ul><li>_Z — General prefix for all external C++ symbols</li><li>3foo — Function foo(), <em>&lt;number of characters&gt;&lt;function&gt;</em></li><li>i — Builtin type int</li><li>c — Builtin type char</li></ul><p>There are a lot of <a href="https://itanium-cxx-abi.github.io/cxx-abi/abi-examples.html#mangling">examples</a> in the official documentation. You can refer to those for more details. But I hope the above examples gave you some idea around it. Now lets look at an actual <em>production rule</em> and a pretty complex example around it.</p><pre>class A {<br>    void foo (int) {<br>        class B { };<br>    }<br> };<br><br>void foo () {<br>    class C {<br>        class D { };<br>        void bar () {<br>            struct E {<br>                void baz() { }<br>            };<br>        }<br>    };<br>}</pre><pre>&lt;encoding&gt; ::- &lt;name&gt;<br>           ::- &lt;local-name&gt;<br>           ::- Z &lt;function encoding&gt; E &lt;entity name&gt;<br><br>where:<br>&lt;function encoding&gt; ::- &lt;name&gt; &lt;bare-function-type&gt;<br>                    ::- &lt;nested-name&gt; &lt;bare-function-type&gt;<br>                    ...<br>                    ::- N &lt;unqualified-name&gt; &lt;unqualified-name&gt; E &lt;bare-function-type&gt;<br>                    ::- N 1A 3foo E i<br><br>&lt;entity name&gt; ::- &lt;name&gt;<br>              ::- 1B</pre><p>First consider the mangling of <strong><em>A::foo::B</em></strong>, which is the case of a simple local name (B) in a nested function.</p><ul><li>&lt;encoding&gt;— A complete mangled name</li><li>&lt;local-name&gt; — Z &lt;function encoding&gt; E &lt;entity name&gt; — represents a name local to a function</li><li>&lt;function encoding&gt; — Describes the function containing the local entity</li><li>Z and E — Delimiters: Z starts a local-name encoding, E closes scopes</li></ul><p>Walking through A::foo::B.</p><ul><li><strong>B is a local class</strong> inside A::foo(), so it uses the &lt;local-name&gt; rule.</li></ul><pre>Z &lt;function encoding&gt; E &lt;entity name&gt;</pre><ul><li>Function encoding describes A:foo() . This will be N 1A 3foo E i , refer the above examples to understand this.</li></ul><pre>N &lt;unqualified-name&gt; &lt;unqualified-name&gt; E &lt;bare-function-type&gt;</pre><ul><li><strong>The entity name</strong> is the class being defined, which will be Z N 1A 3foo E i E 1B.</li></ul><p>So the final result is<strong><em> “Z N 1A 3foo E i E 1B”</em></strong>.</p><p>There is a dedicated tool on Unix like systems which can be used to de-mangles the mangled symbols, it is c++filt.</p><blockquote>Above example is taken from the <a href="https://itanium-cxx-abi.github.io/cxx-abi/abi-examples.html#mangling">documentation</a> and used here to explain the scheme. This may not work with c++filt .</blockquote><pre>c++filt _Z3fooic<br># foo(int, char)</pre><p>I hope you enjoyed reading this post. If you have any queries or suggestions please comment and share your thoughts. You can reach out to me on <a href="https://www.linkedin.com/in/surajkareppagol/">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0d86b6956eb9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[C Library for Circuit Simulation]]></title>
            <link>https://medium.com/@surajkareppagol.dev/c-library-for-circuit-simulation-398fc28a5e13?source=rss-3503edd13a7b------2</link>
            <guid isPermaLink="false">https://medium.com/p/398fc28a5e13</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[embedded-systems]]></category>
            <category><![CDATA[simulation]]></category>
            <category><![CDATA[c-programming]]></category>
            <dc:creator><![CDATA[Suraj Kareppagol]]></dc:creator>
            <pubDate>Mon, 04 May 2026 17:17:08 GMT</pubDate>
            <atom:updated>2026-05-04T17:17:08.136Z</atom:updated>
            <content:encoded><![CDATA[<p>I recently wrote a very small C library for circuit simulation and I am writing this post to explain how this library is built, how it works and future developments plans around it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gUJBiPuox52VA7Nv35kJ0A.png" /><figcaption>C Library for circuit simulation</figcaption></figure><h3>LOGSIM: C Library for circuit simulation</h3><p>The main idea here was to implement everything as atomic blocks and then using these blocks to build circuits. There are mainly two types of blocks <em>LOGIC BLOCKS</em> and <em>DATA BLOCKS</em>. The former are the actual logic blocks such as <em>AND</em>, <em>OR</em>, <em>NOT</em>, <em>XOR</em> and latter are the data blocks associated with logic blocks.</p><p>There are some basic APIs to create these blocks and then attach them together and this can be repeated to build bigger circuits. Currently only combinational circuits can be built and setup for sequential circuits is still in progress. Lets go through a simple example building an AND block with two <em>INPUT</em> blocks and one <em>OUTPUT</em> block and explore the APIs.</p><pre>/* AND */<br><br>/* Create logic block */<br>logic_block_t *lb = logic_create_logic_block(AND, 2, 1, &quot;lb&quot;, NULL);<br><br>/* Create data block */<br>logic_data_t *input_a = logic_create_data_block(INPUT, 1);<br>logic_data_t *input_b = logic_create_data_block(INPUT, 0);<br><br>logic_data_t *output = logic_create_data_block(OUTPUT, 0);<br><br>/* Connect data block to logic block */<br>logic_block_data_connect(lb, input_a);<br>logic_block_data_connect(lb, input_b);<br><br>logic_block_data_connect(lb, output);<br><br>/* Evaluate */<br>logic_evaluate(1, lb);</pre><ul><li>logic_create_logic_block — Create a logic block based on the input parameter and create input and output streams.</li><li>logic_create_data_block — Create data block either INPUT or OUTPUT</li><li>logic_block_data_connect — Connect logic block with data block</li><li>logic_block_block_connect — Connect logic block with another logic block</li><li>logic_evaluate — Evaluate all the logic gates</li></ul><p>These are the only APIs currently required to build the circuits via stacking multiple logic gates together. Here is the full adder circuit created using these APIs.</p><pre>/*<br> *                 XOR<br> * A -------------|===|<br> *            |   | 5 |-----------|<br> * B ----|----|---|===|   |       |            XOR<br> *       |    |           |       |-----------|===|<br> *       |    |           |                   | 2 |----- SUM<br> * C ---------------------|-------------------|===|<br> *       |    |           |       |<br> *       |    |           |       |            AND<br> *       |    |           |       |-----------|===|<br> *       |    |           |                   | 3 |-----      OR<br> *       |    |           |-------------------|===|    |     |===|<br> *       |    |                                        |-----| 1 |--- CARRY<br> *       |    |                                AND     |     |===|<br> *       |    |                               |===|    |<br> *       |    |-------------------------------| 4 |-----<br> *       |------------------------------------|===|<br> */<br><br>/************************ Create 6 logic blocks ************************/<br><br>logic_block_t *lb_1 = logic_create_logic_block(OR, 2, 1, &quot;lb_1&quot;, &quot;CARRY&quot;);<br>logic_block_t *lb_2 = logic_create_logic_block(XOR, 2, 1, &quot;lb_2&quot;, &quot;SUM&quot;);<br>logic_block_t *lb_3 = logic_create_logic_block(AND, 2, 1, &quot;lb_3&quot;, NULL);<br>logic_block_t *lb_4 = logic_create_logic_block(AND, 2, 1, &quot;lb_4&quot;, NULL);<br>logic_block_t *lb_5 = logic_create_logic_block(XOR, 2, 1, &quot;lb_5&quot;, NULL);<br><br>/************************ Create 6 input blocks ************************/<br><br>logic_data_t *lb_i_5_1 = logic_create_data_block(INPUT, 1);<br>logic_data_t *lb_i_5_2 = logic_create_data_block(INPUT, 0);<br><br>logic_data_t *lb_i_4_1 = logic_create_data_block(INPUT, 1);<br>logic_data_t *lb_i_4_2 = logic_create_data_block(INPUT, 0);<br><br>logic_data_t *lb_i_2_2 = logic_create_data_block(INPUT, 0);<br><br>logic_data_t *lb_i_3_1 = logic_create_data_block(INPUT, 0);<br><br>/************************ Create 3 output blocks ************************/<br><br>logic_data_t *lb_o_1_1 = logic_create_data_block(OUTPUT, 0);<br>logic_data_t *lb_o_2_1 = logic_create_data_block(OUTPUT, 0);<br>logic_data_t *lb_o_3_1 = logic_create_data_block(OUTPUT, 0);<br>logic_data_t *lb_o_4_1 = logic_create_data_block(OUTPUT, 0);<br>logic_data_t *lb_o_5_1 = logic_create_data_block(OUTPUT, 0);<br><br>/************************ Connections ************************/<br><br>/* Connections for block 1 */<br>logic_block_block_connect(lb_1, lb_3);<br>logic_block_block_connect(lb_1, lb_4);<br><br>logic_block_data_connect(lb_1, lb_o_1_1);<br><br>/* Connections for block 2 */<br>logic_block_block_connect(lb_2, lb_5);<br>logic_block_data_connect(lb_2, lb_i_2_2);<br><br>logic_block_data_connect(lb_2, lb_o_2_1);<br><br>/* Connections for block 3 */<br>logic_block_data_connect(lb_3, lb_i_3_1);<br>logic_block_block_connect(lb_3, lb_5);<br><br>logic_block_data_connect(lb_3, lb_o_3_1);<br><br>/* Connections for block 4 */<br>logic_block_data_connect(lb_4, lb_i_4_1);<br>logic_block_data_connect(lb_4, lb_i_4_2);<br><br>logic_block_data_connect(lb_4, lb_o_4_1);<br><br>/* Connections for block 5 */<br>logic_block_data_connect(lb_5, lb_i_5_1);<br>logic_block_data_connect(lb_5, lb_i_5_2);<br><br>logic_block_data_connect(lb_5, lb_o_5_1);<br><br>/************************ Evaluate ************************/<br><br>logic_evaluate(2, lb_1, lb_2);</pre><p>Here the logic_evaluate function is interesting, because here we need to pass all the logic blocks which will have the end output signal. In the above example it is SUM and CARRY.</p><p>The evaluation happens in the logic_evaluate_single_block function. This one starts from the output blocks that we passed and recursively calculates the output signal for all blocks and covers the entire circuit. At this time it is okay to use this recursive approach for small circuits, but higher level circuits it is not the best implementation for evaluation.</p><p>I have also integrated <em>GrpahViz </em>such that circuit diagram will also be automatically generated, although these are not accurate. To compensate this I am working on CGraph a C library to generate circuit diagrams programmatically.</p><p>Although this was fun building but it seriously lacks many features. Going forward I am planning to add support for sequential circuits, a main loop, and exporting the circuits into reusable modules. I will keep posting updates on this here.</p><p>The complete source for this can be found here on <a href="https://github.com/surajkareppagol/logsim">GitHub</a>.</p><p>I hope you enjoyed reading this post. If you have any queries or suggestions please comment and share your thoughts. You can reach out to me on <a href="https://www.linkedin.com/in/surajkareppagol/">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=398fc28a5e13" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[QEMU: The Beginnings]]></title>
            <link>https://medium.com/@surajkareppagol.dev/qemu-the-beginnings-67d5906ca8a8?source=rss-3503edd13a7b------2</link>
            <guid isPermaLink="false">https://medium.com/p/67d5906ca8a8</guid>
            <category><![CDATA[qemu]]></category>
            <category><![CDATA[c-programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[virtualization]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Suraj Kareppagol]]></dc:creator>
            <pubDate>Fri, 01 May 2026 17:43:03 GMT</pubDate>
            <atom:updated>2026-05-01T17:43:03.388Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*rRQfkdcnBAfAkE4wt_TzDg.png" /><figcaption>QEMU Logo</figcaption></figure><p>QEMU (Quick Emulator) is an amazing piece of software that allows to run multiple different guest OS on top of host OS. But when using it as a CLI it might be intimidating. Lets go through from scratch, build QEMU from source and we will run alpine OS on top Linux Mint.</p><h3>Building QEMU from source</h3><p>QEMU has several <a href="https://www.qemu.org/download/">releases</a> and at the time of this post <strong>QEMU 11.0.0</strong> is released so lets use it. Follow the below steps to download and build it from source. Also you can directly get these steps from the download page.</p><pre>wget https://download.qemu.org/qemu-11.0.0.tar.xz<br>tar xvJf qemu-11.0.0.tar.xz<br>cd qemu-11.0.0</pre><p>The above commands are used to download the tar file and extract it. Once extracted, we will cd into the extracted directory.</p><pre>sudo apt install make cmake gcc ninja-build meson libglib2.0-dev libgtk2.0-dev</pre><p>Before configuring the build lets make sure we have everything installed. This is on Linux Mint and if you are using other distributions such as Fedora then the package names might change.</p><p>Now once we are in the extracted directory we will create a build directory such that we don’t pollute the source.</p><pre>mkdir build<br>cd build</pre><p>Lets configure the build. QEMU is very flexible when it comes to configuration, with the --help argument you will see a very large set of options to choose.</p><pre>../configuration --help</pre><p>Currently we will stick to just two options, --target-list=x86_64-softmmu and --enable-gtk. The former option will allow us to emulate full x86_64 systems and later will allows us to have a GUI window for the virtual machine.</p><pre>../configure --target-list=x86_64-softmmu --enable-gtk</pre><p>Once completed we will run the below two commands to build all the binaries and install them system wide.</p><pre>make -j 4<br>sudo make install</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T6eyN-nu4xbblzUiJPmZ8g.png" /><figcaption>Building QEMU from source</figcaption></figure><h3>Using QEMU CLI</h3><p>Before we start using QEMU CLI we will download the alpine OS . It is a lightweight OS and we will be able to quickly <a href="https://alpinelinux.org/downloads/">download</a> and use it. You can download it from official page or use the below command.</p><pre>wget https://dl-cdn.alpinelinux.org/alpine/v3.23/releases/x86_64/alpine-standard-3.23.4-x86_64.iso</pre><p>Using QEMU is similar to using a real system. We need explicitly configure all the options such as RAM, CPU Cores, Disk Image and others. Here Disk Image is important because the OS will be installed into it and at later this will be used to boot. For this particular requirement it provides qemu-img. Using this we can create a disk image of desired size and will pass it to the CLI such that OS can be installed and can be used later.</p><pre>qemu-img create -f qcow2 alpine.qcow2 2G</pre><pre>qemu-system-x86_64 \<br>  -cdrom alpine-standard-3.23.4-x86_64.iso \<br>  -hda alpine.img \<br>  -boot d \<br>  -m 4096 \<br>  -smp 4 \<br>  -display gtk</pre><p>Lets unpack this command.</p><ul><li>-cdrom — Attaches the ISO image</li><li>-hda — Attaches the empty disk for installation</li><li>-boot d — Boots from CD-ROM first</li><li>-m 4096 — Allocates 4 GB RAM</li><li>-smp 4 — Allocates 4 CPU cores</li><li>-display gtk — Opens a graphical window</li></ul><p>These commands are enough to get started. Once you install the OS and want to launch QEMU again use the below command. This time it boots from the disk image.</p><pre>qemu-system-x86_64 \<br>  -hda alpine.img \<br>  -boot c\<br>  -m 4096 \<br>  -smp 4 \<br>  -display gtk</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PpugYWsFZUsfQwMLyeIGWA.png" /><figcaption>Alpine as Guest OS</figcaption></figure><p>This was just an introduction to the world of QEMU. In the upcoming post I will explore more concepts both on how to use it and the related tools and how it works internally.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=67d5906ca8a8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[extern “C”: Use C++ with C]]></title>
            <link>https://medium.com/@surajkareppagol.dev/extern-c-use-c-with-c-1630a3e2bb85?source=rss-3503edd13a7b------2</link>
            <guid isPermaLink="false">https://medium.com/p/1630a3e2bb85</guid>
            <category><![CDATA[c-programming]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Suraj Kareppagol]]></dc:creator>
            <pubDate>Wed, 29 Apr 2026 03:21:34 GMT</pubDate>
            <atom:updated>2026-04-29T03:21:34.331Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*OtGS_59SXdBN8Ra4Z1H4_Q.png" /><figcaption>extern “C”</figcaption></figure><p>I recently started working with QEMU and there was a requirement for me to use gRPC. If you know gRPC, you would know that the protoc supports C++ and other languages except C. Yes, we do have protobuf-c-compiler to use C instead of these other target languages. But that seemed deprecated and I wanted to stick to C++.</p><p>Had to make sure that QEMU which is a massive C project, should be able to call the C++ functions from gRPC client. To resolve this issue I had to use the extern &quot;C&quot; feature.</p><p>To understand this lets take a look at below simple C program which has an add function. Lets compile this into an executable via the gcc command.</p><pre>#include &lt;stdio.h&gt;<br><br>int add(int a, int b) { return a + b; }<br><br>int main() {<br>  printf(&quot;%d\n&quot;, add(1, 2));<br>  return 0;<br>}</pre><pre>gcc test_c.c -o test_c</pre><p>Using nm command lets look for the add symbol. The symbol name is identical to the function name.</p><pre>nm test_c | grep add<br># 0000000000001149 T add</pre><p>Take a look at the same program but written in C++ and compiled with the command g++ .</p><pre>#include &lt;iostream&gt;<br><br>using namespace std;<br><br>int add(int a, int b) { return a + b; }<br><br>int main() {<br>  cout &lt;&lt; add(1, 2) &lt;&lt; endl;<br>  return 0;<br>}</pre><pre>g++ test_cpp.c -o test_cpp</pre><p>Again lets take a look at add symbol using the nm command.</p><pre>nm test_cpp | grep add<br># 0000000000001169 T _Z3addii</pre><p>The function name is not identical to the one used in the program, this is because by default C++ compiler mangles the names of the functions. This is to support C++ features such as function overloading, templates and others.</p><p>Now coming to the main topic extern &quot;C&quot;. Lets wrap the C++ program inside this and recompile the C++ program again via g++ and take a look at the add symbol using the nm command.</p><pre>#include &lt;iostream&gt;<br><br>using namespace std;<br><br>extern &quot;C&quot; {<br>  int add(int a, int b) { return a + b; }<br>}<br><br>int main() {<br>  cout &lt;&lt; add(1, 2) &lt;&lt; endl;<br>  return 0;<br>}</pre><pre>g++ test_cpp.cpp -o test_cpp</pre><pre>nm test_cpp | grep add<br># 0000000000001169 T add</pre><p>The function name is now identical to the way it was declared in the program. This is great, because when linking C programs the linker uses the same name as they are defined in the program. But if the previous mangled version was used linker would throw errors such as _Z3addi function not defined because the linker doesn’t know that this is the same function.</p><p>To make this work we use extern &quot;C&quot; . This tells the C++ compiler to treat the function under this as C functions and not to mangle the names in the compiled executable and object files such that these can be used with C programs.</p><p>This is a very powerful feature, but this feature can’t be used with some C++ specific features such as templates and others. It would be interesting to see how name mangling works and how the linker when linking C++ files works with these. I will explore these in the next post.</p><p>Coming to the issue I was facing, using this feature got the object files for the gRPC client and started using it inside QEMU.</p><p>If you have some interesting topics and questions please do put a comment and also if you have any suggestions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1630a3e2bb85" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Linux Commands From Scratch  clear Command]]></title>
            <link>https://medium.com/@surajkareppagol.dev/building-linux-commands-from-scratch-clear-command-85b044e92c9d?source=rss-3503edd13a7b------2</link>
            <guid isPermaLink="false">https://medium.com/p/85b044e92c9d</guid>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[commands]]></category>
            <category><![CDATA[command-line]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[c-programming]]></category>
            <dc:creator><![CDATA[Suraj Kareppagol]]></dc:creator>
            <pubDate>Sat, 30 Mar 2024 12:54:38 GMT</pubDate>
            <atom:updated>2024-03-30T12:57:14.005Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mvRiQZnl80936z34kA6AyA.jpeg" /><figcaption>Building Linux Commands From Scratch 🐧 clear Command</figcaption></figure><p>Here i am building <strong><em>clear</em></strong> command from scratch in C/C++. The clear command is used to <strong><em>clear</em></strong><em> the terminal screen.</em></p><p>This command can be implemented in many ways. Here are some of the methods.</p><pre>#include &lt;stdio.h&gt;<br>#include &lt;sys/ioctl.h&gt;<br>#include &lt;unistd.h&gt;<br><br>int main()<br>{<br>  // Get Terminal Size<br><br>  struct winsize w;<br>  ioctl(STDOUT_FILENO, TIOCGWINSZ, &amp;w);<br><br>  // printf(&quot;%d %d\n&quot;, w.ws_row, w.ws_col);<br><br>  for (int i = 0; i &lt; w.ws_row + 40; i++)<br>    printf(&quot;\n&quot;);<br><br>  printf(&quot;\033[0;0H&quot;);<br><br>  return 0;<br>}</pre><pre>struct winsize w;</pre><p>Here <strong>winsize</strong> is a structure that has <strong>ws_row</strong>, <strong>ws_col</strong> as members. This can be populated using <strong><em>ioctl()</em></strong>.</p><pre>ioctl(STDOUT_FILENO, TIOCGWINSZ, &amp;w);</pre><pre>int ioctl(int __fd, unsigned long __request, …);</pre><p>This is the function prototype of the <strong><em>ioctl()</em></strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S7hIY58w3i-6yMCFGcGDmA.png" /></figure><p>Here we will print <strong>“\n” </strong>for <strong><em>Terminal Rows + 40</em></strong> times. This will although works but the prompt will be moved to the bottom. However <em>ASCII</em> <em>sequence</em> <strong><em>“&lt;esp&gt;[m;hH”</em></strong> can be used to move the cursor to the top left of the terminal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-jYZgtihRrey96zCm99j_w.png" /></figure><pre>printf(&quot;\033[0;0H&quot;);</pre><p>This will move the cursor back to the top left of the terminal.</p><p>This is will work exactly like clear command, but there is another <em>ASCII sequence</em> that will directly clear the terminal screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kBisTqWOMBcIY5VRznlA8A.png" /></figure><pre>printf(&quot;\033c&quot;);</pre><p>This is another method for writing the clear command and an easy one (just one line to clear the screen).</p><pre>#include &lt;stdio.h&gt;<br><br>int main()<br>{<br>  printf(&quot;\033c&quot;);<br><br>  return 0;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BqIH33Fu7RRunQ4ZCsuuzw.png" /></figure><p>Also instead of loop and ASCII sequence, the ASCII sequence also works just fine.</p><pre>#include &lt;stdio.h&gt;<br><br>int main()<br>{<br>  printf(&quot;\033[0;0H&quot;);<br><br>  return 0;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eXGn3K1l0AB_wt0x82dKGQ.png" /></figure><p>The code can be found at <a href="https://github.com/surajkareppagol/Linux-Commands">GitHub</a>.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FPYXfm5FCeBE%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DPYXfm5FCeBE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FPYXfm5FCeBE%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/8f6db3da4f11c943595edc1dce00b9ee/href">https://medium.com/media/8f6db3da4f11c943595edc1dce00b9ee/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=85b044e92c9d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>