Debian Codegraph @

clang/docs/Modules.rst

raw
1 =======
2 Modules
3 =======
4
5 .. contents::
6 :local:
7
8 Introduction
9 ============
10 Most software is built using a number of software libraries, including libraries supplied by the platform, internal libraries built as part of the software itself to provide structure, and third-party libraries. For each library, one needs to access both its interface (API) and its implementation. In the C family of languages, the interface to a library is accessed by including the appropriate header files(s):
11
12 .. code-block:: c
13
14 #include <SomeLib.h>
15
16 The implementation is handled separately by linking against the appropriate library. For example, by passing ``-lSomeLib`` to the linker.
17
18 Modules provide an alternative, simpler way to use software libraries that provides better compile-time scalability and eliminates many of the problems inherent to using the C preprocessor to access the API of a library.
19
20 Problems with the current model
21 -------------------------------
22 The ``#include`` mechanism provided by the C preprocessor is a very poor way to access the API of a library, for a number of reasons:
23
24 * **Compile-time scalability**: Each time a header is included, the
25 compiler must preprocess and parse the text in that header and every
26 header it includes, transitively. This process must be repeated for
27 every translation unit in the application, which involves a huge
28 amount of redundant work. In a project with *N* translation units
29 and *M* headers included in each translation unit, the compiler is
30 performing *M x N* work even though most of the *M* headers are
31 shared among multiple translation units. C++ is particularly bad,
32 because the compilation model for templates forces a huge amount of
33 code into headers.
34
35 * **Fragility**: ``#include`` directives are treated as textual
36 inclusion by the preprocessor, and are therefore subject to any
37 active macro definitions at the time of inclusion. If any of the
38 active macro definitions happens to collide with a name in the
39 library, it can break the library API or cause compilation failures
40 in the library header itself. For an extreme example,
41 ``#define std "The C++ Standard"`` and then include a standard
42 library header: the result is a horrific cascade of failures in the
43 C++ Standard Library's implementation. More subtle real-world
44 problems occur when the headers for two different libraries interact
45 due to macro collisions, and users are forced to reorder
46 ``#include`` directives or introduce ``#undef`` directives to break
47 the (unintended) dependency.
48
49 * **Conventional workarounds**: C programmers have
50 adopted a number of conventions to work around the fragility of the
51 C preprocessor model. Include guards, for example, are required for
52 the vast majority of headers to ensure that multiple inclusion
53 doesn't break the compile. Macro names are written with
54 ``LONG_PREFIXED_UPPERCASE_IDENTIFIERS`` to avoid collisions, and some
55 library/framework developers even use ``__underscored`` names
56 in headers to avoid collisions with "normal" names that (by
57 convention) shouldn't even be macros. These conventions are a
58 barrier to entry for developers coming from non-C languages, are
59 boilerplate for more experienced developers, and make our headers
60 far uglier than they should be.
61
62 * **Tool confusion**: In a C-based language, it is hard to build tools
63 that work well with software libraries, because the boundaries of
64 the libraries are not clear. Which headers belong to a particular
65 library, and in what order should those headers be included to
66 guarantee that they compile correctly? Are the headers C, C++,
67 Objective-C++, or one of the variants of these languages? What
68 declarations in those headers are actually meant to be part of the
69 API, and what declarations are present only because they had to be
70 written as part of the header file?
71
72 Semantic import
73 ---------------
74 Modules improve access to the API of software libraries by replacing the textual preprocessor inclusion model with a more robust, more efficient semantic model. From the user's perspective, the code looks only slightly different, because one uses an ``import`` declaration rather than a ``#include`` preprocessor directive:
75
76 .. code-block:: c
77
78 import std.io; // pseudo-code; see below for syntax discussion
79
80 However, this module import behaves quite differently from the corresponding ``#include <stdio.h>``: when the compiler sees the module import above, it loads a binary representation of the ``std.io`` module and makes its API available to the application directly. Preprocessor definitions that precede the import declaration have no impact on the API provided by ``std.io``, because the module itself was compiled as a separate, standalone module. Additionally, any linker flags required to use the ``std.io`` module will automatically be provided when the module is imported [#]_
81 This semantic import model addresses many of the problems of the preprocessor inclusion model:
82
83 * **Compile-time scalability**: The ``std.io`` module is only compiled once, and importing the module into a translation unit is a constant-time operation (independent of module system). Thus, the API of each software library is only parsed once, reducing the *M x N* compilation problem to an *M + N* problem.
84
85 * **Fragility**: Each module is parsed as a standalone entity, so it has a consistent preprocessor environment. This completely eliminates the need for ``__underscored`` names and similarly defensive tricks. Moreover, the current preprocessor definitions when an import declaration is encountered are ignored, so one software library can not affect how another software library is compiled, eliminating include-order dependencies.
86
87 * **Tool confusion**: Modules describe the API of software libraries, and tools can reason about and present a module as a representation of that API. Because modules can only be built standalone, tools can rely on the module definition to ensure that they get the complete API for the library. Moreover, modules can specify which languages they work with, so, e.g., one can not accidentally attempt to load a C++ module into a C program.
88
89 Problems modules do not solve
90 -----------------------------
91 Many programming languages have a module or package system, and because of the variety of features provided by these languages it is important to define what modules do *not* do. In particular, all of the following are considered out-of-scope for modules:
92
93 * **Rewrite the world's code**: It is not realistic to require applications or software libraries to make drastic or non-backward-compatible changes, nor is it feasible to completely eliminate headers. Modules must interoperate with existing software libraries and allow a gradual transition.
94
95 * **Versioning**: Modules have no notion of version information. Programmers must still rely on the existing versioning mechanisms of the underlying language (if any exist) to version software libraries.
96
97 * **Namespaces**: Unlike in some languages, modules do not imply any notion of namespaces. Thus, a struct declared in one module will still conflict with a struct of the same name declared in a different module, just as they would if declared in two different headers. This aspect is important for backward compatibility, because (for example) the mangled names of entities in software libraries must not change when introducing modules.
98
99 * **Binary distribution of modules**: Headers (particularly C++ headers) expose the full complexity of the language. Maintaining a stable binary module format across architectures, compiler versions, and compiler vendors is technically infeasible.
100
101 Using Modules
102 =============
103 To enable modules, pass the command-line flag ``-fmodules``. This will make any modules-enabled software libraries available as modules as well as introducing any modules-specific syntax. Additional `command-line parameters`_ are described in a separate section later.
104
105 Standard C++ Modules
106 --------------------
107 .. note::
108 Modules are adopted into C++20 Standard. And its semantic and command line interface are very different from the Clang C++ modules. See `StandardCPlusPlusModules <StandardCPlusPlusModules.html>`_ for details.
109
110 Objective-C Import declaration
111 ------------------------------
112 Objective-C provides syntax for importing a module via an *@import declaration*, which imports the named module:
113
114 .. parsed-literal::
115
116 @import std;
117
118 The ``@import`` declaration above imports the entire contents of the ``std`` module (which would contain, e.g., the entire C or C++ standard library) and make its API available within the current translation unit. To import only part of a module, one may use dot syntax to specify a particular submodule, e.g.,
119
120 .. parsed-literal::
121
122 @import std.io;
123
124 Redundant import declarations are ignored, and one is free to import modules at any point within the translation unit, so long as the import declaration is at global scope.
125
126 At present, there is no C or C++ syntax for import declarations. Clang
127 will track the modules proposal in the C++ committee. See the section
128 `Includes as imports`_ to see how modules get imported today.
129
130 Includes as imports
131 -------------------
132 The primary user-level feature of modules is the import operation, which provides access to the API of software libraries. However, today's programs make extensive use of ``#include``, and it is unrealistic to assume that all of this code will change overnight. Instead, modules automatically translate ``#include`` directives into the corresponding module import. For example, the include directive
133
134 .. code-block:: c
135
136 #include <stdio.h>
137
138 will be automatically mapped to an import of the module ``std.io``. Even with specific ``import`` syntax in the language, this particular feature is important for both adoption and backward compatibility: automatic translation of ``#include`` to ``import`` allows an application to get the benefits of modules (for all modules-enabled libraries) without any changes to the application itself. Thus, users can easily use modules with one compiler while falling back to the preprocessor-inclusion mechanism with other compilers.
139
140 .. note::
141
142 The automatic mapping of ``#include`` to ``import`` also solves an implementation problem: importing a module with a definition of some entity (say, a ``struct Point``) and then parsing a header containing another definition of ``struct Point`` would cause a redefinition error, even if it is the same ``struct Point``. By mapping ``#include`` to ``import``, the compiler can guarantee that it always sees just the already-parsed definition from the module.
143
144 While building a module, ``#include_next`` is also supported, with one caveat.
145 The usual behavior of ``#include_next`` is to search for the specified filename
146 in the list of include paths, starting from the path *after* the one
147 in which the current file was found.
148 Because files listed in module maps are not found through include paths, a
149 different strategy is used for ``#include_next`` directives in such files: the
150 list of include paths is searched for the specified header name, to find the
151 first include path that would refer to the current file. ``#include_next`` is
152 interpreted as if the current file had been found in that path.
153 If this search finds a file named by a module map, the ``#include_next``
154 directive is translated into an import, just like for a ``#include``
155 directive.
156
157 Module maps
158 -----------
159 The crucial link between modules and headers is described by a *module map*, which describes how a collection of existing headers maps on to the (logical) structure of a module. For example, one could imagine a module ``std`` covering the C standard library. Each of the C standard library headers (``<stdio.h>``, ``<stdlib.h>``, ``<math.h>``, etc.) would contribute to the ``std`` module, by placing their respective APIs into the corresponding submodule (``std.io``, ``std.lib``, ``std.math``, etc.). Having a list of the headers that are part of the ``std`` module allows the compiler to build the ``std`` module as a standalone entity, and having the mapping from header names to (sub)modules allows the automatic translation of ``#include`` directives to module imports.
160
161 Module maps are specified as separate files (each named ``module.modulemap``) alongside the headers they describe, which allows them to be added to existing software libraries without having to change the library headers themselves (in most cases [#]_). The actual `Module map language`_ is described in a later section.
162
163 .. note::
164
165 To actually see any benefits from modules, one first has to introduce module maps for the underlying C standard library and the libraries and headers on which it depends. The section `Modularizing a Platform`_ describes the steps one must take to write these module maps.
166
167 One can use module maps without modules to check the integrity of the use of header files. To do this, use the ``-fimplicit-module-maps`` option instead of the ``-fmodules`` option, or use ``-fmodule-map-file=`` option to explicitly specify the module map files to load.
168
169 Compilation model
170 -----------------
171 The binary representation of modules is automatically generated by the compiler on an as-needed basis. When a module is imported (e.g., by an ``#include`` of one of the module's headers), the compiler will spawn a second instance of itself [#]_, with a fresh preprocessing context [#]_, to parse just the headers in that module. The resulting Abstract Syntax Tree (AST) is then persisted into the binary representation of the module that is then loaded into translation unit where the module import was encountered.
172
173 The binary representation of modules is persisted in the *module cache*. Imports of a module will first query the module cache and, if a binary representation of the required module is already available, will load that representation directly. Thus, a module's headers will only be parsed once per language configuration, rather than once per translation unit that uses the module.
174
175 Modules maintain references to each of the headers that were part of the module build. If any of those headers changes, or if any of the modules on which a module depends change, then the module will be (automatically) recompiled. The process should never require any user intervention.
176
177 Command-line parameters
178 -----------------------
179 ``-fmodules``
180 Enable the modules feature.
181
182 ``-fbuiltin-module-map``
183 Load the Clang builtins module map file. (Equivalent to ``-fmodule-map-file=<resource dir>/include/module.modulemap``)
184
185 ``-fimplicit-module-maps``
186 Enable implicit search for module map files named ``module.modulemap`` and similar. This option is implied by ``-fmodules``. If this is disabled with ``-fno-implicit-module-maps``, module map files will only be loaded if they are explicitly specified via ``-fmodule-map-file`` or transitively used by another module map file.
187
188 ``-fmodules-cache-path=<directory>``
189 Specify the path to the modules cache. If not provided, Clang will select a system-appropriate default.
190
191 ``-fno-autolink``
192 Disable automatic linking against the libraries associated with imported modules.
193
194 ``-fmodules-ignore-macro=macroname``
195 Instruct modules to ignore the named macro when selecting an appropriate module variant. Use this for macros defined on the command line that don't affect how modules are built, to improve sharing of compiled module files.
196
197 ``-fmodules-prune-interval=seconds``
198 Specify the minimum delay (in seconds) between attempts to prune the module cache. Module cache pruning attempts to clear out old, unused module files so that the module cache itself does not grow without bound. The default delay is large (604,800 seconds, or 7 days) because this is an expensive operation. Set this value to 0 to turn off pruning.
199
200 ``-fmodules-prune-after=seconds``
201 Specify the minimum time (in seconds) for which a file in the module cache must be unused (according to access time) before module pruning will remove it. The default delay is large (2,678,400 seconds, or 31 days) to avoid excessive module rebuilding.
202
203 ``-module-file-info <module file name>``
204 Debugging aid that prints information about a given module file (with a ``.pcm`` extension), including the language and preprocessor options that particular module variant was built with.
205
206 ``-fmodules-decluse``
207 Enable checking of module ``use`` declarations.
208
209 ``-fmodule-name=module-id``
210 Consider a source file as a part of the given module.
211
212 ``-fmodule-map-file=<file>``
213 Load the given module map file if a header from its directory or one of its subdirectories is loaded.
214
215 ``-fmodules-search-all``
216 If a symbol is not found, search modules referenced in the current module maps but not imported for symbols, so the error message can reference the module by name. Note that if the global module index has not been built before, this might take some time as it needs to build all the modules. Note that this option doesn't apply in module builds, to avoid the recursion.
217
218 ``-fno-implicit-modules``
219 All modules used by the build must be specified with ``-fmodule-file``.
220
221 ``-fmodule-file=[<name>=]<file>``
222 Specify the mapping of module names to precompiled module files. If the
223 name is omitted, then the module file is loaded whether actually required
224 or not. If the name is specified, then the mapping is treated as another
225 prebuilt module search mechanism (in addition to ``-fprebuilt-module-path``)
226 and the module is only loaded if required. Note that in this case the
227 specified file also overrides this module's paths that might be embedded
228 in other precompiled module files.
229
230 ``-fprebuilt-module-path=<directory>``
231 Specify the path to the prebuilt modules. If specified, we will look for modules in this directory for a given top-level module name. We don't need a module map for loading prebuilt modules in this directory and the compiler will not try to rebuild these modules. This can be specified multiple times.
232
233 ``-fprebuilt-implicit-modules``
234 Enable prebuilt implicit modules. If a prebuilt module is not found in the
235 prebuilt modules paths (specified via ``-fprebuilt-module-path``), we will
236 look for a matching implicit module in the prebuilt modules paths.
237
238 -cc1 Options
239 ~~~~~~~~~~~~
240
241 ``-fmodules-strict-context-hash``
242 Enables hashing of all compiler options that could impact the semantics of a
243 module in an implicit build. This includes things such as header search paths
244 and diagnostics. Using this option may lead to an excessive number of modules
245 being built if the command line arguments are not homogeneous across your
246 build.
247
248 Using Prebuilt Modules
249 ----------------------
250
251 Below are a few examples illustrating uses of prebuilt modules via the different options.
252
253 First, let's set up files for our examples.
254
255 .. code-block:: c
256
257 /* A.h */
258 #ifdef ENABLE_A
259 void a() {}
260 #endif
261
262 .. code-block:: c
263
264 /* B.h */
265 #include "A.h"
266
267 .. code-block:: c
268
269 /* use.c */
270 #include "B.h"
271 void use() {
272 #ifdef ENABLE_A
273 a();
274 #endif
275 }
276
277 .. code-block:: c
278
279 /* module.modulemap */
280 module A {
281 header "A.h"
282 }
283 module B {
284 header "B.h"
285 export *
286 }
287
288 In the examples below, the compilation of ``use.c`` can be done without ``-cc1``, but the commands used to prebuild the modules would need to be updated to take into account the default options passed to ``clang -cc1``. (See ``clang use.c -v``)
289 Note also that, since we use ``-cc1``, we specify the ``-fmodule-map-file=`` or ``-fimplicit-module-maps`` options explicitly. When using the clang driver, ``-fimplicit-module-maps`` is implied by ``-fmodules``.
290
291 First let us use an explicit mapping from modules to files.
292
293 .. code-block:: sh
294
295 rm -rf prebuilt ; mkdir prebuilt
296 clang -cc1 -emit-module -o prebuilt/A.pcm -fmodules module.modulemap -fmodule-name=A
297 clang -cc1 -emit-module -o prebuilt/B.pcm -fmodules module.modulemap -fmodule-name=B -fmodule-file=A=prebuilt/A.pcm
298 clang -cc1 -emit-obj use.c -fmodules -fmodule-map-file=module.modulemap -fmodule-file=A=prebuilt/A.pcm -fmodule-file=B=prebuilt/B.pcm
299
300 Instead of specifying the mappings manually, it can be convenient to use the ``-fprebuilt-module-path`` option. Let's also use ``-fimplicit-module-maps`` instead of manually pointing to our module map.
301
302 .. code-block:: sh
303
304 rm -rf prebuilt; mkdir prebuilt
305 clang -cc1 -emit-module -o prebuilt/A.pcm -fmodules module.modulemap -fmodule-name=A
306 clang -cc1 -emit-module -o prebuilt/B.pcm -fmodules module.modulemap -fmodule-name=B -fprebuilt-module-path=prebuilt
307 clang -cc1 -emit-obj use.c -fmodules -fimplicit-module-maps -fprebuilt-module-path=prebuilt
308
309 A trick to prebuild all modules required for our source file in one command is to generate implicit modules while using the ``-fdisable-module-hash`` option.
310
311 .. code-block:: sh
312
313 rm -rf prebuilt ; mkdir prebuilt
314 clang -cc1 -emit-obj use.c -fmodules -fimplicit-module-maps -fmodules-cache-path=prebuilt -fdisable-module-hash
315 ls prebuilt/*.pcm
316 # prebuilt/A.pcm prebuilt/B.pcm
317
318 Note that with explicit or prebuilt modules, we are responsible for, and should be particularly careful about the compatibility of our modules.
319 Using mismatching compilation options and modules may lead to issues.
320
321 .. code-block:: sh
322
323 clang -cc1 -emit-obj use.c -fmodules -fimplicit-module-maps -fprebuilt-module-path=prebuilt -DENABLE_A
324 # use.c:4:10: warning: implicit declaration of function 'a' is invalid in C99 [-Wimplicit-function-declaration]
325 # return a(x);
326 # ^
327 # 1 warning generated.
328
329 So we need to maintain multiple versions of prebuilt modules. We can do so using a manual module mapping, or pointing to a different prebuilt module cache path. For example:
330
331 .. code-block:: sh
332
333 rm -rf prebuilt ; mkdir prebuilt ; rm -rf prebuilt_a ; mkdir prebuilt_a
334 clang -cc1 -emit-obj use.c -fmodules -fimplicit-module-maps -fmodules-cache-path=prebuilt -fdisable-module-hash
335 clang -cc1 -emit-obj use.c -fmodules -fimplicit-module-maps -fmodules-cache-path=prebuilt_a -fdisable-module-hash -DENABLE_A
336 clang -cc1 -emit-obj use.c -fmodules -fimplicit-module-maps -fprebuilt-module-path=prebuilt
337 clang -cc1 -emit-obj use.c -fmodules -fimplicit-module-maps -fprebuilt-module-path=prebuilt_a -DENABLE_A
338
339
340 Instead of managing the different module versions manually, we can build implicit modules in a given cache path (using ``-fmodules-cache-path``), and reuse them as prebuilt implicit modules by passing ``-fprebuilt-module-path`` and ``-fprebuilt-implicit-modules``.
341
342 .. code-block:: sh
343
344 rm -rf prebuilt; mkdir prebuilt
345 clang -cc1 -emit-obj -o use.o use.c -fmodules -fimplicit-module-maps -fmodules-cache-path=prebuilt
346 clang -cc1 -emit-obj -o use.o use.c -fmodules -fimplicit-module-maps -fmodules-cache-path=prebuilt -DENABLE_A
347 find prebuilt -name "*.pcm"
348 # prebuilt/1AYBIGPM8R2GA/A-3L1K4LUA6O31.pcm
349 # prebuilt/1AYBIGPM8R2GA/B-3L1K4LUA6O31.pcm
350 # prebuilt/VH0YZMF1OIRK/A-3L1K4LUA6O31.pcm
351 # prebuilt/VH0YZMF1OIRK/B-3L1K4LUA6O31.pcm
352 clang -cc1 -emit-obj -o use.o use.c -fmodules -fimplicit-module-maps -fprebuilt-module-path=prebuilt -fprebuilt-implicit-modules
353 clang -cc1 -emit-obj -o use.o use.c -fmodules -fimplicit-module-maps -fprebuilt-module-path=prebuilt -fprebuilt-implicit-modules -DENABLE_A
354
355 Finally we want to allow implicit modules for configurations that were not prebuilt. When using the clang driver a module cache path is implicitly selected. Using ``-cc1``, we simply add use the ``-fmodules-cache-path`` option.
356
357 .. code-block:: sh
358
359 clang -cc1 -emit-obj -o use.o use.c -fmodules -fimplicit-module-maps -fprebuilt-module-path=prebuilt -fprebuilt-implicit-modules -fmodules-cache-path=cache
360 clang -cc1 -emit-obj -o use.o use.c -fmodules -fimplicit-module-maps -fprebuilt-module-path=prebuilt -fprebuilt-implicit-modules -fmodules-cache-path=cache -DENABLE_A
361 clang -cc1 -emit-obj -o use.o use.c -fmodules -fimplicit-module-maps -fprebuilt-module-path=prebuilt -fprebuilt-implicit-modules -fmodules-cache-path=cache -DENABLE_A -DOTHER_OPTIONS
362
363 This way, a single directory containing multiple variants of modules can be prepared and reused. The options configuring the module cache are independent of other options.
364
365 Module Semantics
366 ================
367
368 Modules are modeled as if each submodule were a separate translation unit, and a module import makes names from the other translation unit visible. Each submodule starts with a new preprocessor state and an empty translation unit.
369
370 .. note::
371
372 This behavior is currently only approximated when building a module with submodules. Entities within a submodule that has already been built are visible when building later submodules in that module. This can lead to fragile modules that depend on the build order used for the submodules of the module, and should not be relied upon. This behavior is subject to change.
373
374 As an example, in C, this implies that if two structs are defined in different submodules with the same name, those two types are distinct types (but may be *compatible* types if their definitions match). In C++, two structs defined with the same name in different submodules are the *same* type, and must be equivalent under C++'s One Definition Rule.
375
376 .. note::
377
378 Clang currently only performs minimal checking for violations of the One Definition Rule.
379
380 If any submodule of a module is imported into any part of a program, the entire top-level module is considered to be part of the program. As a consequence of this, Clang may diagnose conflicts between an entity declared in an unimported submodule and an entity declared in the current translation unit, and Clang may inline or devirtualize based on knowledge from unimported submodules.
381
382 Macros
383 ------
384
385 The C and C++ preprocessor assumes that the input text is a single linear buffer, but with modules this is not the case. It is possible to import two modules that have conflicting definitions for a macro (or where one ``#define``\s a macro and the other ``#undef``\ines it). The rules for handling macro definitions in the presence of modules are as follows:
386
387 * Each definition and undefinition of a macro is considered to be a distinct entity.
388 * Such entities are *visible* if they are from the current submodule or translation unit, or if they were exported from a submodule that has been imported.
389 * A ``#define X`` or ``#undef X`` directive *overrides* all definitions of ``X`` that are visible at the point of the directive.
390 * A ``#define`` or ``#undef`` directive is *active* if it is visible and no visible directive overrides it.
391 * A set of macro directives is *consistent* if it consists of only ``#undef`` directives, or if all ``#define`` directives in the set define the macro name to the same sequence of tokens (following the usual rules for macro redefinitions).
392 * If a macro name is used and the set of active directives is not consistent, the program is ill-formed. Otherwise, the (unique) meaning of the macro name is used.
393
394 For example, suppose:
395
396 * ``<stdio.h>`` defines a macro ``getc`` (and exports its ``#define``)
397 * ``<cstdio>`` imports the ``<stdio.h>`` module and undefines the macro (and exports its ``#undef``)
398
399 The ``#undef`` overrides the ``#define``, and a source file that imports both modules *in any order* will not see ``getc`` defined as a macro.
400
401 Module Map Language
402 ===================
403
404 .. warning::
405
406 The module map language is not currently guaranteed to be stable between major revisions of Clang.
407
408 The module map language describes the mapping from header files to the
409 logical structure of modules. To enable support for using a library as
410 a module, one must write a ``module.modulemap`` file for that library. The
411 ``module.modulemap`` file is placed alongside the header files themselves,
412 and is written in the module map language described below.
413
414 .. note::
415 For compatibility with previous releases, if a module map file named
416 ``module.modulemap`` is not found, Clang will also search for a file named
417 ``module.map``. This behavior is deprecated and we plan to eventually
418 remove it.
419
420 As an example, the module map file for the C standard library might look a bit like this:
421
422 .. parsed-literal::
423
424 module std [system] {
425 module complex {
426 header "complex.h"
427 export *
428 }
429
430 module ctype {
431 header "ctype.h"
432 export *
433 }
434
435 module errno {
436 header "errno.h"
437 export *
438 }
439
440 module fenv {
441 header "fenv.h"
442 export *
443 }
444
445 // ...more headers follow...
446 }
447
448 Here, the top-level module ``std`` encompasses the whole C standard library. It has a number of submodules containing different parts of the standard library: ``complex`` for complex numbers, ``ctype`` for character types, etc. Each submodule lists one of more headers that provide the contents for that submodule. Finally, the ``export *`` command specifies that anything included by that submodule will be automatically re-exported.
449
450 Lexical structure
451 -----------------
452 Module map files use a simplified form of the C99 lexer, with the same rules for identifiers, tokens, string literals, ``/* */`` and ``//`` comments. The module map language has the following reserved words; all other C identifiers are valid identifiers.
453
454 .. parsed-literal::
455
456 ``config_macros`` ``export_as`` ``private``
457 ``conflict`` ``framework`` ``requires``
458 ``exclude`` ``header`` ``textual``
459 ``explicit`` ``link`` ``umbrella``
460 ``extern`` ``module`` ``use``
461 ``export``
462
463 Module map file
464 ---------------
465 A module map file consists of a series of module declarations:
466
467 .. parsed-literal::
468
469 *module-map-file*:
470 *module-declaration**
471
472 Within a module map file, modules are referred to by a *module-id*, which uses periods to separate each part of a module's name:
473
474 .. parsed-literal::
475
476 *module-id*:
477 *identifier* ('.' *identifier*)*
478
479 Module declaration
480 ------------------
481 A module declaration describes a module, including the headers that contribute to that module, its submodules, and other aspects of the module.
482
483 .. parsed-literal::
484
485 *module-declaration*:
486 ``explicit``:sub:`opt` ``framework``:sub:`opt` ``module`` *module-id* *attributes*:sub:`opt` '{' *module-member** '}'
487 ``extern`` ``module`` *module-id* *string-literal*
488
489 The *module-id* should consist of only a single *identifier*, which provides the name of the module being defined. Each module shall have a single definition.
490
491 The ``explicit`` qualifier can only be applied to a submodule, i.e., a module that is nested within another module. The contents of explicit submodules are only made available when the submodule itself was explicitly named in an import declaration or was re-exported from an imported module.
492
493 The ``framework`` qualifier specifies that this module corresponds to a Darwin-style framework. A Darwin-style framework (used primarily on macOS and iOS) is contained entirely in directory ``Name.framework``, where ``Name`` is the name of the framework (and, therefore, the name of the module). That directory has the following layout:
494
495 .. parsed-literal::
496
497 Name.framework/
498 Modules/module.modulemap Module map for the framework
499 Headers/ Subdirectory containing framework headers
500 PrivateHeaders/ Subdirectory containing framework private headers
501 Frameworks/ Subdirectory containing embedded frameworks
502 Resources/ Subdirectory containing additional resources
503 Name Symbolic link to the shared library for the framework
504
505 The ``system`` attribute specifies that the module is a system module. When a system module is rebuilt, all of the module's headers will be considered system headers, which suppresses warnings. This is equivalent to placing ``#pragma GCC system_header`` in each of the module's headers. The form of attributes is described in the section Attributes_, below.
506
507 The ``extern_c`` attribute specifies that the module contains C code that can be used from within C++. When such a module is built for use in C++ code, all of the module's headers will be treated as if they were contained within an implicit ``extern "C"`` block. An import for a module with this attribute can appear within an ``extern "C"`` block. No other restrictions are lifted, however: the module currently cannot be imported within an ``extern "C"`` block in a namespace.
508
509 The ``no_undeclared_includes`` attribute specifies that the module can only reach non-modular headers and headers from used modules. Since some headers could be present in more than one search path and map to different modules in each path, this mechanism helps clang to find the right header, i.e., prefer the one for the current module or in a submodule instead of the first usual match in the search paths.
510
511 Modules can have a number of different kinds of members, each of which is described below:
512
513 .. parsed-literal::
514
515 *module-member*:
516 *requires-declaration*
517 *header-declaration*
518 *umbrella-dir-declaration*
519 *submodule-declaration*
520 *export-declaration*
521 *export-as-declaration*
522 *use-declaration*
523 *link-declaration*
524 *config-macros-declaration*
525 *conflict-declaration*
526
527 An extern module references a module defined by the *module-id* in a file given by the *string-literal*. The file can be referenced either by an absolute path or by a path relative to the current map file.
528
529 Requires declaration
530 ~~~~~~~~~~~~~~~~~~~~
531 A *requires-declaration* specifies the requirements that an importing translation unit must satisfy to use the module.
532
533 .. parsed-literal::
534
535 *requires-declaration*:
536 ``requires`` *feature-list*
537
538 *feature-list*:
539 *feature* (',' *feature*)*
540
541 *feature*:
542 ``!``:sub:`opt` *identifier*
543
544 The requirements clause allows specific modules or submodules to specify that they are only accessible with certain language dialects, platforms, environments and target specific features. The feature list is a set of identifiers, defined below. If any of the features is not available in a given translation unit, that translation unit shall not import the module. When building a module for use by a compilation, submodules requiring unavailable features are ignored. The optional ``!`` indicates that a feature is incompatible with the module.
545
546 The following features are defined:
547
548 altivec
549 The target supports AltiVec.
550
551 blocks
552 The "blocks" language feature is available.
553
554 coroutines
555 Support for the coroutines TS is available.
556
557 cplusplus
558 C++ support is available.
559
560 cplusplus11
561 C++11 support is available.
562
563 cplusplus14
564 C++14 support is available.
565
566 cplusplus17
567 C++17 support is available.
568
569 cplusplus20
570 C++20 support is available.
571
572 cplusplus23
573 C++23 support is available.
574
575 c99
576 C99 support is available.
577
578 c11
579 C11 support is available.
580
581 c17
582 C17 support is available.
583
584 c23
585 C23 support is available.
586
587 freestanding
588 A freestanding environment is available.
589
590 gnuinlineasm
591 GNU inline ASM is available.
592
593 objc
594 Objective-C support is available.
595
596 objc_arc
597 Objective-C Automatic Reference Counting (ARC) is available
598
599 opencl
600 OpenCL is available
601
602 tls
603 Thread local storage is available.
604
605 *target feature*
606 A specific target feature (e.g., ``sse4``, ``avx``, ``neon``) is available.
607
608 *platform/os*
609 An os/platform variant (e.g. ``freebsd``, ``win32``, ``windows``, ``linux``, ``ios``, ``macos``, ``iossimulator``) is available.
610
611 *environment*
612 An environment variant (e.g. ``gnu``, ``gnueabi``, ``android``, ``msvc``) is available.
613
614 **Example:** The ``std`` module can be extended to also include C++ and C++11 headers using a *requires-declaration*:
615
616 .. parsed-literal::
617
618 module std {
619 // C standard library...
620
621 module vector {
622 requires cplusplus
623 header "vector"
624 }
625
626 module type_traits {
627 requires cplusplus11
628 header "type_traits"
629 }
630 }
631
632 Header declaration
633 ~~~~~~~~~~~~~~~~~~
634 A header declaration specifies that a particular header is associated with the enclosing module.
635
636 .. parsed-literal::
637
638 *header-declaration*:
639 ``private``:sub:`opt` ``textual``:sub:`opt` ``header`` *string-literal* *header-attrs*:sub:`opt`
640 ``umbrella`` ``header`` *string-literal* *header-attrs*:sub:`opt`
641 ``exclude`` ``header`` *string-literal* *header-attrs*:sub:`opt`
642
643 *header-attrs*:
644 '{' *header-attr** '}'
645
646 *header-attr*:
647 ``size`` *integer-literal*
648 ``mtime`` *integer-literal*
649
650 A header declaration that does not contain ``exclude`` nor ``textual`` specifies a header that contributes to the enclosing module. Specifically, when the module is built, the named header will be parsed and its declarations will be (logically) placed into the enclosing submodule.
651
652 A header with the ``umbrella`` specifier is called an umbrella header. An umbrella header includes all of the headers within its directory (and any subdirectories), and is typically used (in the ``#include`` world) to easily access the full API provided by a particular library. With modules, an umbrella header is a convenient shortcut that eliminates the need to write out ``header`` declarations for every library header. A given directory can only contain a single umbrella header.
653
654 .. note::
655 Any headers not included by the umbrella header should have
656 explicit ``header`` declarations. Use the
657 ``-Wincomplete-umbrella`` warning option to ask Clang to complain
658 about headers not covered by the umbrella header or the module map.
659
660 A header with the ``private`` specifier may not be included from outside the module itself.
661
662 A header with the ``textual`` specifier will not be compiled when the module is
663 built, and will be textually included if it is named by a ``#include``
664 directive. However, it is considered to be part of the module for the purpose
665 of checking *use-declaration*\s, and must still be a lexically-valid header
666 file. In the future, we intend to pre-tokenize such headers and include the
667 token sequence within the prebuilt module representation.
668
669 A header with the ``exclude`` specifier is excluded from the module. It will not be included when the module is built, nor will it be considered to be part of the module, even if an ``umbrella`` directory would otherwise make it part of the module.
670
671 **Example:** A "X macro" header is an excellent candidate for a textual header, because it is can't be compiled standalone, and by itself does not contain any declarations.
672
673 .. parsed-literal::
674
675 module MyLib [system] {
676 textual header "xmacros.h"
677 }
678
679 A given header shall not be referenced by more than one *header-declaration*.
680
681 Two *header-declaration*\s, or a *header-declaration* and a ``#include``, are
682 considered to refer to the same file if the paths resolve to the same file
683 and the specified *header-attr*\s (if any) match the attributes of that file,
684 even if the file is named differently (for instance, by a relative path or
685 via symlinks).
686
687 .. note::
688 The use of *header-attr*\s avoids the need for Clang to speculatively
689 ``stat`` every header referenced by a module map. It is recommended that
690 *header-attr*\s only be used in machine-generated module maps, to avoid
691 mismatches between attribute values and the corresponding files.
692
693 Umbrella directory declaration
694 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
695 An umbrella directory declaration specifies that all of the headers in the specified directory should be included within the module.
696
697 .. parsed-literal::
698
699 *umbrella-dir-declaration*:
700 ``umbrella`` *string-literal*
701
702 The *string-literal* refers to a directory. When the module is built, all of the header files in that directory (and its subdirectories) are included in the module.
703
704 An *umbrella-dir-declaration* shall not refer to the same directory as the location of an umbrella *header-declaration*. In other words, only a single kind of umbrella can be specified for a given directory.
705
706 .. note::
707
708 Umbrella directories are useful for libraries that have a large number of headers but do not have an umbrella header.
709
710
711 Submodule declaration
712 ~~~~~~~~~~~~~~~~~~~~~
713 Submodule declarations describe modules that are nested within their enclosing module.
714
715 .. parsed-literal::
716
717 *submodule-declaration*:
718 *module-declaration*
719 *inferred-submodule-declaration*
720
721 A *submodule-declaration* that is a *module-declaration* is a nested module. If the *module-declaration* has a ``framework`` specifier, the enclosing module shall have a ``framework`` specifier; the submodule's contents shall be contained within the subdirectory ``Frameworks/SubName.framework``, where ``SubName`` is the name of the submodule.
722
723 A *submodule-declaration* that is an *inferred-submodule-declaration* describes a set of submodules that correspond to any headers that are part of the module but are not explicitly described by a *header-declaration*.
724
725 .. parsed-literal::
726
727 *inferred-submodule-declaration*:
728 ``explicit``:sub:`opt` ``framework``:sub:`opt` ``module`` '*' *attributes*:sub:`opt` '{' *inferred-submodule-member** '}'
729
730 *inferred-submodule-member*:
731 ``export`` '*'
732
733 A module containing an *inferred-submodule-declaration* shall have either an umbrella header or an umbrella directory. The headers to which the *inferred-submodule-declaration* applies are exactly those headers included by the umbrella header (transitively) or included in the module because they reside within the umbrella directory (or its subdirectories).
734
735 For each header included by the umbrella header or in the umbrella directory that is not named by a *header-declaration*, a module declaration is implicitly generated from the *inferred-submodule-declaration*. The module will:
736
737 * Have the same name as the header (without the file extension)
738 * Have the ``explicit`` specifier, if the *inferred-submodule-declaration* has the ``explicit`` specifier
739 * Have the ``framework`` specifier, if the
740 *inferred-submodule-declaration* has the ``framework`` specifier
741 * Have the attributes specified by the \ *inferred-submodule-declaration*
742 * Contain a single *header-declaration* naming that header
743 * Contain a single *export-declaration* ``export *``, if the \ *inferred-submodule-declaration* contains the \ *inferred-submodule-member* ``export *``
744
745 **Example:** If the subdirectory "MyLib" contains the headers ``A.h`` and ``B.h``, then the following module map:
746
747 .. parsed-literal::
748
749 module MyLib {
750 umbrella "MyLib"
751 explicit module * {
752 export *
753 }
754 }
755
756 is equivalent to the (more verbose) module map:
757
758 .. parsed-literal::
759
760 module MyLib {
761 explicit module A {
762 header "A.h"
763 export *
764 }
765
766 explicit module B {
767 header "B.h"
768 export *
769 }
770 }
771
772 Export declaration
773 ~~~~~~~~~~~~~~~~~~
774 An *export-declaration* specifies which imported modules will automatically be re-exported as part of a given module's API.
775
776 .. parsed-literal::
777
778 *export-declaration*:
779 ``export`` *wildcard-module-id*
780
781 *wildcard-module-id*:
782 *identifier*
783 '*'
784 *identifier* '.' *wildcard-module-id*
785
786 The *export-declaration* names a module or a set of modules that will be re-exported to any translation unit that imports the enclosing module. Each imported module that matches the *wildcard-module-id* up to, but not including, the first ``*`` will be re-exported.
787
788 **Example:** In the following example, importing ``MyLib.Derived`` also provides the API for ``MyLib.Base``:
789
790 .. parsed-literal::
791
792 module MyLib {
793 module Base {
794 header "Base.h"
795 }
796
797 module Derived {
798 header "Derived.h"
799 export Base
800 }
801 }
802
803 Note that, if ``Derived.h`` includes ``Base.h``, one can simply use a wildcard export to re-export everything ``Derived.h`` includes:
804
805 .. parsed-literal::
806
807 module MyLib {
808 module Base {
809 header "Base.h"
810 }
811
812 module Derived {
813 header "Derived.h"
814 export *
815 }
816 }
817
818 .. note::
819
820 The wildcard export syntax ``export *`` re-exports all of the
821 modules that were imported in the actual header file. Because
822 ``#include`` directives are automatically mapped to module imports,
823 ``export *`` provides the same transitive-inclusion behavior
824 provided by the C preprocessor, e.g., importing a given module
825 implicitly imports all of the modules on which it depends.
826 Therefore, liberal use of ``export *`` provides excellent backward
827 compatibility for programs that rely on transitive inclusion (i.e.,
828 all of them).
829
830 Re-export Declaration
831 ~~~~~~~~~~~~~~~~~~~~~
832 An *export-as-declaration* specifies that the current module will have
833 its interface re-exported by the named module.
834
835 .. parsed-literal::
836
837 *export-as-declaration*:
838 ``export_as`` *identifier*
839
840 The *export-as-declaration* names the module that the current
841 module will be re-exported through. Only top-level modules
842 can be re-exported, and any given module may only be re-exported
843 through a single module.
844
845 **Example:** In the following example, the module ``MyFrameworkCore``
846 will be re-exported via the module ``MyFramework``:
847
848 .. parsed-literal::
849
850 module MyFrameworkCore {
851 export_as MyFramework
852 }
853
854 Use declaration
855 ~~~~~~~~~~~~~~~
856 A *use-declaration* specifies another module that the current top-level module
857 intends to use. When the option *-fmodules-decluse* is specified, a module can
858 only use other modules that are explicitly specified in this way.
859
860 .. parsed-literal::
861
862 *use-declaration*:
863 ``use`` *module-id*
864
865 **Example:** In the following example, use of A from C is not declared, so will trigger a warning.
866
867 .. parsed-literal::
868
869 module A {
870 header "a.h"
871 }
872
873 module B {
874 header "b.h"
875 }
876
877 module C {
878 header "c.h"
879 use B
880 }
881
882 When compiling a source file that implements a module, use the option
883 ``-fmodule-name=module-id`` to indicate that the source file is logically part
884 of that module.
885
886 The compiler at present only applies restrictions to the module directly being built.
887
888 Link declaration
889 ~~~~~~~~~~~~~~~~
890 A *link-declaration* specifies a library or framework against which a program should be linked if the enclosing module is imported in any translation unit in that program.
891
892 .. parsed-literal::
893
894 *link-declaration*:
895 ``link`` ``framework``:sub:`opt` *string-literal*
896
897 The *string-literal* specifies the name of the library or framework against which the program should be linked. For example, specifying "clangBasic" would instruct the linker to link with ``-lclangBasic`` for a Unix-style linker.
898
899 A *link-declaration* with the ``framework`` specifies that the linker should link against the named framework, e.g., with ``-framework MyFramework``.
900
901 .. note::
902
903 Automatic linking with the ``link`` directive is not yet widely
904 implemented, because it requires support from both the object file
905 format and the linker. The notion is similar to Microsoft Visual
906 Studio's ``#pragma comment(lib...)``.
907
908 Configuration macros declaration
909 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
910 The *config-macros-declaration* specifies the set of configuration macros that have an effect on the API of the enclosing module.
911
912 .. parsed-literal::
913
914 *config-macros-declaration*:
915 ``config_macros`` *attributes*:sub:`opt` *config-macro-list*:sub:`opt`
916
917 *config-macro-list*:
918 *identifier* (',' *identifier*)*
919
920 Each *identifier* in the *config-macro-list* specifies the name of a macro. The compiler is required to maintain different variants of the given module for differing definitions of any of the named macros.
921
922 A *config-macros-declaration* shall only be present on a top-level module, i.e., a module that is not nested within an enclosing module.
923
924 The ``exhaustive`` attribute specifies that the list of macros in the *config-macros-declaration* is exhaustive, meaning that no other macro definition is intended to have an effect on the API of that module.
925
926 .. note::
927
928 The ``exhaustive`` attribute implies that any macro definitions
929 for macros not listed as configuration macros should be ignored
930 completely when building the module. As an optimization, the
931 compiler could reduce the number of unique module variants by not
932 considering these non-configuration macros. This optimization is not
933 yet implemented in Clang.
934
935 A translation unit shall not import the same module under different definitions of the configuration macros.
936
937 .. note::
938
939 Clang implements a weak form of this requirement: the definitions
940 used for configuration macros are fixed based on the definitions
941 provided by the command line. If an import occurs and the definition
942 of any configuration macro has changed, the compiler will produce a
943 warning (under the control of ``-Wconfig-macros``).
944
945 **Example:** A logging library might provide different API (e.g., in the form of different definitions for a logging macro) based on the ``NDEBUG`` macro setting:
946
947 .. parsed-literal::
948
949 module MyLogger {
950 umbrella header "MyLogger.h"
951 config_macros [exhaustive] NDEBUG
952 }
953
954 Conflict declarations
955 ~~~~~~~~~~~~~~~~~~~~~
956 A *conflict-declaration* describes a case where the presence of two different modules in the same translation unit is likely to cause a problem. For example, two modules may provide similar-but-incompatible functionality.
957
958 .. parsed-literal::
959
960 *conflict-declaration*:
961 ``conflict`` *module-id* ',' *string-literal*
962
963 The *module-id* of the *conflict-declaration* specifies the module with which the enclosing module conflicts. The specified module shall not have been imported in the translation unit when the enclosing module is imported.
964
965 The *string-literal* provides a message to be provided as part of the compiler diagnostic when two modules conflict.
966
967 .. note::
968
969 Clang emits a warning (under the control of ``-Wmodule-conflict``)
970 when a module conflict is discovered.
971
972 **Example:**
973
974 .. parsed-literal::
975
976 module Conflicts {
977 explicit module A {
978 header "conflict_a.h"
979 conflict B, "we just don't like B"
980 }
981
982 module B {
983 header "conflict_b.h"
984 }
985 }
986
987
988 Attributes
989 ----------
990 Attributes are used in a number of places in the grammar to describe specific behavior of other declarations. The format of attributes is fairly simple.
991
992 .. parsed-literal::
993
994 *attributes*:
995 *attribute* *attributes*:sub:`opt`
996
997 *attribute*:
998 '[' *identifier* ']'
999
1000 Any *identifier* can be used as an attribute, and each declaration specifies what attributes can be applied to it.
1001
1002 Private Module Map Files
1003 ------------------------
1004 Module map files are typically named ``module.modulemap`` and live
1005 either alongside the headers they describe or in a parent directory of
1006 the headers they describe. These module maps typically describe all of
1007 the API for the library.
1008
1009 However, in some cases, the presence or absence of particular headers
1010 is used to distinguish between the "public" and "private" APIs of a
1011 particular library. For example, a library may contain the headers
1012 ``Foo.h`` and ``Foo_Private.h``, providing public and private APIs,
1013 respectively. Additionally, ``Foo_Private.h`` may only be available on
1014 some versions of library, and absent in others. One cannot easily
1015 express this with a single module map file in the library:
1016
1017 .. parsed-literal::
1018
1019 module Foo {
1020 header "Foo.h"
1021 ...
1022 }
1023
1024 module Foo_Private {
1025 header "Foo_Private.h"
1026 ...
1027 }
1028
1029
1030 because the header ``Foo_Private.h`` won't always be available. The
1031 module map file could be customized based on whether
1032 ``Foo_Private.h`` is available or not, but doing so requires custom
1033 build machinery.
1034
1035 Private module map files, which are named ``module.private.modulemap``
1036 (or, for backward compatibility, ``module_private.map``), allow one to
1037 augment the primary module map file with an additional modules. For
1038 example, we would split the module map file above into two module map
1039 files:
1040
1041 .. code-block:: c
1042
1043 /* module.modulemap */
1044 module Foo {
1045 header "Foo.h"
1046 }
1047
1048 /* module.private.modulemap */
1049 module Foo_Private {
1050 header "Foo_Private.h"
1051 }
1052
1053
1054 When a ``module.private.modulemap`` file is found alongside a
1055 ``module.modulemap`` file, it is loaded after the ``module.modulemap``
1056 file. In our example library, the ``module.private.modulemap`` file
1057 would be available when ``Foo_Private.h`` is available, making it
1058 easier to split a library's public and private APIs along header
1059 boundaries.
1060
1061 When writing a private module as part of a *framework*, it's recommended that:
1062
1063 * Headers for this module are present in the ``PrivateHeaders`` framework
1064 subdirectory.
1065 * The private module is defined as a *top level module* with the name of the
1066 public framework prefixed, like ``Foo_Private`` above. Clang has extra logic
1067 to work with this naming, using ``FooPrivate`` or ``Foo.Private`` (submodule)
1068 trigger warnings and might not work as expected.
1069
1070 Modularizing a Platform
1071 =======================
1072 To get any benefit out of modules, one needs to introduce module maps for software libraries starting at the bottom of the stack. This typically means introducing a module map covering the operating system's headers and the C standard library headers (in ``/usr/include``, for a Unix system).
1073
1074 The module maps will be written using the `module map language`_, which provides the tools necessary to describe the mapping between headers and modules. Because the set of headers differs from one system to the next, the module map will likely have to be somewhat customized for, e.g., a particular distribution and version of the operating system. Moreover, the system headers themselves may require some modification, if they exhibit any anti-patterns that break modules. Such common patterns are described below.
1075
1076 **Macro-guarded copy-and-pasted definitions**
1077 System headers vend core types such as ``size_t`` for users. These types are often needed in a number of system headers, and are almost trivial to write. Hence, it is fairly common to see a definition such as the following copy-and-pasted throughout the headers:
1078
1079 .. parsed-literal::
1080
1081 #ifndef _SIZE_T
1082 #define _SIZE_T
1083 typedef __SIZE_TYPE__ size_t;
1084 #endif
1085
1086 Unfortunately, when modules compiles all of the C library headers together into a single module, only the first actual type definition of ``size_t`` will be visible, and then only in the submodule corresponding to the lucky first header. Any other headers that have copy-and-pasted versions of this pattern will *not* have a definition of ``size_t``. Importing the submodule corresponding to one of those headers will therefore not yield ``size_t`` as part of the API, because it wasn't there when the header was parsed. The fix for this problem is either to pull the copied declarations into a common header that gets included everywhere ``size_t`` is part of the API, or to eliminate the ``#ifndef`` and redefine the ``size_t`` type. The latter works for C++ headers and C11, but will cause an error for non-modules C90/C99, where redefinition of ``typedefs`` is not permitted.
1087
1088 **Conflicting definitions**
1089 Different system headers may provide conflicting definitions for various macros, functions, or types. These conflicting definitions don't tend to cause problems in a pre-modules world unless someone happens to include both headers in one translation unit. Since the fix is often simply "don't do that", such problems persist. Modules requires that the conflicting definitions be eliminated or that they be placed in separate modules (the former is generally the better answer).
1090
1091 **Missing includes**
1092 Headers are often missing ``#include`` directives for headers that they actually depend on. As with the problem of conflicting definitions, this only affects unlucky users who don't happen to include headers in the right order. With modules, the headers of a particular module will be parsed in isolation, so the module may fail to build if there are missing includes.
1093
1094 **Headers that vend multiple APIs at different times**
1095 Some systems have headers that contain a number of different kinds of API definitions, only some of which are made available with a given include. For example, the header may vend ``size_t`` only when the macro ``__need_size_t`` is defined before that header is included, and also vend ``wchar_t`` only when the macro ``__need_wchar_t`` is defined. Such headers are often included many times in a single translation unit, and will have no include guards. There is no sane way to map this header to a submodule. One can either eliminate the header (e.g., by splitting it into separate headers, one per actual API) or simply ``exclude`` it in the module map.
1096
1097 To detect and help address some of these problems, the ``clang-tools-extra`` repository contains a ``modularize`` tool that parses a set of given headers and attempts to detect these problems and produce a report. See the tool's in-source documentation for information on how to check your system or library headers.
1098
1099 Future Directions
1100 =================
1101 Modules support is under active development, and there are many opportunities remaining to improve it. Here are a few ideas:
1102
1103 **Detect unused module imports**
1104 Unlike with ``#include`` directives, it should be fairly simple to track whether a directly-imported module has ever been used. By doing so, Clang can emit ``unused import`` or ``unused #include`` diagnostics, including Fix-Its to remove the useless imports/includes.
1105
1106 **Fix-Its for missing imports**
1107 It's fairly common for one to make use of some API while writing code, only to get a compiler error about "unknown type" or "no function named" because the corresponding header has not been included. Clang can detect such cases and auto-import the required module, but should provide a Fix-It to add the import.
1108
1109 **Improve modularize**
1110 The modularize tool is both extremely important (for deployment) and extremely crude. It needs better UI, better detection of problems (especially for C++), and perhaps an assistant mode to help write module maps for you.
1111
1112 Where To Learn More About Modules
1113 =================================
1114 The Clang source code provides additional information about modules:
1115
1116 ``clang/lib/Headers/module.modulemap``
1117 Module map for Clang's compiler-specific header files.
1118
1119 ``clang/test/Modules/``
1120 Tests specifically related to modules functionality.
1121
1122 ``clang/include/clang/Basic/Module.h``
1123 The ``Module`` class in this header describes a module, and is used throughout the compiler to implement modules.
1124
1125 ``clang/include/clang/Lex/ModuleMap.h``
1126 The ``ModuleMap`` class in this header describes the full module map, consisting of all of the module map files that have been parsed, and providing facilities for looking up module maps and mapping between modules and headers (in both directions).
1127
1128 PCHInternals_
1129 Information about the serialized AST format used for precompiled headers and modules. The actual implementation is in the ``clangSerialization`` library.
1130
1131 .. [#] Automatic linking against the libraries of modules requires specific linker support, which is not widely available.
1132
1133 .. [#] There are certain anti-patterns that occur in headers, particularly system headers, that cause problems for modules. The section `Modularizing a Platform`_ describes some of them.
1134
1135 .. [#] The second instance is actually a new thread within the current process, not a separate process. However, the original compiler instance is blocked on the execution of this thread.
1136
1137 .. [#] The preprocessing context in which the modules are parsed is actually dependent on the command-line options provided to the compiler, including the language dialect and any ``-D`` options. However, the compiled modules for different command-line options are kept distinct, and any preprocessor directives that occur within the translation unit are ignored. See the section on the `Configuration macros declaration`_ for more information.
1138
1139 .. _PCHInternals: PCHInternals.html