<?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" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ Jayant Chowdhary - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ Jayant Chowdhary - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Tue, 26 May 2026 10:36:20 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/author/jayantc11/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How to Design and Build Sustainable Software ]]>
                </title>
                <description>
                    <![CDATA[ Electronic devices that run software are all around us. Your mobile phone, your car, your microwave, and virtually anything around you – there’s a very good chance that they have electronic components running some form of software. These devices inev... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/design-and-build-sustainable-software/</link>
                <guid isPermaLink="false">66b99d6465fc624db0255e0b</guid>
                
                    <category>
                        <![CDATA[ MathJax ]]>
                    </category>
                
                    <category>
                        <![CDATA[ software architecture ]]>
                    </category>
                
                    <category>
                        <![CDATA[ sustainability ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Jayant Chowdhary ]]>
                </dc:creator>
                <pubDate>Thu, 18 Jan 2024 01:28:38 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/01/Cover-4.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Electronic devices that run software are all around us. Your mobile phone, your car, your microwave, and virtually anything around you – there’s a very good chance that they have electronic components running some form of software.</p>
<p>These devices inevitably use power and have batteries and circuits, which degrade over time. As time passes, these devices get replaced by newer upgraded ones. But this also means that more and more electronic waste builds up on our planet. </p>
<p>Also, since we have more electronic devices entering our ecosystem every day, we’re also using more power, leading to more carbon emissions. </p>
<p>This means we need to design both hardware and software in a way which acknowledges that the earth’s resources are limited. This article will give you an introduction on how you can architect your software for sustainability. </p>
<h3 id="heading-here-is-what-well-cover">Here is what we'll cover:</h3>
<ul>
    <li><a href="#prerequisites">Prerequisites</a> </li>
    <li><a href="#whyarewethinkingaboutthisnow">Why are we thinking about this now?</a> </li>
    <li><a href="#whatsinvolvedinarchitectingandprogrammingforsustainability">What's involved in architecting and programming for sustainability?</a></li>
    <li><a href="#profileyoursoftwareforpowerandenergyconsumption">Profile your software for power and energy consumption</a>
    <ul><li><a href="#energydelayproductedt">Energy Delay Product</a></li></ul>
    <ul><li><a href="#greenuppowerupandspeedup">Greenup, Powerup and Speedup</a></li></ul>
    <ul><li><a href="#toolsforprofiling">Tools for Profiling</a></li></ul></li>
    <li><a href="#softwaretechniquesanddesignpatternsforsustainability">Software Techniques and Design Patterns for Sustainability</a>

   <ul><li><a href="#considerwhichprogramminglanguagetouse"> Consider which programming language to use </a></li></ul>
   <ul><li><a href="#makesoftwarepowerawarereacttothermalevents">Make software Power aware: React to Thermal events </a></li></ul>

    <ul><li><a href="#whenappropriateuselowpowerstatesonhardware"> When appropriate use low power states on hardware </a></li></ul>
    <ul><li><a href="#investigatethetradeoffsbetweeninterruptdrivenioandpolling"> Investigate the tradeoffs between Interrupt driven I/O and Polling </a></li></ul>
     <ul><li><a href="#lookintocaching"> Look into Caching </a></li></ul>
     <ul><li><a href="#designsoftwarewithlifetimeandupdatabilityinmind"> Design software with lifetime and updatability in mind</a></li></ul></li>
     <li><a href="#conclusion">Conclusion</a>
    </li>
</ul>

<p>##Prerequisites</p>
<p>I wrote this article with a focus on general ideas in computer science. This <a target="_blank" href="http://wla.berkeley.edu/~ee42/sp01/LectNotes/Lect6.PDF">lecture</a> will help with some background on Power and Energy in electrical circuits. </p>
<p>Other parts of this article provide references wherever you might need some background.</p>
<h2 id="heading-why-are-we-thinking-about-this-now">Why Are We Thinking About this Now?</h2>
<p><a target="_blank" href="https://climate.nasa.gov/scientific-consensus/">Human made climate change</a> has been steadily accelerating for decades. Carbon emissions have been rising. As a part of the technology community, we can help reduce some factors which have been contributing towards the degradation of the earth’s environment. </p>
<p>In this article I will present a few ideas and techniques on how you as a programmer and a software architect can make choices which will lead to more sustainable technology.</p>
<h2 id="heading-whats-involved-in-architecting-and-programming-for-sustainability">What's Involved in Architecting and Programming for Sustainability?</h2>
<p>In the context of this article, when I describe architecting software and programming for sustainability, I’m referring to the following aims: </p>
<p>Designing software so that it:</p>
<ol>
<li>Consumes the smallest amount of energy possible, to get the task at hand done.</li>
<li>Results in the least amount of battery degradation possible, while maintaining the minimum amount of performance needed for the task.</li>
<li>Needs a minimum amount of cooling for the hardware that it is running on.</li>
<li>Results in devices lasting longer.</li>
</ol>
<p>You’ll see that the techniques we'll discuss here all have the same theme behind them: make electronic hardware do the minimum amount of work possible to complete the task at hand. </p>
<p>Let's start with some techniques that you can use to accomplish this while architecting and writing software.</p>
<p>##Profile Your Software for Power and Energy Consumption</p>
<p>A problem which cannot be measured, cannot be solved. As a result, measuring the energy and power consumption of software is one of the most important tasks we need to do when designing with sustainability in mind. </p>
<p>Let’s take a step back and cover some of the basics of power and energy. </p>
<p>As you may know, power is the rate at which energy is consumed. That is:</p>
<p>$$P = dE/dt$$</p><p>In continuous time domain, we could also say that:</p>
<p>$$Energy = \int_{0}^{t} P \,dt$$</p><p>Practically, we never really get power measurements in the continous time domain. We usually have discrete power measurements over an interval of time. So our Power vs time graph might look something like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/image-94.png" alt="Image" width="600" height="400" loading="lazy">
<em>Figure 1: Power vs time and computing energy consumption</em></p>
<p>Since we have <code>n</code> discrete Power measurements over time, the energy consumption can be estimated as the area under the curve. This can be modeled as the sum of <code>n-1</code>  trapezoids.</p>
<p> (Energy = \sum_{i=1}^{n-1} A^{i}) where  (A^{i}) is the area of the ith trapezoid.</p>
<p>Profiling software for energy consumption refers to the process of measuring the energy consumed by the software being run.</p>
<p>So should you be profiling power or energy ? The answer is – it depends. In some scenarios which involve heavy user interaction (where the user controls the amount of time spent), it makes more sense to measure power. </p>
<p>For example: When a user is watching a video on a laptop or a mobile phone, they control many things such as the duration of the video watched, the screen’s brigthness, speaker volume, and so on. </p>
<p>In other scenarios where the user doesn’t have as much control over the work being performed by the electronic device, it makes sense for energy to be profiled. An example of such a case might be the energy needed to send a message via SMS / IP messaging service (not counting the energy needed to type out the message).</p>
<p>Let's look at some common metrics for profiling energy consumption next.</p>
<p>###Energy Delay Product (EDT)</p>
<p>Used in the research paper <a target="_blank" href="https://discovery.ucl.ac.uk/id/eprint/10074516/1/GKLS18_MSR18.pdf">What are your programming language's Energy delay implications?</a>, the energy delay product is a weighted metric which is defined as follows:</p>
<p> $$EDT = E *  T^{w}$$</p>
<p>where E is the Energy consumption for the task and T is the time taken for the task to be completed.</p>
<p>This metric aims to give us a measure of how much energy an operation takes, while at the same time penalizing the metric for the amount of time taken. That is, an operation consuming the same amount of energy but taking longer to perform by a system, has a higher EDT and is therefore considered less energy efficient.</p>
<p>The weight <code>w</code> can be chosen to be:</p>
<ul>
<li>1: When energy efficiency is of major concern</li>
<li>2: When both energy and performance are important</li>
<li>3: When performance is more important than energy efficiency </li>
</ul>
<p>So, you can tailor <code>w</code> to give you an idea of your software system’s energy and performance, based on indicators fit for your use case – whether energy is more important or performance.</p>
<h3 id="heading-greenup-powerup-and-speedup">Greenup, Powerup, and SpeedUp</h3>
<p>In the thesis <a target="_blank" href="https://digital.library.txst.edu/items/e8174fcc-4799-4612-88ad-5e3b7e3c3efb">Using the Greenup, Powerup And Speedup Metrics To Evaluate Software Energy Efficiency</a>, AbdulSalam et al introduced new metrics to measure energy efficiency. </p>
<p>They saw that EDT had one shortcoming: since it was a product of two quantities (Energy and weighted time taken to complete the task at hand), it was possible that two systems which had the same EDT for a task, actually differed when it came to energy efficiency and performance - but their EDT was still the same. </p>
<p>As a result, it was hard to conclude which system was better from an energy + performance point of view, where energy and performance had equal importance.</p>
<p>They introduced 3 metrics to address this issue.</p>
<ol>
<li><strong>Speedup</strong>, which is defined as:</li>
</ol>
<p>$$Speedup = T_{base} / T_{opt}$$</p><p>where (T<em>{base}) = Time taken to complete the task for the unoptimized case, (T</em>{opt}) = Time to complete the task for the optimized case. </p>
<p>If the optimized case is more performant than the unoptimized case (since remember, we could be optimizing for only energy, only performance, or both) then Speedup &gt; 1.</p>
<ol start="2">
<li><p><strong>Greenup</strong>, which is defined as:</p>
<p>$$Greenup = Energy_{base} / Energy_{opt} = P_{base} * T_{base} / P_{opt} * T_{opt}$$</p><p>. </p>
</li>
</ol>
<p>Here (P<em>{base}) is the average power consumed by the task in the unoptimized case and similarly, (P</em>{opt}) is the average power consumed by the task in the unoptimized case.</p>
<p>If we look at different values of Speedup and Powerup, they can fall into the following categories:</p>
<ol>
<li><strong>Zone 1</strong>: Powerup &lt; 1 and Speedup &lt; 1 and Speedup &gt; Powerup – in this scenario, the optimized solution sacrificed some performance, but there was a greater power reduction. As a result Greenup  &gt; 1, so there are energy savings.</li>
<li><strong>Zone 2</strong>: Powerup &lt; 1, Speedup &gt; 1 – in this scenario, the optimized solution improved in performance and at the same time, reduced power consumption. As a result, energy consumption decreased and performance improved. This is the best case scenario for any optimization.</li>
<li><strong>Zone 3</strong>: Powerup &gt; 1, Speedup &gt; 1 and Speedup &gt; Powerup – in this case, average power consumption improved, but the speedup more than made up for the increase in power consumption. As a result, energy consumed still reduced between the optimized and unoptimized solutions.</li>
<li><strong>Zone 4</strong>: Powerup &gt; 1, Speedup &gt; 1 and Powerup &gt; Speedup – in this case, power consumption decreased, but so did performance. Still, the energy consumption as a whole increased since the loss of performance was greater than the power savings.</li>
<li><strong>Zone 5</strong>: Powerup &gt; 1, Speedup &lt; 1 – in this case, the energy consumption increased since there was a performance degradation and also there was an increase in power consumption.</li>
<li><strong>Zone 6</strong>: Powerup &lt; 1, Speedup &lt; 1, Powerup &gt; Speedup – in this case, performance improved, but power increased more than the amount that performance improved. As a result, the energy consumption increased as a whole.</li>
</ol>
<p>The figure below (inspired by this <a target="_blank" href="https://digital.library.txst.edu/items/e8174fcc-4799-4612-88ad-5e3b7e3c3efb">thesis)</a> shows the zones where energy consumption increases and where it decreases. The red (4, 5 and 6) and the green areas (1, 2 and 3) depict these zones.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/image-90.png" alt="Image" width="600" height="400" loading="lazy">
<em>Figure 2 : The different zones for Speedup and Powerup</em></p>
<p>We went over a couple of metrics which both have their strengths and weaknesses. EDT’s strength is that you can give more weightage to performance. But its weakness is that many a time, it may not tell you whether one solution is really better than the other. </p>
<p>While knowing about energy consumption is very important, you should not ignore power consumption. High power consumption, amongst other effects, can have adverse thermal impacts on electronic devices. That is, your device’s skin and component temperature can increase. This may lead to: </p>
<ol>
<li><strong>Component damage</strong>: Electronic components such as memory, wires, and capacitors on your device can get damaged as temperature increases.</li>
<li><strong>Battery damage</strong>: Batteries can get damaged at higher temperatures. Their <a target="_blank" href="https://www.intercel.eu/frequently-asked-questions/temperature-effects-on-batteries/#:~:text=Battery%20capacity%20is%20reduced%20by,%2C%20AGM%2C%20industrial%20or%20whatever.">life</a> may decrease and in some extreme cases they may also <a target="_blank" href="https://www.sciencedirect.com/science/article/pii/S2215098618310000">explode</a>.</li>
</ol>
<p>Commercial electronics are usually built to operate within a 0 - 70 degrees Celsius temperature range. But for mobile phones it is usually recommended that the operating temperature not exceed 35 degrees celsius. </p>
<p>Before you profile the energy and power being consumed by a specific task on your devices, it's important to isolate the task as much as possible. </p>
<p>By this, I mean that its important that we take out as many other power consuming tasks or variables. These may be other services / daemons or settings on the device which may affect the power consumed in unreliable ways. </p>
<p><strong>For example</strong>, if the device uses the internet, background processes may be doing some activities which may vary between multiple profile runs, so in general it is a good idea to switch off the internet (unless the task being measured uses the internet). We want to do this since we want reproducible power profiling numbers from run to run. </p>
<p>So in general, it is a good idea to make a checklist of the conditions which need to be constant for power profiling to be reliable and reproducible. This could vary from system to system.</p>
<p>##Tools for Profiling</p>
<p>Now, let's talk about how power can be profiled. Different systems may offer different ways of profiling energy consumed. </p>
<p>Depending on the operating system and the underlying hardware, there are a few options. I won’t go into details of these tools since there are many options and there is also good documentation available on their official websites. </p>
<p>###Linux</p>
<ol>
<li><a target="_blank" href="https://manpages.ubuntu.com/manpages/xenial/man8/powerstat.8.html">PowerStat</a> is a tool that can measure power consumption on Intel hardware that supports the <a target="_blank" href="https://sustainable-computing.io/design/kepler-energy-sources/#:~:text=Intel's%20Running%20Average%20Power%20Limit,versions%20of%20Intel's%20processing%20architecture.">RAPL</a> (Running  average power limit) interface.</li>
<li><a target="_blank" href="https://github.com/sosy-lab/cpu-energy-meter/blob/main/README.md">Cpu-energy-meter</a> is a tool that measures the energy consumed by CPUs in a given time period.</li>
<li><a target="_blank" href="https://www.intel.com/content/www/us/en/developer/articles/tool/powertop-primer.html">Powertop</a> is a tool authored by Intel which gives you information about many things of interest such as power consumption, CPU <a target="_blank" href="https://www.intel.com/content/www/us/en/docs/socwatch/user-guide/2020/c-state.html#:~:text=C%2DState%20residencies%20are%20collected,the%20processor%20is%20%22idle%22.">C / P States</a>, CPU usage, and file system operations per second (and so on).</li>
</ol>
<p>###macOS</p>
<ol>
<li><a target="_blank" href="https://www.intel.com/content/www/us/en/developer/articles/tool/power-gadget.html">Intel power gadget</a> is a tool authored by Intel which gives users the ability to monitor power consumption, CPU frequency, CPU utilization, and even temperature on Intel based Mac machines. Note: According to Intel’s website, Power gadget will not get updates anymore and it recommends using <a target="_blank" href="https://www.intel.com/content/www/us/en/developer/articles/tool/performance-counter-monitor.html">Intel Performance Counter</a> instead.</li>
<li><a target="_blank" href="https://www.seense.com/menubarstats/mxpg/">MxPower Gadget</a> is a tool similar to the Intel power gadget, but for Apple silicon-based Macs.</li>
<li><a target="_blank" href="https://developer.apple.com/library/archive/documentation/Performance/Conceptual/power_efficiency_guidelines_osx/MonitoringEnergyUsage.html">Powermetrics</a> is a <a target="_blank" href="https://firefox-source-docs.mozilla.org/performance/powermetrics.html">command line tool</a> that is pre-installed on Apple Silicon and Intel-based machines. It helps you obtain power measurements for CPU and GPU operation.</li>
<li><a target="_blank" href="https://developer.apple.com/library/archive/documentation/Performance/Conceptual/power_efficiency_guidelines_osx/MonitoringEnergyUsage.html">The Activity Monitor App</a> is pre-installed on Macs, and gives you an overview of how your app is performing. It also gives you an overview of various metrics about your Mac. While it doesn’t give you power numbers, it is still a useful tool.</li>
</ol>
<p>###Android</p>
<p>The <a target="_blank" href="https://source.android.com/">AOSP</a> (Android Open Source Project) official documentation provides some guidelines on how to measure system component power <a target="_blank" href="https://source.android.com/docs/core/power/component">here</a>. This process may vary depending on the manufacturer of the device.</p>
<p>Android Studio, Android’s official development IDE also offers a <a target="_blank" href="https://developer.android.com/studio/profile/power-profiler">Power Profiler</a> to measure power. The On-Device Power Monitor (ODPM) reports power consumed by all profilable sub-systems through their power rails. Note: These measurements are not specific to any app, as they measure device power on the whole.</p>
<p>###iOS</p>
<p>During iOS app development, developers can measure the energy impact of their app using XCode’s inbuilt <a target="_blank" href="https://developer.apple.com/library/archive/documentation/Performance/Conceptual/EnergyGuide-iOS/MonitorEnergyWithInstruments.html">Instruments</a> profiler.</p>
<p>We talked about various ways to profile power and energy in this section. In the coming sections, I'll discuss some techniques and considerations to keep in mind to make your software more sustainable.</p>
<p>##Software Techniques and Design Patterns for Sustainability</p>
<p>###Consider which programming language to use</p>
<p>Programming languages have multiple levels of abstraction over the hardware that they are running on. Some have a model of the machine presented to the programmer which is really close to the actual hardware they are running on.</p>
<p>Languages which are directly compiled to machine code are generally more power efficient. They also are generally more performant, since there is less overhead compared to languages which are interpreted or run on a virtual machine, such as Java. </p>
<p>The research paper I mentioned earlier (<a target="_blank" href="https://discovery.ucl.ac.uk/id/eprint/10074516/1/GKLS18_MSR18.pdf">What are your programming language's Energy delay implications</a>) discusses this in detail and is a great read. </p>
<p>While many popular operating systems have the majority of their APIs in languages like Java, Kotlin, and Swift (which are not native), they usually have performance critical APIs available in native code as well – for example, Android’s <code>C</code> interface-based <a target="_blank" href="https://developer.android.com/ndk">NDK</a> library. These can interface with their virtual machine-run counterparts and in combination be used to write efficient applications.</p>
<p>###Make software power aware: React to thermal events</p>
<p>In the previous section, I talked about the importance of keeping power consumption low on the devices which run your software. This is not only important to reduce energy consumption, it's also important so that your device’s operating temperature doesn’t go into territory which can damage your device. </p>
<p>The operating temperature of your device doesn’t only depend on the software running on it (which includes your software). It also depends on the ambient temperature. </p>
<p>For example: if a smartphone is used in a car on a hot day, there’s a good chance that when a demanding application is run on it, it’ll thermally stress out the device. So what can you as a software architect do about this? </p>
<p>You cannot control ambient temperature, but you can control how your software responds to thermal events. Many popular operating systems offer APIs to ‘listen’ for thermal events. When apps get notifications that the device’s thermal load has crossed a certain limit, they should take appropriate actions. </p>
<p><strong>For example</strong>, if a device is streaming video and it gets a notification about thermally heating up, it may lower the resolution at which it is streaming video in order to reduce power consumption. </p>
<p>If a video conferencing app gets a worrisome thermal event notification, it may want to reduce the frame rate at which it is capturing video / reduce the resolution.</p>
<p>The following are thermal event APIs on popular operating systems</p>
<p><strong>MacOS and iOS:</strong> the <code>NSNotificationCenter</code> offers a <a target="_blank" href="https://developer.apple.com/library/archive/documentation/Performance/Conceptual/power_efficiency_guidelines_osx/RespondToThermalStateChanges.html">thermal event listener</a> which userspace applications can register for<strong>.</strong></p>
<p><strong>Android:</strong> PowerManager offers an <a target="_blank" href="https://developer.android.com/reference/android/os/PowerManager.OnThermalStatusChangedListener">onThermalStatusChangedListener</a> which apps can register for, to receive thermal event notification.</p>
<p>###When appropriate, use low power states on hardware</p>
<p>Most modern processors have provisions for reducing power consumption. In these modes, the processor consumes less power by changing the CPU clock speed, putting the CPU into various idle states among various methods. Operating systems give the user the ability to leverage these low power states. </p>
<p><strong>For example</strong>, Linux has the <a target="_blank" href="https://linux.die.net/man/1/cpupower-frequency-set"><code>cpupower-frequency-set</code></a> tool which allows users to modify CPU frequency settings. </p>
<p>As another example, <a target="_blank" href="https://docs.arduino.cc/learn/electronics/low-power">Arduino microcontrollers</a> give programmers the ability to put them in various sleep modes when there are no active tasks to be run. These microcontrollers are typically woken up by an interrupt when a task to be processed is ready. </p>
<p>###Investigate the tradeoffs between Interrupt driven-I/O and Polling</p>
<p>Often, software needs to wait on another component of hardware or software for data to process. There are usually two parties involved: the producer of the data and the consumer of the data </p>
<p>For example, a mobile application may be waiting on a touch event on the display. Here the consumer is the mobile application and the producer is the display hardware + software. </p>
<p>Another example could be a native embedded program that is waiting on the status of a CPU register to change in order to perform some task. Here the consumer is the native embedded program and the producer is the CPU register (well, the producer may actually be producing some other data, but for simplicity we’re only considering a CPU register here).  </p>
<p>There are broadly 2 ways of doing this:</p>
<p><strong>Polling</strong>: The process of checking the status of a data-readiness at regular predetermined intervals of time is referred to as polling. Typically it looks something like this in code:</p>
<pre><code><span class="hljs-comment">// psuedo-code</span>
<span class="hljs-keyword">while</span>(poll) {
    bool data_available =  check_data();
    <span class="hljs-keyword">if</span> (data_available) {
        process_data();
    }
    sleep(SLEEP_TIME); <span class="hljs-comment">// to avoid wasting cpu cycles</span>
}
</code></pre><p>Polling seems pretty simple to implement. But unless you’re absolutely sure that the data or condition you’re waiting on is going to be available at a regular frequency, it has some disadvantages:</p>
<ol>
<li>Polling doesn’t respond to the data being available as soon as it is available, since it checks for availability after every SLEEP_TIME ms.</li>
<li>By constantly checking every time the polling thread wakes up, it still wastes cpu cycles and as a result some power.</li>
</ol>
<p><strong>Interrupt-driven I/O:</strong> in this strategy, there are no explicit checks for the data that is being waited on to be ready. Instead, it is the responsibility of the producer to inform the consumer whenever the data is ready. The consumer does not explicitly check in with the producer, even periodically. As a result, this saves CPU cycles and also power! </p>
<p>There are multiple ways of implementing interrupt-driven I/O. There can be hardware interrupts as well as software interrupts. </p>
<p>For example, when a user touches a mobile phone screen at a particular location, the operating system could send a callback to one of  the application’s thread’s notifying it that a touch input event is ready to process. Until the thread gets the notification, it can either do something else, or just stay asleep! </p>
<p>So in short, interrupt-driven I/O is generally more power efficient than polling, and you should prefer it, unless there’s a very good reason to use polling.</p>
<h3 id="heading-look-into-caching">Look into Caching</h3>
<p>Caching in computer science refers to the process of saving data in a storage location that is typically faster to access than high latency storage (which are generally larger in capacity).</p>
<p>Caching is useful when the same set of data needs to be read or modified repeatedly by software. It allows efficient retrieval and re-use of data. </p>
<p>You can see caching in action in many forms such as:</p>
<ol>
<li>Random Access Memory (RAM) is a cache for underlying disk</li>
<li>CPU cache – L(n) – where n is the level of the cache. As n decreases, the cache size usually gets smaller and the latency of data retrieval gets smaller as well.</li>
<li>Applications can cache data retrieved from the internet into their on device memory for quick access.</li>
<li>Local servers can cache data from remote servers for quicker access as well.</li>
</ol>
<p>And many more.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/image-98.png" alt="Image" width="600" height="400" loading="lazy">
<em>Figure 3: Flow of data from disk to CPU via cache hierarchy</em></p>
<p>As a result of being more efficient with data access, caching usually reduces power consumption and saves energy as well.</p>
<p>Before software can take advantage of caching, it needs to be architected so that that's possible. In general, the following steps can help you:</p>
<ol>
<li>The very first thing is to make sure you're on the lookout for opportunities to cache data.</li>
<li>Then, implement caching. How you implement it will depend on the type of software you’re building. It might range from tiling data matrix operations to caching data retrieved from the internet for re-use later on.</li>
<li>Monitor profile performance, energy and power usage – and make sure that these metrics are actually improving. It is possible with sub-optimal implementations to cause thrashing of the cache – which may increase power consumption and reduce performance.</li>
</ol>
<p>###Design software with lifetime and updatability in mind</p>
<p>This article has talked a lot about your software’s energy and power consumption. Finally, there’s something else that is very important as well: the ability for your software to last a long time and be updatable. </p>
<p>It's very beneficial for software to last a long time, since that in turn means that devices will work well for longer. Software being updatable means that older devices get important feature and security updates, which leads to users not necessarily needing to buy newer devices just to get better software. This leads to a reduction in electronic waste and energy being spent on recycling electronic components. </p>
<p>Software updatability is a large topic which I will not cover in detail here. But there are some principles that you shoulder consider which will serve you well while designing for updatability:</p>
<p><strong>Design your software in modules which are updatable by themselves</strong>: This may involve having strict interfaces between different modules so that on updating one module the software package as a whole still functions correctly.</p>
<p><strong>Focus on using memory as efficiently as possible</strong>: If all software was designed keeping in mind memory efficiency, electronic devices would last longer, since the amount of memory they had would be sufficient for longer. </p>
<p>As an example, consider the iPhone: the first generation in 2007 had 128MB of RAM and 16GB of flash storage (maximum). Today, the iPhone 15 has 6GB of RAM and has a maximum storage option of 1 TB (1024GB). That is a nearly 16x increase in RAM and 64x increase in flash memory. This was needed since the amount of memory needed by applications and the operating system itself grew in size by a huge amount. </p>
<p>As time passes, if memory is used judiciously, we can think of a future where electronic devices last for multiple decades instead of being phased out every 5-6 years.</p>
<p><strong>Testing needs to be bulletproof</strong>: When software is going to be updated frequently, there’ll be multiple version of software running on devices which interact with other pieces of software which might be older. These pieces of software must still function correctly. </p>
<p>For this to happen, before deploying updates, software must be tested thoroughly. As an example: when an app developer releases an app, they must test with multiple versions of operating systems to make sure that their app behaves well on all of them.</p>
<p>##Conclusion</p>
<p>This article introduced the concept of engineering software for sustainability and discussed why this is necessary. </p>
<p>You also learned about various metrics as well as some techniques to make your software sustainable and more efficient. </p>
<p>Finally, I hope it inspired you to think about a very serious problem we're facing right now and how we in the tech community can do our part.</p>
<p>I hope you enjoyed the article!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ C++ Tutorial – What Are the constexpr and constinit Specifiers? ]]>
                </title>
                <description>
                    <![CDATA[ When we write programs, many operations which are performed at runtime can actually be done at compile time – that is, baked into code.  This improves program performance since operations are no longer being computed on the fly, during runtime.  Whil... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/cpp-constexpr-and-constinit/</link>
                <guid isPermaLink="false">66b99d54c39234149cf01149</guid>
                
                    <category>
                        <![CDATA[ C++ ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Jayant Chowdhary ]]>
                </dc:creator>
                <pubDate>Mon, 11 Dec 2023 18:50:12 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/12/ConstCover-1.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>When we write programs, many operations which are performed at runtime can actually be done at compile time – that is, baked into code. </p>
<p>This improves program performance since operations are no longer being computed on the fly, during runtime. </p>
<p>While these techniques of offloading operations to compile time improve performance, they can also help subtle problems such as a the 'Static initialization Order Fiasco' which I covered in a previous <a target="_blank" href="https://www.freecodecamp.org/news/cpp-static-initialization-order-fiasco/">article</a>.  </p>
<p>This tutorial teaches you two ways to make this happen in C++. Here is what we'll cover:</p>
<ul>
<li><a class="post-section-overview" href="#heading-prerequisites">Prerequisites</a></li>
<li><a class="post-section-overview" href="#heading-how-to-evaluate-functions-at-compile-time-using-constexpr">How to evaluate functions at compile time using <code>constexpr</code></a></li>
<li><a class="post-section-overview" href="#heading-the-constinit-specifier-and-its-uses">The <code>constinit</code> specifier and its uses</a></li>
<li><a class="post-section-overview" href="#heading-summary">Summary</a></li>
</ul>
<p>##Prerequisites</p>
<ul>
<li>A basic understanding of C++: For readers not familiar with C++, <a target="_blank" href="https://www.freecodecamp.org/news/learn-c-with-free-31-hour-course/">Learn C++ Programming for Beginners – Free 31-Hour Course</a> is a helpful resource</li>
<li>A read through of my previous article <a target="_blank" href="https://www.freecodecamp.org/news/cpp-static-initialization-order-fiasco/">What is the Static Initialization Order Fiasco in C++</a> will benefit you with context around <code>constinit</code>.</li>
</ul>
<h2 id="heading-how-to-evaluate-functions-at-compile-time-using-constexpr">How to Evaluate Functions at Compile Time Using <code>constexpr</code></h2>
<p>To understand this, let's first take a look at an example of a function which performs a very simple computation:</p>
<pre><code class="lang-cpp"><span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">add2</span><span class="hljs-params">(<span class="hljs-keyword">int</span> input)</span> </span>{
    <span class="hljs-keyword">return</span> input + <span class="hljs-number">2</span>;
}

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-keyword">int</span> b = add2(<span class="hljs-number">3</span>);
    <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"b = "</span> &lt;&lt; b;
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>Here, all that the function <code>add2()</code> does is it adds 2 to the input. In <code>main()</code>, <code>add2()</code> was called with input <code>2</code>. So, it's pretty straightforward for anyone looking at the program to tell what the output of the function is going to be: 5. There is no sort of non-determinism here. </p>
<p>But if we look at the x86 assembly code generated by the compiler it would look similar to the below:</p>
<pre><code>add2(int):
        push    rbp
        mov     rbp, rsp
        mov     DWORD PTR [rbp<span class="hljs-number">-4</span>], edi
        mov     eax, DWORD PTR [rbp<span class="hljs-number">-4</span>]
        add     eax, <span class="hljs-number">2</span>
        pop     rbp
        ret
.LC0:
        .string <span class="hljs-string">"b = "</span>
<span class="hljs-attr">main</span>:
        push    rbp
        mov     rbp, rsp
        sub     rsp, <span class="hljs-number">16</span>
        mov     edi, <span class="hljs-number">3</span>
        <span class="hljs-comment">// Function add2() getting called</span>
        call    add2(int)
        mov     DWORD PTR [rbp<span class="hljs-number">-4</span>], eax
        mov     esi, OFFSET FLAT:.LC0
        mov     edi, OFFSET FLAT:_ZSt4cout
        call    std::basic_ostream&lt;char, <span class="hljs-attr">std</span>::char_traits&lt;char&gt; &gt;&amp; std::operator&lt;&lt; &lt;std::char_traits&lt;char&gt; &gt;(std::basic_ostream&lt;char, std::char_traits&lt;char&gt; &gt;&amp;, char const*)
        mov     rdx, rax
        mov     eax, DWORD PTR [rbp-4]
        mov     esi, eax
        mov     rdi, rdx
        call    std::basic_ostream&lt;char, std::char_traits&lt;char&gt; &gt;::operator&lt;&lt;(int)
        mov     eax, 0
        leave
        ret
</code></pre><p>(Note that the reference assembly codes in this article were generated by using the compiler explorer tool at <a target="_blank" href="https://godbolt.org/">godbolt.org</a>.)</p>
<p>The function <code>add2()</code> actually gets called at runtime in <code>main()</code> with the <code>call add2(int)</code> line. </p>
<p>Since this function does something that can be completely computed before the program actually executes (2+3 = 5, even in our heads!), wouldn't it be cool if we could have the compiler not create a function for this operation and just fill in the answer directly in assembly code? This is exactly what <code>constexpr</code> does. </p>
<p>If the code was changed to this:</p>
<pre><code class="lang-cpp"><span class="hljs-function"><span class="hljs-keyword">constexpr</span> <span class="hljs-keyword">int</span> <span class="hljs-title">add2</span><span class="hljs-params">(<span class="hljs-keyword">int</span> input)</span> </span>{
    <span class="hljs-keyword">return</span> input +<span class="hljs-number">2</span>;
}

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-keyword">int</span> b = add2(<span class="hljs-number">3</span>);
    <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"b = "</span> &lt;&lt; b;
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>the compiler would output the following assembly code:</p>
<pre><code>.LC0:
        .string <span class="hljs-string">"b = "</span>
<span class="hljs-attr">main</span>:
        push    rbp
        mov     rbp, rsp
        sub     rsp, <span class="hljs-number">16</span>
        mov     DWORD PTR [rbp<span class="hljs-number">-4</span>], <span class="hljs-number">5</span>
        mov     esi, OFFSET FLAT:.LC0
        mov     edi, OFFSET FLAT:_ZSt4cout
        call    std::basic_ostream&lt;char, <span class="hljs-attr">std</span>::char_traits&lt;char&gt; &gt;&amp; std::operator&lt;&lt; &lt;std::char_traits&lt;char&gt; &gt;(std::basic_ostream&lt;char, std::char_traits&lt;char&gt; &gt;&amp;, char const*)
        mov     rdx, rax
        mov     eax, DWORD PTR [rbp-4]
        mov     esi, eax
        mov     rdi, rdx
        call    std::basic_ostream&lt;char, std::char_traits&lt;char&gt; &gt;::operator&lt;&lt;(int)
        mov     eax, 0
        leave
        ret
</code></pre><p>The function <code>add2()</code> has disappeared and the line <code>mov DWORD PTR [rbp-4], 5</code> has baked into the program the evaluation of the function <code>add2()</code> at compile time. There is no runtime call to <code>add2()</code>. </p>
<p>Mind you, this is possible since we've passed in 3 – an expression that is known at compile time – to the <code>add2()</code> function. If something that couldn't be evaluated at compile time was passed in, the compiler would again generate an <code>add2()</code> function. </p>
<p>You can see what I mean in this snippet:</p>
<pre><code class="lang-cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span><span class="hljs-meta-string">&lt;iostream&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;random&gt;</span></span>

<span class="hljs-function"><span class="hljs-keyword">constexpr</span> <span class="hljs-keyword">int</span> <span class="hljs-title">add2</span><span class="hljs-params">(<span class="hljs-keyword">int</span> input)</span> </span>{
    <span class="hljs-keyword">return</span> input +<span class="hljs-number">2</span>;
}

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-keyword">int</span> rd = <span class="hljs-built_in">std</span>::rand();
    <span class="hljs-keyword">int</span> b = add2(rd);
    <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"b = "</span> &lt;&lt; b;
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>The assembly generated again has the <code>add2()</code> function:</p>
<pre><code>add2(int):
        push    rbp
        mov     rbp, rsp
        mov     DWORD PTR [rbp<span class="hljs-number">-4</span>], edi
        mov     eax, DWORD PTR [rbp<span class="hljs-number">-4</span>]
        add     eax, <span class="hljs-number">2</span>
        pop     rbp
        ret
.LC0:
        .string <span class="hljs-string">"b = "</span>
<span class="hljs-attr">main</span>:
        push    rbp
<span class="hljs-comment">// Snip</span>
</code></pre><p>Alright, you've now seen how using the <code>constexpr</code> specifier can help programs move runtime costs to compile time costs in many cases. </p>
<p>Let's now look at another specifier introduced recently, in C++20, which verifies that variables are initialized at compile time.</p>
<h2 id="heading-the-constinit-specifier-and-its-uses">The <code>constinit</code> Specifier and its Uses</h2>
<p>The <a target="_blank" href="https://en.cppreference.com/w/cpp/language/constant_initialization"><code>constinit</code></a> specifier was introduced in C++ 20. This specifier <em>asserts</em> that a variable has constant initialization – it <a target="_blank" href="https://en.cppreference.com/w/cpp/language/constant_initialization">sets the initial values of the static variables to a compile-time constant</a>. Otherwise, the program is ill-formed and the compiler produces an error. For example:</p>
<pre><code class="lang-cpp"><span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">add2</span><span class="hljs-params">(<span class="hljs-keyword">int</span> v)</span> </span>{
    <span class="hljs-keyword">return</span> v + <span class="hljs-number">2</span>;
}

<span class="hljs-comment">//Error: 'constinit' variable 'glob' does not have a constant initializer  </span>
<span class="hljs-keyword">constinit</span> <span class="hljs-keyword">int</span> glob = add2(<span class="hljs-number">2</span>);

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>The compiler errors out here since the <code>add2()</code> function isn't <em>sure</em> to have constant initialization – which can be determined at compile time. Now if the <code>add2()</code> function is marked <code>constexpr</code>, it will have constant initialization, so the code compiles.</p>
<pre><code class="lang-cpp"><span class="hljs-function"><span class="hljs-keyword">constexpr</span> <span class="hljs-keyword">int</span> <span class="hljs-title">add2</span><span class="hljs-params">(<span class="hljs-keyword">int</span> v)</span> </span>{
    <span class="hljs-keyword">return</span> v + <span class="hljs-number">2</span>;
}

<span class="hljs-comment">//OKAY 'constinit' variable 'glob' does have a constant initializer.  </span>
<span class="hljs-keyword">constinit</span> <span class="hljs-keyword">int</span> glob = add2(<span class="hljs-number">2</span>);

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>Now you may ask – what's really the use of this specifier?</p>
<p>The answer is it that can be used in certain cases to solve the 'Static Initialization Order Fiasco'. </p>
<p>I talked about the 'Static Initialization order Fiasco' in an <a target="_blank" href="https://www.freecodecamp.org/news/cpp-static-initialization-order-fiasco/">earlier article</a>. If we use <code>constinit</code>, the compiler is giving the programmer its word that the <code>constinit</code> variable will be constant initialized – so that's before any other static variables are constructed at runtime. We get rid of the 'Static Initialization / Destruction Order Fiasco'. </p>
<p>Another example where we use strings that are constant initialized illustrates this:</p>
<pre><code class="lang-cpp"><span class="hljs-comment">// Parent.h</span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">pragma</span> once</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Parent</span> {</span>
    <span class="hljs-keyword">public</span>:
       <span class="hljs-function"><span class="hljs-keyword">size_t</span> <span class="hljs-title">getMoneyCount</span><span class="hljs-params">()</span></span>;
       <span class="hljs-function"><span class="hljs-keyword">constexpr</span> <span class="hljs-title">Parent</span><span class="hljs-params">(<span class="hljs-keyword">const</span> <span class="hljs-keyword">char</span> *moneyString)</span>: <span class="hljs-title">mData</span><span class="hljs-params">(moneyString)</span> </span>{};
    <span class="hljs-keyword">private</span>:
        <span class="hljs-built_in">std</span>::string_view mData;     
};
<span class="hljs-keyword">extern</span> Parent everyonesParent;

