1UNITY_BUILD_UNIQUE_ID
2---------------------
3
4.. versionadded:: 3.20
5
6The name of a valid C-identifier which is set to a unique per-file
7value during unity builds.
8
9When this property is populated and when :prop_tgt:`UNITY_BUILD`
10is true, the property value is used to define a compiler definition
11of the specified name. The value of the defined symbol is unspecified,
12but it is unique per file path.
13
14Given:
15
16.. code-block:: cmake
17
18  set_target_properties(myTarget PROPERTIES
19    UNITY_BUILD "ON"
20    UNITY_BUILD_UNIQUE_ID "MY_UNITY_ID"
21  )
22
23the ``MY_UNITY_ID`` symbol is defined to a unique per-file value.
24
25One known use case for this identifier is to disambiguate the
26variables in an anonymous namespace in a limited scope.
27Anonymous namespaces present a problem for unity builds because
28they are used to ensure that certain variables and declarations
29are scoped to a translation unit which is approximated by a
30single source file.  When source files are combined in a unity
31build file, those variables in different files are combined in
32a single translation unit and the names clash.  This property can
33be used to avoid that with code like the following:
34
35.. code-block:: cpp
36
37  // Needed for when unity builds are disabled
38  #ifndef MY_UNITY_ID
39  #define MY_UNITY_ID
40  #endif
41
42  namespace { namespace MY_UNITY_ID {
43    // The name 'i' clashes (or could clash) with other
44    // variables in other anonymous namespaces
45    int i = 42;
46  }}
47
48  int use_var()
49  {
50    return MY_UNITY_ID::i;
51  }
52
53The pseudonymous namespace is used within a truly anonymous namespace.
54On many platforms, this maintains the invariant that the symbols within
55do not get external linkage when performing a unity build.
56