1<!DOCTYPE html> 2<html lang="en" class="dark"> 3 <head> 4 <meta charset="utf-8" /> 5 <meta name="viewport" content="width=device-width, initial-scale=1" /> 6 <link rel="icon" href="/favicon.png" /> 7 <title>Rust's cfg Attribute</title><meta name="description" data-svelte="svelte-13mrx5r"><meta name="author" content="Parker Codes â Blog" data-svelte="svelte-13mrx5r"><meta property="og:url" content="https://parker-codes.onrender.com/rusts-cfg-attribute" data-svelte="svelte-13mrx5r"><meta property="og:type" content="website" data-svelte="svelte-13mrx5r"><meta property="og:title" content="Rust's cfg Attribute" data-svelte="svelte-13mrx5r"><meta property="og:description" data-svelte="svelte-13mrx5r"><meta property="og:image" content="https://og-image.vercel.app/**Rust's%20cfg%20Attribute**?theme=light&md=1&fontSize=100px&images=https%3A%2F%2Fassets.vercel.com%2Fimage%2Fupload%2Ffront%2Fassets%2Fdesign%2Fhyper-color-logo.svg" data-svelte="svelte-13mrx5r"><meta name="twitter:card" content="summary_large_image" data-svelte="svelte-13mrx5r"><meta property="twitter:domain" content="https://parker-codes.onrender.com" data-svelte="svelte-13mrx5r"><meta property="twitter:url" content="https://parker-codes.onrender.com/rusts-cfg-attribute" data-svelte="svelte-13mrx5r"><meta name="twitter:title" content="Rust's cfg Attribute" data-svelte="svelte-13mrx5r"><meta name="twitter:description" data-svelte="svelte-13mrx5r"><meta name="twitter:image" content="https://og-image.vercel.app/**Rust's%20cfg%20Attribute**?theme=light&md=1&fontSize=100px&images=https%3A%2F%2Fassets.vercel.com%2Fimage%2Fupload%2Ffront%2Fassets%2Fdesign%2Fhyper-color-logo.svg" data-svelte="svelte-13mrx5r"> 8 9 10 11 <link rel="stylesheet" href="/_app/assets/start-d977ffc4.css"> 12 <link rel="stylesheet" href="/_app/assets/pages/__layout.svelte-7bc16a4d.css"> 13 <link rel="stylesheet" href="/_app/assets/pages/posts/_slug_.svelte-2022a594.css"> 14 <link rel="stylesheet" href="/_app/assets/PostPreview-4f0d7754.css"> 15 <link rel="modulepreload" href="/_app/start-47edef97.js"> 16 <link rel="modulepreload" href="/_app/chunks/vendor-f1d98b68.js"> 17 <link rel="modulepreload" href="/_app/chunks/preload-helper-ec9aa979.js"> 18 <link rel="modulepreload" href="/_app/pages/__layout.svelte-4d46aee8.js"> 19 <link rel="modulepreload" href="/_app/chunks/info-510e793d.js"> 20 <link rel="modulepreload" href="/_app/pages/posts/_slug_.svelte-5fccf50f.js"> 21 <link rel="modulepreload" href="/_app/chunks/PostPreview-476c59e7.js"> 22 <link rel="modulepreload" href="/_app/chunks/ArrowLeftIcon-9ecadb12.js"> 23 24
24<script type="module"> 25 import { start } from "/_app/start-47edef97.js"; 26 start({ 27 target: document.querySelector("#svelte"), 28 paths: {"base":"","assets":""}, 29 session: {}, 30 route: true, 31 spa: false, 32 trailing_slash: "never", 33 hydrate: { 34 status: 200, 35 error: null, 36 nodes: [ 37 import("/_app/pages/__layout.svelte-4d46aee8.js"), 38 import("/_app/pages/posts/_slug_.svelte-5fccf50f.js") 39 ], 40 url: new URL("http://prerender/posts/rusts-cfg-attribute"), 41 params: {slug:"rusts-cfg-attribute"} 42 } 43 }); 44 </script>
44 45
45<script> 46 const storageValue = JSON.parse(localStorage.getItem('prefersLight')); 47 const prefersLight = storageValue 48 ? Boolean(storageValue) 49 : window?.matchMedia('(prefers-color-scheme: light)').matches; 50 51 localStorage.setItem('prefersLight', prefersLight); 52 53 // default to dark mode unless explicitly set preference to light 54 if (prefersLight) { 55 document.querySelector('html').classList.remove('dark'); 56 } 57 </script>
57 58 </head> 59 60 <body class="relative transition-colors duration-100 bg-slate-100 dark:bg-slate-900"> 61 <div 62 class="fixed inset-0 -z-50 dark:bg-gradient-to-br dark:from-slate-900 dark:to-slate-800" 63 ></div> 64 <div id="svelte" class="z-0"> 65 66 67<div class="flex flex-col min-h-screen"><div class="mx-auto flex flex-col flex-grow w-full max-w-4xl"><div class="flex h-16 px-4 py-2 justify-between items-center"><h2 class="!text-transparent bg-clip-text bg-gradient-to-r from-blue-500 to-teal-500 dark:from-violet-500 dark:to-pink-500"><a class="text-lg sm:text-2xl font-bold" href="/">Parker Codes â Blog</a></h2> 68 </div> 69 70 <main class="prose prose-slate prose-sm sm:prose sm:prose-slate sm:prose-lg sm:max-w-none dark:prose-invert flex flex-col w-full flex-grow py-4 px-4"> 71 72<article class="relative"><h1 class="!mt-0 !mb-2"><a class="!font-medium" href="/posts/rusts-cfg-attribute">Rust's cfg Attribute</a></h1> 73 <div class="opacity-70"><time datetime="2023-06-01T00:00:00.000Z">June 1, 2023</time> 74 ⢠75 <span>12 min read</span></div> 76 77 <div class="relative break-words"> 78 <h2 id="how-it-works"><a href="#how-it-works">How it works</a></h2> 79<p>Rustâs <code>#[cfg()]</code> attribute is a powerful feature that allows developers to conditionally compile code based on specified conditions at compile time. It enables fine-grained control over which portions of code are included or excluded during the compilation process, resulting in more efficient and optimized programs.</p> 80<p>At its core, <code>#[cfg()]</code> is a compile-time attribute macro (as opposed to a function-like macro). It allows Rust to evaluate the predicate and decide whether to include or exclude specific code blocks or items during compilation. Weâll walk through many examples of how to express the predicate as well as where this attribute can be used.</p> 81<blockquote><p><strong><em>NOTE:</em></strong> <code>cfg</code> is short for <em>configuration</em>! You can read it as âif this configuration exists, include this codeâ.</p></blockquote> 82<hr> 83<h2 id="conditions"><a href="#conditions">Conditions</a></h2> 84<p>Rust provides several built-in options that can be used with <code>#[cfg()]</code> to define what conditions should allow the code to be included in the build.</p> 85<h3 id="target-operating-system"><a href="#target-operating-system">Target Operating System</a></h3> 86<a href="https://doc.rust-lang.org/reference/conditional-compilation.html#target_os" target="_blank">Docs</a> 87<pre class="language-rust"><!-- HTML_TAG_START --><code class="language-rust"><span class="token attribute attr-name">#[cfg(target_os = <span class="token string">"android"</span>)]</span> 88<span class="token keyword">fn</span> <span class="token function-definition function">connect_to_instant_apps</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span> 89 <span class="token comment">// ...</span> 90<span class="token punctuation">}</span></code><!-- HTML_TAG_END --></pre> 91<h3 id="target-arch"><a href="#target-arch">Target Arch</a></h3> 92<a href="https://doc.rust-lang.org/reference/conditional-compilation.html#target_arch" target="_blank">Docs</a> 93<pre class="language-rust"><!-- HTML_TAG_START --><code class="language-rust"><span class="token attribute attr-name">#[cfg(target_arch = <span class="token string">"x86_64"</span>)]</span> 94<span class="token keyword">fn</span> <span class="token function-definition function">target_system_config</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">-></span> <span class="token class-name">Option</span><span class="token operator"><</span><span class="token class-name">SystemConfig</span><span class="token operator">></span> <span class="token punctuation">{</span> 95 <span class="token comment">// ...</span> 96<span class="token punctuation">}</span></code><!-- HTML_TAG_END --></pre> 97<h3 id="feature-flags"><a href="#feature-flags">Feature flags</a></h3> 98<p>With the <code>feature</code> option, developers can conditionally compile code based on whether a specific feature flag is enabled. This is particularly useful when building libraries or applications with optional features.</p> 99<pre class="language-rust"><!-- HTML_TAG_START --><code class="language-rust"><span class="token attribute attr-name">#[cfg(feature = <span class="token string">"server"</span>)]</span> 100<span class="token keyword">fn</span> <span class="token function-definition function">render</span><span class="token punctuation">(</span>nodes<span class="token punctuation">:</span> <span class="token class-name">Vec</span><span class="token operator"><</span><span class="token class-name">Node</span><span class="token operator">></span><span class="token punctuation">)</span> <span class="token punctuation">-></span> <span class="token keyword">impl</span> <span class="token class-name">View</span> <span class="token punctuation">{</span> 101 <span class="token comment">
101// ...</span> 102<span class="token punctuation">}</span></code><!-- HTML_TAG_END --></pre> 103<h3 id="debug-mode"><a href="#debug-mode">Debug Mode</a></h3> 104<a href="https://doc.rust-lang.org/reference/conditional-compilation.html#debug_assertions" target="_blank">Docs</a> 105<p>The <code>debug_assertions</code> option allows you to selectively compile code for debugging purposes.</p> 106<pre class="language-rust"><!-- HTML_TAG_START --><code class="language-rust"><span class="token attribute attr-name">#[cfg(debug_assertions)]</span> 107<span class="token keyword">fn</span> <span class="token function-definition function">debug_payload</span><span class="token punctuation">(</span>payload<span class="token punctuation">:</span> <span class="token operator">&</span><span class="token class-name">Payload</span><span class="token punctuation">)</span> <span class="token punctuation">{</span> 108 <span class="token comment">// Code runs only in debug mode</span> 109<span class="token punctuation">}</span></code><!-- HTML_TAG_END --></pre> 110<h3 id="tests"><a href="#tests">Tests</a></h3> 111<a href="https://doc.rust-lang.org/reference/conditional-compilation.html#test" target="_blank">Docs</a> 112<pre class="language-rust"><!-- HTML_TAG_START --><code class="language-rust"><span class="token attribute attr-name">#[cfg(test)]</span> 113<span class="token keyword">fn</span> <span class="token function-definition function">save</span><span class="token punctuation">(</span><span class="token operator">&</span><span class="token keyword">self</span><span class="token punctuation">)</span> <span class="token punctuation">{</span> 114 <span class="token comment">// Don't persist since this isn't production code</span> 115<span class="token punctuation">}</span></code><!-- HTML_TAG_END --></pre> 116<hr> 117<h2 id="combinators"><a href="#combinators">Combinators</a></h2> 118<p><code>#[cfg()]</code> has the ability to handle complex conditions using various combinators while still remaining readable.</p> 119<h3 id="all-conditions"><a href="#all-conditions">All conditions</a></h3> 120<p>For instance, the <code>all()</code> combinator allows multiple conditions to be combined using logical AND, ensuring that all conditions must evaluate to true for the associated code to be compiled.</p> 121<pre class="language-rust"><!-- HTML_TAG_START --><code class="language-rust"><span class="token comment">// Only included when compiling for a unixish OS with a 32-bit architecture</span> 122<span class="token attribute attr-name">#[cfg(all(unix, target_pointer_width = <span class="token string">"32"</span>))]</span> 123<span class="token keyword">fn</span> <span class="token function-definition function">on_32bit_unix</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span> 124 <span class="token comment">// ...</span> 125<span class="token punctuation">}</span></code><!-- HTML_TAG_END --></pre> 126<h3 id="any-conditions"><a href="#any-conditions">Any conditions</a></h3> 127<p>On the other hand, the <code>any()</code> combinator uses logical OR, allowing the code to be compiled if any of the specified conditions are true.</p> 128<pre class="language-rust"><!-- HTML_TAG_START --><code class="language-rust"><span class="token comment">// This will compile when targetting Android or iOS</span> 129<span class="token attribute attr-name">#[cfg(any(target_os = <span class="token string">"android"</span>, target_os = <span class="token string">"ios"</span>))]</span> 130<span class="token keyword">fn</span> <span class="token function-definition function">on_mobile</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span> 131 <span class="token comment">// ...</span> 132<span class="token punctuation">}</span></code><!-- HTML_TAG_END --></pre> 133<h3 id="negate-conditions"><a href="#negate-conditions">Negate condition(s)</a></h3> 134<p>Additionally, the <code>not()</code> combinator negates the condition (or set of conditions), allowing the code to be compiled when the specified condition is false. Hereâs the opposite of the previous function:</p> 135<pre class="language-rust"><!-- HTML_TAG_START --><code class="language-rust"><span class="token comment">// This will compile when NOT targetting Android or iOS</span> 136<span class="token attribute attr-name">#[cfg(not(any(target_os = <span class="token string">"android"</span>, target_os = <span class="token string">"ios"</span>)))]</span> 137<span class="token keyword">fn</span> <span class="token function-definition function">not_on_mobile</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span> 138 <span class="token comment">
138// ...</span> 139<span class="token punctuation">}</span></code><!-- HTML_TAG_END --></pre> 140<hr> 141<h2 id="expressiveness"><a href="#expressiveness">Expressiveness</a></h2> 142<p>A notable application of <code>#[cfg()]</code> is compile-time function overriding. By defining multiple implementations of a function with different conditions, Rust allows for clean and concise code that adapts to different target platforms or compilation configurations. This flexibility ensures that only the relevant code paths are compiled and executed, leading to more efficient binaries.</p> 143<pre class="language-rust"><!-- HTML_TAG_START --><code class="language-rust"><span class="token comment">// Determine cache dir for Windows.</span> 144<span class="token attribute attr-name">#[cfg(target_os = <span class="token string">"windows"</span>)]</span> 145<span class="token keyword">const</span> <span class="token keyword">fn</span> <span class="token function-definition function">default_cache_dir</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">-></span> <span class="token operator">&</span><span class="token lifetime-annotation symbol">'static</span> <span class="token keyword">str</span> <span class="token punctuation">{</span> 146 <span class="token string">"C:/cache"</span> 147<span class="token punctuation">}</span> 148 149<span class="token comment">/// Determine cache dir for Linux.</span> 150<span class="token attribute attr-name">#[cfg(target_os = <span class="token string">"linux"</span>)]</span> 151<span class="token keyword">const</span> <span class="token keyword">fn</span> <span class="token function-definition function">default_cache_dir</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">-></span> <span class="token operator">&</span><span class="token lifetime-annotation symbol">'static</span> <span class="token keyword">str</span> <span class="token punctuation">{</span> 152 <span class="token string">"/mnt/c/cache"</span> 153<span class="token punctuation">}</span></code><!-- HTML_TAG_END --></pre> 154<p>And then somewhere else:</p> 155<pre class="language-rust"><!-- HTML_TAG_START --><code class="language-rust"><span class="token function">generate_cache_items_from</span><span class="token punctuation">(</span><span class="token function">default_cache_dir</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span></code><!-- HTML_TAG_END --></pre> 156<p>Rust ensures that any unused variables or unsupported function invocations are detected and handled appropriately. For example, if a function is only available when running on Linux targets, then calling that function must also be marked as conditional to match. But if there are functions to handle the other targets then at compile time it will know which function will be called.</p> 157<p>To continue our previous example, trying to compile our program on Windows or Linux will work fine. Weâll need to explicitly state which combination of targets that statement supports if we want our program to compile on MacOS though, like so:</p> 158<pre class="language-rust"><!-- HTML_TAG_START --><code class="language-rust"><span class="token attribute attr-name">#[cfg(any(target_os = <span class="token string">"windows"</span>, target_os = <span class="token string">"linux"</span>))]</span> 159<span class="token function">generate_cache_items_from</span><span class="token punctuation">(</span><span class="token function">default_cache_dir</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span> 160 161<span class="token attribute attr-name">#[cfg(target_os = <span class="token string">"macos"</span>)]</span> 162<span class="token macro property">println!</span><span class="token punctuation">(</span><span class="token string">"Caching is not supported on MacOS"</span><span class="token punctuation">)</span><span class="token punctuation">;</span></code><!-- HTML_TAG_END --></pre> 163<p>
163This attribute is not limited to specific code constructs. It can be applied to statements, functions, blocks, imports, and more. This versatility allows developers to selectively include or exclude code at various levels of granularity, depending on their specific requirements. Here are several examples:</p> 164<h3 id="modules"><a href="#modules">Modules</a></h3> 165<p>This is one youâve probably seen before!</p> 166<pre class="language-rust"><!-- HTML_TAG_START --><code class="language-rust"><span class="token attribute attr-name">#[cfg(test)]</span> 167<span class="token keyword">mod</span> <span class="token module-declaration namespace">tests</span> <span class="token punctuation">{</span> 168 <span class="token keyword">use</span> <span class="token keyword">super</span><span class="token punctuation">::</span><span class="token operator">*</span><span class="token punctuation">;</span> 169 170 <span class="token attribute attr-name">#[test]</span> 171 <span class="token keyword">fn</span> <span class="token function-definition function">insert_and_get</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span> 172 <span class="token comment">// ...</span> 173 <span class="token punctuation">}</span> 174<span class="token punctuation">}</span></code><!-- HTML_TAG_END --></pre> 175<h3 id="code-blocks"><a href="#code-blocks">Code blocks</a></h3> 176<pre class="language-rust"><!-- HTML_TAG_START --><code class="language-rust"><span class="token comment">// The real deal</span> 177<span class="token attribute attr-name">#[cfg(not(vendor_testing))]</span> 178<span class="token punctuation">{</span> 179 <span class="token macro property">trace!</span><span class="token punctuation">(</span><span class="token string">"Starting payment processing"</span><span class="token punctuation">)</span><span class="token punctuation">;</span> 180 <span class="token keyword">if</span> <span class="token keyword">let</span> <span class="token class-name">Ok</span><span class="token punctuation">(</span>details<span class="token punctuation">)</span> <span class="token operator">=</span> <span class="token function">process_payment</span><span class="token punctuation">(</span><span class="token operator">&</span>transaction<span class="token punctuation">)</span> <span class="token punctuation">{</span> 181 db<span class="token punctuation">.</span><span class="token function">store</span><span class="token punctuation">(</span><span class="token operator">&</span>details<span class="token punctuation">)</span><span class="token punctuation">;</span> 182 <span class="token punctuation">}</span> 183 <span class="token macro property">trace!</span><span class="token punctuation">(</span><span class="token string">"Ending payment processing"</span><span class="token punctuation">)</span><span class="token punctuation">;</span> 184<span class="token punctuation">}</span> 185<span class="token comment">// When testing vendor payments</span> 186<span class="token attribute attr-name">#[cfg(vendor_testing)]</span> 187<span class="token punctuation">{</span> 188 <span class="token macro property">debug!</span><span class="token punctuation">(</span><span class="token string">"Starting mock payment processing"</span><span class="token punctuation">)</span><span class="token punctuation">;</span> 189 <span class="token keyword">if</span> <span class="token keyword">let</span> <span class="token class-name">Ok</span><span class="token punctuation">(</span>details<span class="token punctuation">)</span> <span class="token operator">=</span> <span class="token function">mock_process_payment</span><span class="token punctuation">(</span><span class="token operator">&</span>transaction<span class="token punctuation">)</span> <span class="token punctuation">{</span> 190 <span class="token macro property">debug!</span><span class="token punctuation">(</span><span class="token string">"Payment details"</span><span class="token punctuation">,</span> <span class="token operator">&</span>details<span class="token punctuation">)</span><span class="token punctuation">;</span> 191 <span class="token punctuation">}</span> 192 <span class="token macro property">debug!</span><span class="token punctuation">(</span><span class="token string">"Ending mock payment processing"</span><span class="token punctuation">)</span><span class="token punctuation">;</span> 193<span class="token punctuation">}</span></code><!-- HTML_TAG_END --></pre> 194<h3 id="enum-variants"><a href="#enum-variants">Enum variants</a></h3> 195<pre class="language-rust"><!-- HTML_TAG_START --><code class="language-rust"><span class="token comment">
195// This should be marked as non_exhaustive for a better public DX</span> 196<span class="token attribute attr-name">#[non_exhaustive]</span> 197<span class="token keyword">pub</span> <span class="token keyword">enum</span> <span class="token type-definition class-name">Tab</span> <span class="token punctuation">{</span> 198 <span class="token class-name">Dashboard</span><span class="token punctuation">,</span> 199 <span class="token class-name">Settings</span><span class="token punctuation">,</span> 200 <span class="token attribute attr-name">#[cfg(feature = <span class="token string">"admin"</span>)]</span> 201 <span class="token class-name">Admin</span><span class="token punctuation">,</span> 202<span class="token punctuation">}</span></code><!-- HTML_TAG_END --></pre> 203<h3 id="vec-items"><a href="#vec-items">Vec items</a></h3> 204<pre class="language-rust"><!-- HTML_TAG_START --><code class="language-rust"><span class="token keyword">impl</span> <span class="token class-name">Tab</span> <span class="token punctuation">{</span> 205 <span class="token keyword">pub</span> <span class="token keyword">fn</span> <span class="token function-definition function">all</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">-></span> <span class="token class-name">Vec</span><span class="token operator"><</span><span class="token keyword">Self</span><span class="token operator">></span> <span class="token punctuation">{</span> 206 <span class="token macro property">vec!</span><span class="token punctuation">[</span> 207 <span class="token keyword">Self</span><span class="token punctuation">::</span><span class="token class-name">Dashboard</span><span class="token punctuation">,</span> 208 <span class="token keyword">Self</span><span class="token punctuation">::</span><span class="token class-name">Settings</span><span class="token punctuation">,</span> 209 <span class="token attribute attr-name">#[cfg(feature = <span class="token string">"admin"</span>)]</span> 210 <span class="token keyword">Self</span><span class="token punctuation">::</span><span class="token class-name">Admin</span><span class="token punctuation">,</span> 211 <span class="token punctuation">]</span> 212 <span class="token punctuation">}</span> 213<span class="token punctuation">}</span></code><!-- HTML_TAG_END --></pre> 214<h3 id="structs"><a href="#structs">Structs</a></h3> 215<pre class="language-rust"><!-- HTML_TAG_START --><code class="language-rust"><span class="token comment">// In src/state.rs</span> 216<span class="token attribute attr-name">#[cfg(debug_assertions)]</span> 217<span class="token attribute attr-name">#[derive(Default)]</span> 218<span class="token keyword">pub</span> <span class="token keyword">struct</span> <span class="token type-definition class-name">DevBuildState</span> <span class="token punctuation">{</span> 219 dev_id<span class="token punctuation">:</span> <span class="token class-name">Mutex</span><span class="token operator"><</span><span class="token class-name">Option</span><span class="token operator"><</span><span class="token class-name">String</span><span class="token operator">>></span><span class="token punctuation">,</span> 220<span class="token punctuation">}</span></code><!-- HTML_TAG_END --></pre> 221<h3 id="import-statements"><a href="#import-statements">Import statements</a></h3> 222<pre class="language-rust"><!-- HTML_TAG_START --><code class="language-rust"><span class="token comment">// In another file:</span> 223<span class="token attribute attr-name">#[cfg(debug_assertions)]</span> 224<span class="token keyword">
224use</span> <span class="token keyword">crate</span><span class="token module-declaration namespace"><span class="token punctuation">::</span>state<span class="token punctuation">::</span></span><span class="token class-name">DevBuildState</span><span class="token punctuation">;</span></code><!-- HTML_TAG_END --></pre> 225<h3 id="cargo-deps"><a href="#cargo-deps">Cargo deps</a></h3> 226<pre class="language-undefined"><!-- HTML_TAG_START --><code class="language-undefined">[target."cfg(not(target_os = "macos"))".dependencies] 227some-crate = "0.53.1" 228 229[target."cfg(target_os = "macos")".dependencies] 230some-crate-macos-patch = { git = "https://github.com/some-org/some-crate", branch = "macos-patch" }</code><!-- HTML_TAG_END --></pre> 231<hr> 232<h2 id="related-features"><a href="#related-features">Related features</a></h2> 233<h3 id="macro-option"><a href="#macro-option">Macro option</a></h3> 234<p>In addition to the <code>#[cfg()]</code> attribute, Rust also provides a macro version called <code>cfg!()</code>. This macro can be used to perform inline if-statements based on compile-time conditions.</p> 235<p>This macro does not conditionally include/exclude the code blocks. The condition will still be checked and replaced at compile-time, but no code is actually removed.</p> 236<pre class="language-rust"><!-- HTML_TAG_START --><code class="language-rust">window<span class="token punctuation">.</span><span class="token function">set_title</span><span class="token punctuation">(</span><span class="token keyword">if</span> <span class="token macro property">cfg!</span><span class="token punctuation">(</span>feature <span class="token operator">=</span> <span class="token string">"admin"</span><span class="token punctuation">)</span> <span class="token operator">&&</span> user<span class="token punctuation">.</span>is_admin <span class="token punctuation">{</span> 237 <span class="token string">"Admin User Settings"</span> 238<span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token punctuation">{</span> 239 <span class="token string">"User Settings"</span> 240<span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span></code><!-- HTML_TAG_END --></pre> 241<h3 id="attribute-expansion"><a href="#attribute-expansion">Attribute expansion</a></h3> 242<p>This <code>#[cfg_attr()]</code> attribute allows developers to conditionally include other attributes based on a predicate, as shown below:</p> 243<pre class="language-rust"><!-- HTML_TAG_START --><code class="language-rust"><span class="token attribute attr-name">#[cfg_attr(feature = <span class="token string">"magic"</span>, sparkles, crackles)]</span> 244<span class="token keyword">fn</span> <span class="token function-definition function">bewitched</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span><span class="token punctuation">}</span> 245 246<span class="token comment">// When the `magic` feature flag is enabled, the above will expand to:</span> 247<span class="token attribute attr-name">#[sparkles]</span> 248<span class="token attribute attr-name">#[crackles]</span> 249<span class="token keyword">fn</span> <span class="token function-definition function">bewitched</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span><span class="token punctuation">}</span></code><!-- HTML_TAG_END --></pre> 250<h3 id="custom-flags"><a href="#custom-flags">Custom flags</a></h3> 251<p>If additional <code>--cfg</code> options are supplied when running the program:</p> 252<pre class="language-sh"><!-- HTML_TAG_START --><code class="language-sh">rustc --cfg "foobar" main.rs</code><!-- HTML_TAG_END --></pre> 253<p>or by instructing Cargo in a build script:</p> 254<pre class="language-rust"><!-- HTML_TAG_START --><code class="language-rust"><span class="token macro property">println!</span><span class="token punctuation">(</span><span class="token string">"cargo:rustc-cfg=foobar"</span><span class="token punctuation">)</span><span class="token punctuation">;</span></code><!-- HTML_TAG_END --></pre> 255<p>Then it will be accessible to you via:</p> 256<pre class="language-rust"><!-- HTML_TAG_START --><code class="language-rust"><span class="token attribute attr-name">#[cfg(foobar)]</span></code><!-- HTML_TAG_END --></pre> 257<hr> 258<h2 id="see-it-in-action"><a href="#see-it-in-action">See it in action</a></h2> 259<a href="https://tauri.app/" target="_blank">Tauri</a>, a wonderful framework for making applications, is using it for 260<a href="https://github.com/tauri-apps/tauri/blob/0ddbb3a1dc1961ba5c6c1a60081513c1380c8af1/core/tauri/src/app/tray.rs#L46-L68" target="_blank">configuring the system tray</a>: 261<pre class="language-rust"><!-- HTML_TAG_START --><code class="language-rust"><span class="token attribute attr-name">#[non_exhaustive]</span> 262<span class="token keyword">pub</span> <span class="token keyword">
262struct</span> <span class="token type-definition class-name">SystemTray</span> <span class="token punctuation">{</span> 263 <span class="token comment">/// The tray identifier. Defaults to a random string.</span> 264 <span class="token keyword">pub</span> id<span class="token punctuation">:</span> <span class="token class-name">String</span><span class="token punctuation">,</span> 265 <span class="token comment">/// The tray icon.</span> 266 <span class="token keyword">pub</span> icon<span class="token punctuation">:</span> <span class="token class-name">Option</span><span class="token operator"><</span><span class="token namespace">tauri_runtime<span class="token punctuation">::</span></span><span class="token class-name">Icon</span><span class="token operator">></span><span class="token punctuation">,</span> 267 <span class="token comment">/// The tray menu.</span> 268 <span class="token keyword">pub</span> menu<span class="token punctuation">:</span> <span class="token class-name">Option</span><span class="token operator"><</span><span class="token class-name">SystemTrayMenu</span><span class="token operator">></span><span class="token punctuation">,</span> 269 <span class="token comment">/// Whether the icon is a template icon or not.</span> 270 <span class="token attribute attr-name">#[cfg(target_os = <span class="token string">"macos"</span>)]</span> 271 <span class="token keyword">pub</span> icon_as_template<span class="token punctuation">:</span> <span class="token keyword">bool</span><span class="token punctuation">,</span> 272 <span class="token comment">/// Whether the menu should appear when the tray receives a left click.</span> 273 <span class="token comment">/// Defaults to `true`</span> 274 <span class="token attribute attr-name">#[cfg(target_os = <span class="token string">"macos"</span>)]</span> 275 <span class="token keyword">pub</span> menu_on_left_click<span class="token punctuation">:</span> <span class="token keyword">bool</span><span class="token punctuation">,</span> 276 on_event<span class="token punctuation">:</span> <span class="token class-name">Option</span><span class="token operator"><</span><span class="token class-name">Arc</span><span class="token operator"><</span><span class="token class-name">TrayEventHandler</span><span class="token operator">>></span><span class="token punctuation">,</span> 277 <span class="token attribute attr-name">#[cfg(target_os = <span class="token string">"macos"</span>)]</span> 278 menu_on_left_click_set<span class="token punctuation">:</span> <span class="token keyword">bool</span><span class="token punctuation">,</span> 279 <span class="token attribute attr-name">#[cfg(target_os = <span class="token string">"macos"</span>)]</span> 280 icon_as_template_set<span class="token punctuation">:</span> <span class="token keyword">bool</span><span class="token punctuation">,</span> 281 <span class="token attribute attr-name">#[cfg(target_os = <span class="token string">"macos"</span>)]</span> 282 title<span class="token punctuation">:</span> <span class="token class-name">Option</span><span class="token operator"><</span><span class="token class-name">String</span><span class="token operator">></span><span class="token punctuation">,</span> 283 tooltip<span class="token punctuation">:</span> <span class="token class-name">Option</span><span class="token operator"><</span><span class="token class-name">String</span><span class="token operator">></span><span class="token punctuation">,</span> 284<span class="token punctuation">}</span></code><!-- HTML_TAG_END --></pre> 285<a href="https://github.com/search?q=%23%5Bcfg%28+lang%3ARust+&type=code" target="_blank">Here are more examples</a> 286of open source projects using this feature. Enjoy! 287<hr> 288<h2 id="summary"><a href="#summary">Summary</a></h2> 289<p>Rustâs <code>#[cfg()]</code> attribute is a powerful tool for conditionally compiling code based on specified conditions at compile time. It enables fine-grained control over which portions of code are included or excluded, resulting in more efficient and optimized programs! By utilizing a mix of conditions and combinators, developers can tailor their codebase to different platforms, features, and compilation configurations.</p> 290 291 292 <div class="hidden xl:block absolute not-prose left-[100%]" aria-label="Table of Contents"><div class="fixed z-10 px-4 py-2 ml-8 top-[4.5rem]"> 293 294 295<h6 id="__sections" class="uppercase text-slate-400/75 dark:text-slate-600 font-bold text-sm">Sections 296</h6> 297 298<ul class="mt-2 !pl-0"> 299</ul></div></div></div></article> 300 301<div class="pt-12 flex justify-between"><div class="not-prose"><a href="/posts" class="block text-slate-800 dark:text-slate-200 dark:text-opacity-90 rounded-md no-underline medium raised svelte-zohxso"><div class="flex items-center space-x-1"> 302 <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" class="h-5 w-5"><path fill-rule="evenodd" d="M9.707 14.707a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414l4-4a1 1 0 011.414 1.414L7.414 9H15a1 1 0 110 2H7.414l2.293 2.293a1 1 0 010 1.414z" clip-rule="evenodd"></path></svg> 303 304 <span>Back to Posts 305 </span> 306 </div></a> 307</div></div> 308 309 310<hr> 311 <div class="grid gap-8 grid-cols-1 sm:grid-cols-2"><div class="flex flex-col"><h6 class="not-prose post-preview-label svelte-8ybs7b">Previous Post</h6> 312 <div class="flex-1 post-preview svelte-8ybs7b"><div class="flex flex-col"><div><h3 class="!mt-0 !mb-2"><a href="/posts/working-away-from-home">Working Away From Home</a></h3> 313 <div class="opacity-70"><time>December 26, 2022</time> 314 ⢠315 <span>6 min read</span></div></div> 316 <div class="flex-1"><!-- HTML_TAG_START -->Discussing some pros and cons of working from home, and what an alternative could achieve.<!-- HTML_TAG_END --></div> 317 318 <div class="mt-4 flex justify-end w-full"><div class="not-prose"><a href="/posts/working-away-from-home" class="block text-slate-800 dark:text-slate-200 dark:text-opacity-90 rounded-md no-underline medium raised svelte-zohxso"><div class="flex items-center space-x-1"> 319 <span>Read More</span> 320 321 <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" class="h-5 w-5"><path fill-rule="evenodd" d="M10.293 5.293a1 1 0 011.414 0l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414-1.414L12.586 11H5a1 1 0 110-2h7.586l-2.293-2.293a1 1 0 010-1.414z" clip-rule="evenodd"></path></svg> 322 </div></a> 323</div></div> 324 </div></div></div> 325 <div class="flex flex-col"><h6 class="not-prose post-preview-label flex justify-end svelte-8ybs7b">Next Post</h6> 326 <div class="flex-1 post-preview svelte-8ybs7b"><div class="flex flex-col"><div><h3 class="!mt-0 !mb-2"><a href="/posts/care-for-your-racers">Care for Your Racers</a></h3> 327 <div class="opacity-70"><time>July 10, 2023</time> 328 ⢠329 <span>7 min read</span></div></div> 330 <div class="flex-1"><!-- HTML_TAG_START -->Nurturing the Race Horses and Race Cars at Work - Strategies for Maximum Performance and Fulfillment<!-- HTML_TAG_END --></div> 331 332 <div class="mt-4 flex justify-end w-full"><div class="not-prose"><a href="/posts/care-for-your-racers" class="block text-slate-800 dark:text-slate-200 dark:text-opacity-90 rounded-md no-underline medium raised svelte-zohxso"><div class="flex items-center space-x-1"> 333 <span>Read More</span> 334 335 <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" class="h-5 w-5"><path fill-rule="evenodd" d="M10.293 5.293a1 1 0 011.414 0l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414-1.414L12.586 11H5a1 1 0 110-2h7.586l-2.293-2.293a1 1 0 010-1.414z" clip-rule="evenodd"></path></svg> 336 </div></a> 337</div></div> 338 </div></div></div></div></main> 339 340 <div class="mt-8 mb-4 h-16 px-4 py-2 flex justify-center items-center gap-6"><a href="https://twitter.com/parker_codes" target="_blank" rel="me"><img src="/icons/twitter.png" alt="Twitter profile" class="w-10 h-10 " loading="lazy"> 341 </a><a href="https://github.com/parker-codes" target="_blank" rel="me"><img src="/icons/github.png" alt="Github profile" class="w-10 h-10 dar
341k:invert" loading="lazy"> 342 </a></div></div></div> 343
344<script type="application/json" data-type="svelte-data" data-url="/posts.json">{"status":200,"statusText":"","headers":{"content-type":"text/plain;charset=UTF-8"},"body":"[{\"title\":\"Overwhelming Transitions\",\"date\":\"2023-09-21\",\"preview\":{\"html\":\"One developer's challenge of adapting to a new tech stack, and effective strategies to overcome it with a growth mindset\"},\"slug\":\"overwhelming-transitions\",\"isIndexFile\":true,\"component\":{},\"customPreview\":\"One developer's challenge of adapting to a new tech stack, and effective strategies to overcome it with a growth mindset\",\"readingTime\":\"5 min read\",\"previous\":{\"title\":\"Care for Your Racers\",\"date\":\"2023-07-10\",\"preview\":{\"html\":\"Nurturing the Race Horses and Race Cars at Work - Strategies for Maximum Performance and Fulfillment\"},\"slug\":\"care-for-your-racers\",\"isIndexFile\":true,\"component\":{},\"customPreview\":\"Nurturing the Race Horses and Race Cars at Work - Strategies for Maximum Performance and Fulfillment\",\"readingTime\":\"7 min read\"}},{\"title\":\"Care for Your Racers\",\"date\":\"2023-07-10\",\"preview\":{\"html\":\"Nurturing the Race Horses and Race Cars at Work - Strategies for Maximum Performance and Fulfillment\"},\"slug\":\"care-for-your-racers\",\"isIndexFile\":true,\"component\":{},\"customPreview\":\"Nurturing the Race Horses and Race Cars at Work - Strategies for Maximum Performance and Fulfillment\",\"readingTime\":\"7 min read\",\"next\":{\"title\":\"Overwhelming Transitions\",\"date\":\"2023-09-21\",\"preview\":{\"html\":\"One developer's challenge of adapting to a new tech stack, and effective strategies to overcome it with a growth mindset\"},\"slug\":\"overwhelming-transitions\",\"isIndexFile\":true,\"component\":{},\"customPreview\":\"One developer's challenge of adapting to a new tech stack, and effective strategies to overcome it with a growth mindset\",\"readingTime\":\"5 min read\"},\"previous\":{\"title\":\"Rust's cfg Attribute\",\"date\":\"2023-06-01\",\"preview\":{\"html\":\"What the `#[cfg(...)]` attribute offers to DX and architecture.\"},\"slug\":\"rusts-cfg-attribute\",\"isIndexFile\":true,\"component\":{},\"customPreview\":\"What the `#[cfg(...)]` attribute offers to DX and architecture.\",\"readingTime\":\"12 min read\"}},{\"title\":\"Rust's cfg Attribute\",\"date\":\"2023-06-01\",\"preview\":{\"html\":\"What the `#[cfg(...)]` attribute offers to DX and architecture.\"},\"slug\":\"rusts-cfg-attribute\",\"isIndexFile\":true,\"component\":{},\"customPreview\":\"What the `#[cfg(...)]` attribute offers to DX and architecture.\",\"readingTime\":\"12 min read\",\"next\":{\"title\":\"Care for Your Racers\",\"date\":\"2023-07-10\",\"preview\":{\"html\":\"Nurturing the Race Horses and Race Cars at Work - Strategies for Maximum Performance and Fulfillment\"},\"slug\":\"care-for-your-racers\",\"isIndexFile\":true,\"component\":{},\"customPreview\":\"Nurturing the Race Horses and Race Cars at Work - Strategies for Maximum Performance and Fulfillment\",\"readingTime\":\"7 min read\"},\"previous\":{\"title\":\"Working Away From Home\",\"date\":\"2022-12-26\",\"preview\":{\"html\":\"Discussing some pros and cons of working from home, and what an alternative could achieve.\"},\"slug\":\"working-away-from-home\",\"isIndexFile\":true,\"component\":{},\"customPreview\":\"Discussing some pros and cons of working from home, and what an alternative could achieve.\",\"readingTime\":\"6 min read\"}},{\"title\":\"Working Away From Home\",\"date\":\"2022-12-26\",\"preview\":{\"html\":\"Discussing some pros and cons of working from home, and what an alternative could achieve.\"},\"slug\":\"working-away-from-home\",\"isIndexFile\":true,\"component\":{},\"customPreview\":\"Discussing some pros and cons of working from home, and what an alternative could achieve.\",\"readingTime\":\"6 min read\",\"next\":{\"title\":\"Rust's cfg Attribute\",\"date\":\"2023-06-01\",\"preview\":{\"html\":\"What the `#[cfg(...)]` attribute offers to DX and architecture.\"},\"slug\":\"rusts-cfg-attribute\",\"isIndexFile\":true,\"component\":{},\"customPreview\":\"What the `#[cfg(...)]` attribute offers to DX and architecture.\",\"readingTime\":\"12 min read\"},\"previous\":{\"title\":\"Fractals\",\"date\":\"2022-06-24\",\"preview\":{\"html\":\"A playground for making fractals using a web canvas!\"},\"slug\":\"fractals\",\"isIndexFile\":true,\"component\":{},\"customPreview\":\"A playground for making fractals using a web canvas!\",\"readingTime\":\"12 min read\"}},{\"title\":\"Fractals\",\"date\":\"2022-06-24\",\"preview\":{\"html\":\"A playground for making fractals using a web canvas!\"},\"slug\":\"fractals\",\"isIndexFile\":true,\"component\":{},\"customPreview\":\"A playground for making fractals using a web canvas!\",\"readingTime\":\"12 min read\",\"next\":{\"title\":\"Working Away From Home\",\"date\":\"2022-12-26\",\"preview\":{\"html\":\"Discussing some pros and cons of working from home, and what an alternative could achieve.\"},\"slug\":\"working-away-from-home\",\"isIndexFile\":true,\"component\":{},\"customPreview\":\"Discussing some pros and cons of working from home, and what an alternative could achieve.\",\"readingTime\":\"6 min read\"},\"previous\":{\"title\":\"Concentric Time\",\"date\":\"2022-04-15\",\"preview\":{\"html\":\"A simple and fun way to view the time!\"},\"slug\":\"concentric-time\",\"isIndexFile\":true,\"component\":{},\"customPreview\":\"A simple and fun way to view the time!\",\"readingTime\":\"7 min read\"}},{\"title\":\"Concentric Time\",\"date\":\"2022-04-15\",\"preview\":{\"html\":\"A simple and fun way to view the time!\"},\"slug\":\"concentric-time\",\"isIndexFile\":true,\"component\":{},\"customPreview\":\"A simple and fun way to view the time!\",\"readingTime\":\"7 min read\",\"next\":{\"title\":\"Fractals\",\"date\":\"2022-06-24\",\"preview\":{\"html\":\"A playground for making fractals using a web canvas!\"},\"slug\":\"fractals\",\"isIndexFile\":true,\"component\":{},\"customPreview\":\"A playground for making fractals using a web canvas!\",\"readingTime\":\"12 min read\"}}]"}</script>
344</div> 345 346 <!-- this fixes a bug in chrome where animations trigger from unstyled to styled content on page load --> 347 <!-- https://stackoverflow.com/a/42969257/6342734 --> 348 <!-- prettier-ignore --> 349
349<script> </script>
349 350 </body> 351</html>
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.