<span class="hljs-comment">// Parent.cpp</span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span><span class="hljs-meta-string">&lt;Producer.h&gt;</span></span>

<span class="hljs-function"><span class="hljs-keyword">constinit</span> <span class="hljs-keyword">static</span> Parent <span class="hljs-title">everyonesParent</span><span class="hljs-params">(<span class="hljs-string">"TheParent"</span>)</span></span>;

<span class="hljs-function"><span class="hljs-keyword">size_t</span> <span class="hljs-title">Parent::getMoneyCount</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-keyword">return</span> mData.size();
}

<span class="hljs-comment">//Child.cpp</span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span><span class="hljs-meta-string">&lt;Child.h&gt;</span></span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Child</span> {</span>
    <span class="hljs-keyword">public</span>:
    Child(Parent &amp;parent) : mMoneyCount(parent.getMoneyCount()) {};
    <span class="hljs-keyword">private</span>:
    <span class="hljs-keyword">size_t</span> mMoneyCount;
};

<span class="hljs-function"><span class="hljs-keyword">static</span> Child <span class="hljs-title">everyonesChild</span><span class="hljs-params">(everyonesParent)</span></span>;
</code></pre>
<p>There is no static initialization order problem here, since the static object <code>everyonesParent</code> is guaranteed to be initialized before <code>everyonesChild</code>, since it was marked <code>constinit</code>. </p>
<p>It was okay to mark <code>everyonesParent</code> <code>constinit</code> since it used <code>std::string_view</code> which can be constant initialized – unlike <code>std::string</code>. Also, it had a <code>constexpr</code> constructor. If it didn't use either of these, compilation would have failed!</p>
<p>In closing, something to note about <code>constinit</code>: <code>constinit</code> does not imply <code>const</code>.</p>
<p><code>constinit</code> values can be modified after construction. Take this example – it is perfectly legal:</p>
<pre><code class="lang-cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span><span class="hljs-meta-string">&lt;iostream&gt;</span></span>

