Debian Codegraph @

subprojects/meson-docs/docs/markdown/howtox.md

raw
1 # How do I do X in Meson?
2
3 This page lists code snippets for common tasks. These are written
4 mostly using the C compiler, but the same approach should work on
5 almost all other compilers.
6
7 ## Set compiler
8
9 When first running Meson, set it in an environment variable.
10
11 ```console
12 $ CC=mycc meson <options>
13 ```
14
15 Note that environment variables like `CC` only refer to the host
16 platform in cross builds. That is, `CC` refers to the compiler used to
17 compile programs that run on the machine we will eventually install the
18 project on. The compiler used to build things that run on the machine we
19 do the building can be specified with `CC_FOR_BUILD`. You can use it in
20 cross builds.
21
22 Note that environment variables are never the idiomatic way to do
23 anything with Meson, however. It is better to use the native and cross
24 files. And the tools for the host platform in cross builds can only be
25 specified with a cross file.
26
27 There is a table of all environment variables supported
28 [Here](Reference-tables.md#compiler-and-linker-selection-variables)
29
30
31 ## Set linker
32
33 *New in 0.53.0*
34
35 Like the compiler, the linker is selected via the `<compiler
36 variable>_LD` environment variable, or through the `<compiler
37 entry>_ld` entry in a native or cross file. You must be aware of
38 whether you're using a compiler that invokes the linker itself (most
39 compilers including GCC and Clang) or a linker that is invoked
40 directly (when using MSVC or compilers that act like it, including
41 Clang-Cl). With the former `c_ld` or `CC_LD` should be the value to
42 pass to the compiler's special argument (such as `-fuse-ld` with clang
43 and gcc), with the latter it should be an executable, such as
44 `lld-link.exe`.
45
46 *NOTE* In Meson 0.53.0 the `ld` entry in the cross/native file and the
47 `LD` environment variable were used, this resulted in a large number
48 of regressions and was changed in 0.53.1 to `<lang>_ld` and `<comp
49 variable>_LD`.
50
51 ```console
52 $ CC=clang CC_LD=lld meson <options>
53 ```
54
55 or
56
57 ```console
58 $ CC=clang-cl CC_LD=link meson <options>
59 ```
60
61 or in a cross or native file:
62
63 ```ini
64 [binaries]
65 c = 'clang'
66 c_ld = 'lld'
67 ```
68
69 There is a table of all environment variables supported
70 [Here](Reference-tables.md#compiler-and-linker-selection-variables)
71
72
73 ## Set default C/C++ language version
74
75 ```meson
76 project('myproj', 'c', 'cpp',
77 default_options : ['c_std=c11', 'cpp_std=c++11'])
78 ```
79
80 The language version can also be set on a per-target basis.
81
82 ```meson
83 executable(..., override_options : ['c_std=c11'])
84 ```
85
86 ## Enable threads
87
88 Lots of people seem to do this manually with `cc.find_library('pthread')`
89 or something similar. Do not do that. It is not portable. Instead do
90 this.
91
92 ```meson
93 thread_dep = dependency('threads')
94 executable(..., dependencies : thread_dep)
95 ```
96
97 ## Set extra compiler and linker flags from the outside (when e.g. building distro packages)
98
99 The behavior is the same as with other build systems, with environment
100 variables during first invocation. Do not use these when you need to
101 rebuild the source
102
103 ```console
104 $ CFLAGS=-fsomething LDFLAGS=-Wl,--linker-flag meson <options>
105 ```
106
107 ## Use an argument only with a specific compiler
108
109 First check which arguments to use.
110
111 ```meson
112 if meson.get_compiler('c').get_id() == 'clang'
113 extra_args = ['-fclang-flag']
114 else
115 extra_args = []
116 endif
117 ```
118
119 Then use it in a target.
120
121 ```meson
122 executable(..., c_args : extra_args)
123 ```
124
125 If you want to use the arguments on all targets, then do this.
126
127 ```meson
128 if meson.get_compiler('c').get_id() == 'clang'
129 add_global_arguments('-fclang-flag', language : 'c')
130 endif
131 ```
132
133 ## Set a command's output to configuration
134
135 ```meson
136 txt = run_command('script', 'argument', check: true).stdout().strip()
137 cdata = configuration_data()
138 cdata.set('SOMETHING', txt)
139 configure_file(...)
140 ```
141
142 ## Generate configuration data from files
143
144 The [fs module](#Fs-modules) offers the `read` function which enables adding
145 the contents of arbitrary files to configuration data (among other uses):
146
147 ```meson
148 fs = import('fs')
149 cdata = configuration_data()
150 copyright = fs.read('LICENSE')
151 cdata.set('COPYRIGHT', copyright)
152 if build_machine.system() == 'linux'
153 os_release = fs.read('/etc/os-release')
154 cdata.set('LINUX_BUILDER', os_release)
155 endif
156 configure_file(...)
157 ```
158
159 ## Generate a runnable script with `configure_file`
160
161 `configure_file` preserves metadata so if your template file has
162 execute permissions, the generated file will have them too.
163
164 ## Producing a coverage report
165
166 First initialize the build directory with this command.
167
168 ```console
169 $ meson setup <other flags> -Db_coverage=true
170 ```
171
172 Then issue the following commands.
173
174 ```console
175 $ meson compile
176 $ meson test
177 $ ninja coverage-html (or coverage-xml)
178 ```
179
180 The coverage report can be found in the meson-logs subdirectory.
181
182 *New in 0.55.0* llvm-cov support for use with clang
183
184 ## Add some optimization to debug builds
185
186 By default the debug build does not use any optimizations. This is the
187 desired approach most of the time. However some projects benefit from
188 having some minor optimizations enabled. GCC even has a specific
189 compiler flag `-Og` for this. To enable its use, just issue the
190 following command.
191
192 ```console
193 $ meson configure -Dc_args=-Og
194 ```
195
196 This causes all subsequent builds to use this command line argument.
197
198 ## Use address sanitizer
199
200 Clang and gcc come with a selection of analysis tools such as the [address
201 sanitizer](https://clang.llvm.org/docs/AddressSanitizer.html). Meson
202 has native support for these with the `b_sanitize` option.
203
204 ```console
205 $ meson setup <other options> -Db_sanitize=address
206 ```
207
208 After this you just compile your code and run the test suite. Address
209 sanitizer will abort executables which have bugs so they show up as
210 test failures.
211
212 ## Use Clang static analyzer
213
214 Install scan-build program, then do this:
215
216 ```console
217 $ meson setup builddir
218 $ ninja -C builddir scan-build
219 ```
220
221 You can use the `SCANBUILD` environment variable to choose the
222 scan-build executable.
223
224 ```console
225 $ SCANBUILD=<your exe> ninja -C builddir scan-build
226 ```
227
228 You can use it for passing arguments to scan-build program by
229 creating a script, for example:
230
231 ```sh
232 #!/bin/sh
233 scan-build -v --status-bugs "$@"
234 ```
235
236 And then pass it through the variable (remember to use absolute path):
237
238 ```console
239 $ SCANBUILD=$(pwd)/my-scan-build.sh ninja -C builddir scan-build
240 ```
241
242 ## Use clippy
243
244 If your project includes Rust targets, you can invoke clippy like this:
245
246 ```console
247 $ meson setup builddir
248 $ ninja -C builddir clippy
249 ```
250
251 Clippy will also obey the `werror` [builtin option](Builtin-options.md#core-options).
252
253 By default Meson uses as many concurrent processes as there are cores
254 on the test machine. You can override this with the environment
255 variable `MESON_NUM_PROCESSES`.
256
257 Meson will look for `clippy-driver` in the same directory as `rustc`,
258 or try to invoke it using `rustup` if `rustc` points to a `rustup`
259 binary. If `clippy-driver` is not detected properly, you can add it to
260 a [machine file](Machine-files.md).
261
262 ## Use profile guided optimization
263
264 Using profile guided optimization with GCC is a two phase
265 operation. First we set up the project with profile measurements
266 enabled and compile it.
267
268 ```console
269 $ meson setup <Meson options, such as --buildtype=debugoptimized> -Db_pgo=generate
270 $ meson compile -C builddir
271 ```
272
273 Then we need to run the program with some representative input. This
274 step depends on your project.
275
276 Once that is done we change the compiler flags to use the generated
277 information and rebuild.
278
279 ```console
280 $ meson configure -Db_pgo=use
281 $ meson compile
282 ```
283
284 After these steps the resulting binary is fully optimized.
285
286 ## Add math library (`-lm`) portably
287
288 Some platforms (e.g. Linux) have a standalone math library. Other
289 platforms (pretty much everyone else) do not. How to specify that `m`
290 is used only when needed?
291
292 ```meson
293 cc = meson.get_compiler('c')
294 m_dep = cc.find_library('m', required : false)
295 executable(..., dependencies : m_dep)
296 ```
297
298 ## Install an executable to `libexecdir`
299
300 ```meson
301 executable(..., install : true, install_dir : get_option('libexecdir'))
302 ```
303
304 ## Use existing `Find<name>.cmake` files
305
306 Meson can use the CMake `find_package()` ecosystem if CMake is
307 installed. To find a dependency with custom `Find<name>.cmake`, set
308 the `cmake_module_path` property to the path in your project where the
309 CMake scripts are stored.
310
311 Example for a `FindCmakeOnlyDep.cmake` in a `cmake` subdirectory:
312
313 ```meson
314 cm_dep = dependency('CmakeOnlyDep', cmake_module_path : 'cmake')
315 ```
316
317 The `cmake_module_path` property is only needed for custom CMake scripts. System
318 wide CMake scripts are found automatically.
319
320 More information can be found [here](Dependencies.md#cmake)
321
322 ## Get a default not-found dependency?
323
324 ```meson
325 null_dep = dependency('', required : false)
326 ```
327
328 This can be used in cases where you want a default value, but might override it
329 later.
330
331 ```meson
332 # Not needed on Windows!
333 my_dep = dependency('', required : false)
334 if host_machine.system() in ['freebsd', 'netbsd', 'openbsd', 'dragonfly']
335 my_dep = dependency('some dep', required : false)
336 elif host_machine.system() == 'linux'
337 my_dep = dependency('some other dep', required : false)
338 endif
339
340 executable(
341 'myexe',
342 my_sources,
343 deps : [my_dep]
344 )
345 ```
346
347 ## Exclude a file from unity builds
348
349 If your project supports unity builds, you should fix any bugs that crop up when
350 source files are concatenated together.
351 Sometimes this isn't possible, though, for example if the source files are
352 generated.
353
354 In this case, you can put them in a separate static library build target and
355 override the unity setting.
356
357 ```meson
358 generated_files = ...
359 unityproof_lib = static_library('unityproof', generated_files,
360 override_options : ['unity=off'])
361
362 main_exe = executable('main', main_sources, link_with : unityproof_lib)
363 ```
364
365 To link the static library into another library target, you may need to use
366 `link_whole` instead of `link_with`.