Merge branch 'release-4.0'
[kiteware-cmake.git] / Modules / GenerateExportHeader.cmake
blob9c369b645a81470939a87eb0b4a28a3ecf34f468
1 # Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
2 # file Copyright.txt or https://cmake.org/licensing for details.
4 #[=======================================================================[.rst:
5 GenerateExportHeader
6 --------------------
8 This module provides the ``generate_export_header()`` function to generate
9 export macros for libraries.
11 .. versionadded:: 3.12
12   Added support for C projects.  Previous versions supported C++ project only.
14 .. command:: generate_export_header
16   The ``generate_export_header()`` function can be used to generate a file
17   suitable for preprocessor inclusion which contains EXPORT macros to be
18   used in library classes:
20   .. code-block:: cmake
22     generate_export_header(LIBRARY_TARGET
23              [BASE_NAME <base_name>]
24              [EXPORT_MACRO_NAME <export_macro_name>]
25              [EXPORT_FILE_NAME <export_file_name>]
26              [DEPRECATED_MACRO_NAME <deprecated_macro_name>]
27              [NO_EXPORT_MACRO_NAME <no_export_macro_name>]
28              [INCLUDE_GUARD_NAME <include_guard_name>]
29              [STATIC_DEFINE <static_define>]
30              [NO_DEPRECATED_MACRO_NAME <no_deprecated_macro_name>]
31              [DEFINE_NO_DEPRECATED]
32              [PREFIX_NAME <prefix_name>]
33              [CUSTOM_CONTENT_FROM_VARIABLE <variable>]
34     )
36 The target properties :prop_tgt:`CXX_VISIBILITY_PRESET <<LANG>_VISIBILITY_PRESET>`
37 and :prop_tgt:`VISIBILITY_INLINES_HIDDEN` can be used to add the appropriate
38 compile flags for targets.  See the documentation of those target properties,
39 and the convenience variables
40 :variable:`CMAKE_CXX_VISIBILITY_PRESET <CMAKE_<LANG>_VISIBILITY_PRESET>` and
41 :variable:`CMAKE_VISIBILITY_INLINES_HIDDEN`.
43 By default ``generate_export_header()`` generates macro names in a file
44 name determined by the name of the library.  This means that in the
45 simplest case, users of ``GenerateExportHeader`` will be equivalent to:
47 .. code-block:: cmake
49    set(CMAKE_CXX_VISIBILITY_PRESET hidden)
50    set(CMAKE_VISIBILITY_INLINES_HIDDEN 1)
51    add_library(somelib someclass.cpp)
52    generate_export_header(somelib)
53    install(TARGETS somelib DESTINATION ${LIBRARY_INSTALL_DIR})
54    install(FILES
55     someclass.h
56     ${PROJECT_BINARY_DIR}/somelib_export.h DESTINATION ${INCLUDE_INSTALL_DIR}
57    )
60 And in the ABI header files:
62 .. code-block:: c++
64    #include "somelib_export.h"
65    class SOMELIB_EXPORT SomeClass {
66      ...
67    };
70 The CMake fragment will generate a file in the
71 ``${CMAKE_CURRENT_BINARY_DIR}`` called ``somelib_export.h`` containing the
72 macros ``SOMELIB_EXPORT``, ``SOMELIB_NO_EXPORT``, ``SOMELIB_DEPRECATED``,
73 ``SOMELIB_DEPRECATED_EXPORT`` and ``SOMELIB_DEPRECATED_NO_EXPORT``.
74 They will be followed by content taken from the variable specified by
75 the ``CUSTOM_CONTENT_FROM_VARIABLE`` option, if any.
76 The resulting file should be installed with other headers in the library.
78 The ``BASE_NAME`` argument can be used to override the file name and the
79 names used for the macros:
81 .. code-block:: cmake
83    add_library(somelib someclass.cpp)
84    generate_export_header(somelib
85      BASE_NAME other_name
86    )
89 Generates a file called ``other_name_export.h`` containing the macros
90 ``OTHER_NAME_EXPORT``, ``OTHER_NAME_NO_EXPORT`` and ``OTHER_NAME_DEPRECATED``
91 etc.
93 The ``BASE_NAME`` may be overridden by specifying other options in the
94 function.  For example:
96 .. code-block:: cmake
98    add_library(somelib someclass.cpp)
99    generate_export_header(somelib
100      EXPORT_MACRO_NAME OTHER_NAME_EXPORT
101    )
104 creates the macro ``OTHER_NAME_EXPORT`` instead of ``SOMELIB_EXPORT``, but
105 other macros and the generated file name is as default:
107 .. code-block:: cmake
109    add_library(somelib someclass.cpp)
110    generate_export_header(somelib
111      DEPRECATED_MACRO_NAME KDE_DEPRECATED
112    )
115 creates the macro ``KDE_DEPRECATED`` instead of ``SOMELIB_DEPRECATED``.
117 If ``LIBRARY_TARGET`` is a static library, macros are defined without
118 values.
120 If the same sources are used to create both a shared and a static
121 library, the uppercased symbol ``${BASE_NAME}_STATIC_DEFINE`` should be
122 used when building the static library:
124 .. code-block:: cmake
126    add_library(shared_variant SHARED ${lib_SRCS})
127    add_library(static_variant ${lib_SRCS})
128    generate_export_header(shared_variant BASE_NAME libshared_and_static)
129    set_target_properties(static_variant PROPERTIES
130      COMPILE_FLAGS -DLIBSHARED_AND_STATIC_STATIC_DEFINE)
132 This will cause the export macros to expand to nothing when building
133 the static library.
135 If ``DEFINE_NO_DEPRECATED`` is specified, then a macro
136 ``${BASE_NAME}_NO_DEPRECATED`` will be defined This macro can be used to
137 remove deprecated code from preprocessor output:
139 .. code-block:: cmake
141    option(EXCLUDE_DEPRECATED "Exclude deprecated parts of the library" FALSE)
142    if (EXCLUDE_DEPRECATED)
143      set(NO_BUILD_DEPRECATED DEFINE_NO_DEPRECATED)
144    endif()
145    generate_export_header(somelib ${NO_BUILD_DEPRECATED})
148 And then in somelib:
150 .. code-block:: c++
152    class SOMELIB_EXPORT SomeClass
153    {
154    public:
155    #ifndef SOMELIB_NO_DEPRECATED
156      SOMELIB_DEPRECATED void oldMethod();
157    #endif
158    };
160 .. code-block:: c++
162    #ifndef SOMELIB_NO_DEPRECATED
163    void SomeClass::oldMethod() {  }
164    #endif
167 If ``PREFIX_NAME`` is specified, the argument will be used as a prefix to
168 all generated macros.
170 For example:
172 .. code-block:: cmake
174    generate_export_header(somelib PREFIX_NAME VTK_)
176 Generates the macros ``VTK_SOMELIB_EXPORT`` etc.
178 .. versionadded:: 3.1
179   Library target can be an ``OBJECT`` library.
181 .. versionadded:: 3.7
182   Added the ``CUSTOM_CONTENT_FROM_VARIABLE`` option.
184 .. versionadded:: 3.11
185   Added the ``INCLUDE_GUARD_NAME`` option.
187 .. command:: add_compiler_export_flags
189   .. code-block:: cmake
191     add_compiler_export_flags([<output_variable>])
193   .. deprecated:: 3.0
195     Set the target properties
196     :prop_tgt:`CXX_VISIBILITY_PRESET <<LANG>_VISIBILITY_PRESET>` and
197     :prop_tgt:`VISIBILITY_INLINES_HIDDEN` instead.
199 The ``add_compiler_export_flags()`` function adds ``-fvisibility=hidden`` to
200 :variable:`CMAKE_CXX_FLAGS <CMAKE_<LANG>_FLAGS>` if supported, and is a no-op
201 on Windows which does not need extra compiler flags for exporting support.
202 You may optionally pass a single argument to ``add_compiler_export_flags()``
203 that will be populated with the ``CXX_FLAGS`` required to enable visibility
204 support for the compiler/architecture in use.
205 #]=======================================================================]
207 include(CheckCompilerFlag)
208 include(CheckSourceCompiles)
210 # TODO: Install this macro separately?
211 macro(_check_cxx_compiler_attribute _ATTRIBUTE _RESULT)
212   check_source_compiles(CXX "${_ATTRIBUTE} int somefunc() { return 0; }
213     int main() { return somefunc();}" ${_RESULT}
214   )
215 endmacro()
217 # TODO: Install this macro separately?
218 macro(_check_c_compiler_attribute _ATTRIBUTE _RESULT)
219   check_source_compiles(C "${_ATTRIBUTE} int somefunc(void) { return 0; }
220     int main(void) { return somefunc();}" ${_RESULT}
221   )
222 endmacro()
224 macro(_test_compiler_hidden_visibility)
226   if(CMAKE_COMPILER_IS_GNUCXX AND CMAKE_CXX_COMPILER_VERSION VERSION_LESS "4.2")
227     set(GCC_TOO_OLD TRUE)
228   elseif(CMAKE_COMPILER_IS_GNUCC AND CMAKE_C_COMPILER_VERSION VERSION_LESS "4.2")
229     set(GCC_TOO_OLD TRUE)
230   elseif(CMAKE_CXX_COMPILER_ID STREQUAL "Intel" AND CMAKE_CXX_COMPILER_VERSION VERSION_LESS "12.0")
231     set(_INTEL_TOO_OLD TRUE)
232   endif()
234   # Exclude XL here because it misinterprets -fvisibility=hidden even though
235   # the check_compiler_flag passes
236   if(NOT GCC_TOO_OLD
237       AND NOT _INTEL_TOO_OLD
238       AND NOT WIN32
239       AND NOT CYGWIN
240       AND NOT CMAKE_CXX_COMPILER_ID MATCHES "^(IBMClang|XLClang|XL)$"
241       AND NOT CMAKE_CXX_COMPILER_ID MATCHES "^(PGI|NVHPC)$"
242       AND NOT CMAKE_CXX_COMPILER_ID MATCHES Watcom)
243     if (CMAKE_CXX_COMPILER_LOADED)
244       check_compiler_flag(CXX -fvisibility=hidden COMPILER_HAS_HIDDEN_VISIBILITY)
245       check_compiler_flag(CXX -fvisibility-inlines-hidden
246         COMPILER_HAS_HIDDEN_INLINE_VISIBILITY)
247     else()
248       check_compiler_flag(C -fvisibility=hidden COMPILER_HAS_HIDDEN_VISIBILITY)
249       check_compiler_flag(C -fvisibility-inlines-hidden
250         COMPILER_HAS_HIDDEN_INLINE_VISIBILITY)
251     endif()
252   endif()
253 endmacro()
255 macro(_test_compiler_has_deprecated)
256   # NOTE:  Some Embarcadero compilers silently compile __declspec(deprecated)
257   # without error, but this is not a documented feature and the attribute does
258   # not actually generate any warnings.
259   if(CMAKE_CXX_COMPILER_ID MATCHES Borland
260       OR CMAKE_CXX_COMPILER_ID MATCHES Embarcadero
261       OR CMAKE_CXX_COMPILER_ID MATCHES HP
262       OR GCC_TOO_OLD
263       OR CMAKE_CXX_COMPILER_ID MATCHES "^(PGI|NVHPC)$"
264       OR CMAKE_CXX_COMPILER_ID MATCHES Watcom)
265     set(COMPILER_HAS_DEPRECATED "" CACHE INTERNAL
266       "Compiler support for a deprecated attribute")
267   else()
268     if (CMAKE_CXX_COMPILER_LOADED)
269       _check_cxx_compiler_attribute("__attribute__((__deprecated__))"
270         COMPILER_HAS_DEPRECATED_ATTR)
271       if(COMPILER_HAS_DEPRECATED_ATTR)
272         set(COMPILER_HAS_DEPRECATED "${COMPILER_HAS_DEPRECATED_ATTR}"
273           CACHE INTERNAL "Compiler support for a deprecated attribute")
274       else()
275         _check_cxx_compiler_attribute("__declspec(deprecated)"
276           COMPILER_HAS_DEPRECATED)
277       endif()
278     else()
279       _check_c_compiler_attribute("__attribute__((__deprecated__))"
280         COMPILER_HAS_DEPRECATED_ATTR)
281       if(COMPILER_HAS_DEPRECATED_ATTR)
282         set(COMPILER_HAS_DEPRECATED "${COMPILER_HAS_DEPRECATED_ATTR}"
283           CACHE INTERNAL "Compiler support for a deprecated attribute")
284       else()
285         _check_c_compiler_attribute("__declspec(deprecated)"
286           COMPILER_HAS_DEPRECATED)
287       endif()
289     endif()
290   endif()
291 endmacro()
293 get_filename_component(_GENERATE_EXPORT_HEADER_MODULE_DIR
294   "${CMAKE_CURRENT_LIST_FILE}" PATH)
296 macro(_DO_SET_MACRO_VALUES TARGET_LIBRARY)
297   set(DEFINE_DEPRECATED)
298   set(DEFINE_EXPORT)
299   set(DEFINE_IMPORT)
300   set(DEFINE_NO_EXPORT)
302   if (COMPILER_HAS_DEPRECATED_ATTR AND NOT WIN32)
303     set(DEFINE_DEPRECATED "__attribute__ ((__deprecated__))")
304   elseif(COMPILER_HAS_DEPRECATED)
305     set(DEFINE_DEPRECATED "__declspec(deprecated)")
306   endif()
308   get_property(type TARGET ${TARGET_LIBRARY} PROPERTY TYPE)
310   if(NOT ${type} STREQUAL "STATIC_LIBRARY")
311     if(WIN32 OR CYGWIN)
312       set(DEFINE_EXPORT "__declspec(dllexport)")
313       set(DEFINE_IMPORT "__declspec(dllimport)")
314     elseif(COMPILER_HAS_HIDDEN_VISIBILITY)
315       set(DEFINE_EXPORT "__attribute__((visibility(\"default\")))")
316       set(DEFINE_IMPORT "__attribute__((visibility(\"default\")))")
317       set(DEFINE_NO_EXPORT "__attribute__((visibility(\"hidden\")))")
318     endif()
319   endif()
320 endmacro()
322 macro(_DO_GENERATE_EXPORT_HEADER TARGET_LIBRARY)
323   # Option overrides
324   set(options DEFINE_NO_DEPRECATED)
325   set(oneValueArgs PREFIX_NAME BASE_NAME EXPORT_MACRO_NAME EXPORT_FILE_NAME
326     DEPRECATED_MACRO_NAME NO_EXPORT_MACRO_NAME STATIC_DEFINE
327     NO_DEPRECATED_MACRO_NAME CUSTOM_CONTENT_FROM_VARIABLE INCLUDE_GUARD_NAME)
328   set(multiValueArgs)
330   cmake_parse_arguments(_GEH "${options}" "${oneValueArgs}" "${multiValueArgs}"
331     ${ARGN})
333   set(BASE_NAME "${TARGET_LIBRARY}")
335   if(_GEH_BASE_NAME)
336     set(BASE_NAME ${_GEH_BASE_NAME})
337   endif()
339   string(TOUPPER ${BASE_NAME} BASE_NAME_UPPER)
340   string(TOLOWER ${BASE_NAME} BASE_NAME_LOWER)
342   # Default options
343   set(EXPORT_MACRO_NAME "${_GEH_PREFIX_NAME}${BASE_NAME_UPPER}_EXPORT")
344   set(NO_EXPORT_MACRO_NAME "${_GEH_PREFIX_NAME}${BASE_NAME_UPPER}_NO_EXPORT")
345   set(EXPORT_FILE_NAME "${CMAKE_CURRENT_BINARY_DIR}/${BASE_NAME_LOWER}_export.h")
346   set(DEPRECATED_MACRO_NAME "${_GEH_PREFIX_NAME}${BASE_NAME_UPPER}_DEPRECATED")
347   set(STATIC_DEFINE "${_GEH_PREFIX_NAME}${BASE_NAME_UPPER}_STATIC_DEFINE")
348   set(NO_DEPRECATED_MACRO_NAME
349     "${_GEH_PREFIX_NAME}${BASE_NAME_UPPER}_NO_DEPRECATED")
351   if(_GEH_UNPARSED_ARGUMENTS)
352     message(FATAL_ERROR "Unknown keywords given to generate_export_header(): \"${_GEH_UNPARSED_ARGUMENTS}\"")
353   endif()
355   if(_GEH_EXPORT_MACRO_NAME)
356     set(EXPORT_MACRO_NAME ${_GEH_PREFIX_NAME}${_GEH_EXPORT_MACRO_NAME})
357   endif()
358   string(MAKE_C_IDENTIFIER ${EXPORT_MACRO_NAME} EXPORT_MACRO_NAME)
359   if(_GEH_EXPORT_FILE_NAME)
360     if(IS_ABSOLUTE ${_GEH_EXPORT_FILE_NAME})
361       set(EXPORT_FILE_NAME ${_GEH_EXPORT_FILE_NAME})
362     else()
363       set(EXPORT_FILE_NAME "${CMAKE_CURRENT_BINARY_DIR}/${_GEH_EXPORT_FILE_NAME}")
364     endif()
365   endif()
366   if(_GEH_DEPRECATED_MACRO_NAME)
367     set(DEPRECATED_MACRO_NAME ${_GEH_PREFIX_NAME}${_GEH_DEPRECATED_MACRO_NAME})
368   endif()
369   string(MAKE_C_IDENTIFIER ${DEPRECATED_MACRO_NAME} DEPRECATED_MACRO_NAME)
370   if(_GEH_NO_EXPORT_MACRO_NAME)
371     set(NO_EXPORT_MACRO_NAME ${_GEH_PREFIX_NAME}${_GEH_NO_EXPORT_MACRO_NAME})
372   endif()
373   string(MAKE_C_IDENTIFIER ${NO_EXPORT_MACRO_NAME} NO_EXPORT_MACRO_NAME)
374   if(_GEH_STATIC_DEFINE)
375     set(STATIC_DEFINE ${_GEH_PREFIX_NAME}${_GEH_STATIC_DEFINE})
376   endif()
377   string(MAKE_C_IDENTIFIER ${STATIC_DEFINE} STATIC_DEFINE)
379   if(_GEH_DEFINE_NO_DEPRECATED)
380     set(DEFINE_NO_DEPRECATED 1)
381   else()
382     set(DEFINE_NO_DEPRECATED 0)
383   endif()
385   if(_GEH_NO_DEPRECATED_MACRO_NAME)
386     set(NO_DEPRECATED_MACRO_NAME
387       ${_GEH_PREFIX_NAME}${_GEH_NO_DEPRECATED_MACRO_NAME})
388   endif()
389   string(MAKE_C_IDENTIFIER ${NO_DEPRECATED_MACRO_NAME} NO_DEPRECATED_MACRO_NAME)
391   if(_GEH_INCLUDE_GUARD_NAME)
392     set(INCLUDE_GUARD_NAME ${_GEH_INCLUDE_GUARD_NAME})
393   else()
394     set(INCLUDE_GUARD_NAME "${EXPORT_MACRO_NAME}_H")
395   endif()
397   get_target_property(EXPORT_IMPORT_CONDITION ${TARGET_LIBRARY} DEFINE_SYMBOL)
399   if(NOT EXPORT_IMPORT_CONDITION)
400     set(EXPORT_IMPORT_CONDITION ${TARGET_LIBRARY}_EXPORTS)
401   endif()
402   string(MAKE_C_IDENTIFIER ${EXPORT_IMPORT_CONDITION} EXPORT_IMPORT_CONDITION)
404   if(_GEH_CUSTOM_CONTENT_FROM_VARIABLE)
405     if(DEFINED "${_GEH_CUSTOM_CONTENT_FROM_VARIABLE}")
406       set(CUSTOM_CONTENT "${${_GEH_CUSTOM_CONTENT_FROM_VARIABLE}}")
407     else()
408       set(CUSTOM_CONTENT "")
409     endif()
410   endif()
412   configure_file("${_GENERATE_EXPORT_HEADER_MODULE_DIR}/exportheader.cmake.in"
413     "${EXPORT_FILE_NAME}" @ONLY)
414 endmacro()
416 function(GENERATE_EXPORT_HEADER TARGET_LIBRARY)
417   get_property(type TARGET ${TARGET_LIBRARY} PROPERTY TYPE)
418   if(NOT ${type} STREQUAL "STATIC_LIBRARY"
419       AND NOT ${type} STREQUAL "SHARED_LIBRARY"
420       AND NOT ${type} STREQUAL "OBJECT_LIBRARY"
421       AND NOT ${type} STREQUAL "MODULE_LIBRARY")
422     message(WARNING "This macro can only be used with libraries")
423     return()
424   endif()
425   _test_compiler_hidden_visibility()
426   _test_compiler_has_deprecated()
427   _do_set_macro_values(${TARGET_LIBRARY})
428   _do_generate_export_header(${TARGET_LIBRARY} ${ARGN})
429 endfunction()
431 function(add_compiler_export_flags)
432   if(NOT CMAKE_MINIMUM_REQUIRED_VERSION VERSION_LESS 2.8.12)
433     message(DEPRECATION "The add_compiler_export_flags function is obsolete. Use the CXX_VISIBILITY_PRESET and VISIBILITY_INLINES_HIDDEN target properties instead.")
434   endif()
436   _test_compiler_hidden_visibility()
437   _test_compiler_has_deprecated()
439   option(USE_COMPILER_HIDDEN_VISIBILITY
440     "Use HIDDEN visibility support if available." ON)
441   mark_as_advanced(USE_COMPILER_HIDDEN_VISIBILITY)
442   if(NOT (USE_COMPILER_HIDDEN_VISIBILITY AND COMPILER_HAS_HIDDEN_VISIBILITY))
443     # Just return if there are no flags to add.
444     return()
445   endif()
447   set (EXTRA_FLAGS "-fvisibility=hidden")
449   if(COMPILER_HAS_HIDDEN_INLINE_VISIBILITY)
450     set (EXTRA_FLAGS "${EXTRA_FLAGS} -fvisibility-inlines-hidden")
451   endif()
453   # Either return the extra flags needed in the supplied argument, or to the
454   # CMAKE_CXX_FLAGS if no argument is supplied.
455   if(ARGC GREATER 0)
456     set(${ARGV0} "${EXTRA_FLAGS}" PARENT_SCOPE)
457   else()
458     string(APPEND CMAKE_CXX_FLAGS " ${EXTRA_FLAGS}")
459     set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}" PARENT_SCOPE)
460   endif()
461 endfunction()
463 # FIXME(#24994): The following module(s) are included only for compatibility
464 # with projects that accidentally relied on them with CMake 3.26 and below.
465 include(CheckCCompilerFlag)
466 include(CheckCXXCompilerFlag)