<span class="hljs-keyword">constinit</span> <span class="hljs-keyword">int</span> i = <span class="hljs-number">42</span>;
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
 i++;
 <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">" i is "</span> &lt;&lt; i &lt;&lt; <span class="hljs-string">"\n"</span>;
}
</code></pre>
<p>##Summary</p>
<p>This article covered compile time operations and run time operations. It analyzed how compilers produce code to either generate functions used at runtime or evaluate them at compile time. </p>
<p>You learned about the <code>constexpr</code> and <code>constinit</code> specifiers in C++, and how they are extremely useful.</p>
<p>I hope you enjoyed the article!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What is the Static Initialization Order Fiasco in C++? [Solved] ]]>
                </title>
                <description>
                    <![CDATA[ In this article, I'll be covering a subtle but egregious problem that can occur in C++ programs. This problem is popularly called the 'Static Initialization Order Fiasco'.  I'll first go over what the problem is, then go onto some solutions and explo... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/cpp-static-initialization-order-fiasco/</link>
                <guid isPermaLink="false">66b99d5865fc624db0255e09</guid>
                
                    <category>
                        <![CDATA[ C++ ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Jayant Chowdhary ]]>
                </dc:creator>
                <pubDate>Wed, 06 Dec 2023 23:11:52 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/12/StaticCover.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In this article, I'll be covering a subtle but egregious problem that can occur in C++ programs. This problem is popularly called the 'Static Initialization Order Fiasco'. </p>
<p>I'll first go over what the problem is, then go onto some solutions and explore how they work. Let's get started. </p>
<p>This is what we'll cover:</p>
<ul>
    <li><a href="#prerequisites">Prerequisites</a></li>
    <li><a href="#whatisthestaticinitializationorderfiascoinc">What is the 'Static Initialization Order Fiasco' in C++ ?</a></li>
     <li><a href="#solutionstothestaticdeinitializationorderproblem">Solutions to the static de-initialization order problem</a>
          </li><li><a href="#constructonfirstuseidiom">Construct on first use idiom</a></li>
    <li><a href="#niftycountersolution">Nifty Counter Solution</a></li>
    
    <li><a href="#summary"> Summary</a></li>
</ul>

<p>##Prerequisites</p>
<ul>
<li>A basic understanding of C++: For readers not familiar with C++, <a target="_blank" href="https://www.freecodecamp.org/news/learn-c-with-free-31-hour-course/">Learn C++ Programming for Beginners – Free 31-Hour Course</a> is a helpful resource</li>
<li>In particular, an understanding of <a target="_blank" href="https://learn.microsoft.com/en-us/cpp/cpp/storage-classes-cpp?view=msvc-170">storage classes</a> in C++ will be helpful.</li>
</ul>
<p>##What is the 'Static Initialization Order Fiasco' in C++ ?</p>
<p>The C++ standard states: </p>
<blockquote>
<p><em>"The order in which static objects are initialized across different translation units is <a target="_blank" href="https://en.cppreference.com/w/cpp/language/siof">undefined</a> or ambiguous</em>."</p>
</blockquote>
<p>A translation unit is just a way of saying a file that is fed into the compiler. It's a C++ source file with all the code from the headers included in it. </p>
<p>One thing to note though, for later in the article: static objects in the same translation unit are constructed in order of declaration and destructed in the reverse order.</p>
<p>So, how is this a problem?</p>
<p>It can be a problem in the following situation:</p>
<p>Let's say there are 2 static objects in 2 different files. <code>File1.cpp</code> has a static object of type class A – <code>aObj</code> . <code>File2.cpp</code> has a static object of type class B – <code>bObj</code>. The static object in <code>File1.cpp</code> is visible to <code>File2.cpp</code> since it declares <code>aObj</code> as <code>extern</code> in <code>File1.h</code>.</p>
<pre><code class="lang-cpp">
<span class="hljs-comment">// Static initialization order problem</span>
<span class="hljs-comment">// File1.h</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">A</span> {</span>
....
  <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">doSomething</span><span class="hljs-params">()</span> </span>{
    ...
  } 
}
<span class="hljs-keyword">extern</span> A aObj;

<span class="hljs-comment">//File1.cpp</span>


<span class="hljs-keyword">static</span> A aObj;

<span class="hljs-comment">// File2.cpp</span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">B</span> {</span>
B() {
 aObj.doSomething();<span class="hljs-comment">// Not okay! aObj may not have been constructed</span>
}
....
}

<span class="hljs-keyword">static</span> B bObj;
</code></pre>
<p>In this program, it is possible that the object <code>aObj</code> in File1.cpp gets initialized before <code>bObj</code> in File2.cpp. That is all good since in that case, the constructor for <code>bObj</code> runs after <code>aObj</code> has been constructed. It is safe to call call methods on <code>aObj</code>.</p>
<p>But it is also possible that the object <code>bObj</code> in File2.cpp gets initialized before <code>aObj</code> in File1.cpp. In that case, <em>the constructor of</em> <code>bObj</code> <em>calls</em> <code>doSomething()</code> <em>on</em> <code>aObj</code> <em>which has not been constructed!</em> The memory has been allocated for <code>aObj</code>, but it hasn't been constructed. This could lead to unintended behavior / a corrupt program.</p>
<p>So this is what the static initialization order fiasco is all about. </p>
<p>But we're not done: the other problem is the <strong>static de-initialization order fiasco</strong>! This is pretty much the same problem, just applied to the order of de-initialization of static objects. </p>
<p>The C++ standard doesn't specify the order in which static objects get de-initialized as well. So it is possible that static object <code>aObj</code> gets destroyed before <code>bObj</code>. This is a problem if <code>bObj</code>'s destructor uses or references <code>aObj</code>. </p>
<p>This is illustrated in the code snippet below – it is pretty much the same as the example above, just that its the de-initialization order which is dangerous this time:</p>
<pre><code class="lang-cpp"><span class="hljs-comment">// Static de-initialization order problem</span>
<span class="hljs-comment">// File1.h</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">A</span> {</span>
....
  <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">doSomething</span><span class="hljs-params">()</span> </span>{
    ...
  } 
}
<span class="hljs-keyword">extern</span> A aObj;

<span class="hljs-comment">//File1.cpp</span>

<span class="hljs-keyword">static</span> A aObj;

<span class="hljs-comment">// File2.cpp</span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">B</span> {</span>
B() {}
~B() {
 aObj.doSomething(); <span class="hljs-comment">// Not okay! aObj may have already been destructed!</span>
}
....
}

<span class="hljs-keyword">static</span> B bObj;
</code></pre>
<p><strong>Note:</strong> These problems are only applicable to objects with <em>static</em> storage scope. They won't occur if <code>bObj</code> was a variable with automatic storage scope. In that case, the C++ standard guarantees that <code>aObj</code> is constructed before <code>bObj</code> and destructed after it.</p>
<p><strong>Another note:</strong> These problems also do not occur in C programs. Why is that so? Well in C, there's no concept of constructors and destructors. Static objects are completely defined during compile time.</p>
<h2 id="heading-how-to-solve-the-static-de-initialization-order-problem">How to Solve the Static De-initialization Order Problem</h2>
<p>Now that it is clear what the problem is, I will discuss some solutions. There are multiple ways of solving this problem – each with its tradeoffs. Let's take a look.</p>
<p>###Construct on first use idiom:</p>
<p>This idiom tries to make sure that there is always a fully constructed object whenever the static object in question is used. Following the examples in the previous section, we can do this by replacing all references to <code>aObj</code> by a function call <code>aObj()</code> which returns a reference to an object of type <code>A</code>. </p>
<p>In code it looks like this:</p>
<pre><code class="lang-cpp"><span class="hljs-comment">// Static initialization order problem</span>
<span class="hljs-comment">// File1.h</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">A</span> {</span>
....
  <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">doSomething</span><span class="hljs-params">()</span> </span>{
    ...
  } 
};

<span class="hljs-function">A&amp; <span class="hljs-title">aObj</span><span class="hljs-params">()</span></span>;

<span class="hljs-comment">//File1.cpp</span>

<span class="hljs-function">A&amp; <span class="hljs-title">aObj</span><span class="hljs-params">()</span> </span>{
  <span class="hljs-keyword">static</span> A *aObj = <span class="hljs-keyword">new</span> A();
  <span class="hljs-keyword">return</span> *aObj; 
}

<span class="hljs-comment">// File2.cpp</span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">B</span> {</span>
 B() {
   <span class="hljs-comment">/*
    * Okay since calling aObj() gaurantees that
    * static A *aObj = new A(); ran
    */</span>
   aObj().doSomething();  
  }
  ....
};

<span class="hljs-keyword">static</span> B bObj;
</code></pre>
<p><code>bObj</code> can safely assume that calling aObj() returns a fully constructed <code>aObj</code> since this line:</p>
<pre><code class="lang-cpp"><span class="hljs-keyword">static</span> A *aObj = <span class="hljs-keyword">new</span> A();
</code></pre>
<p>would have run on the function call and will give it a fully constructed object. Also, since the program never calls delete on <code>aObj</code>, it is never destructed so it is also safe to use <code>aObj</code> in <code>bObj</code>'s destructor. </p>
<p>But this does mean that the memory allocated for <code>aObj</code> always stays alive and valid throughout the lifetime of the program. And this may or may not be a problem (it does get reclaimed by the OS after the program exits, of course).</p>
<p>So, in which situation is this solution not great? In the case that <code>aObj</code>'s destructor does something desirable. For example: when <code>aObj</code> gets destructed – it writes to a log file / does something else that has some side effects.</p>
<p>Now you may ask, okay, why don't just I replace the static pointer in the <code>aObj()</code> function call with a static <code>aObj</code> object?</p>
<pre><code class="lang-cpp"><span class="hljs-function">A&amp; <span class="hljs-title">aObj</span><span class="hljs-params">()</span> </span>{
  <span class="hljs-keyword">static</span> A aObj;
  <span class="hljs-keyword">return</span> aObj; 
}
</code></pre>
<p>That still ensures that <code>aObj</code> has been fully constructed by the time the function is called right? Right. But it does not save us from the static de-initialization order problem. It is still possible that <code>aObj</code>'s destructor runs before <code>bObj</code> 's destructor.</p>
<p>There is an interesting trick that solves both of these problems: The Nifty Counter Idiom.</p>
<p>###Nifty Counter Solution</p>
<p>Reference: this resource on the <a target="_blank" href="https://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Nifty_Counter#:~:text=The%20%22nifty%20counter%22%20or%20%22,the%20initialization%20of%20static%20objects.&amp;text=The%20header%20file%20of%20the,called%20on%20the%20Stream%20object.">Nifty counter idiom</a> presents the idea behind this idiom. Let's examine it.</p>
<p>The idea is to ensure that:</p>
<ol>
<li>The static object being used gets constructed before any other static object in the translation unit that it is being used in.</li>
<li>The static object being used gets destructed after any other static object in the translation unit that it is being used in.</li>
</ol>
<pre><code class="lang-cpp"><span class="hljs-comment">// File1.h</span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">pragma</span> once</span>

<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">A</span> {</span>
  A();
  ~A();
};
<span class="hljs-keyword">extern</span> A&amp; aObj;

<span class="hljs-keyword">static</span> <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">AInitializer</span> {</span>
  AInitializer ();
  ~AInitializer ();
} aInitializer; <span class="hljs-comment">// static initializer for every translation unit that aObj is used in</span>
</code></pre>
<pre><code class="lang-cpp"><span class="hljs-comment">// File1.cpp</span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">"File1.h"</span></span>

<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;new&gt;         // Used for placement new</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;type_traits&gt; // Used for aligned_storage</span></span>

<span class="hljs-keyword">static</span> <span class="hljs-keyword">int</span> niftyCounter; <span class="hljs-comment">// this is zero initialized at load time</span>

<span class="hljs-comment">/*
 * Memory for the static object aObj - memory itself is valid throughout the
 * the lifetime of the program.
 */</span>
<span class="hljs-keyword">static</span> <span class="hljs-keyword">typename</span> <span class="hljs-built_in">std</span>::aligned_storage&lt;<span class="hljs-keyword">sizeof</span> (A), <span class="hljs-keyword">alignof</span> (A)&gt;::type
  aObjBuf; 

A&amp; aObj = <span class="hljs-keyword">reinterpret_cast</span>&lt;A&amp;&gt; (aObj);

A::A ()
{
  <span class="hljs-comment">// Construct A</span>
}
A::~A ()
{
  <span class="hljs-comment">/*
   * Destruct A: with possible side effects
   * like writing to a file.
   */</span>
} 

AInitializer::AInitializer ()
{
  <span class="hljs-keyword">if</span> (niftyCounter++ == <span class="hljs-number">0</span>) {
    <span class="hljs-keyword">new</span> (&amp;aObj) A (); <span class="hljs-comment">// use placement new operator</span>
  }
}

AInitializer::~AInitializer ()
{
  <span class="hljs-keyword">if</span> (--niftyCounter == <span class="hljs-number">0</span>) {
    (&amp;aObj)-&gt;~A(); <span class="hljs-comment">// run the destructor</span>
  }
}
</code></pre>
<p>Let's try to understand what this code does.</p>
<p>First, in the header file, <code>File1.h</code> has the definition of <code>class A</code> first. After that, is have the definition of a class called <code>AInitializer</code>. </p>
<p>There is also a static object <strong>defined</strong> in the header file of type <code>AInitializer</code>. This makes sure that the constructor for <code>AInitializer</code> runs before the constructor for any other static object in the translation unit that <code>File1.h</code> is included in (of course you have to include File1.h before any other static object's definition in source files). </p>
<p>Remember: <em>static objects in the same translation unit are constructed in order of declaration and destructed in the reverse order</em>.</p>
<p>So now that <code>AInitializer</code> is constructed before any other static objects in a translation unit, how can we use this to our advantage? <code>aObj</code> can be constructed in the constructor of <code>AInitializer</code>! Which is what is happening in the lines below:</p>
<pre><code class="lang-cpp">AInitializer::AInitializer ()
{
  <span class="hljs-keyword">if</span> (nifty_counter++ == <span class="hljs-number">0</span>) {
    <span class="hljs-keyword">new</span> (&amp;aObj) A (); <span class="hljs-comment">// use placement new</span>
  }
}
</code></pre>
<p>Note that the <a target="_blank" href="https://en.cppreference.com/w/cpp/language/new">placement new</a> operator is being used here instead of the <code>new</code> operator to construct <code>aObj</code>. Let's see what would happen if we used <code>new</code> instead. The code would look like this:</p>
<pre><code class="lang-cpp">A&amp; aObj;
A *aObjp = <span class="hljs-literal">nullptr</span>;

AInitializer::AInitializer ()
{
  <span class="hljs-keyword">if</span> (nifty_counter++ == <span class="hljs-number">0</span>) {
    aObjp = <span class="hljs-keyword">new</span> A (); 
    aObj = *aObjp; <span class="hljs-comment">// Not okay! Cannot re-assign a reference</span>
  }
}
</code></pre>
<p>This doesn't work since a reference needs to be defined and declared at the same time. That is precisely why the placement <code>new</code> operator needs to be used.</p>
<pre><code class="lang-cpp"><span class="hljs-keyword">static</span> <span class="hljs-keyword">typename</span> <span class="hljs-built_in">std</span>::aligned_storage&lt;<span class="hljs-keyword">sizeof</span> (A), <span class="hljs-keyword">alignof</span> (A)&gt;::type
  aObjBuf; 

A&amp; aObj = <span class="hljs-keyword">reinterpret_cast</span>&lt;A&amp;&gt; (aObj)
</code></pre>
<p>This allocates memory to fit an object of type <code>A</code> and later assigns that to the reference. Now all that's left to be done is to actually <em>construct</em> the object in <code>AInitializer</code>'s constructor – which is what is done with the placement new operator.</p>
<p>Another question that may arise in your mind: here, there is a static object <code>aObjBuf</code>. But isn't that subject to the same de-initialization order problem that we talked about in the second part of the Construct <em>on first use</em> idiom? </p>
<p>The answer is that the memory for <code>aObjBuf</code> stays alive and valid until the program is alive. Nothing happens in the construction of the memory. So it's valid to this.</p>
<p>This approach also makes sure that the static de-initialization order problem isn't hit, since the last <code>AInitializer</code> object destructed will call the destructor of <code>aObj</code>. That is guaranteed to run after any static objects in other translation units run, since within the particular translation unit, the static object <code>aInitializer</code> is declared before any other static object using <code>aObj</code>. This means it will get destructed in the reverse order – that is after the destructor for any other static objects have run.</p>
<p>There are some caveats here: this solution isn't the easiest to understand and implement. This is also not thread safe. You can find more information in the article on Nifty counters presented in the The C/C++ Users Journal, May, 1999 <a target="_blank" href="http://www.petebecker.com/js/js199905.html">here</a>.</p>
<p>##Summary</p>
<p>Using statically initialized objects in C++ is tricky and should be done with care. Fortunately, there are multiple solutions and ways to get around the problem. </p>
<p>In this article, we covered some common solutions: the 'Construct on first use' idiom and the 'Nifty counter solution', along with their merits and challenges.</p>
<p>Hope you enjoyed this article!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Keeping Time in C++: How to use the std::chrono API ]]>
                </title>
                <description>
                    <![CDATA[ Keeping track of time is a very important aspect of computer programs. Some common use cases are: Measure/profile the performance of certain parts of code. Do work at certain periods of time, from within a program.  Detect whether threads are in a d... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/cpp-std-chrono-api/</link>
                <guid isPermaLink="false">66b99d5fc39234149cf0114b</guid>
                
                    <category>
                        <![CDATA[ C++ ]]>
                    </category>
                
                    <category>
                        <![CDATA[ profiling ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Jayant Chowdhary ]]>
                </dc:creator>
                <pubDate>Mon, 04 Dec 2023 23:38:45 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/12/ClangCover.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Keeping track of time is a very important aspect of computer programs. Some common use cases are:</p>
<ul>
<li>Measure/profile the performance of certain parts of code.</li>
<li>Do work at certain periods of time, from within a program. </li>
<li>Detect whether threads are in a deadlock / taking too long to complete an operation.</li>
<li>Synchronize tasks between different components of software</li>
</ul>
<p>and many more…</p>
<p>This article will guide you through how you can measure time in modern C++. </p>
<h3 id="heading-prerequisites">Prerequisites</h3>
<ul>
<li>A basic understanding of C++: For readers not familiar with C++, <a target="_blank" href="https://www.freecodecamp.org/news/learn-c-with-free-31-hour-course/">Learn C++ Programming for Beginners – Free 31-Hour Course</a> is a helpful resource.</li>
<li>A quick read through Linux time tracking infrastructure – <a target="_blank" href="https://man7.org/linux/man-pages/man2/gettimeofday.2.html">such as you can find here</a> – will help you get familiar with the ideas presented in the article.</li>
</ul>
<h2 id="heading-common-ways-to-track-time-in-c">Common Ways to Track Time in C++</h2>
<p>This article covers how you can keep track of time in C++. In C, on UNIX like systems, you can use the <a target="_blank" href="https://linux.die.net/man/3/clock_gettime">clock_gettime()</a> function to keep track of time. It returns time in a structured way through the <a target="_blank" href="https://www.gnu.org/software/libc/manual/html_node/Time-Types.html"><code>timespec</code></a> struct. </p>
<p>The <a target="_blank" href="https://linux.die.net/man/3/clock_gettime"><code>clock_gettime()</code></a> /<a target="_blank" href="https://linux.die.net/man/2/gettimeofday">gettimeofday</a> function gives us back a filled <a target="_blank" href="https://www.gnu.org/software/libc/manual/html_node/Time-Types.html"><code>timespec</code></a> struct which has two fields:</p>
<ol>
<li><code>tv_sec</code>, which gives us the time in seconds since the time source – CLOCK_REALTIME / CLOCK_MONOTONIC that was passed into clock_gettime. The 'type' of this field is <a target="_blank" href="https://en.cppreference.com/w/c/chrono/time_t"><code>time_t</code></a> which is usually an integral value.</li>
<li><code>tv_nsec</code>, which gives the time after <code>tv_sec</code>, in nanoseconds since the time source that was specified while calling <code>clock_gettime()</code>. The type of this field is a long int.</li>
</ol>
<p>So why is <a target="_blank" href="https://linux.die.net/man/3/clock_gettime"><code>clock_gettime()</code></a> not good enough? The answer is that the members of <code>struct timespec</code> can easily be passed to functions as they're really just <code>int</code>s / <code>float</code>s. They're not strongly typed. </p>
<p>It's also easy to forget about the units in which they represent time while passing information around to functions. This can happen when you're dealing with projects that have thousands of lines of code.</p>
<p>So what's the solution?</p>
<p>##The std::chrono API</p>
<p>C++11 introduced the std::chrono API, which can help you avoid some of these problems.</p>
<p>There are 3 important parts of the API.</p>
<p>###1. <code>std::chrono::duration</code></p>
<p>As its name suggests, <code>std::chrono::duration</code> is a type that represents a time interval. The official C++ reference mentions that <code>std::chrono::duration</code> is a templated type with the following signature:</p>
<pre><code class="lang-cpp"><span class="hljs-keyword">template</span>&lt;
    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Rep</span>,
    <span class="hljs-title">class</span> <span class="hljs-title">Period</span> = <span class="hljs-title">std</span>:</span>:ratio&lt;<span class="hljs-number">1</span>&gt;
&gt; <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">duration</span>;</span>
</code></pre>
<p>Here, the <code>Rep</code> template parameter represents the type that is used to count 'ticks' of time. A tick is just a unit of time which is a given fraction of a second. <code>Period</code>, the second parameter, defines what exactly that fraction is.</p>
<p>So, for example, if you write:</p>
<pre><code class="lang-cpp"><span class="hljs-keyword">using</span> my_ms_type = <span class="hljs-built_in">std</span>::chrono::duration&lt;<span class="hljs-keyword">int</span>, <span class="hljs-built_in">std</span>::ratio&lt;<span class="hljs-number">1</span>, <span class="hljs-number">1000</span>&gt;&gt;

my_ms_type duration_ms duration = <span class="hljs-number">3</span>; <span class="hljs-comment">// error: cannot convert from int</span>
my_ms_type duration_ms duration_ok{<span class="hljs-number">3</span>} <span class="hljs-comment">// OK, can construct from int</span>
</code></pre>
<p><code>my_ms_type</code> is a type that has been defined, which counts in units of milliseconds (1/1000th of a second). This count is expressed as an integer. As you might be able to guess, the <code>Rep</code> template parameter is <code>int</code> and Period is <code>std::ratio&lt;1,1000&gt;</code> (which really is a way of saying 1/1000).</p>
<p>Now that it's clear how durations are represented, let's see what we can and cannot do with these.</p>
<p>If there is a function that takes in a <code>my_ms_type</code> duration and you instead try to pass in any non-<code>std::chrono::duration</code> type, you'll get a compiler error.</p>
<p>It is possible to implicitly convert between different types of <code>std::chrono::duration</code> as long as information isn't lost with the type of <code>Rep</code>, since the standard library can compute the relationship between two <code>std::chrono::duration</code>types. It is not possible to implicitly convert if there is a loss of information. For example:</p>
<pre><code class="lang-cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span><span class="hljs-meta-string">&lt;chrono&gt;</span></span>

<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>::chrono;
<span class="hljs-keyword">using</span> my_type_ms = <span class="hljs-built_in">std</span>::chrono::duration&lt;<span class="hljs-keyword">int</span>, <span class="hljs-built_in">std</span>::ratio&lt;<span class="hljs-number">1</span>, <span class="hljs-number">1000</span>&gt;&gt;;
<span class="hljs-keyword">using</span> my_type_ms_f = <span class="hljs-built_in">std</span>::chrono::duration&lt;<span class="hljs-keyword">float</span>, <span class="hljs-built_in">std</span>::ratio&lt;<span class="hljs-number">1</span>, <span class="hljs-number">1000</span>&gt;&gt;;
<span class="hljs-keyword">using</span> my_type_hundredth_s = <span class="hljs-built_in">std</span>::chrono::duration&lt;<span class="hljs-keyword">int</span>, <span class="hljs-built_in">std</span>::ratio&lt;<span class="hljs-number">1</span>, <span class="hljs-number">100</span>&gt;&gt;;
<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">f</span><span class="hljs-params">(my_type_ms millis)</span> </span>{}
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span>
</span>{
   <span class="hljs-keyword">int</span> duration = <span class="hljs-number">2</span>;
   my_type_ms_f duration_f{<span class="hljs-number">2.5</span>};
   my_type_hundredth_s duration_compatible{<span class="hljs-number">100</span>};

   f(duration); <span class="hljs-comment">// error: could not convert 'duration' from 'int' to 'my_type_ms'</span>

   f(duration_f) <span class="hljs-comment">//error: since float -&gt; int will lose information</span>

   f(duration_compatible) <span class="hljs-comment">// OK since no information is lost</span>
}
</code></pre>
<p>The standard library also has some predefined <code>std::chrono::duration</code> template specializations for common time durations such as <code>std::chrono::duration::seconds</code>, <code>milliseconds</code>, <code>microseconds</code>, and so on.</p>
<p>You can also get the 'count' value contained in a duration by using the <code>count</code> method in a duration.</p>
<pre><code class="lang-cpp"><span class="hljs-built_in">std</span>::chrono::seconds duration{<span class="hljs-number">3</span>};
<span class="hljs-comment">// Prints: 'Duration count: 3 seconds'</span>
<span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"Duration count: "</span> &lt;&lt; duration.count() &lt;&lt; <span class="hljs-string">" seconds"</span>;
</code></pre>
<p>Interestingly, converting from a unit with higher precision like <code>nanosecond</code> to something with a lower precision such as <code>millisecond</code> may also lead to a loss of information. For these specific cases, you need to use an <em>explicit cast</em> for conversion. This is called <code>duration_cast</code>. For example:</p>
<pre><code class="lang-cpp">nanoseconds durationInNs = <span class="hljs-number">3000000000</span>;
seconds ms = duration_cast&lt;seconds&gt;(durationInNs); <span class="hljs-comment">//OK 3s</span>
durationInNs = <span class="hljs-number">3500000000</span>;
ms = duration_cast&lt;nanoseconds&gt;(durationInNs); <span class="hljs-comment">// OK 3s - truncates down</span>
</code></pre>
<p>Now that we know why <code>std::chrono::duration</code> is useful, let's move on. The next section explores <code>std::chrono::time_point</code>.</p>
<p>###2. <code>std::chrono::time_point</code></p>
<p><code>std::chrono::time_point</code> is a way of expressing a particular point in time – surprise, surprise! </p>
<p>If you think about it, how can you logically define a point in time ? We need to have a reference starting point and a duration from the starting point. This is exactly what <code>std::chrono::time_point</code> does. </p>
<p>The class declaration looks like this:</p>
<pre><code class="lang-cpp"><span class="hljs-keyword">template</span>&lt;
    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Clock</span>,
    <span class="hljs-title">class</span> <span class="hljs-title">Duration</span> = <span class="hljs-title">typename</span> <span class="hljs-title">Clock</span>:</span>:duration
&gt; <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">time_point</span>;</span>
</code></pre>
<p>There are two template parameters here:</p>
<p>The first one is <code>Clock</code> which represents a reference clock relative to which the point in time is being measured. For now, some examples of clocks are:</p>
<ul>
<li><code>system_clock</code>: this represents a real-world wall clock. It's useful when you want to measure time in terms of real-world times. It's important to note that the system time can usually be changed on any system, so you shouldn't depend on this clock to calculate time periods between tasks / performance profiling.</li>
<li><code>steady_clock</code>: this represents a monotonically increasing clock. It's useful when you need stop-watch like clock accounting.</li>
</ul>
<p>The second template parameter is <code>Duration</code> which is what we discussed in the previous section. A <code>time_point</code> needs to be associated with a <code>duration</code> type since that's what is being used to measure ticks since the 'epoch' of the <code>Clock</code>. </p>
<p>Epoch is just a way of saying a reference point in time. While there's no mandate for which reference to use, Unix Time - that is, the time since 00:00:00 Coordinated Universal Time (UTC), Thursday, 1 January 1970 is a common one.</p>
<p>Time points based on the <em>same</em> clock can be subtracted and not added. For example:</p>
<pre><code class="lang-cpp"><span class="hljs-keyword">auto</span> tp1 = <span class="hljs-built_in">std</span>::chrono::system_clock::now();
...
<span class="hljs-keyword">auto</span> tp2 = <span class="hljs-built_in">std</span>::chrono::system_clock::now()
<span class="hljs-keyword">auto</span> tp3 = <span class="hljs-built_in">std</span>::chrono::steady_clock::now();

<span class="hljs-keyword">auto</span> diff = tp2 - tp1; <span class="hljs-comment">// OK</span>
<span class="hljs-keyword">auto</span> add = tp1 + tp2; <span class="hljs-comment">// Not Ok</span>
<span class="hljs-keyword">auto</span> add = tp3 - tp2; <span class="hljs-comment">// Not Ok - based on different clocks</span>
</code></pre>
<p>Let's now see what clocks are.</p>
<p>###3. Clock Types</p>
<p>A <code>Clock</code> is a type that ties together <code>std::chrono::duration</code> and <code>std::chrono::time_point</code>. It has a function <code>now()</code> that returns the current <code>time_point</code>. The formal requirements for a type to be a <code>Clock</code> can be found in the C++ spec <a target="_blank" href="https://en.cppreference.com/w/cpp/named_req/Clock">here</a>.</p>
<p>As mentioned before, <code>system_clock</code> and <code>steady_clock</code> are two popular clocks provided by the standard library. Each clock has its own associated <code>duration</code> as well.</p>
<p>Each <code>time_point</code> is associated with some clock, since it really has to be relative to some given reference.</p>
<p>Finally, let's see some examples of how you can tie together <code>duration</code>, <code>time_point</code>, and <code>Clock</code>. Let's say you want to measure the time that looping 100,000,000 times takes in nanoseconds, and you also want to print out the current wall time:</p>
<pre><code class="lang-cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;chrono&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;ratio&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;thread&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;ctime&gt;</span></span>

<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>::chrono;
<span class="hljs-keyword">constexpr</span> <span class="hljs-keyword">size_t</span> kIterations = <span class="hljs-number">100000000</span>;
<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">testFunction</span> <span class="hljs-params">()</span> </span>{
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">size_t</span> i = <span class="hljs-number">0</span>; i &lt; kIterations; i++) {
    }
}

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span>
</span>{
    <span class="hljs-keyword">auto</span> tStartSteady = <span class="hljs-built_in">std</span>::chrono::steady_clock::now();
    <span class="hljs-built_in">std</span>::<span class="hljs-keyword">time_t</span> startWallTime = system_clock::<span class="hljs-keyword">to_time_t</span>(system_clock::now());
    <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"Time start = "</span> &lt;&lt; <span class="hljs-built_in">std</span>::ctime(&amp;startWallTime) &lt;&lt; <span class="hljs-string">" \n"</span>;
    testFunction();
    <span class="hljs-keyword">auto</span> tEndSteady = <span class="hljs-built_in">std</span>::chrono::steady_clock::now();
    nanoseconds diff = tEndSteady - tStartSteady;
    <span class="hljs-built_in">std</span>::<span class="hljs-keyword">time_t</span> endWallTime = system_clock::<span class="hljs-keyword">to_time_t</span>(system_clock::now());
    <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"Time end = "</span> &lt;&lt; <span class="hljs-built_in">std</span>::ctime(&amp;endWallTime) &lt;&lt; <span class="hljs-string">" \n"</span>;
    <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"Time taken = "</span> &lt;&lt; diff.count() &lt;&lt; <span class="hljs-string">" ns"</span>;
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>; 
}
</code></pre>
<p>The output of the program is the following:</p>
<pre><code>Output:
<span class="hljs-comment">// This can of course vary from system to system</span>
Time start = Tue Nov  <span class="hljs-number">7</span> <span class="hljs-number">07</span>:<span class="hljs-number">11</span>:<span class="hljs-number">13</span> <span class="hljs-number">2023</span>

Time end = Tue Nov  <span class="hljs-number">7</span> <span class="hljs-number">07</span>:<span class="hljs-number">11</span>:<span class="hljs-number">13</span> <span class="hljs-number">2023</span>

Time taken = <span class="hljs-number">50998885</span> ns
</code></pre><h2 id="heading-summary">Summary</h2>
<p>This article explored various facets of the <code>std::chrono</code> API in C++. The <code>std::chrono</code> API allows C++ programmers to safely keep track of time thanks to its strongly typed system. It also helps maintain support for convenient conversions between different 'types' of time points.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Build a Clang AST-Based C++ Static Analysis Tool ]]>
                </title>
                <description>
                    <![CDATA[ Clang is a set of tools and projects that provides infrastructure for languages in the C family like C, C++, OpenCL, and CUDA. It is a part of the LLVM project. This article will show you how to use Clang's front end libraries to build a simple stati... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/clang-ast-based-static-analysis-tools/</link>
                <guid isPermaLink="false">66b99d5065fc624db0255e07</guid>
                
                    <category>
                        <![CDATA[ C++ ]]>
                    </category>
                
                    <category>
                        <![CDATA[ compilers ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Jayant Chowdhary ]]>
                </dc:creator>
                <pubDate>Thu, 30 Nov 2023 19:01:21 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/11/ClangCover-2.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Clang is a set of tools and projects that provides infrastructure for languages in the C family like C, C++, OpenCL, and CUDA. It is a part of the <a target="_blank" href="https://www.llvm.org/">LLVM</a> project.</p>
<p>This article will show you how to use Clang's front end libraries to build a simple static analysis tool which will operate on C++ source / header files. It will use the power of AST (Abstract Syntax Tree) traversal. </p>
<p>An abstract syntax tree is a tree structure representing the syntactical structure of code. <a target="_blank" href="https://en.wikipedia.org/wiki/Abstract_syntax_tree">Here</a> is a good explanation of how it works, and <a target="_blank" href="https://astexplorer.net/">here</a> is a tool to help you explore the AST for a given piece of code. </p>
<p>Here, I will teach you how you can use the Clang AST to find information about the code given to it to show you how powerful it is.</p>
<p>This article goes through everything step by step, and I’ll explain the terminology I'm using briefly at each step.</p>
<p>In the first section, you'll learn how to get the open source Clang project. Then, we'll explore how you can build a static analysis tool with a simple goal: to check if each <code>Class</code> defined in a source / header file starts with an uppercase character. We'll do this using Clang's frontend libraries which will analyze the C++ source AST. </p>
<p>So go ahead and grab your favorite coding beverage, get comfortable, and read on!</p>
<p>Here's what we'll cover:</p>
<ul>
<li><a class="post-section-overview" href="#heading-prerequisites">Prerequisites</a></li>
<li><a class="post-section-overview" href="#how-to-get-the-clang-project-and-access-front-end-libraries">How to Get the Clang Project and Access the Front-end Libraries</a></li>
<li><a class="post-section-overview" href="#heading-how-to-create-the-scaffolding-for-the-static-analysis-tool">How to Create the Scaffolding for the Static Analysis Tool</a></li>
<li><a class="post-section-overview" href="#heading-putting-it-all-together-in-code">Putting it All Together in Code</a></li>
<li><a class="post-section-overview" href="#heading-summary">Summary</a></li>
</ul>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>Before getting started, it would be beneficial to have a basic understanding of the following:</p>
<ul>
<li>Compilers: <a target="_blank" href="https://en.wikipedia.org/wiki/Compiler#:~:text=In%20computing%2C%20a%20compiler%20is,language%20(the%20target%20language).">this</a> page is a good primer for beginners.</li>
<li>C++ : For readers not familiar with C++, <a target="_blank" href="https://www.freecodecamp.org/news/learn-c-with-free-31-hour-course/">Learn C++ Programming for Beginners – Free 31-Hour Course</a> is a helpful resource.</li>
<li>Git: <a target="_blank" href="https://www.freecodecamp.org/news/how-to-use-git-best-practices-for-beginners/">Git Best Practices – A Guide to Version Control for Beginners</a> is an excellent starting point.</li>
</ul>
<h2 id="heading-how-to-get-the-clang-project-and-access-the-front-end-libraries">How to Get the Clang Project and Access the Front-end Libraries</h2>
<p>Since <code>clang</code> and <code>llvm</code> are open source projects, they have very comprehensive documentation around how to get started with getting the code and building tools using them. </p>
<p>You can check out the <a target="_blank" href="https://llvm.org/docs/GettingStarted.html">Getting Started</a> page of the <code>llvm</code> project to get more information about this. I've referenced that in this article as well.</p>
<p>###1. Get the Clang project </p>
<p>On a UNIX like terminal, clone the <code>llvm</code> Git project into your own directory. I'll call it <code>ast-anaylzer</code>.</p>
<ol>
<li><code>mkdir -p  ~/ast-analyzer; cd ~/ast-analyzer</code></li>
<li><code>git clone https://github.com/llvm/llvm-project.git</code> #Clone the llvm project source </li>
</ol>
<p>###2. Get the CMake build system and Ninja build tool</p>
<p><a target="_blank" href="https://cmake.org/">CMake</a> and <a target="_blank" href="https://ninja-build.org/">ninja</a> work in conjunction to form a build system. <code>CMake</code> generates <code>build.ninja</code> files, which contain commands that tell <code>ninja</code> how to generate output targets. We’ll get into this more a little later.</p>
<p>####2.1 Get and install Ninja</p>
<p>Here are the steps you can follow to install Ninja:</p>
<ol>
<li><code>cd ~/ast-analyzer</code></li>
<li>Clone the ninja source project with this command: <code>git clone https://github.com/martine/ninja.git</code> </li>
<li><code>cd ninja</code></li>
<li>Checkout the release branch - this is the stable branch - with this command: <code>git checkout release</code></li>
<li><code>python3 configure.py –bootstrap</code> This prepares and creates a Ninja binary (<code>configure.py –help</code> will give you more information).</li>
<li>Install ninja with this command: <code>sudo cp ninja /usr/local/bin</code>. After this step, as a basic validity check, do <code>which ninja</code> to make sure it says /usr/local/bin/ninja.</li>
</ol>
<p>####2.2. Get and install CMake</p>
<p>Here are the steps you can follow to install cmake:</p>
<ol>
<li><code>cd ~/ast-analyzer</code></li>
<li>Clone the cmake project source code: <code>git clone git://cmake.org/stage/cmake.git</code></li>
<li><code>cd cmake</code></li>
<li>Checkout the release branch - this is the stable branch - with this command: <code>git checkout release</code>.</li>
<li>Run the bootstrap script: <code>./bootstrap</code>. This prepares cmake to be built and installed on your host machine.</li>
<li>Build cmake from source with this command: <code>make</code>.</li>
<li>Then finally install cmake: <code>sudo make install</code>.</li>
</ol>
<p>Once we’ve gotten Clang, we’ll build it and configure it so we can build Clang-based tools as well.</p>
<p>###3. Build Clang and configure it</p>
<p>Create a ‘build’ directory. This is where our build.ninja/ output binaries and so on will get created:</p>
<pre><code>cd ~/ast-analyzer; mkdir -p build; cd build
</code></pre><p>Now we need to generate the <code>build.ninja file</code> in order to build Clang and also the tools in the directory from the project cloned earlier (<code>llvm/clang-tools-extra</code>). You can do this using <code>CMake</code> like this:</p>
<pre><code>cmake -G Ninja ../llvm-project/llvm -DLLVM_ENABLE_PROJECTS=<span class="hljs-string">"clang;clang-tools-extra"</span> # Enable the clang-tools projects <span class="hljs-keyword">in</span> our build <span class="hljs-keyword">as</span> well
</code></pre><p>This should generate a build.ninja file, which I encourage you to open and check out the contents. You will see that it contains a list of targets followed by dependencies. For example, one of the targets may look something like this: </p>
<pre><code>#############################################
# Utility command <span class="hljs-keyword">for</span> install-llvm-headers

build install-llvm-headers: phony CMakeFiles/install-llvm-headers llvm-headers
</code></pre><p> We’ll also do this for the custom static analysis tool we build in the next steps.</p>
<p>###4. Build and install all targets specified in the build.ninja file</p>
<p><code>ninja; ninja install</code></p>
<p>Okay, the setup is done and now we get to the fun part!</p>
<h2 id="heading-how-to-create-the-scaffolding-for-the-static-analysis-tool">How to Create the Scaffolding for the Static Analysis Tool</h2>
<p>We’ll be building our tool as a part of the <code>clang-tools-extra</code> directory in <code>llvm-project/clang-tools-extra</code>. Let's go ahead and create that directory. We’ll call our tool <code>class-analyzer</code>.</p>
<pre><code>mkdir ~<span class="hljs-regexp">/ast-analyzer/</span>llvm-project/clang-tools-extra/<span class="hljs-class"><span class="hljs-keyword">class</span>-<span class="hljs-title">analyzer</span>
<span class="hljs-title">cd</span> ~/<span class="hljs-title">ast</span>-<span class="hljs-title">analyzer</span>/<span class="hljs-title">llvm</span>-<span class="hljs-title">project</span>/<span class="hljs-title">clang</span>-<span class="hljs-title">tools</span>-<span class="hljs-title">extra</span>/<span class="hljs-title">class</span>-<span class="hljs-title">analyzer</span></span>
</code></pre><p>Now we need to create a <code>CMakeLists.txt</code>. This is basically a file that tells the <code>CMake</code> build system to add the source files in this tool to the <code>build.ninja</code> file it will generate. This lets <code>ninja</code> know how to build our tool.</p>
<p>Our <code>CMakeLists.txt</code> file will look like this:</p>
<p>CMakeLists.txt</p>
<pre><code>set(LLVM_LINK_COMPONENTS support)
set(CMAKE_CXX_COMPILER /usr/bin/clang++)  


add_clang_executable(<span class="hljs-class"><span class="hljs-keyword">class</span>-<span class="hljs-title">analyzer</span>
  <span class="hljs-title">ClassAnalzyer</span>.<span class="hljs-title">cpp</span>
  <span class="hljs-title">MyFrontendActionFactory</span>.<span class="hljs-title">cpp</span>
  <span class="hljs-title">MyFrontendAction</span>.<span class="hljs-title">cpp</span>
  <span class="hljs-title">MyASTConsumer</span>.<span class="hljs-title">cpp</span>
  )
<span class="hljs-title">target_link_libraries</span>(<span class="hljs-title">class</span>-<span class="hljs-title">analyzer</span>
  <span class="hljs-title">PRIVATE</span>
  <span class="hljs-title">clangAST</span>
  <span class="hljs-title">clangFrontend</span>
  <span class="hljs-title">clangTooling</span>
  )</span>
</code></pre><p>The first couple lines tell the build system that the compiler should be <code>/usr/local/bin/clang++</code> (the one just built in the previous steps).</p>
<p>The next <code>add_clang_executable</code> section tells the build system which source files to build as a part of our executable. We'll get more into the details of what each source file does soon. It also tells defines the name of the executable for the build system. Here it is called <code>class-analyzer</code> since it analyzes class names. </p>
<p>The <code>target_link_libraries</code> section informs the build system about the Clang front end libraries we should be linking against. These are the libraries which really expose the power of Clang’s AST to the tool we'll build.</p>
<p>Clang's API documentation is a good place to start looking for hints on how we should start writing the <code>class-analyzer</code> tool. Another good place to start is by scanning the source code of the Clang project we cloned earlier, for other tools! <code>[clang-tools-extra](https://github.com/llvm/llvm-project/tree/main/clang-tools-extra)</code> has multiple examples – these have been a source of inspiration for the code written here.</p>
<p>So now, let's start with the code for our very first source file. This file is contains the <code>main()</code> function of the executable. It looks something like this:</p>
<pre><code class="lang-cpp">
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">"clang/Tooling/CommonOptionsParser.h"</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">"clang/Tooling/Tooling.h"</span></span>

<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">"MyFrontendActionFactory.h"</span></span>

<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;memory&gt;</span></span>

<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> clang::tooling;
<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> llvm;

<span class="hljs-keyword">static</span> llvm::<span class="hljs-function">cl::OptionCategory <span class="hljs-title">toolCategory</span><span class="hljs-params">(<span class="hljs-string">"class-analyzer &lt;options&gt;"</span>)</span></span>;

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">(<span class="hljs-keyword">int</span> argc, <span class="hljs-keyword">const</span> <span class="hljs-keyword">char</span>** argv)</span>
</span>{
    <span class="hljs-comment">// Use clang's argument parser infrastructure</span>
    <span class="hljs-comment">// This is used for giving clang tooling the path</span>
    <span class="hljs-comment">// to the source files passed in to the tool.</span>
    <span class="hljs-comment">// It also gets the compilation database - a collection</span>
    <span class="hljs-comment">// of the compiler options used in the invocation of the tool</span>
    <span class="hljs-keyword">auto</span> argsParser = CommonOptionsParser::create(
        argc, argv, toolCategory);
    <span class="hljs-keyword">if</span> (!expectedArgsParser) {
        llvm::errs() &lt;&lt; argsParser.takeError();
        <span class="hljs-keyword">return</span> <span class="hljs-number">-1</span>;
    }
    CommonOptionsParser&amp; optionsParser
        = argsParser.get();
    <span class="hljs-function">ClangTool <span class="hljs-title">tool</span><span class="hljs-params">(optionsParser.getCompilations(),
                   optionsParser.getSourcePathList())</span></span>;
    <span class="hljs-keyword">auto</span> myActionFactory
        = <span class="hljs-built_in">std</span>::make_unique&lt;MyFrontendActionFactory&gt;();

    <span class="hljs-keyword">return</span> tool.run(myActionFactory.get());
}
</code></pre>
<p>This source file essentially creates a tool which runs a <code>clang</code> <a target="_blank" href="https://clang.llvm.org/doxygen/classclang_1_1tooling_1_1FrontendActionFactory.html"><code>FrontendActionFactory</code></a>. Now to understand what <code>FrontendActionFactory</code> does, let's take a look at Clang's documentation for it. </p>
<p>We see that it has a pure virtual method, </p>
<pre><code class="lang-cpp"><span class="hljs-function"><span class="hljs-keyword">virtual</span> <span class="hljs-built_in">std</span>::<span class="hljs-built_in">unique_ptr</span>&lt;FrontendAction&gt; <span class="hljs-title">create</span> <span class="hljs-params">()</span> </span>= <span class="hljs-number">0</span>;
</code></pre>
<p>which returns an <a target="_blank" href="https://en.cppreference.com/w/cpp/memory/unique_ptr"><code>std::unique_ptr</code></a> to a <code>[FrontendAction](https://clang.llvm.org/doxygen/classclang_1_1FrontendAction.html)</code> object. <code>FrontendAction</code> is, in its essence, a class which allows callers to perform custom actions as Clang parses the AST of a translation unit given to it. A <a target="_blank" href="https://en.wikipedia.org/wiki/Translation_unit_(programming)">translation unit</a> in simple words is the combined code given to the compiler to create an object file. It contains code included through all the header files + code in a C / C++ source file</p>
<p> This will become clearer as we get further along in the article.</p>
<p>Now we come to writing our own <code>FrontendActionFactory</code> which you can call <code>MyFrontendActionFactory</code>. This is a very simple class which just overrides the <code>create()</code> virtual method. It looks like this:</p>
<pre><code class="lang-cpp"><span class="hljs-comment">// Header file MyFrontendActionFactory.h</span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">pragma</span> once</span>

include&lt;clang/Tooling/Tooling.h&gt;


<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyFrontendActionFactory</span> :</span> <span class="hljs-keyword">public</span> clang::tooling::FrontendActionFactory{
    <span class="hljs-keyword">public</span>:
    MyFrontendActionFactory();
    <span class="hljs-function"><span class="hljs-built_in">std</span>::<span class="hljs-built_in">unique_ptr</span>&lt;clang::FrontendAction&gt; <span class="hljs-title">create</span><span class="hljs-params">()</span> <span class="hljs-keyword">override</span></span>;
};                                                         

<span class="hljs-comment">// Source file MyFrontendActionFactory.cpp</span>

<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">"MyFrontendActionFactory.h"</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">"MyFrontendAction.h"</span></span>

MyFrontendActionFactory::MyFrontendActionFactory() {

}

<span class="hljs-function"><span class="hljs-built_in">std</span>::<span class="hljs-built_in">unique_ptr</span>&lt;clang::FrontendAction&gt; <span class="hljs-title">MyFrontendActionFactory::create</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">std</span>::make_unique&lt;MyFrontendAction&gt;();
}
</code></pre>
<p>Since <code>MyFrontendActionFactory::create()</code> needs to return an <code>std::unique_ptr</code> to <code>clang::FrontendAction</code>, we'll need to create a <code>clang::FrontendAction</code> object. </p>
<p>If we look at the Clang documentation for <a target="_blank" href="https://clang.llvm.org/doxygen/classclang_1_1FrontendAction.html"><code>FrontendAction</code></a>, we'll be particularly interested in looking at what we can do with the AST (Abstract Syntax Tree) of the source. </p>
<p>We might spot the following method:</p>
<pre><code class="lang-cpp"><span class="hljs-function"><span class="hljs-keyword">virtual</span> <span class="hljs-built_in">std</span>::<span class="hljs-built_in">unique_ptr</span>&lt; ASTConsumer &gt;
<span class="hljs-title">CreateASTConsumer</span> <span class="hljs-params">(CompilerInstance &amp;CI, StringRef InFile)</span> </span>= <span class="hljs-number">0</span>;
</code></pre>
<p>This is a virtual method that a class which inherits from FrontendAction can implement. It returns an <a target="_blank" href="https://clang.llvm.org/doxygen/classclang_1_1ASTConsumer.html#details"><code>ASTConsumer</code></a> which according to the documentation,</p>
<blockquote>
<p> <em>"...is an abstract interface that should be implemented by clients that read ASTs."</em></p>
</blockquote>
<p>So, this method looks really promising if we want to create something that will let us read the Clang generated AST!</p>
<p>If we look at the <code>FrontendAction</code> documentation again, it shows us that <code>ASTFrontend</code> is a class that inherits from <code>FrontendAction</code>. We also learn that it is:</p>
<blockquote>
<p>"The Abstract base class to use for AST consumer-based frontend actions."</p>
</blockquote>
<p>It only has one pure virtual method: <code>CreateASTConsumer()</code>. This seems promising, since...we might be able to create our own <code>ASTConsumer</code> object.</p>
<p>So, we start by reading through <code>ASTConsumer</code>'s <a target="_blank" href="https://clang.llvm.org/doxygen/classclang_1_1ASTConsumer.html">documentation</a>. We see that it has a virtual method</p>
<pre><code class="lang-cpp"><span class="hljs-keyword">virtual</span> <span class="hljs-keyword">void</span>
clang::ASTConsumer::HandleTranslationUnit(ASTContext &amp;Ctx)
</code></pre>
<p>where the documentation states:</p>
<blockquote>
<p> "<code>HandleTranslationUnit</code> - This method is called when the ASTs for entire translation unit have been parsed". </p>
</blockquote>
<p>This is exactly what we want. We can override this method to do interesting things with the parsed AST.</p>
<p>You might now be wondering – how exactly can we use the parameter passed to this function <code>ASTContext</code> to actually go through the AST? </p>
<p>There's a class in the Clang front end API which can help us here: <a target="_blank" href="https://clang.llvm.org/doxygen/classclang_1_1RecursiveASTVisitor.html"><code>RecursiveASTVisitor</code></a>. This is a class that does a depth-first traversal of the Clang AST and visits each node. It has methods such as <code>VisitDecl()</code>, <code>VisitStmt()</code> and so on which can help us go through virtually the whole source file's AST. </p>
<p>It also has a method which is particularly interesting: <a target="_blank" href="https://clang.llvm.org/doxygen/classclang_1_1RecursiveASTVisitor.html#a99a9e941a07a015bc18d3613c5aa0914"><code>TraverseDecl()</code></a>. This method recursively traverses through all the declarations starting from the root declaration given to it.</p>
<h2 id="heading-putting-it-all-together-in-code">Putting it All Together in Code</h2>
<p>So now what we need to do is give <code>TraverseDecl()</code> the root declaration of our translation unit and it will traverse the entirety of it. We can define special 'hooks' which will get called as this traversal happens. One such hook is:</p>
<pre><code class="lang-cpp"><span class="hljs-function"><span class="hljs-keyword">bool</span> <span class="hljs-title">VisitRecordDecl</span><span class="hljs-params">(<span class="hljs-keyword">const</span> clang::RecordDecl *record)</span></span>;
</code></pre>
<p>This is called each time the <code>RecursiveASTVisitor</code> traverses through a <code>CXXRecordDecl</code> – which is Clang speak for a C++ class. We'll overload this method with our own version to do something interesting: getting the C++ Class' name and seeing if it starts with an upper-case character. </p>
<p>Putting all this together, here's what we get:</p>
<pre><code class="lang-cpp"><span class="hljs-comment">// MyFrontendAction.h header file</span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">pragma</span> once</span>

<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;clang/Frontend/FrontendAction.h&gt;</span></span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyFrontendAction</span> :</span> <span class="hljs-keyword">public</span> clang::ASTFrontendAction {
    <span class="hljs-keyword">protected</span>:
        <span class="hljs-function"><span class="hljs-built_in">std</span>::<span class="hljs-built_in">unique_ptr</span>&lt;clang::ASTConsumer&gt; <span class="hljs-title">CreateASTConsumer</span><span class="hljs-params">(clang::CompilerInstance &amp;ci, llvm::StringRef file)</span> <span class="hljs-keyword">override</span></span>;
};    

<span class="hljs-comment">// MyFrontendAction.cpp source file</span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">"MyFrontendAction.h"</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">"MyASTConsumer.h"</span></span>

<span class="hljs-function"><span class="hljs-built_in">std</span>::<span class="hljs-built_in">unique_ptr</span>&lt;clang::ASTConsumer&gt; <span class="hljs-title">MyFrontendAction::CreateASTConsumer</span><span class="hljs-params">(clang::CompilerInstance &amp;ci, llvm::StringRef file)</span> </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">std</span>::make_unique&lt;MyASTConsumer&gt;(ci, file);
}
</code></pre>
<pre><code class="lang-cpp">
<span class="hljs-comment">//MyASTConsumer.h header file</span>

<span class="hljs-meta">#<span class="hljs-meta-keyword">pragma</span> once</span>

<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span><span class="hljs-meta-string">&lt;clang/AST/ASTConsumer.h&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span><span class="hljs-meta-string">&lt;clang/Frontend/CompilerInstance.h&gt;</span></span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyASTConsumer</span> :</span> <span class="hljs-keyword">public</span> clang::ASTConsumer {

<span class="hljs-keyword">public</span>:
    MyASTConsumer(clang::CompilerInstance &amp;ci, llvm::StringRef file) {}
    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">HandleTranslationUnit</span><span class="hljs-params">(clang::ASTContext &amp;context)</span> <span class="hljs-keyword">override</span></span>;
};

<span class="hljs-comment">// MyASTConsumer.cpp source file</span>

<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;clang/AST/RecursiveASTVisitor.h&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">"MyASTConsumer.h"</span></span>

<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>

<span class="hljs-function"><span class="hljs-keyword">static</span> <span class="hljs-keyword">bool</span> <span class="hljs-title">isFirstLetterUpperCase</span><span class="hljs-params">(<span class="hljs-keyword">const</span> <span class="hljs-built_in">std</span>::<span class="hljs-built_in">string</span> &amp;str)</span> </span>{
    <span class="hljs-keyword">return</span> str.size() != <span class="hljs-number">0</span> &amp;&amp; <span class="hljs-built_in">std</span>::<span class="hljs-built_in">isupper</span>(str[<span class="hljs-number">0</span>]);
}
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyASTVisitor</span> :</span> <span class="hljs-keyword">public</span> clang::RecursiveASTVisitor&lt;MyASTVisitor&gt; {
    <span class="hljs-keyword">public</span>:
    <span class="hljs-function"><span class="hljs-keyword">bool</span> <span class="hljs-title">VisitCXXRecordDecl</span><span class="hljs-params">(<span class="hljs-keyword">const</span> clang::RecordDecl *record)</span> </span>{
        <span class="hljs-built_in">std</span>::<span class="hljs-built_in">string</span> name = record-&gt;getNameAsString();

        <span class="hljs-keyword">if</span> (!isFirstLetterUpperCase(name)) {
            <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"Record Decl : "</span> &lt;&lt; name
                      &lt;&lt;<span class="hljs-string">" doesn't start with uppercase! \n"</span>;
        }

        <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
    }
    <span class="hljs-function"><span class="hljs-keyword">bool</span> <span class="hljs-title">TraverseDecl</span><span class="hljs-params">(clang::Decl *decl)</span>  </span>{
        <span class="hljs-keyword">return</span>
           clang::RecursiveASTVisitor&lt;MyASTVisitor&gt;::TraverseDecl(decl);
    }
};

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">MyASTConsumer::HandleTranslationUnit</span><span class="hljs-params">(clang::ASTContext &amp;ctx)</span> </span>{
    clang::TranslationUnitDecl *tuDecl = ctx.getTranslationUnitDecl();
    MyASTVisitor visitor;
    visitor.TraverseDecl(tuDecl);
}
</code></pre>
<p>Now to build, we just do:</p>
<p><code>cd ~/ast-analyzer/build/;  ninja class-analyzer</code></p>
<p>This builds the <code>class-analyzer</code> executable in the <code>build/bin</code> directory.</p>
<p>Now to test out the analyzer, we create a test.cpp source file:</p>
<pre><code class="lang-cpp"><span class="hljs-comment">// test.cpp</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Test</span> {</span>
<span class="hljs-keyword">public</span>:
 <span class="hljs-keyword">int</span> a;
};

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">testLower</span> {</span>
<span class="hljs-keyword">public</span>:
 <span class="hljs-keyword">int</span> b;
};

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>Run <code>class-analyzer</code> on it:</p>
<pre><code>bin/<span class="hljs-class"><span class="hljs-keyword">class</span>-<span class="hljs-title">analyzer</span> <span class="hljs-title">test</span>.<span class="hljs-title">cpp</span></span>
</code></pre><p>The output of this command is :</p>
<pre><code>Record Decl : testLower doesn<span class="hljs-string">'t start with uppercase!</span>
</code></pre><p>We can use a multitude of such <code>Visit*</code> methods such as <code>VisitEnumDecl</code>, <code>VisitFunctionDecl</code>, <code>VisitVarDecl</code>, and so on to get valuable information about the source file and create our own tools. Just think about any tool which runs and performs actions on code or gives suggestions to the user. </p>
<p>You may think that this seems like a lot of work for a small task. But think about the potential. For example, you could write a tool which automatically gives a user suggestions to improve their code style. Or you could create a tool which analyses C++ code and finds lines of code where there might be security vulnerabilities. </p>
<p>The possibilities are endless. Clang's front-end libraries are extremely powerful and you can build many cool projects and tools with them.</p>
<h2 id="heading-summary">Summary</h2>
<p>In this article, you learned how to get and use the rich collection of Clang's Front-end libraries to parse a C++ source AST. You can use these libraries to write interesting static code analysis tools. </p>
<p>As this article showed, one of the most important parts of the journey of exploring Clang's libraries is the art of reading the API documentation and applying it to the problems your tools aim to solve. I hope you enjoyed the article! </p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
