diff options
915 files changed, 14200 insertions, 3791 deletions
@@ -5,3 +5,6 @@ *.pyc Testing + +# Visual Studio work directory +.vs/ diff --git a/CMakeLists.txt b/CMakeLists.txt index 3ab679e..3ee67cb 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -573,23 +573,25 @@ macro (CMAKE_BUILD_UTILITIES) #--------------------------------------------------------------------- # Use curses? if (UNIX) - # there is a bug in the Syllable libraries which makes linking ccmake fail, Alex - if(NOT CMAKE_SYSTEM_NAME MATCHES syllable) - set(CURSES_NEED_NCURSES TRUE) - find_package(Curses QUIET) - if (CURSES_LIBRARY) - option(BUILD_CursesDialog "Build the CMake Curses Dialog ccmake" ON) - else () - message("Curses libraries were not found. Curses GUI for CMake will not be built.") - set(BUILD_CursesDialog 0) - endif () - else() - set(BUILD_CursesDialog 0) + if(NOT DEFINED BUILD_CursesDialog) + include(${CMake_SOURCE_DIR}/Source/Checks/Curses.cmake) + option(BUILD_CursesDialog "Build the CMake Curses Dialog ccmake" "${CMakeCheckCurses_COMPILED}") endif() else () set(BUILD_CursesDialog 0) endif () if(BUILD_CursesDialog) + set(CURSES_NEED_NCURSES TRUE) + find_package(Curses) + if(NOT CURSES_FOUND) + message(WARNING + "'ccmake' will not be built because Curses was not found.\n" + "Turn off BUILD_CursesDialog to suppress this message." + ) + set(BUILD_CursesDialog 0) + endif() + endif() + if(BUILD_CursesDialog) if(NOT CMAKE_USE_SYSTEM_FORM) add_subdirectory(Source/CursesDialog/form) elseif(NOT CURSES_FORM_LIBRARY) diff --git a/CONTRIBUTING.rst b/CONTRIBUTING.rst index 381769d..01987be 100644 --- a/CONTRIBUTING.rst +++ b/CONTRIBUTING.rst @@ -29,11 +29,14 @@ To contribute patches: #. Base all new work on the upstream ``master`` branch. Base work on the upstream ``release`` branch only if it fixes a regression or bug in a feature new to that release. + If in doubt, prefer ``master``. Reviewers may simply ask for + a rebase if deemed appropriate in particular cases. #. Create commits making incremental, distinct, logically complete changes with appropriate `commit messages`_. #. Push a topic branch to a personal repository fork on GitLab. #. Create a GitLab Merge Request targeting the upstream ``master`` branch (even if the change is intended for merge to the ``release`` branch). + Check the box to allow edits from maintainers. The merge request will enter the `CMake Review Process`_ for consideration. diff --git a/CompileFlags.cmake b/CompileFlags.cmake index 32e7005..ec9b31b 100644 --- a/CompileFlags.cmake +++ b/CompileFlags.cmake @@ -82,3 +82,26 @@ endif () if (CMAKE_ANSI_CFLAGS) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${CMAKE_ANSI_CFLAGS}") endif () + +# Allow per-translation-unit parallel builds when using MSVC +if(CMAKE_GENERATOR MATCHES "Visual Studio" AND + (CMAKE_C_COMPILER_ID MATCHES "MSVC|Intel" OR + CMAKE_CXX_COMPILER_ID MATCHES "MSVC|Intel")) + + set(CMake_MSVC_PARALLEL ON CACHE STRING "\ +Enables /MP flag for parallel builds using MSVC. Specify an \ +integer value to control the number of threads used (Only \ +works on some older versions of Visual Studio). Setting to \ +ON lets the toolchain decide how many threads to use. Set to \ +OFF to disable /MP completely." ) + + if(CMake_MSVC_PARALLEL) + if(CMake_MSVC_PARALLEL GREATER 0) + string(APPEND CMAKE_C_FLAGS " /MP${CMake_MSVC_PARALLEL}") + string(APPEND CMAKE_CXX_FLAGS " /MP${CMake_MSVC_PARALLEL}") + else() + string(APPEND CMAKE_C_FLAGS " /MP") + string(APPEND CMAKE_CXX_FLAGS " /MP") + endif() + endif() +endif() diff --git a/Help/command/COMPILE_OPTIONS_SHELL.txt b/Help/command/COMPILE_OPTIONS_SHELL.txt new file mode 100644 index 0000000..a1316c8 --- /dev/null +++ b/Help/command/COMPILE_OPTIONS_SHELL.txt @@ -0,0 +1,9 @@ +The final set of compile options used for a target is constructed by +accumulating options from the current target and the usage requirements of +it dependencies. The set of options is de-duplicated to avoid repetition. +While beneficial for individual options, the de-duplication step can break +up option groups. For example, ``-D A -D B`` becomes ``-D A B``. One may +specify a group of options using shell-like quoting along with a ``SHELL:`` +prefix. The ``SHELL:`` prefix is dropped and the rest of the option string +is parsed using the :command:`separate_arguments` ``UNIX_COMMAND`` mode. +For example, ``"SHELL:-D A" "SHELL:-D B"`` becomes ``-D A -D B``. diff --git a/Help/command/FIND_XXX.txt b/Help/command/FIND_XXX.txt index 7db221c..8f34b75 100644 --- a/Help/command/FIND_XXX.txt +++ b/Help/command/FIND_XXX.txt @@ -16,6 +16,7 @@ The general signature is: [PATH_SUFFIXES suffix1 [suffix2 ...]] [DOC "cache documentation string"] [NO_DEFAULT_PATH] + [NO_PACKAGE_ROOT_PATH] [NO_CMAKE_PATH] [NO_CMAKE_ENVIRONMENT_PATH] [NO_SYSTEM_ENVIRONMENT_PATH] @@ -60,6 +61,10 @@ If ``NO_DEFAULT_PATH`` is specified, then no additional paths are added to the search. If ``NO_DEFAULT_PATH`` is not specified, the search process is as follows: +.. |FIND_PACKAGE_ROOT_PREFIX_PATH_XXX_SUBDIR| replace:: + |prefix_XXX_SUBDIR| for each ``<prefix>`` in ``PackageName_ROOT`` if called + from within a find module + .. |CMAKE_PREFIX_PATH_XXX_SUBDIR| replace:: |prefix_XXX_SUBDIR| for each ``<prefix>`` in :variable:`CMAKE_PREFIX_PATH` @@ -71,7 +76,19 @@ If ``NO_DEFAULT_PATH`` is not specified, the search process is as follows: |prefix_XXX_SUBDIR| for each ``<prefix>`` in :variable:`CMAKE_SYSTEM_PREFIX_PATH` -1. Search paths specified in cmake-specific cache variables. +1. If called from within a find module, search prefix paths unique to the + current package being found. Specifically look in the ``PackageName_ROOT`` + CMake and environment variables. The package root variables are maintained + as a stack so if called from nested find modules, root paths from the + parent's find module will be searched after paths from the current module, + i.e. ``CurrentPackage_ROOT``, ``ENV{CurrentPackage_ROOT}``, + ``ParentPackage_ROOT``, ``ENV{ParentPacakge_ROOT}``, etc. + This can be skipped if ``NO_PACKAGE_ROOT_PATH`` is passed. + See policy :policy:`CMP0074`. + + * |FIND_PACKAGE_ROOT_PREFIX_PATH_XXX| + +2. Search paths specified in cmake-specific cache variables. These are intended to be used on the command line with a ``-DVAR=value``. The values are interpreted as :ref:`;-lists <CMake Language Lists>`. This can be skipped if ``NO_CMAKE_PATH`` is passed. @@ -80,7 +97,7 @@ If ``NO_DEFAULT_PATH`` is not specified, the search process is as follows: * |CMAKE_XXX_PATH| * |CMAKE_XXX_MAC_PATH| -2. Search paths specified in cmake-specific environment variables. +3. Search paths specified in cmake-specific environment variables. These are intended to be set in the user's shell configuration, and therefore use the host's native path separator (``;`` on Windows and ``:`` on UNIX). @@ -90,17 +107,17 @@ If ``NO_DEFAULT_PATH`` is not specified, the search process is as follows: * |CMAKE_XXX_PATH| * |CMAKE_XXX_MAC_PATH| -3. Search the paths specified by the ``HINTS`` option. +4. Search the paths specified by the ``HINTS`` option. These should be paths computed by system introspection, such as a hint provided by the location of another item already found. Hard-coded guesses should be specified with the ``PATHS`` option. -4. Search the standard system environment variables. +5. Search the standard system environment variables. This can be skipped if ``NO_SYSTEM_ENVIRONMENT_PATH`` is an argument. * |SYSTEM_ENVIRONMENT_PATH_XXX| -5. Search cmake variables defined in the Platform files +6. Search cmake variables defined in the Platform files for the current system. This can be skipped if ``NO_CMAKE_SYSTEM_PATH`` is passed. @@ -108,7 +125,7 @@ If ``NO_DEFAULT_PATH`` is not specified, the search process is as follows: * |CMAKE_SYSTEM_XXX_PATH| * |CMAKE_SYSTEM_XXX_MAC_PATH| -6. Search the paths specified by the PATHS option +7. Search the paths specified by the PATHS option or in the short-hand version of the command. These are typically hard-coded guesses. diff --git a/Help/command/add_compile_definitions.rst b/Help/command/add_compile_definitions.rst new file mode 100644 index 0000000..37f6650 --- /dev/null +++ b/Help/command/add_compile_definitions.rst @@ -0,0 +1,23 @@ +add_compile_definitions +----------------------- + +Adds preprocessor definitions to the compilation of source files. + +:: + + add_compile_definitions(<definition> ...) + +Adds preprocessor definitions to the compiler command line for targets in the +current directory and below that are added after this command is invoked. +See documentation of the :prop_dir:`directory <COMPILE_DEFINITIONS>` and +:prop_tgt:`target <COMPILE_DEFINITIONS>` ``COMPILE_DEFINITIONS`` properties. + +Definitions are specified using the syntax ``VAR`` or ``VAR=value``. +Function-style definitions are not supported. CMake will automatically +escape the value correctly for the native build system (note that CMake +language syntax may require escapes to specify some values). + +Arguments to ``add_compile_definitions`` may use "generator expressions" with +the syntax ``$<...>``. See the :manual:`cmake-generator-expressions(7)` +manual for available expressions. See the :manual:`cmake-buildsystem(7)` +manual for more on defining buildsystem properties. diff --git a/Help/command/add_compile_options.rst b/Help/command/add_compile_options.rst index 3fe2a33..c445608 100644 --- a/Help/command/add_compile_options.rst +++ b/Help/command/add_compile_options.rst @@ -14,10 +14,12 @@ See documentation of the :prop_dir:`directory <COMPILE_OPTIONS>` and This command can be used to add any options, but alternative commands exist to add preprocessor definitions (:command:`target_compile_definitions` -and :command:`add_definitions`) or include directories +and :command:`add_compile_definitions`) or include directories (:command:`target_include_directories` and :command:`include_directories`). Arguments to ``add_compile_options`` may use "generator expressions" with the syntax ``$<...>``. See the :manual:`cmake-generator-expressions(7)` manual for available expressions. See the :manual:`cmake-buildsystem(7)` manual for more on defining buildsystem properties. + +.. include:: COMPILE_OPTIONS_SHELL.txt diff --git a/Help/command/add_custom_command.rst b/Help/command/add_custom_command.rst index d4f644a..e3fb6b6 100644 --- a/Help/command/add_custom_command.rst +++ b/Help/command/add_custom_command.rst @@ -217,7 +217,7 @@ of the following is specified: ``PRE_BUILD`` Run before any other rules are executed within the target. - This is supported only on Visual Studio 8 or later. + This is supported only on Visual Studio 9 or later. For all other generators ``PRE_BUILD`` will be treated as ``PRE_LINK``. ``PRE_LINK`` diff --git a/Help/command/add_definitions.rst b/Help/command/add_definitions.rst index a04faf5..1da15a6 100644 --- a/Help/command/add_definitions.rst +++ b/Help/command/add_definitions.rst @@ -10,8 +10,16 @@ Adds -D define flags to the compilation of source files. Adds definitions to the compiler command line for targets in the current directory and below (whether added before or after this command is invoked). This command can be used to add any flags, but it is intended to add -preprocessor definitions (see the :command:`add_compile_options` command -to add other flags). +preprocessor definitions. + +.. note:: + + This command has been superseded by alternatives: + + * Use :command:`add_compile_definitions` to add preprocessor definitions. + * Use :command:`include_directories` to add include directories. + * Use :command:`add_compile_options` to add other options. + Flags beginning in -D or /D that look like preprocessor definitions are automatically added to the :prop_dir:`COMPILE_DEFINITIONS` directory property for the current directory. Definitions with non-trivial values diff --git a/Help/command/add_library.rst b/Help/command/add_library.rst index 3706153..8fa0df7 100644 --- a/Help/command/add_library.rst +++ b/Help/command/add_library.rst @@ -110,10 +110,10 @@ along with those compiled from their own sources. Object libraries may contain only sources that compile, header files, and other files that would not affect linking of a normal library (e.g. ``.txt``). They may contain custom commands generating such sources, but not -``PRE_BUILD``, ``PRE_LINK``, or ``POST_BUILD`` commands. Object libraries -cannot be linked. Some native build systems (such as Xcode) may not like -targets that have only object files, so consider adding at least one real -source file to any target that references ``$<TARGET_OBJECTS:objlib>``. +``PRE_BUILD``, ``PRE_LINK``, or ``POST_BUILD`` commands. Some native build +systems (such as Xcode) may not like targets that have only object files, so +consider adding at least one real source file to any target that references +``$<TARGET_OBJECTS:objlib>``. Alias Libraries ^^^^^^^^^^^^^^^ diff --git a/Help/command/cmake_host_system_information.rst b/Help/command/cmake_host_system_information.rst index 7199874..9893151 100644 --- a/Help/command/cmake_host_system_information.rst +++ b/Help/command/cmake_host_system_information.rst @@ -27,13 +27,13 @@ Key Description ``IS_64BIT`` One if processor is 64Bit ``HAS_FPU`` One if processor has floating point unit ``HAS_MMX`` One if processor supports MMX instructions -``HAS_MMX_PLUS`` One if porcessor supports Ext. MMX instructions -``HAS_SSE`` One if porcessor supports SSE instructions -``HAS_SSE2`` One if porcessor supports SSE2 instructions -``HAS_SSE_FP`` One if porcessor supports SSE FP instructions -``HAS_SSE_MMX`` One if porcessor supports SSE MMX instructions -``HAS_AMD_3DNOW`` One if porcessor supports 3DNow instructions -``HAS_AMD_3DNOW_PLUS`` One if porcessor supports 3DNow+ instructions +``HAS_MMX_PLUS`` One if processor supports Ext. MMX instructions +``HAS_SSE`` One if processor supports SSE instructions +``HAS_SSE2`` One if processor supports SSE2 instructions +``HAS_SSE_FP`` One if processor supports SSE FP instructions +``HAS_SSE_MMX`` One if processor supports SSE MMX instructions +``HAS_AMD_3DNOW`` One if processor supports 3DNow instructions +``HAS_AMD_3DNOW_PLUS`` One if processor supports 3DNow+ instructions ``HAS_IA64`` One if IA64 processor emulating x86 ``HAS_SERIAL_NUMBER`` One if processor has serial number ``PROCESSOR_SERIAL_NUMBER`` Processor serial number diff --git a/Help/command/cmake_minimum_required.rst b/Help/command/cmake_minimum_required.rst index 9535bf3..7c02190 100644 --- a/Help/command/cmake_minimum_required.rst +++ b/Help/command/cmake_minimum_required.rst @@ -4,11 +4,15 @@ cmake_minimum_required Set the minimum required version of cmake for a project and update `Policy Settings`_ to match the version given:: - cmake_minimum_required(VERSION major.minor[.patch[.tweak]] - [FATAL_ERROR]) + cmake_minimum_required(VERSION <min>[...<max>] [FATAL_ERROR]) -If the current version of CMake is lower than that required it will -stop processing the project and report an error. +``<min>`` and the optional ``<max>`` are each CMake versions of the form +``major.minor[.patch[.tweak]]``, and the ``...`` is literal. + +If the running version of CMake is lower than the ``<min>`` required +version it will stop processing the project and report an error. +The optional ``<max>`` version, if specified, must be at least the +``<min>`` version and affects policy settings as described below. The ``FATAL_ERROR`` option is accepted but ignored by CMake 2.6 and higher. It should be specified so CMake versions 2.4 and lower fail @@ -30,21 +34,23 @@ Policy Settings The ``cmake_minimum_required(VERSION)`` command implicitly invokes the :command:`cmake_policy(VERSION)` command to specify that the current -project code is written for the given version of CMake. -All policies introduced in the specified version or earlier will be -set to use NEW behavior. All policies introduced after the specified -version will be unset. This effectively requests behavior preferred +project code is written for the given range of CMake versions. +All policies known to the running version of CMake and introduced +in the ``<min>`` (or ``<max>``, if specified) version or earlier will +be set to use ``NEW`` behavior. All policies introduced in later +versions will be unset. This effectively requests behavior preferred as of a given CMake version and tells newer CMake versions to warn about their new policies. -When a version higher than 2.4 is specified the command implicitly -invokes:: +When a ``<min>`` version higher than 2.4 is specified the command +implicitly invokes:: - cmake_policy(VERSION major[.minor[.patch[.tweak]]]) + cmake_policy(VERSION <min>[...<max>]) -which sets the cmake policy version level to the version specified. -When version 2.4 or lower is given the command implicitly invokes:: +which sets CMake policies based on the range of versions specified. +When a ``<min>`` version 2.4 or lower is given the command implicitly +invokes:: - cmake_policy(VERSION 2.4) + cmake_policy(VERSION 2.4[...<max>]) which enables compatibility features for CMake 2.4 and lower. diff --git a/Help/command/cmake_policy.rst b/Help/command/cmake_policy.rst index b51b951..6a8dd62 100644 --- a/Help/command/cmake_policy.rst +++ b/Help/command/cmake_policy.rst @@ -24,17 +24,22 @@ The ``cmake_policy`` command is used to set policies to ``OLD`` or ``NEW`` behavior. While setting policies individually is supported, we encourage projects to set policies based on CMake versions:: - cmake_policy(VERSION major.minor[.patch[.tweak]]) - -Specify that the current CMake code is written for the given -version of CMake. All policies introduced in the specified version or -earlier will be set to use ``NEW`` behavior. All policies introduced -after the specified version will be unset (unless the + cmake_policy(VERSION <min>[...<max>]) + +``<min>`` and the optional ``<max>`` are each CMake versions of the form +``major.minor[.patch[.tweak]]``, and the ``...`` is literal. The ``<min>`` +version must be at least ``2.4`` and at most the running version of CMake. +The ``<max>`` version, if specified, must be at least the ``<min>`` version +but may exceed the running version of CMake. + +This specifies that the current CMake code is written for the given +range of CMake versions. All policies known to the running version of CMake +and introduced in the ``<min>`` (or ``<max>``, if specified) version +or earlier will be set to use ``NEW`` behavior. All policies +introduced in later versions will be unset (unless the :variable:`CMAKE_POLICY_DEFAULT_CMP<NNNN>` variable sets a default). This effectively requests behavior preferred as of a given CMake version and tells newer CMake versions to warn about their new policies. -The policy version specified must be at least 2.4 or the command will -report an error. Note that the :command:`cmake_minimum_required(VERSION)` command implicitly calls ``cmake_policy(VERSION)`` too. diff --git a/Help/command/ctest_submit.rst b/Help/command/ctest_submit.rst index 6b49da3..cc9612b 100644 --- a/Help/command/ctest_submit.rst +++ b/Help/command/ctest_submit.rst @@ -68,7 +68,7 @@ Submit to CDash Upload API [QUIET]) This second signature is used to upload files to CDash via the CDash -file upload API. The api first sends a request to upload to CDash along +file upload API. The API first sends a request to upload to CDash along with a content hash of the file. If CDash does not already have the file, then it is uploaded. Along with the file, a CDash type string is specified to tell CDash which handler to use to process the data. diff --git a/Help/command/define_property.rst b/Help/command/define_property.rst index 873c6ca..da2631c 100644 --- a/Help/command/define_property.rst +++ b/Help/command/define_property.rst @@ -34,10 +34,24 @@ actual scope needs to be given; only the kind of scope is important. The required ``PROPERTY`` option is immediately followed by the name of the property being defined. -If the ``INHERITED`` option then the :command:`get_property` command will -chain up to the next higher scope when the requested property is not set -in the scope given to the command. ``DIRECTORY`` scope chains to -``GLOBAL``. ``TARGET``, ``SOURCE``, and ``TEST`` chain to ``DIRECTORY``. +If the ``INHERITED`` option is given, then the :command:`get_property` command +will chain up to the next higher scope when the requested property is not set +in the scope given to the command. + +* ``DIRECTORY`` scope chains to its parent directory's scope, continuing the + walk up parent directories until a directory has the property set or there + are no more parents. If still not found at the top level directory, it + chains to the ``GLOBAL`` scope. +* ``TARGET``, ``SOURCE`` and ``TEST`` properties chain to ``DIRECTORY`` scope, + including further chaining up the directories, etc. as needed. + +Note that this scope chaining behavior only applies to calls to +:command:`get_property`, :command:`get_directory_property`, +:command:`get_target_property`, :command:`get_source_file_property` and +:command:`get_test_property`. There is no inheriting behavior when *setting* +properties, so using ``APPEND`` or ``APPEND_STRING`` with the +:command:`set_property` command will not consider inherited values when working +out the contents to append to. The ``BRIEF_DOCS`` and ``FULL_DOCS`` options are followed by strings to be associated with the property as its brief and full documentation. diff --git a/Help/command/export.rst b/Help/command/export.rst index 53675a7..0c676c6 100644 --- a/Help/command/export.rst +++ b/Help/command/export.rst @@ -40,6 +40,15 @@ policy CMP0022 is NEW. If a library target is included in the export but a target to which it links is not included the behavior is unspecified. +.. note:: + + :ref:`Object Libraries` under :generator:`Xcode` have special handling if + multiple architectures are listed in :variable:`CMAKE_OSX_ARCHITECTURES`. + In this case they will be exported as :ref:`Interface Libraries` with + no object files available to clients. This is sufficient to satisfy + transitive usage requirements of other targets that link to the + object libraries in their implementation. + :: export(PACKAGE <name>) diff --git a/Help/command/file.rst b/Help/command/file.rst index 5ce86e5..43ce3d9 100644 --- a/Help/command/file.rst +++ b/Help/command/file.rst @@ -98,10 +98,10 @@ command. :: file(GLOB <variable> - [LIST_DIRECTORIES true|false] [RELATIVE <path>] + [LIST_DIRECTORIES true|false] [RELATIVE <path>] [CONFIGURE_DEPENDS] [<globbing-expressions>...]) file(GLOB_RECURSE <variable> [FOLLOW_SYMLINKS] - [LIST_DIRECTORIES true|false] [RELATIVE <path>] + [LIST_DIRECTORIES true|false] [RELATIVE <path>] [CONFIGURE_DEPENDS] [<globbing-expressions>...]) Generate a list of files that match the ``<globbing-expressions>`` and @@ -110,6 +110,11 @@ regular expressions, but much simpler. If ``RELATIVE`` flag is specified, the results will be returned as relative paths to the given path. The results will be ordered lexicographically. +If the ``CONFIGURE_DEPENDS`` flag is specified, CMake will add logic +to the main build system check target to rerun the flagged ``GLOB`` commands +at build time. If any of the outputs change, CMake will regenerate the build +system. + By default ``GLOB`` lists directories - directories are omitted in result if ``LIST_DIRECTORIES`` is set to false. @@ -118,6 +123,10 @@ By default ``GLOB`` lists directories - directories are omitted in result if your source tree. If no CMakeLists.txt file changes when a source is added or removed then the generated build system cannot know when to ask CMake to regenerate. + The ``CONFIGURE_DEPENDS`` flag may not work reliably on all generators, or if + a new generator is added in the future that cannot support it, projects using + it will be stuck. Even if ``CONFIGURE_DEPENDS`` works reliably, there is + still a cost to perform the check on every rebuild. Examples of globbing expressions include:: @@ -285,6 +294,23 @@ If neither ``TLS`` option is given CMake will check variables :: + file(TOUCH [<files>...]) + file(TOUCH_NOCREATE [<files>...]) + +Create a file with no content if it does not yet exist. If the file already +exists, its access and/or modification will be updated to the time when the +function call is executed. + +Use TOUCH_NOCREATE to touch a file if it exists but not create it. If a file +does not exist it will be silently ignored. + +With TOUCH and TOUCH_NOCREATE the contents of an existing file will not be +modified. + +------------------------------------------------------------------------------ + +:: + file(TIMESTAMP <filename> <variable> [<format>] [UTC]) Compute a string representation of the modification time of ``<filename>`` diff --git a/Help/command/find_file.rst b/Help/command/find_file.rst index e56097b..2a14ad7 100644 --- a/Help/command/find_file.rst +++ b/Help/command/find_file.rst @@ -8,6 +8,9 @@ find_file .. |prefix_XXX_SUBDIR| replace:: ``<prefix>/include`` .. |entry_XXX_SUBDIR| replace:: ``<entry>/include`` +.. |FIND_PACKAGE_ROOT_PREFIX_PATH_XXX| replace:: + ``<prefix>/include/<arch>`` if :variable:`CMAKE_LIBRARY_ARCHITECTURE` + is set, and |FIND_PACKAGE_ROOT_PREFIX_PATH_XXX_SUBDIR| .. |CMAKE_PREFIX_PATH_XXX| replace:: ``<prefix>/include/<arch>`` if :variable:`CMAKE_LIBRARY_ARCHITECTURE` is set, and |CMAKE_PREFIX_PATH_XXX_SUBDIR| diff --git a/Help/command/find_library.rst b/Help/command/find_library.rst index f774f17..0861d67 100644 --- a/Help/command/find_library.rst +++ b/Help/command/find_library.rst @@ -8,6 +8,9 @@ find_library .. |prefix_XXX_SUBDIR| replace:: ``<prefix>/lib`` .. |entry_XXX_SUBDIR| replace:: ``<entry>/lib`` +.. |FIND_PACKAGE_ROOT_PREFIX_PATH_XXX| replace:: + ``<prefix>/lib/<arch>`` if :variable:`CMAKE_LIBRARY_ARCHITECTURE` is set, + and |FIND_PACKAGE_ROOT_PREFIX_PATH_XXX_SUBDIR| .. |CMAKE_PREFIX_PATH_XXX| replace:: ``<prefix>/lib/<arch>`` if :variable:`CMAKE_LIBRARY_ARCHITECTURE` is set, and |CMAKE_PREFIX_PATH_XXX_SUBDIR| diff --git a/Help/command/find_package.rst b/Help/command/find_package.rst index b2e70f2..53f3819 100644 --- a/Help/command/find_package.rst +++ b/Help/command/find_package.rst @@ -64,6 +64,7 @@ The complete Config mode command signature is:: [PATHS path1 [path2 ... ]] [PATH_SUFFIXES suffix1 [suffix2 ...]] [NO_DEFAULT_PATH] + [NO_PACKAGE_ROOT_PATH] [NO_CMAKE_PATH] [NO_CMAKE_ENVIRONMENT_PATH] [NO_SYSTEM_ENVIRONMENT_PATH] @@ -208,12 +209,12 @@ Each entry is meant for installation trees following Windows (W), UNIX <prefix>/(cmake|CMake)/ (W) <prefix>/<name>*/ (W) <prefix>/<name>*/(cmake|CMake)/ (W) - <prefix>/(lib/<arch>|lib|share)/cmake/<name>*/ (U) - <prefix>/(lib/<arch>|lib|share)/<name>*/ (U) - <prefix>/(lib/<arch>|lib|share)/<name>*/(cmake|CMake)/ (U) - <prefix>/<name>*/(lib/<arch>|lib|share)/cmake/<name>*/ (W/U) - <prefix>/<name>*/(lib/<arch>|lib|share)/<name>*/ (W/U) - <prefix>/<name>*/(lib/<arch>|lib|share)/<name>*/(cmake|CMake)/ (W/U) + <prefix>/(lib/<arch>|lib*|share)/cmake/<name>*/ (U) + <prefix>/(lib/<arch>|lib*|share)/<name>*/ (U) + <prefix>/(lib/<arch>|lib*|share)/<name>*/(cmake|CMake)/ (U) + <prefix>/<name>*/(lib/<arch>|lib*|share)/cmake/<name>*/ (W/U) + <prefix>/<name>*/(lib/<arch>|lib*|share)/<name>*/ (W/U) + <prefix>/<name>*/(lib/<arch>|lib*|share)/<name>*/(cmake|CMake)/ (W/U) On systems supporting OS X Frameworks and Application Bundles the following directories are searched for frameworks or bundles @@ -228,10 +229,22 @@ containing a configuration file:: In all cases the ``<name>`` is treated as case-insensitive and corresponds to any of the names specified (``<package>`` or names given by ``NAMES``). + Paths with ``lib/<arch>`` are enabled if the -:variable:`CMAKE_LIBRARY_ARCHITECTURE` variable is set. If ``PATH_SUFFIXES`` -is specified the suffixes are appended to each (W) or (U) directory entry -one-by-one. +:variable:`CMAKE_LIBRARY_ARCHITECTURE` variable is set. ``lib*`` includes one +or more of the values ``lib64``, ``lib32``, ``libx32`` or ``lib`` (searched in +that order). + +* Paths with ``lib64`` are searched on 64 bit platforms if the + :prop_gbl:`FIND_LIBRARY_USE_LIB64_PATHS` property is set to ``TRUE``. +* Paths with ``lib32`` are searched on 32 bit platforms if the + :prop_gbl:`FIND_LIBRARY_USE_LIB32_PATHS` property is set to ``TRUE``. +* Paths with ``libx32`` are searched on platforms using the x32 ABI + if the :prop_gbl:`FIND_LIBRARY_USE_LIBX32_PATHS` property is set to ``TRUE``. +* The ``lib`` path is always searched. + +If ``PATH_SUFFIXES`` is specified, the suffixes are appended to each +(W) or (U) directory entry one-by-one. This set of directories is intended to work in cooperation with projects that provide configuration files in their installation trees. @@ -249,7 +262,14 @@ The set of installation prefixes is constructed using the following steps. If ``NO_DEFAULT_PATH`` is specified all ``NO_*`` options are enabled. -1. Search paths specified in cmake-specific cache variables. These +1. Search paths specified in the ``PackageName_ROOT`` CMake and environment + variables. The package root variables are maintained as a stack so if + called from within a find module, root paths from the parent's find + module will also be searched after paths for the current package. + This can be skipped if ``NO_PACKAGE_ROOT_PATH`` is passed. + See policy :policy:`CMP0074`. + +2. Search paths specified in cmake-specific cache variables. These are intended to be used on the command line with a ``-DVAR=value``. The values are interpreted as :ref:`;-lists <CMake Language Lists>`. This can be skipped if ``NO_CMAKE_PATH`` is passed:: @@ -258,7 +278,7 @@ enabled. CMAKE_FRAMEWORK_PATH CMAKE_APPBUNDLE_PATH -2. Search paths specified in cmake-specific environment variables. +3. Search paths specified in cmake-specific environment variables. These are intended to be set in the user's shell configuration, and therefore use the host's native path separator (``;`` on Windows and ``:`` on UNIX). @@ -269,26 +289,26 @@ enabled. CMAKE_FRAMEWORK_PATH CMAKE_APPBUNDLE_PATH -3. Search paths specified by the ``HINTS`` option. These should be paths +4. Search paths specified by the ``HINTS`` option. These should be paths computed by system introspection, such as a hint provided by the location of another item already found. Hard-coded guesses should be specified with the ``PATHS`` option. -4. Search the standard system environment variables. This can be +5. Search the standard system environment variables. This can be skipped if ``NO_SYSTEM_ENVIRONMENT_PATH`` is passed. Path entries ending in ``/bin`` or ``/sbin`` are automatically converted to their parent directories:: PATH -5. Search paths stored in the CMake :ref:`User Package Registry`. +6. Search paths stored in the CMake :ref:`User Package Registry`. This can be skipped if ``NO_CMAKE_PACKAGE_REGISTRY`` is passed or by setting the :variable:`CMAKE_FIND_PACKAGE_NO_PACKAGE_REGISTRY` to ``TRUE``. See the :manual:`cmake-packages(7)` manual for details on the user package registry. -6. Search cmake variables defined in the Platform files for the +7. Search cmake variables defined in the Platform files for the current system. This can be skipped if ``NO_CMAKE_SYSTEM_PATH`` is passed:: @@ -296,14 +316,14 @@ enabled. CMAKE_SYSTEM_FRAMEWORK_PATH CMAKE_SYSTEM_APPBUNDLE_PATH -7. Search paths stored in the CMake :ref:`System Package Registry`. +8. Search paths stored in the CMake :ref:`System Package Registry`. This can be skipped if ``NO_CMAKE_SYSTEM_PACKAGE_REGISTRY`` is passed or by setting the :variable:`CMAKE_FIND_PACKAGE_NO_SYSTEM_PACKAGE_REGISTRY` to ``TRUE``. See the :manual:`cmake-packages(7)` manual for details on the system package registry. -8. Search paths specified by the ``PATHS`` option. These are typically +9. Search paths specified by the ``PATHS`` option. These are typically hard-coded guesses. .. |FIND_XXX| replace:: find_package diff --git a/Help/command/find_path.rst b/Help/command/find_path.rst index 76342d0..988a3fa 100644 --- a/Help/command/find_path.rst +++ b/Help/command/find_path.rst @@ -8,6 +8,9 @@ find_path .. |prefix_XXX_SUBDIR| replace:: ``<prefix>/include`` .. |entry_XXX_SUBDIR| replace:: ``<entry>/include`` +.. |FIND_PACKAGE_ROOT_PREFIX_PATH_XXX| replace:: + ``<prefix>/include/<arch>`` if :variable:`CMAKE_LIBRARY_ARCHITECTURE` + is set, and |FIND_PACKAGE_ROOT_PREFIX_PATH_XXX_SUBDIR| .. |CMAKE_PREFIX_PATH_XXX| replace:: ``<prefix>/include/<arch>`` if :variable:`CMAKE_LIBRARY_ARCHITECTURE` is set, and |CMAKE_PREFIX_PATH_XXX_SUBDIR| diff --git a/Help/command/find_program.rst b/Help/command/find_program.rst index d3430c0..4f00773 100644 --- a/Help/command/find_program.rst +++ b/Help/command/find_program.rst @@ -8,6 +8,8 @@ find_program .. |prefix_XXX_SUBDIR| replace:: ``<prefix>/[s]bin`` .. |entry_XXX_SUBDIR| replace:: ``<entry>/[s]bin`` +.. |FIND_PACKAGE_ROOT_PREFIX_PATH_XXX| replace:: + |FIND_PACKAGE_ROOT_PREFIX_PATH_XXX_SUBDIR| .. |CMAKE_PREFIX_PATH_XXX| replace:: |CMAKE_PREFIX_PATH_XXX_SUBDIR| .. |CMAKE_XXX_PATH| replace:: :variable:`CMAKE_PROGRAM_PATH` diff --git a/Help/command/get_directory_property.rst b/Help/command/get_directory_property.rst index e50abe0..bf8349c 100644 --- a/Help/command/get_directory_property.rst +++ b/Help/command/get_directory_property.rst @@ -7,11 +7,16 @@ Get a property of ``DIRECTORY`` scope. get_directory_property(<variable> [DIRECTORY <dir>] <prop-name>) -Store a property of directory scope in the named variable. If the -property is not defined the empty-string is returned. The ``DIRECTORY`` -argument specifies another directory from which to retrieve the -property value. The specified directory must have already been -traversed by CMake. +Store a property of directory scope in the named ``<variable>``. +The ``DIRECTORY`` argument specifies another directory from which +to retrieve the property value instead of the current directory. +The specified directory must have already been traversed by CMake. + +If the property is not defined for the nominated directory scope, +an empty string is returned. In the case of ``INHERITED`` properties, +if the property is not found for the nominated directory scope, +the search will chain to a parent scope as described for the +:command:`define_property` command. :: diff --git a/Help/command/get_filename_component.rst b/Help/command/get_filename_component.rst index 14c8cf2..f11c0fc 100644 --- a/Help/command/get_filename_component.rst +++ b/Help/command/get_filename_component.rst @@ -45,7 +45,7 @@ to the given base directory ``<BASE_DIR>``. If no base directory is provided, the default base directory will be :variable:`CMAKE_CURRENT_SOURCE_DIR`. -Paths are returned with forward slashes and have no trailing slahes. If the +Paths are returned with forward slashes and have no trailing slashes. If the optional ``CACHE`` argument is specified, the result variable is added to the cache. diff --git a/Help/command/get_property.rst b/Help/command/get_property.rst index 632ece6..8b85f7d 100644 --- a/Help/command/get_property.rst +++ b/Help/command/get_property.rst @@ -50,7 +50,10 @@ be one of the following: The required ``PROPERTY`` option is immediately followed by the name of the property to get. If the property is not set an empty value is -returned. If the ``SET`` option is given the variable is set to a boolean +returned, although some properties support inheriting from a parent scope +if defined to behave that way (see :command:`define_property`). + +If the ``SET`` option is given the variable is set to a boolean value indicating whether the property has been set. If the ``DEFINED`` option is given the variable is set to a boolean value indicating whether the property has been defined such as with the diff --git a/Help/command/get_source_file_property.rst b/Help/command/get_source_file_property.rst index 3e975c2..51fbd33 100644 --- a/Help/command/get_source_file_property.rst +++ b/Help/command/get_source_file_property.rst @@ -8,9 +8,15 @@ Get a property for a source file. get_source_file_property(VAR file property) Get a property from a source file. The value of the property is -stored in the variable ``VAR``. If the property is not found, ``VAR`` -will be set to "NOTFOUND". Use :command:`set_source_files_properties` -to set property values. Source file properties usually control how the -file is built. One property that is always there is :prop_sf:`LOCATION` +stored in the variable ``VAR``. If the source property is not found, the +behavior depends on whether it has been defined to be an ``INHERITED`` property +or not (see :command:`define_property`). Non-inherited properties will set +``VAR`` to "NOTFOUND", whereas inherited properties will search the relevant +parent scope as described for the :command:`define_property` command and +if still unable to find the property, ``VAR`` will be set to an empty string. + +Use :command:`set_source_files_properties` to set property values. Source +file properties usually control how the file is built. One property that is +always there is :prop_sf:`LOCATION`. See also the more general :command:`get_property` command. diff --git a/Help/command/get_target_property.rst b/Help/command/get_target_property.rst index 2a72c3a..98e9db3 100644 --- a/Help/command/get_target_property.rst +++ b/Help/command/get_target_property.rst @@ -8,8 +8,15 @@ Get a property from a target. get_target_property(VAR target property) Get a property from a target. The value of the property is stored in -the variable ``VAR``. If the property is not found, ``VAR`` will be set to -"NOTFOUND". Use :command:`set_target_properties` to set property values. +the variable ``VAR``. If the target property is not found, the behavior +depends on whether it has been defined to be an ``INHERITED`` property +or not (see :command:`define_property`). Non-inherited properties will +set ``VAR`` to "NOTFOUND", whereas inherited properties will search the +relevant parent scope as described for the :command:`define_property` +command and if still unable to find the property, ``VAR`` will be set to +an empty string. + +Use :command:`set_target_properties` to set target property values. Properties are usually used to control how a target is built, but some query the target instead. This command can get properties for any target so far created. The targets do not need to be in the current diff --git a/Help/command/get_test_property.rst b/Help/command/get_test_property.rst index e359f4b..555c3b2 100644 --- a/Help/command/get_test_property.rst +++ b/Help/command/get_test_property.rst @@ -8,8 +8,14 @@ Get a property of the test. get_test_property(test property VAR) Get a property from the test. The value of the property is stored in -the variable ``VAR``. If the test or property is not found, ``VAR`` will -be set to "NOTFOUND". For a list of standard properties you can type -``cmake --help-property-list``. +the variable ``VAR``. If the test property is not found, the behavior +depends on whether it has been defined to be an ``INHERITED`` property +or not (see :command:`define_property`). Non-inherited properties will +set ``VAR`` to "NOTFOUND", whereas inherited properties will search the +relevant parent scope as described for the :command:`define_property` +command and if still unable to find the property, ``VAR`` will be set to +an empty string. + +For a list of standard properties you can type ``cmake --help-property-list``. See also the more general :command:`get_property` command. diff --git a/Help/command/install.rst b/Help/command/install.rst index 2506f98..d3818d6 100644 --- a/Help/command/install.rst +++ b/Help/command/install.rst @@ -183,6 +183,13 @@ export called ``<export-name>``. It must appear before any ``RUNTIME``, ``LIBRARY``, ``ARCHIVE``, or ``OBJECTS`` options. To actually install the export file itself, call ``install(EXPORT)``, documented below. +:ref:`Interface Libraries` may be listed among the targets to install. +They install no artifacts but will be included in an associated ``EXPORT``. +If :ref:`Object Libraries` are listed but given no destination for their +object files, they will be exported as :ref:`Interface Libraries`. +This is sufficient to satisfy transitive usage requirements of other +targets that link to the object libraries in their implementation. + Installing a target with the :prop_tgt:`EXCLUDE_FROM_ALL` target property set to ``TRUE`` has undefined behavior. @@ -332,12 +339,12 @@ Installing Exports install(EXPORT <export-name> DESTINATION <dir> [NAMESPACE <namespace>] [[FILE <name>.cmake]| - [EXPORT_ANDROID_MK <name>.mk]] [PERMISSIONS permissions...] [CONFIGURATIONS [Debug|Release|...]] [EXPORT_LINK_INTERFACE_LIBRARIES] [COMPONENT <component>] [EXCLUDE_FROM_ALL]) + install(EXPORT_ANDROID_MK <export-name> DESTINATION <dir> [...]) The ``EXPORT`` form generates and installs a CMake file containing code to import targets from the installation tree into another project. @@ -360,8 +367,9 @@ specified that does not match that given to the targets associated with included in the export but a target to which it links is not included the behavior is unspecified. -In addition to cmake language files, the ``EXPORT_ANDROID_MK`` option maybe -used to specify an export to the android ndk build system. The Android +In addition to cmake language files, the ``EXPORT_ANDROID_MK`` mode maybe +used to specify an export to the android ndk build system. This mode +accepts the same options as the normal export mode. The Android NDK supports the use of prebuilt libraries, both static and shared. This allows cmake to build the libraries of a project and make them available to an ndk build system complete with transitive dependencies, include flags @@ -378,7 +386,7 @@ and installed by the current project. For example, the code will install the executable myexe to ``<prefix>/bin`` and code to import it in the file ``<prefix>/lib/myproj/myproj.cmake`` and -``<prefix>/lib/share/ndk-modules/Android.mk``. An outside project +``<prefix>/share/ndk-modules/Android.mk``. An outside project may load this file with the include command and reference the ``myexe`` executable from the installation tree using the imported target name ``mp_myexe`` as if the target were built in its own tree. @@ -392,3 +400,26 @@ executable from the installation tree using the imported target name those generated by :command:`install_targets`, :command:`install_files`, and :command:`install_programs` commands is not defined. + +Generated Installation Script +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The ``install()`` command generates a file, ``cmake_install.cmake``, inside +the build directory, which is used internally by the generated install target +and by CPack. You can also invoke this script manually with ``cmake -P``. This +script accepts several variables: + +``COMPONENT`` + Set this variable to install only a single CPack component as opposed to all + of them. For example, if you only want to install the ``Development`` + component, run ``cmake -DCOMPONENT=Development -P cmake_install.cmake``. + +``BUILD_TYPE`` + Set this variable to change the build type if you are using a multi-config + generator. For example, to install with the ``Debug`` configuration, run + ``cmake -DBUILD_TYPE=Debug -P cmake_install.cmake``. + +``DESTDIR`` + This is an environment variable rather than a CMake variable. It allows you + to change the installation prefix on UNIX systems. See :envvar:`DESTDIR` for + details. diff --git a/Help/command/list.rst b/Help/command/list.rst index f6b75bc..67e9743 100644 --- a/Help/command/list.rst +++ b/Help/command/list.rst @@ -1,68 +1,247 @@ list ---- +.. only:: html + + .. contents:: + List operations. +The list subcommands ``APPEND``, ``INSERT``, ``FILTER``, ``REMOVE_AT``, +``REMOVE_ITEM``, ``REMOVE_DUPLICATES``, ``REVERSE`` and ``SORT`` may create +new values for the list within the current CMake variable scope. Similar to +the :command:`set` command, the LIST command creates new variable values in +the current scope, even if the list itself is actually defined in a parent +scope. To propagate the results of these operations upwards, use +:command:`set` with ``PARENT_SCOPE``, :command:`set` with +``CACHE INTERNAL``, or some other means of value propagation. + +.. note:: + + A list in cmake is a ``;`` separated group of strings. To create a + list the set command can be used. For example, ``set(var a b c d e)`` + creates a list with ``a;b;c;d;e``, and ``set(var "a b c d e")`` creates a + string or a list with one item in it. (Note macro arguments are not + variables, and therefore cannot be used in LIST commands.) + +.. note:: + + When specifying index values, if ``<element index>`` is 0 or greater, it + is indexed from the beginning of the list, with 0 representing the + first list element. If ``<element index>`` is -1 or lesser, it is indexed + from the end of the list, with -1 representing the last list element. + Be careful when counting with negative indices: they do not start from + 0. -0 is equivalent to 0, the first list element. + +Capacity and Element access +^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +LENGTH +"""""" + :: list(LENGTH <list> <output variable>) - list(GET <list> <element index> [<element index> ...] - <output variable>) + +Returns the list's length. + +GET +""" + +:: + + list(GET <list> <element index> [<element index> ...] <output variable>) + +Returns the list of elements specified by indices from the list. + +JOIN +"""" + +:: + + list(JOIN <list> <glue> <output variable>) + +Returns a string joining all list's elements using the glue string. +To join multiple strings, which are not part of a list, use ``JOIN`` operator +from :command:`string` command. + +SUBLIST +""""""" + +:: + + list(SUBLIST <list> <begin> <length> <output variable>) + +Returns a sublist of the given list. +If ``<length>`` is 0, an empty list will be returned. +If ``<length>`` is -1 or the list is smaller than ``<begin>+<length>`` then +the remaining elements of the list starting at ``<begin>`` will be returned. + +Search +^^^^^^ + +FIND +"""" + +:: + + list(FIND <list> <value> <output variable>) + +Returns the index of the element specified in the list or -1 +if it wasn't found. + +Modification +^^^^^^^^^^^^ + +APPEND +"""""" + +:: + list(APPEND <list> [<element> ...]) + +Appends elements to the list. + +FILTER +"""""" + +:: + list(FILTER <list> <INCLUDE|EXCLUDE> REGEX <regular_expression>) - list(FIND <list> <value> <output variable>) + +Includes or removes items from the list that match the mode's pattern. +In ``REGEX`` mode, items will be matched against the given regular expression. + +For more information on regular expressions see also the +:command:`string` command. + +INSERT +"""""" + +:: + list(INSERT <list> <element_index> <element> [<element> ...]) + +Inserts elements to the list to the specified location. + +REMOVE_ITEM +""""""""""" + +:: + list(REMOVE_ITEM <list> <value> [<value> ...]) + +Removes the given items from the list. + +REMOVE_AT +""""""""" + +:: + list(REMOVE_AT <list> <index> [<index> ...]) + +Removes items at given indices from the list. + +REMOVE_DUPLICATES +""""""""""""""""" + +:: + list(REMOVE_DUPLICATES <list>) - list(REVERSE <list>) - list(SORT <list>) -``LENGTH`` will return a given list's length. +Removes duplicated items in the list. -``GET`` will return list of elements specified by indices from the list. +TRANSFORM +""""""""" -``APPEND`` will append elements to the list. +:: -``FILTER`` will include or remove items from the list that match the -mode's pattern. -In ``REGEX`` mode, items will be matched against the given regular expression. -For more information on regular expressions see also the :command:`string` -command. + list(TRANSFORM <list> <ACTION> [<SELECTOR>] + [OUTPUT_VARIABLE <output variable>]) -``FIND`` will return the index of the element specified in the list or -1 -if it wasn't found. +Transforms the list by applying an action to all or, by specifying a +``<SELECTOR>``, to the selected elements of the list, storing result in-place +or in the specified output variable. -``INSERT`` will insert elements to the list to the specified location. +.. note:: -``REMOVE_AT`` and ``REMOVE_ITEM`` will remove items from the list. The -difference is that ``REMOVE_ITEM`` will remove the given items, while -``REMOVE_AT`` will remove the items at the given indices. + ``TRANSFORM`` sub-command does not change the number of elements of the + list. If a ``<SELECTOR>`` is specified, only some elements will be changed, + the other ones will remain same as before the transformation. -``REMOVE_DUPLICATES`` will remove duplicated items in the list. +``<ACTION>`` specify the action to apply to the elements of list. +The actions have exactly the same semantics as sub-commands of +:command:`string` command. -``REVERSE`` reverses the contents of the list in-place. +The ``<ACTION>`` may be one of: -``SORT`` sorts the list in-place alphabetically. +``APPEND``, ``PREPEND``: Append, prepend specified value to each element of +the list. :: + + list(TRANSFORM <list> <APPEND|PREPEND> <value> ...) + +``TOUPPER``, ``TOLOWER``: Convert each element of the list to upper, lower +characters. :: + + list(TRANSFORM <list> <TOLOWER|TOUPPER> ...) + +``STRIP``: Remove leading and trailing spaces from each element of the +list. :: + + list(TRANSFORM <list> STRIP ...) + +``GENEX_STRIP``: Strip any +:manual:`generator expressions <cmake-generator-expressions(7)>` from each +element of the list. :: + + list(TRANSFORM <list> GENEX_STRIP ...) + +``REPLACE``: Match the regular expression as many times as possible and +substitute the replacement expression for the match for each element +of the list +(Same semantic as ``REGEX REPLACE`` from :command:`string` command). :: + + list(TRANSFORM <list> REPLACE <regular_expression> + <replace_expression> ...) + +``<SELECTOR>`` select which elements of the list will be transformed. Only one +type of selector can be specified at a time. + +The ``<SELECTOR>`` may be one of: + +``AT``: Specify a list of indexes. :: + + list(TRANSFORM <list> <ACTION> AT <index> [<index> ...] ...) + +``FOR``: Specify a range with, optionally, an increment used to iterate over +the range. :: + + list(TRANSFORM <list> <ACTION> FOR <start> <stop> [<step>] ...) + +``REGEX``: Specify a regular expression. Only elements matching the regular +expression will be transformed. :: + + list(TRANSFORM <list> <ACTION> REGEX <regular_expression> ...) + + +Sorting +^^^^^^^ + +REVERSE +""""""" + +:: + + list(REVERSE <list>) + +Reverses the contents of the list in-place. + +SORT +"""" + +:: + + list(SORT <list>) -The list subcommands ``APPEND``, ``INSERT``, ``FILTER``, ``REMOVE_AT``, -``REMOVE_ITEM``, ``REMOVE_DUPLICATES``, ``REVERSE`` and ``SORT`` may create new -values for the list within the current CMake variable scope. Similar to the -:command:`set` command, the LIST command creates new variable values in the -current scope, even if the list itself is actually defined in a parent -scope. To propagate the results of these operations upwards, use -:command:`set` with ``PARENT_SCOPE``, :command:`set` with -``CACHE INTERNAL``, or some other means of value propagation. -NOTES: A list in cmake is a ``;`` separated group of strings. To create a -list the set command can be used. For example, ``set(var a b c d e)`` -creates a list with ``a;b;c;d;e``, and ``set(var "a b c d e")`` creates a -string or a list with one item in it. (Note macro arguments are not -variables, and therefore cannot be used in LIST commands.) - -When specifying index values, if ``<element index>`` is 0 or greater, it -is indexed from the beginning of the list, with 0 representing the -first list element. If ``<element index>`` is -1 or lesser, it is indexed -from the end of the list, with -1 representing the last list element. -Be careful when counting with negative indices: they do not start from -0. -0 is equivalent to 0, the first list element. +Sorts the list in-place alphabetically. diff --git a/Help/command/project.rst b/Help/command/project.rst index eb185e4..e46dd69 100644 --- a/Help/command/project.rst +++ b/Help/command/project.rst @@ -1,7 +1,7 @@ project ------- -Set a name, version, and enable languages for the entire project. +Sets project details such as name, version, etc. and enables languages. .. code-block:: cmake @@ -9,6 +9,7 @@ Set a name, version, and enable languages for the entire project. project(<PROJECT-NAME> [VERSION <major>[.<minor>[.<patch>[.<tweak>]]]] [DESCRIPTION <project-description-string>] + [HOMEPAGE_URL <url-string>] [LANGUAGES <language-name>...]) Sets the name of the project and stores the name in the @@ -41,9 +42,18 @@ in variables Variables corresponding to unspecified versions are set to the empty string (if policy :policy:`CMP0048` is set to ``NEW``). -If optional ``DESCRIPTION`` is given, then additional :variable:`PROJECT_DESCRIPTION` -variable will be set to its argument. The argument must be a string with short -description of the project (only a few words). +If the optional ``DESCRIPTION`` is given, then :variable:`PROJECT_DESCRIPTION` +and :variable:`<PROJECT-NAME>_DESCRIPTION` will be set to its argument. +The description is expected to be a relatively short string, usually no more +than a few words. + +The optional ``HOMEPAGE_URL`` sets the analogous variables +:variable:`PROJECT_HOMEPAGE_URL` and :variable:`<PROJECT-NAME>_HOMEPAGE_URL`. +When this option is given, the URL provided should be the canonical home for +the project. + +Note that the description and homepage URL may be used as defaults for +things like packaging meta-data, documentation, etc. Optionally you can specify which languages your project supports. Example languages include ``C``, ``CXX`` (i.e. C++), ``CUDA``, @@ -63,7 +73,11 @@ The top-level ``CMakeLists.txt`` file for a project must contain a literal, direct call to the :command:`project` command; loading one through the :command:`include` command is not sufficient. If no such call exists CMake will implicitly add one to the top that enables the -default languages (``C`` and ``CXX``). +default languages (``C`` and ``CXX``). The name of the project set in +the top level ``CMakeLists.txt`` file is available from the +:variable:`CMAKE_PROJECT_NAME` variable, its description from +:variable:`CMAKE_PROJECT_DESCRIPTION` and its homepage URL from +:variable:`CMAKE_PROJECT_HOMEPAGE_URL`. .. note:: Call the :command:`cmake_minimum_required` command at the beginning diff --git a/Help/command/set_property.rst b/Help/command/set_property.rst index 5ed788e..c89e1ce 100644 --- a/Help/command/set_property.rst +++ b/Help/command/set_property.rst @@ -59,11 +59,17 @@ be one of the following: The required ``PROPERTY`` option is immediately followed by the name of the property to set. Remaining arguments are used to compose the -property value in the form of a semicolon-separated list. If the -``APPEND`` option is given the list is appended to any existing property -value. If the ``APPEND_STRING`` option is given the string is append to any -existing property value as string, i.e. it results in a longer string -and not a list of strings. +property value in the form of a semicolon-separated list. + +If the ``APPEND`` option is given the list is appended to any existing +property value. If the ``APPEND_STRING`` option is given the string is +appended to any existing property value as string, i.e. it results in a +longer string and not a list of strings. When using ``APPEND`` or +``APPEND_STRING`` with a property defined to support ``INHERITED`` +behavior (see :command:`define_property`), no inheriting occurs when +finding the initial value to append to. If the property is not already +directly set in the nominated scope, the command will behave as though +``APPEND`` or ``APPEND_STRING`` had not been given. See the :manual:`cmake-properties(7)` manual for a list of properties in each scope. diff --git a/Help/command/set_target_properties.rst b/Help/command/set_target_properties.rst index b894eac..7db952d 100644 --- a/Help/command/set_target_properties.rst +++ b/Help/command/set_target_properties.rst @@ -9,10 +9,12 @@ Targets can have properties that affect how they are built. PROPERTIES prop1 value1 prop2 value2 ...) -Set properties on a target. The syntax for the command is to list all -the files you want to change, and then provide the values you want to +Set properties on targets. The syntax for the command is to list all +the targets you want to change, and then provide the values you want to set next. You can use any prop value pair you want and extract it later with the :command:`get_property` or :command:`get_target_property` command. +See also the :command:`set_property(TARGET)` command. + See :ref:`Target Properties` for the list of properties known to CMake. diff --git a/Help/command/string.rst b/Help/command/string.rst index fb3893f..e84f788 100644 --- a/Help/command/string.rst +++ b/Help/command/string.rst @@ -151,6 +151,20 @@ CONCAT Concatenate all the input arguments together and store the result in the named output variable. +JOIN +"""" + +:: + + string(JOIN <glue> <output variable> [<input>...]) + +Join all the input arguments together using the glue +string and store the result in the named output variable. + +To join list's elements, use preferably the ``JOIN`` operator +from :command:`list` command. This allows for the elements to have +special characters like ``;`` in them. + TOLOWER """"""" @@ -282,6 +296,18 @@ CONFIGURE Transform a string like :command:`configure_file` transforms a file. +MAKE_C_IDENTIFIER +""""""""""""""""" + +:: + + string(MAKE_C_IDENTIFIER <input string> <output variable>) + +Convert each non-alphanumeric character in the ``<input string>`` to an +underscore and store the result in the ``<output variable>``. If the first +character of the string is a digit, an underscore will also be prepended to +the result. + RANDOM """""" @@ -346,13 +372,6 @@ If no explicit ``<format string>`` is given it will default to: %Y-%m-%dT%H:%M:%S for local time. %Y-%m-%dT%H:%M:%SZ for UTC. - -:: - - string(MAKE_C_IDENTIFIER <input string> <output variable>) - -Write a string which can be used as an identifier in C. - .. note:: If the ``SOURCE_DATE_EPOCH`` environment variable is set, @@ -367,7 +386,7 @@ UUID string(UUID <output variable> NAMESPACE <namespace> NAME <name> TYPE <MD5|SHA1> [UPPER]) -Create a univerally unique identifier (aka GUID) as per RFC4122 +Create a universally unique identifier (aka GUID) as per RFC4122 based on the hash of the combined values of ``<namespace>`` (which itself has to be a valid UUID) and ``<name>``. The hash algorithm can be either ``MD5`` (Version 3 UUID) or diff --git a/Help/command/target_compile_definitions.rst b/Help/command/target_compile_definitions.rst index 3709e7a..a740117 100644 --- a/Help/command/target_compile_definitions.rst +++ b/Help/command/target_compile_definitions.rst @@ -27,3 +27,13 @@ Arguments to ``target_compile_definitions`` may use "generator expressions" with the syntax ``$<...>``. See the :manual:`cmake-generator-expressions(7)` manual for available expressions. See the :manual:`cmake-buildsystem(7)` manual for more on defining buildsystem properties. + +Any leading ``-D`` on an item will be removed. Empty items are ignored. +For example, the following are all equivalent: + +.. code-block:: cmake + + target_compile_definitions(foo PUBLIC FOO) + target_compile_definitions(foo PUBLIC -DFOO) # -D removed + target_compile_definitions(foo PUBLIC "" FOO) # "" ignored + target_compile_definitions(foo PUBLIC -D FOO) # -D becomes "", then ignored diff --git a/Help/command/target_compile_options.rst b/Help/command/target_compile_options.rst index 3e7dc47..194d008 100644 --- a/Help/command/target_compile_options.rst +++ b/Help/command/target_compile_options.rst @@ -19,8 +19,8 @@ instead of being appended. This command can be used to add any options, but alternative commands exist to add preprocessor definitions -(:command:`target_compile_definitions` and :command:`add_definitions`) or -include directories (:command:`target_include_directories` and +(:command:`target_compile_definitions` and :command:`add_compile_definitions`) +or include directories (:command:`target_include_directories` and :command:`include_directories`). See documentation of the :prop_dir:`directory <COMPILE_OPTIONS>` and :prop_tgt:`target <COMPILE_OPTIONS>` ``COMPILE_OPTIONS`` properties. @@ -38,3 +38,5 @@ Arguments to ``target_compile_options`` may use "generator expressions" with the syntax ``$<...>``. See the :manual:`cmake-generator-expressions(7)` manual for available expressions. See the :manual:`cmake-buildsystem(7)` manual for more on defining buildsystem properties. + +.. include:: COMPILE_OPTIONS_SHELL.txt diff --git a/Help/command/target_link_libraries.rst b/Help/command/target_link_libraries.rst index 2ec8744..fcc2c07 100644 --- a/Help/command/target_link_libraries.rst +++ b/Help/command/target_link_libraries.rst @@ -183,6 +183,70 @@ is not ``NEW``, they are also appended to the ``general`` (or without any keyword) are treated as if specified for both ``debug`` and ``optimized``. +Linking Object Libraries +^^^^^^^^^^^^^^^^^^^^^^^^ + +:ref:`Object Libraries` may be used as the ``<target>`` (first) argument +of ``target_link_libraries`` to specify dependencies of their sources +on other libraries. For example, the code + +.. code-block:: cmake + + add_library(A SHARED a.c) + target_compile_definitions(A PUBLIC A) + + add_library(obj OBJECT obj.c) + target_compile_definitions(obj PUBLIC OBJ) + target_link_libraries(obj PUBLIC A) + +compiles ``obj.c`` with ``-DA -DOBJ`` and establishes usage requirements +for ``obj`` that propagate to its dependents. + +Normal libraries and executables may link to :ref:`Object Libraries` +to get their objects and usage requirements. Continuing the above +example, the code + +.. code-block:: cmake + + add_library(B SHARED b.c) + target_link_libraries(B PUBLIC obj) + +compiles ``b.c`` with ``-DA -DOBJ``, creates shared library ``B`` +with object files from ``b.c`` and ``obj.c``, and links ``B`` to ``A``. +Furthermore, the code + +.. code-block:: cmake + + add_executable(main main.c) + target_link_libraries(main B) + +compiles ``main.c`` with ``-DA -DOBJ`` and links executable ``main`` +to ``B`` and ``A``. The object library's usage requirements are +propagated transitively through ``B``, but its object files are not. + +:ref:`Object Libraries` may "link" to other object libraries to get +usage requirements, but since they do not have a link step nothing +is done with their object files. Continuing from the above example, +the code: + +.. code-block:: cmake + + add_library(obj2 OBJECT obj2.c) + target_link_libraries(obj2 PUBLIC obj) + + add_executable(main2 main2.c) + target_link_libraries(main2 obj2) + +compiles ``obj2.c`` with ``-DA -DOBJ``, creates executable ``main2`` +with object files from ``main2.c`` and ``obj2.c``, and links ``main2`` +to ``A``. + +In other words, when :ref:`Object Libraries` appear in a target's +:prop_tgt:`INTERFACE_LINK_LIBRARIES` property they will be +treated as :ref:`Interface Libraries`, but when they appear in +a target's :prop_tgt:`LINK_LIBRARIES` property their object files +will be included in the link too. + Cyclic Dependencies of Static Libraries ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/Help/envvar/DESTDIR.rst b/Help/envvar/DESTDIR.rst new file mode 100644 index 0000000..87f1115 --- /dev/null +++ b/Help/envvar/DESTDIR.rst @@ -0,0 +1,19 @@ +DESTDIR +------- + +On UNIX one can use the ``DESTDIR`` mechanism in order to relocate the +whole installation. ``DESTDIR`` means DESTination DIRectory. It is +commonly used by makefile users in order to install software at +non-default location. It is usually invoked like this: + +:: + + make DESTDIR=/home/john install + +which will install the concerned software using the installation +prefix, e.g. ``/usr/local`` prepended with the ``DESTDIR`` value which +finally gives ``/home/john/usr/local``. + +WARNING: ``DESTDIR`` may not be used on Windows because installation +prefix usually contains a drive letter like in ``C:/Program Files`` +which cannot be prepended with some other prefix. diff --git a/Help/generator/Visual Studio 8 2005.rst b/Help/generator/Visual Studio 8 2005.rst index acbbf01..947e7a5 100644 --- a/Help/generator/Visual Studio 8 2005.rst +++ b/Help/generator/Visual Studio 8 2005.rst @@ -1,23 +1,6 @@ Visual Studio 8 2005 -------------------- -Deprecated. Generates Visual Studio 8 2005 project files. - -.. note:: - This generator is deprecated and will be removed in a future version - of CMake. It will still be possible to build with VS 8 2005 tools - using the :generator:`Visual Studio 10 2010` (or above) generator - with :variable:`CMAKE_GENERATOR_TOOLSET` set to ``v80``, or by - using the :generator:`NMake Makefiles` generator. - -The :variable:`CMAKE_GENERATOR_PLATFORM` variable may be set -to specify a target platform name. - -For compatibility with CMake versions prior to 3.1, one may specify -a target platform name optionally at the end of this generator name: - -``Visual Studio 8 2005 Win64`` - Specify target platform ``x64``. - -``Visual Studio 8 2005 <WinCE-SDK>`` - Specify target platform matching a Windows CE SDK name. +Removed. This once generated Visual Studio 8 2005 project files, but +the generator has been removed since CMake 3.12. It is still possible to +build with VS 2005 tools using the :generator:`NMake Makefiles` generator. diff --git a/Help/index.rst b/Help/index.rst index 3dccdda..fa5273c 100644 --- a/Help/index.rst +++ b/Help/index.rst @@ -29,18 +29,18 @@ Reference Manuals /manual/cmake-commands.7 /manual/cmake-compile-features.7 /manual/cmake-developer.7 + /manual/cmake-env-variables.7 /manual/cmake-generator-expressions.7 /manual/cmake-generators.7 /manual/cmake-language.7 - /manual/cmake-server.7 /manual/cmake-modules.7 /manual/cmake-packages.7 /manual/cmake-policies.7 /manual/cmake-properties.7 /manual/cmake-qt.7 + /manual/cmake-server.7 /manual/cmake-toolchains.7 /manual/cmake-variables.7 - /manual/cmake-env-variables.7 .. only:: html or text diff --git a/Help/manual/LINKS.txt b/Help/manual/LINKS.txt index 3993ff8..8e53c0c 100644 --- a/Help/manual/LINKS.txt +++ b/Help/manual/LINKS.txt @@ -5,15 +5,11 @@ Home Page The primary starting point for learning about CMake. -Frequently Asked Questions - https://cmake.org/Wiki/CMake_FAQ - - A Wiki is provided containing answers to frequently asked questions. - -Online Documentation +Online Documentation and Community Resources https://cmake.org/documentation - Links to available documentation may be found on this web page. + Links to available documentation and community resources may be + found on this web page. Mailing List https://cmake.org/mailing-lists diff --git a/Help/manual/ccmake.1.rst b/Help/manual/ccmake.1.rst index a5fe191..cc3ceec 100644 --- a/Help/manual/ccmake.1.rst +++ b/Help/manual/ccmake.1.rst @@ -8,7 +8,7 @@ Synopsis .. parsed-literal:: - ccmake [<options>] (<path-to-source> | <path-to-existing-build>) + ccmake [<options>] {<path-to-source> | <path-to-existing-build>} Description =========== diff --git a/Help/manual/cmake-buildsystem.7.rst b/Help/manual/cmake-buildsystem.7.rst index b672ea6..49375e9 100644 --- a/Help/manual/cmake-buildsystem.7.rst +++ b/Help/manual/cmake-buildsystem.7.rst @@ -113,9 +113,9 @@ and it uniquely identifies the bundle. Object Libraries ^^^^^^^^^^^^^^^^ -The ``OBJECT`` library type is also not linked to. It defines a non-archival -collection of object files resulting from compiling the given source files. -The object files collection can be used as source inputs to other targets: +The ``OBJECT`` library type defines a non-archival collection of object files +resulting from compiling the given source files. The object files collection +may be used as source inputs to other targets: .. code-block:: cmake @@ -125,22 +125,31 @@ The object files collection can be used as source inputs to other targets: add_executable(test_exe $<TARGET_OBJECTS:archive> test.cpp) -``OBJECT`` libraries may not be used in the right hand side of -:command:`target_link_libraries`. They also may not be used as the ``TARGET`` -in a use of the :command:`add_custom_command(TARGET)` command signature. They -may be installed, and will be exported as an INTERFACE library. +The link (or archiving) step of those other targets will use the object +files collection in addition to those from their own sources. -Although object libraries may not be named directly in calls to -the :command:`target_link_libraries` command, they can be "linked" -indirectly by using an :ref:`Interface Library <Interface Libraries>` -whose :prop_tgt:`INTERFACE_SOURCES` target property is set to name -``$<TARGET_OBJECTS:objlib>``. +Alternatively, object libraries may be linked into other targets: -Although object libraries may not be used as the ``TARGET`` -in a use of the :command:`add_custom_command(TARGET)` command signature, -the list of objects can be used by :command:`add_custom_command(OUTPUT)` or -:command:`file(GENERATE)` by using ``$<TARGET_OBJECTS:objlib>``. +.. code-block:: cmake + + add_library(archive OBJECT archive.cpp zip.cpp lzma.cpp) + + add_library(archiveExtras STATIC extras.cpp) + target_link_libraries(archiveExtras PUBLIC archive) + + add_executable(test_exe test.cpp) + target_link_libraries(test_exe archive) + +The link (or archiving) step of those other targets will use the object +files from object libraries that are *directly* linked. Additionally, +usage requirements of the object libraries will be honored when compiling +sources in those other targets. Furthermore, those usage requirements +will propagate transitively to dependents of those other targets. +Object libraries may not be used as the ``TARGET`` in a use of the +:command:`add_custom_command(TARGET)` command signature. However, +the list of objects can be used by :command:`add_custom_command(OUTPUT)` +or :command:`file(GENERATE)` by using ``$<TARGET_OBJECTS:objlib>``. Build Specification and Usage Requirements ========================================== @@ -812,7 +821,7 @@ Directory-Scoped Commands The :command:`target_include_directories`, :command:`target_compile_definitions` and :command:`target_compile_options` commands have an effect on only one -target at a time. The commands :command:`add_definitions`, +target at a time. The commands :command:`add_compile_definitions`, :command:`add_compile_options` and :command:`include_directories` have a similar function, but operate at directory scope instead of target scope for convenience. diff --git a/Help/manual/cmake-commands.7.rst b/Help/manual/cmake-commands.7.rst index f8bfb32..408a3a0 100644 --- a/Help/manual/cmake-commands.7.rst +++ b/Help/manual/cmake-commands.7.rst @@ -70,6 +70,7 @@ These commands are available only in CMake projects. .. toctree:: :maxdepth: 1 + /command/add_compile_definitions /command/add_compile_options /command/add_custom_command /command/add_custom_target diff --git a/Help/manual/cmake-compile-features.7.rst b/Help/manual/cmake-compile-features.7.rst index e9495c6..634da10 100644 --- a/Help/manual/cmake-compile-features.7.rst +++ b/Help/manual/cmake-compile-features.7.rst @@ -331,9 +331,9 @@ and :prop_gbl:`compile features <CMAKE_CXX_KNOWN_FEATURES>` available from the following :variable:`compiler ids <CMAKE_<LANG>_COMPILER_ID>` as of the versions specified for each: -* ``AppleClang``: Apple Clang for Xcode versions 4.4 though 6.2. -* ``Clang``: Clang compiler versions 2.9 through 3.4. -* ``GNU``: GNU compiler versions 4.4 through 5.0. +* ``AppleClang``: Apple Clang for Xcode versions 4.4 though 9.2. +* ``Clang``: Clang compiler versions 2.9 through 6.0. +* ``GNU``: GNU compiler versions 4.4 through 8.0. * ``MSVC``: Microsoft Visual Studio versions 2010 through 2017. * ``SunPro``: Oracle SolarisStudio versions 12.4 through 12.6. * ``Intel``: Intel compiler versions 12.1 through 17.0. @@ -344,7 +344,7 @@ the following :variable:`compiler ids <CMAKE_<LANG>_COMPILER_ID>` as of the versions specified for each: * all compilers and versions listed above for C++. -* ``GNU``: GNU compiler versions 3.4 through 5.0. +* ``GNU``: GNU compiler versions 3.4 through 8.0. CMake is currently aware of the :prop_tgt:`C++ standards <CXX_STANDARD>` and their associated meta-features (e.g. ``cxx_std_11``) available from the @@ -366,4 +366,4 @@ CMake is currently aware of the :prop_tgt:`CUDA standards <CUDA_STANDARD>` from the following :variable:`compiler ids <CMAKE_<LANG>_COMPILER_ID>` as of the versions specified for each: -* ``NVIDIA``: NVIDIA nvcc compiler 7.5 though 8.0. +* ``NVIDIA``: NVIDIA nvcc compiler 7.5 though 9.1. diff --git a/Help/manual/cmake-developer.7.rst b/Help/manual/cmake-developer.7.rst index cd509ac..32e8cfc 100644 --- a/Help/manual/cmake-developer.7.rst +++ b/Help/manual/cmake-developer.7.rst @@ -644,6 +644,8 @@ Documentation`_ section above. +.. _`CMake Developer Standard Variable Names`: + Standard Variable Names ^^^^^^^^^^^^^^^^^^^^^^^ @@ -943,7 +945,7 @@ populated: endif() The ``RELEASE`` variant should be listed first in the property -so that that variant is chosen if the user uses a configuration which is +so that the variant is chosen if the user uses a configuration which is not an exact match for any listed ``IMPORTED_CONFIGURATIONS``. Most of the cache variables should be hidden in the ``ccmake`` interface unless diff --git a/Help/manual/cmake-env-variables.7.rst b/Help/manual/cmake-env-variables.7.rst index fed129e..2d8869f 100644 --- a/Help/manual/cmake-env-variables.7.rst +++ b/Help/manual/cmake-env-variables.7.rst @@ -16,6 +16,7 @@ Environment Variables that Control the Build /envvar/CMAKE_CONFIG_TYPE /envvar/CMAKE_MSVCIDE_RUN_PATH /envvar/CMAKE_OSX_ARCHITECTURES + /envvar/DESTDIR /envvar/LDFLAGS /envvar/MACOSX_DEPLOYMENT_TARGET diff --git a/Help/manual/cmake-generator-expressions.7.rst b/Help/manual/cmake-generator-expressions.7.rst index 0f6d4cf..8fd07d7 100644 --- a/Help/manual/cmake-generator-expressions.7.rst +++ b/Help/manual/cmake-generator-expressions.7.rst @@ -57,6 +57,10 @@ Available logical expressions are: ``1`` if ``a`` is STREQUAL ``b``, else ``0`` ``$<EQUAL:a,b>`` ``1`` if ``a`` is EQUAL ``b`` in a numeric comparison, else ``0`` +``$<IN_LIST:a,b>`` + ``1`` if ``a`` is IN_LIST ``b``, else ``0`` +``$<TARGET_EXISTS:tgt>`` + ``1`` if ``tgt`` is an existed target name, else ``0``. ``$<CONFIG:cfg>`` ``1`` if config is ``cfg``, else ``0``. This is a case-insensitive comparison. The mapping in :prop_tgt:`MAP_IMPORTED_CONFIG_<CONFIG>` is also considered by @@ -270,6 +274,9 @@ Available output expressions are: Marks ``...`` as being the name of a target. This is required if exporting targets to multiple dependent export sets. The ``...`` must be a literal name of a target- it may not contain generator expressions. +``$<TARGET_NAME_IF_EXISTS:...>`` + Expands to the ``...`` if the given target exists, an empty string + otherwise. ``$<LINK_ONLY:...>`` Content of ``...`` except when evaluated in a link interface while propagating :ref:`Target Usage Requirements`, in which case it is the @@ -289,7 +296,8 @@ Available output expressions are: ``$<UPPER_CASE:...>`` Content of ``...`` converted to upper case. ``$<MAKE_C_IDENTIFIER:...>`` - Content of ``...`` converted to a C identifier. + Content of ``...`` converted to a C identifier. The conversion follows the + same behavior as :command:`string(MAKE_C_IDENTIFIER)`. ``$<TARGET_OBJECTS:objLib>`` List of objects resulting from build of ``objLib``. ``objLib`` must be an object of type ``OBJECT_LIBRARY``. @@ -297,3 +305,42 @@ Available output expressions are: Content of ``...`` converted to shell path style. For example, slashes are converted to backslashes in Windows shells and drive letters are converted to posix paths in MSYS shells. The ``...`` must be an absolute path. +``$<GENEX_EVAL:...>`` + Content of ``...`` evaluated as a generator expression in the current + context. This enables consumption of generator expressions + whose evaluation results itself in generator expressions. +``$<TARGET_GENEX_EVAL:tgt,...>`` + Content of ``...`` evaluated as a generator expression in the context of + ``tgt`` target. This enables consumption of custom target properties that + themselves contain generator expressions. + + Having the capability to evaluate generator expressions is very useful when + you want to manage custom properties supporting generator expressions. + For example: + + .. code-block:: cmake + + add_library(foo ...) + + set_property(TARGET foo PROPERTY + CUSTOM_KEYS $<$<CONFIG:DEBUG>:FOO_EXTRA_THINGS> + ) + + add_custom_target(printFooKeys + COMMAND ${CMAKE_COMMAND} -E echo $<TARGET_PROPERTY:foo,CUSTOM_KEYS> + ) + + This naive implementation of the ``printFooKeys`` custom command is wrong + because ``CUSTOM_KEYS`` target property is not evaluated and the content + is passed as is (i.e. ``$<$<CONFIG:DEBUG>:FOO_EXTRA_THINGS>``). + + To have the expected result (i.e. ``FOO_EXTRA_THINGS`` if config is + ``Debug``), it is required to evaluate the output of + ``$<TARGET_PROPERTY:foo,CUSTOM_KEYS>``: + + .. code-block:: cmake + + add_custom_target(printFooKeys + COMMAND ${CMAKE_COMMAND} -E + echo $<TARGET_GENEX_EVAL:foo,$<TARGET_PROPERTY:foo,CUSTOM_KEYS>> + ) diff --git a/Help/manual/cmake-gui.1.rst b/Help/manual/cmake-gui.1.rst index 032b51f..57a9850 100644 --- a/Help/manual/cmake-gui.1.rst +++ b/Help/manual/cmake-gui.1.rst @@ -9,7 +9,7 @@ Synopsis .. parsed-literal:: cmake-gui [<options>] - cmake-gui [<options>] (<path-to-source> | <path-to-existing-build>) + cmake-gui [<options>] {<path-to-source> | <path-to-existing-build>} Description =========== diff --git a/Help/manual/cmake-modules.7.rst b/Help/manual/cmake-modules.7.rst index 694bae5..070c6ed 100644 --- a/Help/manual/cmake-modules.7.rst +++ b/Help/manual/cmake-modules.7.rst @@ -196,6 +196,9 @@ All Modules /module/FindPostgreSQL /module/FindProducer /module/FindProtobuf + /module/FindPython + /module/FindPython2 + /module/FindPython3 /module/FindPythonInterp /module/FindPythonLibs /module/FindQt3 diff --git a/Help/manual/cmake-policies.7.rst b/Help/manual/cmake-policies.7.rst index 96d5c7d..631f75b 100644 --- a/Help/manual/cmake-policies.7.rst +++ b/Help/manual/cmake-policies.7.rst @@ -51,6 +51,16 @@ The :variable:`CMAKE_MINIMUM_REQUIRED_VERSION` variable may also be used to determine whether to report an error on use of deprecated macros or functions. +Policies Introduced by CMake 3.12 +================================= + +.. toctree:: + :maxdepth: 1 + + CMP0075: Include file check macros honor CMAKE_REQUIRED_LIBRARIES. </policy/CMP0075> + CMP0074: find_package uses PackageName_ROOT variables. </policy/CMP0074> + CMP0073: Do not produce legacy _LIB_DEPENDS cache entries. </policy/CMP0073> + Policies Introduced by CMake 3.11 ================================= diff --git a/Help/manual/cmake-properties.7.rst b/Help/manual/cmake-properties.7.rst index 00a932f..b3e2fec 100644 --- a/Help/manual/cmake-properties.7.rst +++ b/Help/manual/cmake-properties.7.rst @@ -84,6 +84,7 @@ Properties on Directories /prop_dir/RULE_LAUNCH_LINK /prop_dir/SOURCE_DIR /prop_dir/SUBDIRECTORIES + /prop_dir/TESTS /prop_dir/TEST_INCLUDE_FILES /prop_dir/VARIABLES /prop_dir/VS_GLOBAL_SECTION_POST_section @@ -142,6 +143,7 @@ Properties on Targets /prop_tgt/C_EXTENSIONS /prop_tgt/C_STANDARD /prop_tgt/C_STANDARD_REQUIRED + /prop_tgt/COMMON_LANGUAGE_RUNTIME /prop_tgt/COMPATIBLE_INTERFACE_BOOL /prop_tgt/COMPATIBLE_INTERFACE_NUMBER_MAX /prop_tgt/COMPATIBLE_INTERFACE_NUMBER_MIN @@ -175,6 +177,7 @@ Properties on Targets /prop_tgt/EXCLUDE_FROM_DEFAULT_BUILD_CONFIG /prop_tgt/EXCLUDE_FROM_DEFAULT_BUILD /prop_tgt/EXPORT_NAME + /prop_tgt/EXPORT_PROPERTIES /prop_tgt/FOLDER /prop_tgt/Fortran_FORMAT /prop_tgt/Fortran_MODULE_DIRECTORY @@ -184,6 +187,7 @@ Properties on Targets /prop_tgt/GNUtoMS /prop_tgt/HAS_CXX /prop_tgt/IMPLICIT_DEPENDS_INCLUDE_TRANSFORM + /prop_tgt/IMPORTED_COMMON_LANGUAGE_RUNTIME /prop_tgt/IMPORTED_CONFIGURATIONS /prop_tgt/IMPORTED_GLOBAL /prop_tgt/IMPORTED_IMPLIB_CONFIG @@ -295,6 +299,7 @@ Properties on Targets /prop_tgt/VISIBILITY_INLINES_HIDDEN /prop_tgt/VS_CONFIGURATION_TYPE /prop_tgt/VS_DEBUGGER_WORKING_DIRECTORY + /prop_tgt/VS_DEBUGGER_COMMAND /prop_tgt/VS_DESKTOP_EXTENSIONS_VERSION /prop_tgt/VS_DOTNET_REFERENCE_refname /prop_tgt/VS_DOTNET_REFERENCEPROP_refname_TAG_tagname @@ -347,6 +352,7 @@ Properties on Tests /prop_test/LABELS /prop_test/MEASUREMENT /prop_test/PASS_REGULAR_EXPRESSION + /prop_test/PROCESSOR_AFFINITY /prop_test/PROCESSORS /prop_test/REQUIRED_FILES /prop_test/RESOURCE_LOCK @@ -399,6 +405,7 @@ Properties on Source Files /prop_sf/VS_SHADER_ENTRYPOINT /prop_sf/VS_SHADER_FLAGS /prop_sf/VS_SHADER_MODEL + /prop_sf/VS_SHADER_OBJECT_FILE_NAME /prop_sf/VS_SHADER_OUTPUT_HEADER_FILE /prop_sf/VS_SHADER_TYPE /prop_sf/VS_SHADER_VARIABLE_NAME diff --git a/Help/manual/cmake-variables.7.rst b/Help/manual/cmake-variables.7.rst index 3ac5123..44271c1 100644 --- a/Help/manual/cmake-variables.7.rst +++ b/Help/manual/cmake-variables.7.rst @@ -67,6 +67,7 @@ Variables that Provide Information /variable/CMAKE_PARENT_LIST_FILE /variable/CMAKE_PATCH_VERSION /variable/CMAKE_PROJECT_DESCRIPTION + /variable/CMAKE_PROJECT_HOMEPAGE_URL /variable/CMAKE_PROJECT_NAME /variable/CMAKE_RANLIB /variable/CMAKE_ROOT @@ -97,6 +98,8 @@ Variables that Provide Information /variable/CMAKE_XCODE_GENERATE_SCHEME /variable/CMAKE_XCODE_PLATFORM_TOOLSET /variable/PROJECT-NAME_BINARY_DIR + /variable/PROJECT-NAME_DESCRIPTION + /variable/PROJECT-NAME_HOMEPAGE_URL /variable/PROJECT-NAME_SOURCE_DIR /variable/PROJECT-NAME_VERSION /variable/PROJECT-NAME_VERSION_MAJOR @@ -105,6 +108,7 @@ Variables that Provide Information /variable/PROJECT-NAME_VERSION_TWEAK /variable/PROJECT_BINARY_DIR /variable/PROJECT_DESCRIPTION + /variable/PROJECT_HOMEPAGE_URL /variable/PROJECT_NAME /variable/PROJECT_SOURCE_DIR /variable/PROJECT_VERSION @@ -178,6 +182,7 @@ Variables that Change Behavior /variable/CMAKE_STAGING_PREFIX /variable/CMAKE_SUBLIME_TEXT_2_ENV_SETTINGS /variable/CMAKE_SUBLIME_TEXT_2_EXCLUDE_BUILD_TREE + /variable/CMAKE_SUPPRESS_REGENERATION /variable/CMAKE_SYSROOT /variable/CMAKE_SYSROOT_COMPILE /variable/CMAKE_SYSROOT_LINK @@ -234,6 +239,7 @@ Variables that Describe the System /variable/MSVC80 /variable/MSVC90 /variable/MSVC_IDE + /variable/MSVC_TOOLSET_VERSION /variable/MSVC_VERSION /variable/UNIX /variable/WIN32 @@ -300,6 +306,7 @@ Variables that Control the Build /variable/CMAKE_EXE_LINKER_FLAGS_CONFIG /variable/CMAKE_EXE_LINKER_FLAGS_CONFIG_INIT /variable/CMAKE_EXE_LINKER_FLAGS_INIT + /variable/CMAKE_FOLDER /variable/CMAKE_Fortran_FORMAT /variable/CMAKE_Fortran_MODULE_DIRECTORY /variable/CMAKE_GNUtoMS @@ -362,6 +369,13 @@ Variables that Control the Build /variable/CMAKE_VISIBILITY_INLINES_HIDDEN /variable/CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD /variable/CMAKE_VS_INCLUDE_PACKAGE_TO_DEFAULT_BUILD + /variable/CMAKE_VS_SDK_EXCLUDE_DIRECTORIES + /variable/CMAKE_VS_SDK_EXECUTABLE_DIRECTORIES + /variable/CMAKE_VS_SDK_INCLUDE_DIRECTORIES + /variable/CMAKE_VS_SDK_LIBRARY_DIRECTORIES + /variable/CMAKE_VS_SDK_LIBRARY_WINRT_DIRECTORIES + /variable/CMAKE_VS_SDK_REFERENCE_DIRECTORIES + /variable/CMAKE_VS_SDK_SOURCE_DIRECTORIES /variable/CMAKE_WIN32_EXECUTABLE /variable/CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS /variable/CMAKE_XCODE_ATTRIBUTE_an-attribute diff --git a/Help/manual/cmake.1.rst b/Help/manual/cmake.1.rst index c2e6435..577d321 100644 --- a/Help/manual/cmake.1.rst +++ b/Help/manual/cmake.1.rst @@ -8,8 +8,8 @@ Synopsis .. parsed-literal:: - cmake [<options>] (<path-to-source> | <path-to-existing-build>) - cmake [(-D <var>=<value>)...] -P <cmake-script-file> + cmake [<options>] {<path-to-source> | <path-to-existing-build>} + cmake [{-D <var>=<value>}...] -P <cmake-script-file> cmake --build <dir> [<options>...] [-- <build-tool-options>...] cmake --open <dir> cmake -E <command> [<options>...] diff --git a/Help/manual/ctest.1.rst b/Help/manual/ctest.1.rst index a04c403..9553d15 100644 --- a/Help/manual/ctest.1.rst +++ b/Help/manual/ctest.1.rst @@ -13,7 +13,7 @@ Synopsis ctest [<options>] ctest <path-to-source> <path-to-build> --build-generator <generator> [<options>...] [-- <build-options>...] [--test-command <test>] - ctest (-D <dashboard> | -M <model> -T <action> | -S <script> | -SP <script>) + ctest {-D <dashboard> | -M <model> -T <action> | -S <script> | -SP <script>} [-- <dashboard-options>...] Description @@ -368,15 +368,17 @@ for "SubprojectB"). Build and Test Mode =================== -CTest provides a command-line signature to to configure (i.e. run cmake on), -build, and or execute a test:: +CTest provides a command-line signature to configure (i.e. run cmake on), +build, and/or execute a test:: ctest --build-and-test <path-to-source> <path-to-build> - --build-generator <generator> [<options>...] [-- <build-options>...] - [--test-command <test>] + --build-generator <generator> + [<options>...] + [--build-options <opts>...] + [--test-command <command> [<args>...]] The configure and test steps are optional. The arguments to this command line -are the source and binary directories. The ``--build-generator`` option *must* +are the source and binary directories. The ``--build-generator`` option *must* be provided to use ``--build-and-test``. If ``--test-command`` is specified then that will be run after the build is complete. Other options that affect this mode include: @@ -425,13 +427,15 @@ this mode include: should be used. e.g. Debug/Release/etc. ``--build-options`` - Add extra options to the build step. - - This option must be the last option with the exception of - ``--test-command`` + Additional options for configuring the build (i.e. for CMake, not for + the build tool). Note that if this is specified, the ``--build-options`` + keyword and its arguments must be the last option given on the command + line, with the possible exception of ``--test-command``. ``--test-command`` - The test to run with the ``--build-and-test`` option. + The command to run as the test step with the ``--build-and-test`` option. + All arguments following this keyword will be assumed to be part of the + test command line, so it must be the last option given. ``--test-timeout`` The time limit in seconds diff --git a/Help/module/FindPython.rst b/Help/module/FindPython.rst new file mode 100644 index 0000000..057a350 --- /dev/null +++ b/Help/module/FindPython.rst @@ -0,0 +1 @@ +.. cmake-module:: ../../Modules/FindPython.cmake diff --git a/Help/module/FindPython2.rst b/Help/module/FindPython2.rst new file mode 100644 index 0000000..1696bed --- /dev/null +++ b/Help/module/FindPython2.rst @@ -0,0 +1 @@ +.. cmake-module:: ../../Modules/FindPython2.cmake diff --git a/Help/module/FindPython3.rst b/Help/module/FindPython3.rst new file mode 100644 index 0000000..e530ab8 --- /dev/null +++ b/Help/module/FindPython3.rst @@ -0,0 +1 @@ +.. cmake-module:: ../../Modules/FindPython3.cmake diff --git a/Help/policy/CMP0073.rst b/Help/policy/CMP0073.rst new file mode 100644 index 0000000..9bfa0e9 --- /dev/null +++ b/Help/policy/CMP0073.rst @@ -0,0 +1,25 @@ +CMP0073 +------- + +Do not produce legacy ``_LIB_DEPENDS`` cache entries. + +Ancient CMake versions once used ``<tgt>_LIB_DEPENDS`` cache entries to +propagate library link dependencies. This has long been done by other +means, leaving the :command:`export_library_dependencies` command as the +only user of these values. That command has long been disallowed by +policy :policy:`CMP0033`, but the ``<tgt>_LIB_DEPENDS`` cache entries +were left for compatibility with possible non-standard uses by projects. + +CMake 3.12 and above now prefer to not produce these cache entries +at all. This policy provides compatibility with projects that have +not been updated to avoid using them. + +The ``OLD`` behavior for this policy is to set ``<tgt>_LIB_DEPENDS`` cache +entries. The ``NEW`` behavior for this policy is to not set them. + +This policy was introduced in CMake version 3.12. Use the +:command:`cmake_policy` command to set it to ``OLD`` or ``NEW`` explicitly. +Unlike most policies, CMake version |release| does *not* warn +when this policy is not set and simply uses ``OLD`` behavior. + +.. include:: DEPRECATED.txt diff --git a/Help/policy/CMP0074.rst b/Help/policy/CMP0074.rst new file mode 100644 index 0000000..ffac4a7 --- /dev/null +++ b/Help/policy/CMP0074.rst @@ -0,0 +1,22 @@ +CMP0074 +------- + +:command:`find_package` uses ``PackageName_ROOT`` variables. + +In CMake 3.12 and above the ``find_package(PackageName)`` command now searches +a prefix specified by a ``PackageName_ROOT`` CMake or environment variable. +Package roots are maintained as a stack so nested calls to all ``find_*`` +commands inside find modules also search the roots as prefixes. This policy +provides compatibility with projects that have not been updated to avoid using +``PackageName_ROOT`` variables for other purposes. + +The ``OLD`` behavior for this policy is to ignore ``PackageName_ROOT`` +variables. The ``NEW`` behavior for this policy is to use ``PackageName_ROOT`` +variables. + +This policy was introduced in CMake version 3.12. CMake version +|release| warns when the policy is not set and uses ``OLD`` behavior. +Use the :command:`cmake_policy` command to set it to ``OLD`` or ``NEW`` +explicitly. + +.. include:: DEPRECATED.txt diff --git a/Help/policy/CMP0075.rst b/Help/policy/CMP0075.rst new file mode 100644 index 0000000..aa5c3f7 --- /dev/null +++ b/Help/policy/CMP0075.rst @@ -0,0 +1,26 @@ +CMP0075 +------- + +Include file check macros honor ``CMAKE_REQUIRED_LIBRARIES``. + +In CMake 3.12 and above, the + +* ``check_include_file`` macro in the :module:`CheckIncludeFile` module, the +* ``check_include_file_cxx`` macro in the + :module:`CheckIncludeFileCXX` module, and the +* ``check_include_files`` macro in the :module:`CheckIncludeFiles` module + +now prefer to link the check executable to the libraries listed in the +``CMAKE_REQUIRED_LIBRARIES`` variable. This policy provides compatibility +with projects that have not been updated to expect this behavior. + +The ``OLD`` behavior for this policy is to ignore ``CMAKE_REQUIRED_LIBRARIES`` +in the include file check macros. The ``NEW`` behavior of this policy is to +honor ``CMAKE_REQUIRED_LIBRARIES`` in the include file check macros. + +This policy was introduced in CMake version 3.12. CMake version +|release| warns when the policy is not set and uses ``OLD`` behavior. +Use the :command:`cmake_policy` command to set it to ``OLD`` or ``NEW`` +explicitly. + +.. include:: DEPRECATED.txt diff --git a/Help/prop_dir/COMPILE_DEFINITIONS.rst b/Help/prop_dir/COMPILE_DEFINITIONS.rst index 85adcb5..18f4567 100644 --- a/Help/prop_dir/COMPILE_DEFINITIONS.rst +++ b/Help/prop_dir/COMPILE_DEFINITIONS.rst @@ -4,7 +4,7 @@ COMPILE_DEFINITIONS Preprocessor definitions for compiling a directory's sources. This property specifies the list of options given so far to the -:command:`add_definitions` command. +:command:`add_compile_definitions` (or :command:`add_definitions`) command. The ``COMPILE_DEFINITIONS`` property may be set to a semicolon-separated list of preprocessor definitions using the syntax ``VAR`` or ``VAR=value``. diff --git a/Help/prop_dir/TESTS.rst b/Help/prop_dir/TESTS.rst new file mode 100644 index 0000000..c6e1d88 --- /dev/null +++ b/Help/prop_dir/TESTS.rst @@ -0,0 +1,7 @@ +TESTS +----- + +List of tests. + +This read-only property holds a :ref:`;-list <CMake Language Lists>` of tests +defined so far by the :command:`add_test` command. diff --git a/Help/prop_dir/VS_GLOBAL_SECTION_POST_section.rst b/Help/prop_dir/VS_GLOBAL_SECTION_POST_section.rst index a316abe..814bd5f 100644 --- a/Help/prop_dir/VS_GLOBAL_SECTION_POST_section.rst +++ b/Help/prop_dir/VS_GLOBAL_SECTION_POST_section.rst @@ -17,7 +17,7 @@ pairs. Each such pair will be transformed into an entry in the solution global section. Whitespace around key and value is ignored. List elements which do not contain an equal sign are skipped. -This property only works for Visual Studio 8 and above; it is ignored +This property only works for Visual Studio 9 and above; it is ignored on other generators. The property only applies when set on a directory whose CMakeLists.txt contains a project() command. diff --git a/Help/prop_dir/VS_GLOBAL_SECTION_PRE_section.rst b/Help/prop_dir/VS_GLOBAL_SECTION_PRE_section.rst index 200e8e6..f70e9f1 100644 --- a/Help/prop_dir/VS_GLOBAL_SECTION_PRE_section.rst +++ b/Help/prop_dir/VS_GLOBAL_SECTION_PRE_section.rst @@ -17,6 +17,6 @@ pairs. Each such pair will be transformed into an entry in the solution global section. Whitespace around key and value is ignored. List elements which do not contain an equal sign are skipped. -This property only works for Visual Studio 8 and above; it is ignored +This property only works for Visual Studio 9 and above; it is ignored on other generators. The property only applies when set on a directory whose CMakeLists.txt contains a project() command. diff --git a/Help/prop_gbl/CMAKE_CXX_KNOWN_FEATURES.rst b/Help/prop_gbl/CMAKE_CXX_KNOWN_FEATURES.rst index 2ad8157..262a67c 100644 --- a/Help/prop_gbl/CMAKE_CXX_KNOWN_FEATURES.rst +++ b/Help/prop_gbl/CMAKE_CXX_KNOWN_FEATURES.rst @@ -26,6 +26,9 @@ The features known to this version of CMake are: ``cxx_std_17`` Compiler mode is aware of C++ 17. +``cxx_std_20`` + Compiler mode is aware of C++ 20. + ``cxx_aggregate_default_initializers`` Aggregate default initializers, as defined in N3605_. diff --git a/Help/prop_sf/VS_SHADER_OBJECT_FILE_NAME.rst b/Help/prop_sf/VS_SHADER_OBJECT_FILE_NAME.rst new file mode 100644 index 0000000..093bcc6 --- /dev/null +++ b/Help/prop_sf/VS_SHADER_OBJECT_FILE_NAME.rst @@ -0,0 +1,6 @@ +VS_SHADER_OBJECT_FILE_NAME +-------------------------- + +Specifies a file name for the compiled shader object file for an ``.hlsl`` +source file. This adds the ``-Fo`` flag to the command line for the FxCompiler +tool. diff --git a/Help/prop_test/PROCESSORS.rst b/Help/prop_test/PROCESSORS.rst index a1211fb..a927c10 100644 --- a/Help/prop_test/PROCESSORS.rst +++ b/Help/prop_test/PROCESSORS.rst @@ -2,6 +2,7 @@ PROCESSORS ---------- Set to specify how many process slots this test requires. +If not set, the default is ``1`` processor. Denotes the number of processors that this test will require. This is typically used for MPI tests, and should be used in conjunction with @@ -11,3 +12,5 @@ This will also be used to display a weighted test timing result in label and subproject summaries in the command line output of :manual:`ctest(1)`. The wall clock time for the test run will be multiplied by this property to give a better idea of how much cpu resource CTest allocated for the test. + +See also the :prop_test:`PROCESSOR_AFFINITY` test property. diff --git a/Help/prop_test/PROCESSOR_AFFINITY.rst b/Help/prop_test/PROCESSOR_AFFINITY.rst new file mode 100644 index 0000000..38ec179 --- /dev/null +++ b/Help/prop_test/PROCESSOR_AFFINITY.rst @@ -0,0 +1,11 @@ +PROCESSOR_AFFINITY +------------------ + +Set to a true value to ask CTest to launch the test process with CPU affinity +for a fixed set of processors. If enabled and supported for the current +platform, CTest will choose a set of processors to place in the CPU affinity +mask when launching the test process. The number of processors in the set is +determined by the :prop_test:`PROCESSORS` test property or the number of +processors available to CTest, whichever is smaller. The set of processors +chosen will be disjoint from the processors assigned to other concurrently +running tests that also have the ``PROCESSOR_AFFINITY`` property enabled. diff --git a/Help/prop_test/WORKING_DIRECTORY.rst b/Help/prop_test/WORKING_DIRECTORY.rst index 5222a19..92a0409 100644 --- a/Help/prop_test/WORKING_DIRECTORY.rst +++ b/Help/prop_test/WORKING_DIRECTORY.rst @@ -3,5 +3,7 @@ WORKING_DIRECTORY The directory from which the test executable will be called. -If this is not set it is called from the directory the test executable -is located in. +If this is not set, the test will be run with the working directory set to the +binary directory associated with where the test was created (i.e. the +:variable:`CMAKE_CURRENT_BINARY_DIR` for where :command:`add_test` was +called). diff --git a/Help/prop_tgt/AUTOMOC_MACRO_NAMES.rst b/Help/prop_tgt/AUTOMOC_MACRO_NAMES.rst index a5ad9d5..a9a0ecf 100644 --- a/Help/prop_tgt/AUTOMOC_MACRO_NAMES.rst +++ b/Help/prop_tgt/AUTOMOC_MACRO_NAMES.rst @@ -25,8 +25,8 @@ with Qt. Example ^^^^^^^ -In this case the the ``Q_OBJECT`` macro is hidden inside an other macro -called ``CUSTOM_MACRO``. To let CMake know that source files, that contain -``CUSTOM_MACRO``, need to be ``moc`` processed, we call:: +In this case the ``Q_OBJECT`` macro is hidden inside another macro +called ``CUSTOM_MACRO``. To let CMake know that source files that contain +``CUSTOM_MACRO`` need to be ``moc`` processed, we call:: set_property(TARGET tgt APPEND PROPERTY AUTOMOC_MACRO_NAMES "CUSTOM_MACRO") diff --git a/Help/prop_tgt/COMMON_LANGUAGE_RUNTIME.rst b/Help/prop_tgt/COMMON_LANGUAGE_RUNTIME.rst new file mode 100644 index 0000000..28517e6 --- /dev/null +++ b/Help/prop_tgt/COMMON_LANGUAGE_RUNTIME.rst @@ -0,0 +1,19 @@ +COMMON_LANGUAGE_RUNTIME +----------------------- + +By setting this target property, the target is configured to build with +``C++/CLI`` support. + +The Visual Studio generator defines the ``clr`` parameter depending on +the value of ``COMMON_LANGUAGE_RUNTIME``: + +* property not set: native C++ (i.e. default) +* property set but empty: mixed unmanaged/managed C++ +* property set to any non empty value: managed C++ + +Supported values: ``""``, ``"pure"``, ``"safe"`` + +This property is only evaluated :ref:`Visual Studio Generators` for +VS 2010 and above. + +See also :prop_tgt:`IMPORTED_COMMON_LANGUAGE_RUNTIME` diff --git a/Help/prop_tgt/CXX_STANDARD.rst b/Help/prop_tgt/CXX_STANDARD.rst index 0762033..ccc0147 100644 --- a/Help/prop_tgt/CXX_STANDARD.rst +++ b/Help/prop_tgt/CXX_STANDARD.rst @@ -9,7 +9,7 @@ flag such as ``-std=gnu++11`` to the compile line. For compilers that have no notion of a standard level, such as Microsoft Visual C++ before 2015 Update 3, this has no effect. -Supported values are ``98``, ``11``, ``14``, and ``17``. +Supported values are ``98``, ``11``, ``14``, ``17``, and ``20``. If the value requested does not result in a compile flag being added for the compiler in use, a previous standard flag will be added instead. This diff --git a/Help/prop_tgt/DEPLOYMENT_REMOTE_DIRECTORY.rst b/Help/prop_tgt/DEPLOYMENT_REMOTE_DIRECTORY.rst index 1ff5bf0..368768a 100644 --- a/Help/prop_tgt/DEPLOYMENT_REMOTE_DIRECTORY.rst +++ b/Help/prop_tgt/DEPLOYMENT_REMOTE_DIRECTORY.rst @@ -3,8 +3,8 @@ DEPLOYMENT_REMOTE_DIRECTORY Set the WinCE project ``RemoteDirectory`` in ``DeploymentTool`` and ``RemoteExecutable`` in ``DebuggerTool`` in ``.vcproj`` files generated -by the :generator:`Visual Studio 9 2008` and :generator:`Visual Studio 8 2005` -generators. This is useful when you want to debug on remote WinCE device. +by the :generator:`Visual Studio 9 2008` generator. +This is useful when you want to debug on remote WinCE device. For example: .. code-block:: cmake diff --git a/Help/prop_tgt/EXPORT_PROPERTIES.rst b/Help/prop_tgt/EXPORT_PROPERTIES.rst new file mode 100644 index 0000000..bcf47a6 --- /dev/null +++ b/Help/prop_tgt/EXPORT_PROPERTIES.rst @@ -0,0 +1,14 @@ +EXPORT_PROPERTIES +----------------- + +List additional properties to export for a target. + +This property contains a list of property names that should be exported by +the :command:`install(EXPORT)` and :command:`export` commands. By default +only a limited number of properties are exported. This property can be used +to additionally export other properties as well. + +Properties starting with ``INTERFACE_`` or ``IMPORTED_`` are not allowed as +they are reserved for internal CMake use. + +Properties containing generator expressions are also not allowed. diff --git a/Help/prop_tgt/FOLDER.rst b/Help/prop_tgt/FOLDER.rst index bfe4e8e..0121125 100644 --- a/Help/prop_tgt/FOLDER.rst +++ b/Help/prop_tgt/FOLDER.rst @@ -8,3 +8,6 @@ IDEs like Visual Studio. Targets with the same FOLDER property value will appear next to each other in a folder of that name. To nest folders, use FOLDER values such as 'GUI/Dialogs' with '/' characters separating folder levels. + +This property is initialized by the value of the variable +:variable:`CMAKE_FOLDER` if it is set when a target is created. diff --git a/Help/prop_tgt/IMPORTED_COMMON_LANGUAGE_RUNTIME.rst b/Help/prop_tgt/IMPORTED_COMMON_LANGUAGE_RUNTIME.rst new file mode 100644 index 0000000..99e3bc4 --- /dev/null +++ b/Help/prop_tgt/IMPORTED_COMMON_LANGUAGE_RUNTIME.rst @@ -0,0 +1,8 @@ +IMPORTED_COMMON_LANGUAGE_RUNTIME +-------------------------------- + +Property to define if the target uses ``C++/CLI``. + +Ignored for non-imported targets. + +See also the :prop_tgt:`COMMON_LANGUAGE_RUNTIME` target property. diff --git a/Help/prop_tgt/INSTALL_NAME_DIR.rst b/Help/prop_tgt/INSTALL_NAME_DIR.rst index a67ec15..34348bb 100644 --- a/Help/prop_tgt/INSTALL_NAME_DIR.rst +++ b/Help/prop_tgt/INSTALL_NAME_DIR.rst @@ -6,3 +6,7 @@ Mac OSX directory name for installed targets. INSTALL_NAME_DIR is a string specifying the directory portion of the "install_name" field of shared libraries on Mac OSX to use in the installed targets. + +This property is initialized by the value of the variable +:variable:`CMAKE_INSTALL_NAME_DIR` if it is set when a target is +created. diff --git a/Help/prop_tgt/VS_DEBUGGER_COMMAND.rst b/Help/prop_tgt/VS_DEBUGGER_COMMAND.rst new file mode 100644 index 0000000..f898750 --- /dev/null +++ b/Help/prop_tgt/VS_DEBUGGER_COMMAND.rst @@ -0,0 +1,9 @@ +VS_DEBUGGER_COMMAND +------------------- + +Sets the local debugger command for Visual Studio C++ targets. +This is defined in ``<LocalDebuggerCommand>`` in the Visual Studio +project file. + +This property only works for Visual Studio 2010 and above; +it is ignored on other generators. diff --git a/Help/prop_tgt/VS_DEBUGGER_WORKING_DIRECTORY.rst b/Help/prop_tgt/VS_DEBUGGER_WORKING_DIRECTORY.rst index 0af85cb..fb0389e 100644 --- a/Help/prop_tgt/VS_DEBUGGER_WORKING_DIRECTORY.rst +++ b/Help/prop_tgt/VS_DEBUGGER_WORKING_DIRECTORY.rst @@ -4,3 +4,6 @@ VS_DEBUGGER_WORKING_DIRECTORY Sets the local debugger working directory for Visual Studio C++ targets. This is defined in ``<LocalDebuggerWorkingDirectory>`` in the Visual Studio project file. + +This property only works for Visual Studio 2010 and above; +it is ignored on other generators. diff --git a/Help/release/dev/0-sample-topic.rst b/Help/release/dev/0-sample-topic.rst new file mode 100644 index 0000000..e4cc01e --- /dev/null +++ b/Help/release/dev/0-sample-topic.rst @@ -0,0 +1,7 @@ +0-sample-topic +-------------- + +* This is a sample release note for the change in a topic. + Developers should add similar notes for each topic branch + making a noteworthy change. Each document should be named + and titled to match the topic name to avoid merge conflicts. diff --git a/Help/release/dev/CheckIncludeFile-required-libs.rst b/Help/release/dev/CheckIncludeFile-required-libs.rst new file mode 100644 index 0000000..6fb5c40 --- /dev/null +++ b/Help/release/dev/CheckIncludeFile-required-libs.rst @@ -0,0 +1,14 @@ +CheckIncludeFile-required-libs +------------------------------ + +* The :module:`CheckIncludeFile` module ``check_include_file`` macro + learned to honor the ``CMAKE_REQUIRED_LIBRARIES`` variable. + See policy :policy:`CMP0075`. + +* The :module:`CheckIncludeFileCXX` module ``check_include_file_cxx`` macro + learned to honor the ``CMAKE_REQUIRED_LIBRARIES`` variable. + See policy :policy:`CMP0075`. + +* The :module:`CheckIncludeFiles` module ``check_include_files`` macro + learned to honor the ``CMAKE_REQUIRED_LIBRARIES`` variable. + See policy :policy:`CMP0075`. diff --git a/Help/release/dev/FindJPEG-imported-targets.rst b/Help/release/dev/FindJPEG-imported-targets.rst new file mode 100644 index 0000000..32cf2f6 --- /dev/null +++ b/Help/release/dev/FindJPEG-imported-targets.rst @@ -0,0 +1,4 @@ +FindJPEG-imported-targets +------------------------- + +* The :module:`FindJPEG` module now provides imported targets. diff --git a/Help/release/dev/FindPython-new-implementation.rst b/Help/release/dev/FindPython-new-implementation.rst new file mode 100644 index 0000000..22051d0 --- /dev/null +++ b/Help/release/dev/FindPython-new-implementation.rst @@ -0,0 +1,5 @@ +FindPython(2|3) +--------------- + +* The new :module:`FindPython3` and :module:`FindPython2` modules, as well as + :module:`FindPython`, provide a new way to locate python environments. diff --git a/Help/release/dev/UseSWIG-Multiple-Behaviors.rst b/Help/release/dev/UseSWIG-Multiple-Behaviors.rst new file mode 100644 index 0000000..043ba50 --- /dev/null +++ b/Help/release/dev/UseSWIG-Multiple-Behaviors.rst @@ -0,0 +1,6 @@ +UseSWIG-multiple-behaviors +-------------------------- + +* The :module:`UseSWIG` module learned to manage multiple behaviors through + ``UseSWIG_MODULE_VERSION`` variable to ensure legacy support as well as more + robust handling of ``SWIG`` advanced features (like ``%template``). diff --git a/Help/release/dev/UseSWIG-fix-library-prefix.rst b/Help/release/dev/UseSWIG-fix-library-prefix.rst new file mode 100644 index 0000000..7ff0f49 --- /dev/null +++ b/Help/release/dev/UseSWIG-fix-library-prefix.rst @@ -0,0 +1,6 @@ +UseSWIG-fix-library-prefix +-------------------------- + +* The :module:`UseSWIG` module :command:`swig_add_library` command + (and legacy ``swig_add_module`` command) now set the prefix of + Java modules to ``""`` for MINGW, MSYS, and CYGWIN environments. diff --git a/Help/release/dev/UseSWIG-modernize-module.rst b/Help/release/dev/UseSWIG-modernize-module.rst new file mode 100644 index 0000000..925c119 --- /dev/null +++ b/Help/release/dev/UseSWIG-modernize-module.rst @@ -0,0 +1,6 @@ +UseSWIG-modernize-module +------------------------ + +* The :module:`UseSWIG` gained a whole refresh and is now more consistent with + standard CMake commands to generate libraries and is fully configurable through + properties. diff --git a/Help/release/dev/avoid-LIB_DEPENDS.rst b/Help/release/dev/avoid-LIB_DEPENDS.rst new file mode 100644 index 0000000..b89d8f9 --- /dev/null +++ b/Help/release/dev/avoid-LIB_DEPENDS.rst @@ -0,0 +1,5 @@ +avoid-LIB_DEPENDS +----------------- + +* CMake no longer produces ``<tgt>_LIB_DEPENDS`` cache entries + for library targets. See policy :policy:`CMP0073`. diff --git a/Help/release/dev/cmake-install-doc.rst b/Help/release/dev/cmake-install-doc.rst new file mode 100644 index 0000000..028aa43 --- /dev/null +++ b/Help/release/dev/cmake-install-doc.rst @@ -0,0 +1,7 @@ +cmake-install-doc +----------------- + +* The existence and functionality of the file + ``${CMAKE_BINARY_DIR}/cmake_install.cmake`` has now been documented in the + :command:`install` documentation so that external packaging software can take + advantage of CPack-style component installs. diff --git a/Help/release/dev/command-add_compile_definitions.rst b/Help/release/dev/command-add_compile_definitions.rst new file mode 100644 index 0000000..504481f --- /dev/null +++ b/Help/release/dev/command-add_compile_definitions.rst @@ -0,0 +1,5 @@ +command-add_compile_definitions +------------------------------- + +* The :command:`add_compile_definitions` command was added to set preprocessor + definitions at directory level. This supersedes :command:`add_definitions`. diff --git a/Help/release/dev/compile-options-shell.rst b/Help/release/dev/compile-options-shell.rst new file mode 100644 index 0000000..3f83e0c --- /dev/null +++ b/Help/release/dev/compile-options-shell.rst @@ -0,0 +1,6 @@ +compile-options-shell +--------------------- + +* :command:`target_compile_options` and :command:`add_compile_options` + commands gained a ``SHELL:`` prefix to specify a group of related + options using shell-like quoting. diff --git a/Help/release/dev/ctest-affinity.rst b/Help/release/dev/ctest-affinity.rst new file mode 100644 index 0000000..f4f72a5 --- /dev/null +++ b/Help/release/dev/ctest-affinity.rst @@ -0,0 +1,6 @@ +ctest-affinity +-------------- + +* A :prop_test:`PROCESSOR_AFFINITY` test property was added to request + that CTest run a test with CPU affinity for a set of processors + disjoint from other concurrently running tests with the property set. diff --git a/Help/release/dev/curl-target.rst b/Help/release/dev/curl-target.rst new file mode 100644 index 0000000..dc65f64 --- /dev/null +++ b/Help/release/dev/curl-target.rst @@ -0,0 +1,4 @@ +curl-target +----------- + +* The :module:`FindCURL` module now provides imported targets. diff --git a/Help/release/dev/directory-property-TESTS.rst b/Help/release/dev/directory-property-TESTS.rst new file mode 100644 index 0000000..9de2531 --- /dev/null +++ b/Help/release/dev/directory-property-TESTS.rst @@ -0,0 +1,5 @@ +directory-property-TESTS +------------------------ + +* The :prop_dir:`TESTS` directory property was added to hold the list of tests defined by + command :command:`add_test`. diff --git a/Help/release/dev/export-properties.rst b/Help/release/dev/export-properties.rst new file mode 100644 index 0000000..9b20799 --- /dev/null +++ b/Help/release/dev/export-properties.rst @@ -0,0 +1,6 @@ +EXPORT_PROPERTIES +----------------- + +* An :prop_tgt:`EXPORT_PROPERTIES` target property was added to specify a + custom list of target properties to include in targets exported by the + :command:`install(EXPORT)` and :command:`export` commands. diff --git a/Help/release/dev/features-c++20.rst b/Help/release/dev/features-c++20.rst new file mode 100644 index 0000000..f7d050b --- /dev/null +++ b/Help/release/dev/features-c++20.rst @@ -0,0 +1,6 @@ +features-c++20 +-------------- + +* The :manual:`Compile Features <cmake-compile-features(7)>` functionality + is now aware of C++ 20. No specific features are yet enumerated besides + the ``cxx_std_20`` meta-feature. diff --git a/Help/release/dev/features-msvc-c.rst b/Help/release/dev/features-msvc-c.rst new file mode 100644 index 0000000..0c55544 --- /dev/null +++ b/Help/release/dev/features-msvc-c.rst @@ -0,0 +1,5 @@ +features-msvc-c +--------------- + +* The :manual:`Compile Features <cmake-compile-features(7)>` functionality + is now aware of the availability of C features in MSVC since VS 2010. diff --git a/Help/release/dev/file_cmd_touch.rst b/Help/release/dev/file_cmd_touch.rst new file mode 100644 index 0000000..b1b1e3c --- /dev/null +++ b/Help/release/dev/file_cmd_touch.rst @@ -0,0 +1,6 @@ +file_cmd_touch +------------------ + +* The :command:`file(TOUCH)` and :command:`file(TOUCH_NOCREATE)` commands + were added to expose TOUCH functionality without having to use CMake's + command-line tool mode with :command:`execute_process`. diff --git a/Help/release/dev/find-package_root-restore.rst b/Help/release/dev/find-package_root-restore.rst new file mode 100644 index 0000000..3e6b69e --- /dev/null +++ b/Help/release/dev/find-package_root-restore.rst @@ -0,0 +1,8 @@ +find-package_root-restore +------------------------- + +* The :command:`find_package` command now searches a prefix specified by + a ``PackageName_ROOT`` CMake or environment variable. Package roots are + maintained as a stack so nested calls to all ``find_*`` commands inside + find modules also search the roots as prefixes. + See policy :policy:`CMP0074`. diff --git a/Help/release/dev/fortran-submodule-depends.rst b/Help/release/dev/fortran-submodule-depends.rst new file mode 100644 index 0000000..b795a84 --- /dev/null +++ b/Help/release/dev/fortran-submodule-depends.rst @@ -0,0 +1,7 @@ +fortran-submodule-depends +------------------------- + +* Fortran dependency scanning now supports dependencies implied by + `Fortran Submodules`_. + +.. _`Fortran Submodules`: http://fortranwiki.org/fortran/show/Submodules diff --git a/Help/release/dev/genex-GENEX_EVAL.rst b/Help/release/dev/genex-GENEX_EVAL.rst new file mode 100644 index 0000000..0869c93 --- /dev/null +++ b/Help/release/dev/genex-GENEX_EVAL.rst @@ -0,0 +1,7 @@ +genex-GENEX_EVAL +---------------- + +* New ``$<GENEX_EVAL:...>`` and ``$<TARGET_GENEX_EVAL:target,...>`` + :manual:`generator expression <cmake-generator-expressions(7)>` + had been added to enable consumption of generator expressions whose + evaluation results itself in generator expressions. diff --git a/Help/release/dev/genex-IN_LIST-logical-operator.rst b/Help/release/dev/genex-IN_LIST-logical-operator.rst new file mode 100644 index 0000000..28fa7ce --- /dev/null +++ b/Help/release/dev/genex-IN_LIST-logical-operator.rst @@ -0,0 +1,5 @@ +genex-IN_LIST-logical-operator +------------------------------ + +* A new ``$<IN_LIST:...>`` :manual:`generator expression <cmake-generator-expressions(7)>` + has been added. diff --git a/Help/release/dev/genex-TARGET_EXISTS.rst b/Help/release/dev/genex-TARGET_EXISTS.rst new file mode 100644 index 0000000..f305522 --- /dev/null +++ b/Help/release/dev/genex-TARGET_EXISTS.rst @@ -0,0 +1,6 @@ +genex-TARGET_EXISTS +------------------- + +* A new ``$<TARGET_EXISTS:...>`` + :manual:`generator expression <cmake-generator-expressions(7)>` + has been added. diff --git a/Help/release/dev/genex-TARGET_NAME_IF_EXISTS.rst b/Help/release/dev/genex-TARGET_NAME_IF_EXISTS.rst new file mode 100644 index 0000000..416e812 --- /dev/null +++ b/Help/release/dev/genex-TARGET_NAME_IF_EXISTS.rst @@ -0,0 +1,6 @@ +genex-TARGET_NAME_IF_EXISTS +--------------------------- + +* A new ``$<TARGET_NAME_IF_EXISTS:...>`` + :manual:`generator expression <cmake-generator-expressions(7)>` + has been added. diff --git a/Help/release/dev/glob_configure_depends.rst b/Help/release/dev/glob_configure_depends.rst new file mode 100644 index 0000000..147e44a --- /dev/null +++ b/Help/release/dev/glob_configure_depends.rst @@ -0,0 +1,6 @@ +glob_configure_depends +---------------------- + +* The :command:`file(GLOB)` and :command:`file(GLOB_RECURSE)` commands + learned a new flag ``CONFIGURE_DEPENDS`` which enables expression of + build system dependency on globbed directory's contents. diff --git a/Help/release/dev/libxml2-target.rst b/Help/release/dev/libxml2-target.rst new file mode 100644 index 0000000..f9933d7 --- /dev/null +++ b/Help/release/dev/libxml2-target.rst @@ -0,0 +1,4 @@ +libxml2-target +-------------- + +* The :module:`FindLibXml2` module now provides imported targets. diff --git a/Help/release/dev/list-join.rst b/Help/release/dev/list-join.rst new file mode 100644 index 0000000..0756b60 --- /dev/null +++ b/Help/release/dev/list-join.rst @@ -0,0 +1,5 @@ +list-join +--------- + +* The :command:`list` command learned a ``JOIN`` sub-command + to concatenate list's elements separated by a glue string. diff --git a/Help/release/dev/list-sublist.rst b/Help/release/dev/list-sublist.rst new file mode 100644 index 0000000..7ad225b --- /dev/null +++ b/Help/release/dev/list-sublist.rst @@ -0,0 +1,5 @@ +list-sublist +------------ + +* The :command:`list` command learned a ``SUBLIST`` sub-command + to get a sublist of the list. diff --git a/Help/release/dev/list-transform.rst b/Help/release/dev/list-transform.rst new file mode 100644 index 0000000..4a6dacc --- /dev/null +++ b/Help/release/dev/list-transform.rst @@ -0,0 +1,5 @@ +list-transform +-------------- + +* The :command:`list` command learned a ``TRANSFORM`` sub-command + to apply various string transformation to list's elements. diff --git a/Help/release/dev/managed-target-property.rst b/Help/release/dev/managed-target-property.rst new file mode 100644 index 0000000..b961512 --- /dev/null +++ b/Help/release/dev/managed-target-property.rst @@ -0,0 +1,8 @@ +target property COMMON_LANGUAGE_RUNTIME +--------------------------------------- + +* The :prop_tgt:`COMMON_LANGUAGE_RUNTIME` target property was introduced + to configure the use of managed C++ for :ref:`Visual Studio Generators` + for VS 2010 and above. +* To support ``C++/CLI`` for imported targets, the + :prop_tgt:`IMPORTED_COMMON_LANGUAGE_RUNTIME` was added. diff --git a/Help/release/dev/msvc-toolset-version-variable.rst b/Help/release/dev/msvc-toolset-version-variable.rst new file mode 100644 index 0000000..28ba0b9 --- /dev/null +++ b/Help/release/dev/msvc-toolset-version-variable.rst @@ -0,0 +1,6 @@ +msvc-toolset-version-variable +----------------------------- + +* A :variable:`MSVC_TOOLSET_VERSION` variable was added to provide the + MSVC toolset version associated with the current MSVC compiler version + in :variable:`MSVC_VERSION`. diff --git a/Help/release/dev/object-library-linking.rst b/Help/release/dev/object-library-linking.rst new file mode 100644 index 0000000..131430f --- /dev/null +++ b/Help/release/dev/object-library-linking.rst @@ -0,0 +1,6 @@ +object-library-linking +---------------------- + +* The :command:`target_link_libraries` command now supports + :ref:`Object Libraries`. Linking to an object library uses its object + files in direct dependents and also propagates usage requirements. diff --git a/Help/release/dev/policy-version-range.rst b/Help/release/dev/policy-version-range.rst new file mode 100644 index 0000000..b2d1f17 --- /dev/null +++ b/Help/release/dev/policy-version-range.rst @@ -0,0 +1,8 @@ +policy-version-range +-------------------- + +* The :command:`cmake_minimum_required` and :command:`cmake_policy(VERSION)` + commands now accept a version range using the form ``<min>[...<max>]``. + The ``<min>`` version is required but policies are set based on the + ``<max>`` version. This allows projects to specify a range of versions + for which they have been updated and avoid explicit policy settings. diff --git a/Help/release/dev/project-homepage.rst b/Help/release/dev/project-homepage.rst new file mode 100644 index 0000000..25799a4 --- /dev/null +++ b/Help/release/dev/project-homepage.rst @@ -0,0 +1,7 @@ +project-homepage +---------------- + +* The :command:`project` command learned an optional ``HOMEPAGE_URL`` + parameter which has the effect of setting variables like + :variable:`PROJECT_HOMEPAGE_URL`, :variable:`<PROJECT-NAME>_HOMEPAGE_URL` + and :variable:`CMAKE_PROJECT_HOMEPAGE_URL`. diff --git a/Help/release/dev/remove-vs8-generator.rst b/Help/release/dev/remove-vs8-generator.rst new file mode 100644 index 0000000..c39529a --- /dev/null +++ b/Help/release/dev/remove-vs8-generator.rst @@ -0,0 +1,4 @@ +remove-vs8-generator +-------------------- + +* The :generator:`Visual Studio 8 2005` generator has been removed. diff --git a/Help/release/dev/reorder-sys-includes.rst b/Help/release/dev/reorder-sys-includes.rst new file mode 100644 index 0000000..14d520f --- /dev/null +++ b/Help/release/dev/reorder-sys-includes.rst @@ -0,0 +1,7 @@ +reorder-sys-includes +-------------------- + +* Include directories marked as ``SYSTEM`` are now moved after non-system + directories. The ``-isystem`` flag does this automatically, so moving + them explicitly to the end makes the behavior consistent on compilers + that do not have any ``-isystem`` flag. diff --git a/Help/release/dev/string-join.rst b/Help/release/dev/string-join.rst new file mode 100644 index 0000000..5cca711 --- /dev/null +++ b/Help/release/dev/string-join.rst @@ -0,0 +1,5 @@ +string-join +----------- + +* The :command:`string` command learned a ``JOIN`` sub-command + to concatenate input strings separated by a glue string. diff --git a/Help/release/dev/variable-CMAKE_FOLDER.rst b/Help/release/dev/variable-CMAKE_FOLDER.rst new file mode 100644 index 0000000..8064edd --- /dev/null +++ b/Help/release/dev/variable-CMAKE_FOLDER.rst @@ -0,0 +1,5 @@ +variable-CMAKE_FOLDER +--------------------- + +* The :variable:`CMAKE_FOLDER` variable was added to initialize the + :prop_tgt:`FOLDER` property on all targets. diff --git a/Help/release/dev/variable-CMAKE_SUPPRESS_REGENERATION.rst b/Help/release/dev/variable-CMAKE_SUPPRESS_REGENERATION.rst new file mode 100644 index 0000000..dfe678c --- /dev/null +++ b/Help/release/dev/variable-CMAKE_SUPPRESS_REGENERATION.rst @@ -0,0 +1,6 @@ +variable-CMAKE_SUPPRESS_REGENERATION +------------------------------------ + +* The :variable:`CMAKE_SUPPRESS_REGENERATION` variable was extended to support the + :generator:`Ninja` and :ref:`Makefile Generators`. +* The :variable:`CMAKE_SUPPRESS_REGENERATION` variable is now documented. diff --git a/Help/release/dev/vs-debugger-config.rst b/Help/release/dev/vs-debugger-config.rst new file mode 100644 index 0000000..bddae0c --- /dev/null +++ b/Help/release/dev/vs-debugger-config.rst @@ -0,0 +1,6 @@ +vs-debugger-configuration +------------------------- + +* For the :ref:`Visual Studio Generators` for VS 2010 and above + the debugging command line can be set using a new + :prop_tgt:`VS_DEBUGGER_COMMAND` target property. diff --git a/Help/release/dev/vs-hlsl-object-name.rst b/Help/release/dev/vs-hlsl-object-name.rst new file mode 100644 index 0000000..625e5ee --- /dev/null +++ b/Help/release/dev/vs-hlsl-object-name.rst @@ -0,0 +1,6 @@ +vs-hlsl-object-name +------------------- + +* HLSL source file property :prop_sf:`VS_SHADER_OBJECT_FILE_NAME` has been + added to the :ref:`Visual Studio Generators` for VS 2010 and above. + The property specifies the file name of the compiled shader object. diff --git a/Help/release/dev/vs-sdk-dirs.rst b/Help/release/dev/vs-sdk-dirs.rst new file mode 100644 index 0000000..3377775 --- /dev/null +++ b/Help/release/dev/vs-sdk-dirs.rst @@ -0,0 +1,15 @@ +vs-sdk-dirs +----------- + +* ``CMAKE_VS_SDK_*_DIRECTORIES`` variables were defined to tell + :ref:`Visual Studio Generators` for VS 2010 and above how to populate + fields in ``.vcxproj`` files that specify SDK directories. The + variables are: + + - :variable:`CMAKE_VS_SDK_EXCLUDE_DIRECTORIES` + - :variable:`CMAKE_VS_SDK_EXECUTABLE_DIRECTORIES` + - :variable:`CMAKE_VS_SDK_INCLUDE_DIRECTORIES` + - :variable:`CMAKE_VS_SDK_LIBRARY_DIRECTORIES` + - :variable:`CMAKE_VS_SDK_LIBRARY_WINRT_DIRECTORIES` + - :variable:`CMAKE_VS_SDK_REFERENCE_DIRECTORIES` + - :variable:`CMAKE_VS_SDK_SOURCE_DIRECTORIES` diff --git a/Help/release/dev/wcdh-raw-features.rst b/Help/release/dev/wcdh-raw-features.rst new file mode 100644 index 0000000..bdc7b62 --- /dev/null +++ b/Help/release/dev/wcdh-raw-features.rst @@ -0,0 +1,6 @@ +wcdh-raw-features +----------------- + +* The :module:`WriteCompilerDetectionHeader` module now supports the + ``BARE_FEATURES`` argument which allows to add a compatibility define for + the exact keyword of a new language feature. diff --git a/Help/release/index.rst b/Help/release/index.rst index 7375faf..552922e 100644 --- a/Help/release/index.rst +++ b/Help/release/index.rst @@ -7,6 +7,8 @@ CMake Release Notes This file should include the adjacent "dev.txt" file in development versions but not in release versions. +.. include:: dev.txt + Releases ======== diff --git a/Help/variable/CMAKE_CFG_INTDIR.rst b/Help/variable/CMAKE_CFG_INTDIR.rst index c36599a..af82f75 100644 --- a/Help/variable/CMAKE_CFG_INTDIR.rst +++ b/Help/variable/CMAKE_CFG_INTDIR.rst @@ -12,7 +12,7 @@ Example values: :: - $(ConfigurationName) = Visual Studio 8, 9 + $(ConfigurationName) = Visual Studio 9 $(Configuration) = Visual Studio 10 $(CONFIGURATION) = Xcode . = Make-based tools diff --git a/Help/variable/CMAKE_FOLDER.rst b/Help/variable/CMAKE_FOLDER.rst new file mode 100644 index 0000000..50a2b88 --- /dev/null +++ b/Help/variable/CMAKE_FOLDER.rst @@ -0,0 +1,7 @@ +CMAKE_FOLDER +------------ + +Set the folder name. Use to organize targets in an IDE. + +This variable is used to initialize the :prop_tgt:`FOLDER` property on all the +targets. See that target property for additional information. diff --git a/Help/variable/CMAKE_INSTALL_PREFIX.rst b/Help/variable/CMAKE_INSTALL_PREFIX.rst index 7bd87d6..02ba645 100644 --- a/Help/variable/CMAKE_INSTALL_PREFIX.rst +++ b/Help/variable/CMAKE_INSTALL_PREFIX.rst @@ -10,21 +10,7 @@ See :variable:`CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT` for how a project might choose its own default. On UNIX one can use the ``DESTDIR`` mechanism in order to relocate the -whole installation. ``DESTDIR`` means DESTination DIRectory. It is -commonly used by makefile users in order to install software at -non-default location. It is usually invoked like this: - -:: - - make DESTDIR=/home/john install - -which will install the concerned software using the installation -prefix, e.g. ``/usr/local`` prepended with the ``DESTDIR`` value which -finally gives ``/home/john/usr/local``. - -WARNING: ``DESTDIR`` may not be used on Windows because installation -prefix usually contains a drive letter like in ``C:/Program Files`` -which cannot be prepended with some other prefix. +whole installation. See :envvar:`DESTDIR` for more information. The installation prefix is also added to :variable:`CMAKE_SYSTEM_PREFIX_PATH` so that :command:`find_package`, :command:`find_program`, diff --git a/Help/variable/CMAKE_LANG_CLANG_TIDY.rst b/Help/variable/CMAKE_LANG_CLANG_TIDY.rst index 492c12c..d1fccbb 100644 --- a/Help/variable/CMAKE_LANG_CLANG_TIDY.rst +++ b/Help/variable/CMAKE_LANG_CLANG_TIDY.rst @@ -1,6 +1,13 @@ CMAKE_<LANG>_CLANG_TIDY ----------------------- -Default value for :prop_tgt:`<LANG>_CLANG_TIDY` target property. +Default value for :prop_tgt:`<LANG>_CLANG_TIDY` target property +when ``<LANG>`` is ``C`` or ``CXX``. + This variable is used to initialize the property on each target as it is -created. This is done only when ``<LANG>`` is ``C`` or ``CXX``. +created. For example: + +.. code-block:: cmake + + set(CMAKE_CXX_CLANG_TIDY clang-tidy checks=-*,readability-*) + add_executable(foo foo.cxx) diff --git a/Help/variable/CMAKE_LANG_FLAGS.rst b/Help/variable/CMAKE_LANG_FLAGS.rst index c57d92c..14b2694 100644 --- a/Help/variable/CMAKE_LANG_FLAGS.rst +++ b/Help/variable/CMAKE_LANG_FLAGS.rst @@ -4,3 +4,14 @@ CMAKE_<LANG>_FLAGS Flags for all build types. ``<LANG>`` flags used regardless of the value of :variable:`CMAKE_BUILD_TYPE`. + +This is initialized for each language from environment variables: + +* ``CMAKE_C_FLAGS``: + Initialized by the :envvar:`CFLAGS` environment variable. +* ``CMAKE_CXX_FLAGS``: + Initialized by the :envvar:`CXXFLAGS` environment variable. +* ``CMAKE_CUDA_FLAGS``: + Initialized by the :envvar:`CUDAFLAGS` environment variable. +* ``CMAKE_Fortran_FLAGS``: + Initialized by the :envvar:`FFLAGS` environment variable. diff --git a/Help/variable/CMAKE_LANG_IMPLICIT_LINK_DIRECTORIES.rst b/Help/variable/CMAKE_LANG_IMPLICIT_LINK_DIRECTORIES.rst index a0bd830..e9e04be 100644 --- a/Help/variable/CMAKE_LANG_IMPLICIT_LINK_DIRECTORIES.rst +++ b/Help/variable/CMAKE_LANG_IMPLICIT_LINK_DIRECTORIES.rst @@ -9,9 +9,12 @@ These paths are implicit linker search directories for the compiler's language. CMake automatically detects these directories for each language and reports the results in this variable. -When a library in one of these directories is given by full path to -:command:`target_link_libraries` CMake will generate the ``-l<name>`` form on -link lines to ensure the linker searches its implicit directories for the -library. Note that some toolchains read implicit directories from an -environment variable such as ``LIBRARY_PATH`` so keep its value consistent -when operating in a given build tree. +Some toolchains read implicit directories from an environment variable such as +``LIBRARY_PATH``. If using such an environment variable, keep its value +consistent when operating in a given build tree because CMake saves the value +detected when first creating a build tree. + +If policy :policy:`CMP0060` is not set to ``NEW``, then when a library in one +of these directories is given by full path to :command:`target_link_libraries` +CMake will generate the ``-l<name>`` form on link lines for historical +purposes. diff --git a/Help/variable/CMAKE_MINIMUM_REQUIRED_VERSION.rst b/Help/variable/CMAKE_MINIMUM_REQUIRED_VERSION.rst index 5a51634..f466468 100644 --- a/Help/variable/CMAKE_MINIMUM_REQUIRED_VERSION.rst +++ b/Help/variable/CMAKE_MINIMUM_REQUIRED_VERSION.rst @@ -1,7 +1,5 @@ CMAKE_MINIMUM_REQUIRED_VERSION ------------------------------ -Version specified to :command:`cmake_minimum_required` command - -Variable containing the ``VERSION`` component specified in the -:command:`cmake_minimum_required` command. +The ``<min>`` version of CMake given to the most recent call to the +:command:`cmake_minimum_required(VERSION)` command. diff --git a/Help/variable/CMAKE_MODULE_PATH.rst b/Help/variable/CMAKE_MODULE_PATH.rst index 5ea7cbb..6490054 100644 --- a/Help/variable/CMAKE_MODULE_PATH.rst +++ b/Help/variable/CMAKE_MODULE_PATH.rst @@ -2,6 +2,6 @@ CMAKE_MODULE_PATH ----------------- :ref:`;-list <CMake Language Lists>` of directories specifying a search path -for CMake modules to be loaded by the the :command:`include` or +for CMake modules to be loaded by the :command:`include` or :command:`find_package` commands before checking the default modules that come with CMake. By default it is empty, it is intended to be set by the project. diff --git a/Help/variable/CMAKE_PROJECT_DESCRIPTION.rst b/Help/variable/CMAKE_PROJECT_DESCRIPTION.rst index f1911ec..51b0592 100644 --- a/Help/variable/CMAKE_PROJECT_DESCRIPTION.rst +++ b/Help/variable/CMAKE_PROJECT_DESCRIPTION.rst @@ -1,7 +1,35 @@ CMAKE_PROJECT_DESCRIPTION ------------------------- -The description of the current project. +The description of the top level project. -This specifies description of the current project from the closest inherited -:command:`project` command. +This variable holds the description of the project as specified in the top +level CMakeLists.txt file by a :command:`project` command. In the event that +the top level CMakeLists.txt contains multiple :command:`project` calls, +the most recently called one from that top level CMakeLists.txt will determine +the value that ``CMAKE_PROJECT_DESCRIPTION`` contains. For example, consider +the following top level CMakeLists.txt: + +.. code-block:: cmake + + cmake_minimum_required(VERSION 3.0) + project(First DESCRIPTION "I am First") + project(Second DESCRIPTION "I am Second") + add_subdirectory(sub) + project(Third DESCRIPTION "I am Third") + +And ``sub/CMakeLists.txt`` with the following contents: + +.. code-block:: cmake + + project(SubProj DESCRIPTION "I am SubProj") + message("CMAKE_PROJECT_DESCRIPTION = ${CMAKE_PROJECT_DESCRIPTION}") + +The most recently seen :command:`project` command from the top level +CMakeLists.txt would be ``project(Second ...)``, so this will print:: + + CMAKE_PROJECT_DESCRIPTION = I am Second + +To obtain the description from the most recent call to :command:`project` in +the current directory scope or above, see the :variable:`PROJECT_DESCRIPTION` +variable. diff --git a/Help/variable/CMAKE_PROJECT_HOMEPAGE_URL.rst b/Help/variable/CMAKE_PROJECT_HOMEPAGE_URL.rst new file mode 100644 index 0000000..ee0bf7c --- /dev/null +++ b/Help/variable/CMAKE_PROJECT_HOMEPAGE_URL.rst @@ -0,0 +1,35 @@ +CMAKE_PROJECT_HOMEPAGE_URL +-------------------------- + +The homepage URL of the top level project. + +This variable holds the homepage URL of the project as specified in the top +level CMakeLists.txt file by a :command:`project` command. In the event that +the top level CMakeLists.txt contains multiple :command:`project` calls, +the most recently called one from that top level CMakeLists.txt will determine +the value that ``CMAKE_PROJECT_HOMEPAGE_URL`` contains. For example, consider +the following top level CMakeLists.txt: + +.. code-block:: cmake + + cmake_minimum_required(VERSION 3.0) + project(First HOMEPAGE_URL "http://first.example.com") + project(Second HOMEPAGE_URL "http://second.example.com") + add_subdirectory(sub) + project(Third HOMEPAGE_URL "http://third.example.com") + +And ``sub/CMakeLists.txt`` with the following contents: + +.. code-block:: cmake + + project(SubProj HOMEPAGE_URL "http://subproj.example.com") + message("CMAKE_PROJECT_HOMEPAGE_URL = ${CMAKE_PROJECT_HOMEPAGE_URL}") + +The most recently seen :command:`project` command from the top level +CMakeLists.txt would be ``project(Second ...)``, so this will print:: + + CMAKE_PROJECT_HOMEPAGE_URL = http://second.example.com + +To obtain the homepage URL from the most recent call to :command:`project` in +the current directory scope or above, see the :variable:`PROJECT_HOMEPAGE_URL` +variable. diff --git a/Help/variable/CMAKE_PROJECT_NAME.rst b/Help/variable/CMAKE_PROJECT_NAME.rst index 431e9f3..94b8dba 100644 --- a/Help/variable/CMAKE_PROJECT_NAME.rst +++ b/Help/variable/CMAKE_PROJECT_NAME.rst @@ -1,7 +1,35 @@ CMAKE_PROJECT_NAME ------------------ -The name of the current project. +The name of the top level project. -This specifies name of the current project from the closest inherited -:command:`project` command. +This variable holds the name of the project as specified in the top +level CMakeLists.txt file by a :command:`project` command. In the event that +the top level CMakeLists.txt contains multiple :command:`project` calls, +the most recently called one from that top level CMakeLists.txt will determine +the name that ``CMAKE_PROJECT_NAME`` contains. For example, consider +the following top level CMakeLists.txt: + +.. code-block:: cmake + + cmake_minimum_required(VERSION 3.0) + project(First) + project(Second) + add_subdirectory(sub) + project(Third) + +And ``sub/CMakeLists.txt`` with the following contents: + +.. code-block:: cmake + + project(SubProj) + message("CMAKE_PROJECT_NAME = ${CMAKE_PROJECT_NAME}") + +The most recently seen :command:`project` command from the top level +CMakeLists.txt would be ``project(Second)``, so this will print:: + + CMAKE_PROJECT_NAME = Second + +To obtain the name from the most recent call to :command:`project` in +the current directory scope or above, see the :variable:`PROJECT_NAME` +variable. diff --git a/Help/variable/CMAKE_SUPPRESS_REGENERATION.rst b/Help/variable/CMAKE_SUPPRESS_REGENERATION.rst new file mode 100644 index 0000000..ed47e1a --- /dev/null +++ b/Help/variable/CMAKE_SUPPRESS_REGENERATION.rst @@ -0,0 +1,11 @@ +CMAKE_SUPPRESS_REGENERATION +--------------------------- + +If CMAKE_SUPPRESS_REGENERATION is ``OFF``, which is default, then CMake adds a +special target on which all other targets depend that checks the build system +and optionally re-runs CMake to regenerate the build system when the target +specification source changes. + +If this variable evaluates to ``ON`` at the end of the top-level +``CMakeLists.txt`` file, CMake will not add the regeneration target to the +build system or perform any build system checks. diff --git a/Help/variable/CMAKE_VS_DEVENV_COMMAND.rst b/Help/variable/CMAKE_VS_DEVENV_COMMAND.rst index 51b42dd..f109a9e 100644 --- a/Help/variable/CMAKE_VS_DEVENV_COMMAND.rst +++ b/Help/variable/CMAKE_VS_DEVENV_COMMAND.rst @@ -1,7 +1,7 @@ CMAKE_VS_DEVENV_COMMAND ----------------------- -The generators for :generator:`Visual Studio 8 2005` and above set this +The generators for :generator:`Visual Studio 9 2008` and above set this variable to the ``devenv.com`` command installed with the corresponding Visual Studio version. Note that this variable may be empty on Visual Studio Express editions because they do not provide this tool. diff --git a/Help/variable/CMAKE_VS_INTEL_Fortran_PROJECT_VERSION.rst b/Help/variable/CMAKE_VS_INTEL_Fortran_PROJECT_VERSION.rst index 6d196f9..ceedf28 100644 --- a/Help/variable/CMAKE_VS_INTEL_Fortran_PROJECT_VERSION.rst +++ b/Help/variable/CMAKE_VS_INTEL_Fortran_PROJECT_VERSION.rst @@ -1,7 +1,7 @@ CMAKE_VS_INTEL_Fortran_PROJECT_VERSION -------------------------------------- -When generating for :generator:`Visual Studio 8 2005` or greater with the Intel +When generating for :generator:`Visual Studio 9 2008` or greater with the Intel Fortran plugin installed, this specifies the ``.vfproj`` project file format version. This is intended for internal use by CMake and should not be used by project code. diff --git a/Help/variable/CMAKE_VS_SDK_EXCLUDE_DIRECTORIES.rst b/Help/variable/CMAKE_VS_SDK_EXCLUDE_DIRECTORIES.rst new file mode 100644 index 0000000..36c4dcc --- /dev/null +++ b/Help/variable/CMAKE_VS_SDK_EXCLUDE_DIRECTORIES.rst @@ -0,0 +1,4 @@ +CMAKE_VS_SDK_EXCLUDE_DIRECTORIES +-------------------------------- + +This variable allows to override Visual Studio default Exclude Directories. diff --git a/Help/variable/CMAKE_VS_SDK_EXECUTABLE_DIRECTORIES.rst b/Help/variable/CMAKE_VS_SDK_EXECUTABLE_DIRECTORIES.rst new file mode 100644 index 0000000..3ec755b --- /dev/null +++ b/Help/variable/CMAKE_VS_SDK_EXECUTABLE_DIRECTORIES.rst @@ -0,0 +1,4 @@ +CMAKE_VS_SDK_EXECUTABLE_DIRECTORIES +----------------------------------- + +This variable allows to override Visual Studio default Executable Directories. diff --git a/Help/variable/CMAKE_VS_SDK_INCLUDE_DIRECTORIES.rst b/Help/variable/CMAKE_VS_SDK_INCLUDE_DIRECTORIES.rst new file mode 100644 index 0000000..da10bde --- /dev/null +++ b/Help/variable/CMAKE_VS_SDK_INCLUDE_DIRECTORIES.rst @@ -0,0 +1,4 @@ +CMAKE_VS_SDK_INCLUDE_DIRECTORIES +-------------------------------- + +This variable allows to override Visual Studio default Include Directories. diff --git a/Help/variable/CMAKE_VS_SDK_LIBRARY_DIRECTORIES.rst b/Help/variable/CMAKE_VS_SDK_LIBRARY_DIRECTORIES.rst new file mode 100644 index 0000000..b33754a --- /dev/null +++ b/Help/variable/CMAKE_VS_SDK_LIBRARY_DIRECTORIES.rst @@ -0,0 +1,4 @@ +CMAKE_VS_SDK_LIBRARY_DIRECTORIES +-------------------------------- + +This variable allows to override Visual Studio default Library Directories. diff --git a/Help/variable/CMAKE_VS_SDK_LIBRARY_WINRT_DIRECTORIES.rst b/Help/variable/CMAKE_VS_SDK_LIBRARY_WINRT_DIRECTORIES.rst new file mode 100644 index 0000000..b022215 --- /dev/null +++ b/Help/variable/CMAKE_VS_SDK_LIBRARY_WINRT_DIRECTORIES.rst @@ -0,0 +1,5 @@ +CMAKE_VS_SDK_LIBRARY_WINRT_DIRECTORIES +-------------------------------------- + +This variable allows to override Visual Studio default Library WinRT +Directories. diff --git a/Help/variable/CMAKE_VS_SDK_REFERENCE_DIRECTORIES.rst b/Help/variable/CMAKE_VS_SDK_REFERENCE_DIRECTORIES.rst new file mode 100644 index 0000000..c03f0ae --- /dev/null +++ b/Help/variable/CMAKE_VS_SDK_REFERENCE_DIRECTORIES.rst @@ -0,0 +1,4 @@ +CMAKE_VS_SDK_REFERENCE_DIRECTORIES +---------------------------------- + +This variable allows to override Visual Studio default Reference Directories. diff --git a/Help/variable/CMAKE_VS_SDK_SOURCE_DIRECTORIES.rst b/Help/variable/CMAKE_VS_SDK_SOURCE_DIRECTORIES.rst new file mode 100644 index 0000000..0c73f06 --- /dev/null +++ b/Help/variable/CMAKE_VS_SDK_SOURCE_DIRECTORIES.rst @@ -0,0 +1,4 @@ +CMAKE_VS_SDK_SOURCE_DIRECTORIES +------------------------------- + +This variable allows to override Visual Studio default Source Directories. diff --git a/Help/variable/MSVC_TOOLSET_VERSION.rst b/Help/variable/MSVC_TOOLSET_VERSION.rst new file mode 100644 index 0000000..77e1ea9 --- /dev/null +++ b/Help/variable/MSVC_TOOLSET_VERSION.rst @@ -0,0 +1,21 @@ +MSVC_TOOLSET_VERSION +-------------------- + +The toolset version of Microsoft Visual C/C++ being used if any. +If MSVC-like is being used, this variable is set based on the version +of the compiler as given by the :variable:`MSVC_VERSION` variable. + +Known toolset version numbers are:: + + 80 = VS 2005 (8.0) + 90 = VS 2008 (9.0) + 100 = VS 2010 (10.0) + 110 = VS 2012 (11.0) + 120 = VS 2013 (12.0) + 140 = VS 2015 (14.0) + 141 = VS 2017 (15.0) + +Compiler versions newer than those known to CMake will be reported +as the latest known toolset version. + +See also the :variable:`MSVC_VERSION` variable. diff --git a/Help/variable/MSVC_VERSION.rst b/Help/variable/MSVC_VERSION.rst index 5f70c02..4ef43d8 100644 --- a/Help/variable/MSVC_VERSION.rst +++ b/Help/variable/MSVC_VERSION.rst @@ -19,4 +19,5 @@ Known version numbers are:: 1900 = VS 14.0 (v140 toolset) 1910-1919 = VS 15.0 (v141 toolset) -See also the :variable:`CMAKE_<LANG>_COMPILER_VERSION` variable. +See also the :variable:`CMAKE_<LANG>_COMPILER_VERSION` and +:variable:`MSVC_TOOLSET_VERSION` variable. diff --git a/Help/variable/PROJECT-NAME_DESCRIPTION.rst b/Help/variable/PROJECT-NAME_DESCRIPTION.rst new file mode 100644 index 0000000..2b88b1a --- /dev/null +++ b/Help/variable/PROJECT-NAME_DESCRIPTION.rst @@ -0,0 +1,5 @@ +<PROJECT-NAME>_DESCRIPTION +-------------------------- + +Value given to the ``DESCRIPTION`` option of the most recent call to the +:command:`project` command with project name ``<PROJECT-NAME>``, if any. diff --git a/Help/variable/PROJECT-NAME_HOMEPAGE_URL.rst b/Help/variable/PROJECT-NAME_HOMEPAGE_URL.rst new file mode 100644 index 0000000..22cc304 --- /dev/null +++ b/Help/variable/PROJECT-NAME_HOMEPAGE_URL.rst @@ -0,0 +1,5 @@ +<PROJECT-NAME>_HOMEPAGE_URL +--------------------------- + +Value given to the ``HOMEPAGE_URL`` option of the most recent call to the +:command:`project` command with project name ``<PROJECT-NAME>``, if any. diff --git a/Help/variable/PROJECT_DESCRIPTION.rst b/Help/variable/PROJECT_DESCRIPTION.rst index 05ede8f..2833e11 100644 --- a/Help/variable/PROJECT_DESCRIPTION.rst +++ b/Help/variable/PROJECT_DESCRIPTION.rst @@ -3,4 +3,7 @@ PROJECT_DESCRIPTION Short project description given to the project command. -This is the description given to the most recent :command:`project` command. +This is the description given to the most recently called :command:`project` +command in the current directory scope or above. To obtain the description +of the top level project, see the :variable:`CMAKE_PROJECT_DESCRIPTION` +variable. diff --git a/Help/variable/PROJECT_HOMEPAGE_URL.rst b/Help/variable/PROJECT_HOMEPAGE_URL.rst new file mode 100644 index 0000000..754c9e8 --- /dev/null +++ b/Help/variable/PROJECT_HOMEPAGE_URL.rst @@ -0,0 +1,9 @@ +PROJECT_HOMEPAGE_URL +-------------------- + +The homepage URL of the project. + +This is the homepage URL given to the most recently called :command:`project` +command in the current directory scope or above. To obtain the homepage URL +of the top level project, see the :variable:`CMAKE_PROJECT_HOMEPAGE_URL` +variable. diff --git a/Help/variable/PROJECT_NAME.rst b/Help/variable/PROJECT_NAME.rst index 61aa8bc..672680a 100644 --- a/Help/variable/PROJECT_NAME.rst +++ b/Help/variable/PROJECT_NAME.rst @@ -3,4 +3,6 @@ PROJECT_NAME Name of the project given to the project command. -This is the name given to the most recent :command:`project` command. +This is the name given to the most recently called :command:`project` +command in the current directory scope or above. To obtain the name of +the top level project, see the :variable:`CMAKE_PROJECT_NAME` variable. diff --git a/Modules/CMakeASMInformation.cmake b/Modules/CMakeASMInformation.cmake index 125c4e3..6b73730 100644 --- a/Modules/CMakeASMInformation.cmake +++ b/Modules/CMakeASMInformation.cmake @@ -29,15 +29,15 @@ if(NOT _INCLUDED_FILE) endif() if(CMAKE_SYSTEM_PROCESSOR) - include(Platform/${CMAKE_SYSTEM_NAME}-${CMAKE_ASM${ASM_DIALECT}_COMPILER_ID}-ASM${ASM_DIALECT}-${CMAKE_SYSTEM_PROCESSOR} OPTIONAL RESULT_VARIABLE _INCLUDED_FILE) + include(Platform/${CMAKE_EFFECTIVE_SYSTEM_NAME}-${CMAKE_ASM${ASM_DIALECT}_COMPILER_ID}-ASM${ASM_DIALECT}-${CMAKE_SYSTEM_PROCESSOR} OPTIONAL RESULT_VARIABLE _INCLUDED_FILE) if(NOT _INCLUDED_FILE) - include(Platform/${CMAKE_SYSTEM_NAME}-${CMAKE_BASE_NAME}-${CMAKE_SYSTEM_PROCESSOR} OPTIONAL) + include(Platform/${CMAKE_EFFECTIVE_SYSTEM_NAME}-${CMAKE_BASE_NAME}-${CMAKE_SYSTEM_PROCESSOR} OPTIONAL) endif() endif() -include(Platform/${CMAKE_SYSTEM_NAME}-${CMAKE_ASM${ASM_DIALECT}_COMPILER_ID}-ASM${ASM_DIALECT} OPTIONAL RESULT_VARIABLE _INCLUDED_FILE) +include(Platform/${CMAKE_EFFECTIVE_SYSTEM_NAME}-${CMAKE_ASM${ASM_DIALECT}_COMPILER_ID}-ASM${ASM_DIALECT} OPTIONAL RESULT_VARIABLE _INCLUDED_FILE) if(NOT _INCLUDED_FILE) - include(Platform/${CMAKE_SYSTEM_NAME}-${CMAKE_BASE_NAME} OPTIONAL) + include(Platform/${CMAKE_EFFECTIVE_SYSTEM_NAME}-${CMAKE_BASE_NAME} OPTIONAL) endif() # This should be included before the _INIT variables are diff --git a/Modules/CMakeCInformation.cmake b/Modules/CMakeCInformation.cmake index 1e46cac..df43559 100644 --- a/Modules/CMakeCInformation.cmake +++ b/Modules/CMakeCInformation.cmake @@ -35,21 +35,21 @@ endif() # load a hardware specific file, mostly useful for embedded compilers if(CMAKE_SYSTEM_PROCESSOR) if(CMAKE_C_COMPILER_ID) - include(Platform/${CMAKE_SYSTEM_NAME}-${CMAKE_C_COMPILER_ID}-C-${CMAKE_SYSTEM_PROCESSOR} OPTIONAL RESULT_VARIABLE _INCLUDED_FILE) + include(Platform/${CMAKE_EFFECTIVE_SYSTEM_NAME}-${CMAKE_C_COMPILER_ID}-C-${CMAKE_SYSTEM_PROCESSOR} OPTIONAL RESULT_VARIABLE _INCLUDED_FILE) endif() if (NOT _INCLUDED_FILE) - include(Platform/${CMAKE_SYSTEM_NAME}-${CMAKE_BASE_NAME}-${CMAKE_SYSTEM_PROCESSOR} OPTIONAL) + include(Platform/${CMAKE_EFFECTIVE_SYSTEM_NAME}-${CMAKE_BASE_NAME}-${CMAKE_SYSTEM_PROCESSOR} OPTIONAL) endif () endif() # load the system- and compiler specific files if(CMAKE_C_COMPILER_ID) - include(Platform/${CMAKE_SYSTEM_NAME}-${CMAKE_C_COMPILER_ID}-C + include(Platform/${CMAKE_EFFECTIVE_SYSTEM_NAME}-${CMAKE_C_COMPILER_ID}-C OPTIONAL RESULT_VARIABLE _INCLUDED_FILE) endif() if (NOT _INCLUDED_FILE) - include(Platform/${CMAKE_SYSTEM_NAME}-${CMAKE_BASE_NAME} + include(Platform/${CMAKE_EFFECTIVE_SYSTEM_NAME}-${CMAKE_BASE_NAME} OPTIONAL RESULT_VARIABLE _INCLUDED_FILE) endif () diff --git a/Modules/CMakeCUDACompiler.cmake.in b/Modules/CMakeCUDACompiler.cmake.in index f524e5f..9761d8c 100644 --- a/Modules/CMakeCUDACompiler.cmake.in +++ b/Modules/CMakeCUDACompiler.cmake.in @@ -11,6 +11,7 @@ set(CMAKE_CUDA_SIMULATE_VERSION "@CMAKE_CUDA_SIMULATE_VERSION@") set(CMAKE_CUDA_COMPILER_ENV_VAR "CUDACXX") set(CMAKE_CUDA_HOST_COMPILER_ENV_VAR "CUDAHOSTCXX") +set(CMAKE_CUDA_COMPILER_LOADED 1) set(CMAKE_CUDA_COMPILER_ID_RUN 1) set(CMAKE_CUDA_SOURCE_FILE_EXTENSIONS cu) set(CMAKE_CUDA_LINKER_PREFERENCE 15) diff --git a/Modules/CMakeCUDACompilerId.cu.in b/Modules/CMakeCUDACompilerId.cu.in index 018bab7..6eda924 100644 --- a/Modules/CMakeCUDACompilerId.cu.in +++ b/Modules/CMakeCUDACompilerId.cu.in @@ -17,7 +17,9 @@ char const* info_simulate = "INFO" ":" "simulate[" SIMULATE_ID "]"; @CMAKE_CUDA_COMPILER_ID_ERROR_FOR_TEST@ const char* info_language_dialect_default = "INFO" ":" "dialect_default[" -#if __cplusplus > 201402L +#if __cplusplus > 201703L + "20" +#elif __cplusplus >= 201703L "17" #elif __cplusplus >= 201402L "14" diff --git a/Modules/CMakeCUDAInformation.cmake b/Modules/CMakeCUDAInformation.cmake index 167e177..479493b 100644 --- a/Modules/CMakeCUDAInformation.cmake +++ b/Modules/CMakeCUDAInformation.cmake @@ -17,9 +17,9 @@ endif() if(CMAKE_CUDA_COMPILER_ID) # load a hardware specific file, mostly useful for embedded compilers if(CMAKE_SYSTEM_PROCESSOR) - include(Platform/${CMAKE_SYSTEM_NAME}-${CMAKE_CUDA_COMPILER_ID}-CUDA-${CMAKE_SYSTEM_PROCESSOR} OPTIONAL) + include(Platform/${CMAKE_EFFECTIVE_SYSTEM_NAME}-${CMAKE_CUDA_COMPILER_ID}-CUDA-${CMAKE_SYSTEM_PROCESSOR} OPTIONAL) endif() - include(Platform/${CMAKE_SYSTEM_NAME}-${CMAKE_CUDA_COMPILER_ID}-CUDA OPTIONAL) + include(Platform/${CMAKE_EFFECTIVE_SYSTEM_NAME}-${CMAKE_CUDA_COMPILER_ID}-CUDA OPTIONAL) endif() @@ -177,17 +177,31 @@ else() set(_CMAKE_CUDA_EXTRA_DEVICE_LINK_FLAGS "") endif() +# Add implicit host link directories that contain device libraries +# to the device link line. +set(__IMPLICT_DLINK_DIRS ${CMAKE_CUDA_IMPLICIT_LINK_DIRECTORIES}) +if(__IMPLICT_DLINK_DIRS) + list(REMOVE_ITEM __IMPLICT_DLINK_DIRS ${CMAKE_CUDA_HOST_IMPLICIT_LINK_DIRECTORIES}) +endif() +set(__IMPLICT_DLINK_FLAGS ) +foreach(dir ${__IMPLICT_DLINK_DIRS}) + if(EXISTS "${dir}/libcublas_device.a") + string(APPEND __IMPLICT_DLINK_FLAGS " -L\"${dir}\"") + endif() +endforeach() +unset(__IMPLICT_DLINK_DIRS) #These are used when linking relocatable (dc) cuda code if(NOT CMAKE_CUDA_DEVICE_LINK_LIBRARY) set(CMAKE_CUDA_DEVICE_LINK_LIBRARY - "<CMAKE_CUDA_COMPILER> ${CMAKE_CUDA_HOST_FLAGS} <CMAKE_CUDA_LINK_FLAGS> <LANGUAGE_COMPILE_FLAGS> ${CMAKE_CUDA_COMPILE_OPTIONS_PIC} ${_CMAKE_CUDA_EXTRA_DEVICE_LINK_FLAGS} -shared -dlink <OBJECTS> -o <TARGET> <LINK_LIBRARIES>") + "<CMAKE_CUDA_COMPILER> ${CMAKE_CUDA_HOST_FLAGS} <CMAKE_CUDA_LINK_FLAGS> <LANGUAGE_COMPILE_FLAGS> ${CMAKE_CUDA_COMPILE_OPTIONS_PIC} ${_CMAKE_CUDA_EXTRA_DEVICE_LINK_FLAGS} -shared -dlink <OBJECTS> -o <TARGET> <LINK_LIBRARIES>${__IMPLICT_DLINK_FLAGS}") endif() if(NOT CMAKE_CUDA_DEVICE_LINK_EXECUTABLE) set(CMAKE_CUDA_DEVICE_LINK_EXECUTABLE - "<CMAKE_CUDA_COMPILER> ${CMAKE_CUDA_HOST_FLAGS} <FLAGS> <CMAKE_CUDA_LINK_FLAGS> ${CMAKE_CUDA_COMPILE_OPTIONS_PIC} ${_CMAKE_CUDA_EXTRA_DEVICE_LINK_FLAGS} -shared -dlink <OBJECTS> -o <TARGET> <LINK_LIBRARIES>") + "<CMAKE_CUDA_COMPILER> ${CMAKE_CUDA_HOST_FLAGS} <FLAGS> <CMAKE_CUDA_LINK_FLAGS> ${CMAKE_CUDA_COMPILE_OPTIONS_PIC} ${_CMAKE_CUDA_EXTRA_DEVICE_LINK_FLAGS} -shared -dlink <OBJECTS> -o <TARGET> <LINK_LIBRARIES>${__IMPLICT_DLINK_FLAGS}") endif() unset(_CMAKE_CUDA_EXTRA_DEVICE_LINK_FLAGS) +unset(__IMPLICT_DLINK_FLAGS) set(CMAKE_CUDA_INFORMATION_LOADED 1) diff --git a/Modules/CMakeCXXCompiler.cmake.in b/Modules/CMakeCXXCompiler.cmake.in index df57a4f..974886d 100644 --- a/Modules/CMakeCXXCompiler.cmake.in +++ b/Modules/CMakeCXXCompiler.cmake.in @@ -10,6 +10,7 @@ set(CMAKE_CXX98_COMPILE_FEATURES "@CMAKE_CXX98_COMPILE_FEATURES@") set(CMAKE_CXX11_COMPILE_FEATURES "@CMAKE_CXX11_COMPILE_FEATURES@") set(CMAKE_CXX14_COMPILE_FEATURES "@CMAKE_CXX14_COMPILE_FEATURES@") set(CMAKE_CXX17_COMPILE_FEATURES "@CMAKE_CXX17_COMPILE_FEATURES@") +set(CMAKE_CXX20_COMPILE_FEATURES "@CMAKE_CXX20_COMPILE_FEATURES@") set(CMAKE_CXX_PLATFORM_ID "@CMAKE_CXX_PLATFORM_ID@") set(CMAKE_CXX_SIMULATE_ID "@CMAKE_CXX_SIMULATE_ID@") diff --git a/Modules/CMakeCXXCompilerId.cpp.in b/Modules/CMakeCXXCompilerId.cpp.in index 4cb2267..34639b4 100644 --- a/Modules/CMakeCXXCompilerId.cpp.in +++ b/Modules/CMakeCXXCompilerId.cpp.in @@ -34,7 +34,9 @@ char const *info_cray = "INFO" ":" "compiler_wrapper[CrayPrgEnv]"; #endif const char* info_language_dialect_default = "INFO" ":" "dialect_default[" -#if CXX_STD > 201402L +#if CXX_STD > 201703L + "20" +#elif CXX_STD >= 201703L "17" #elif CXX_STD >= 201402L "14" diff --git a/Modules/CMakeCXXInformation.cmake b/Modules/CMakeCXXInformation.cmake index 9ac9560..2975874 100644 --- a/Modules/CMakeCXXInformation.cmake +++ b/Modules/CMakeCXXInformation.cmake @@ -36,19 +36,19 @@ endif() # load a hardware specific file, mostly useful for embedded compilers if(CMAKE_SYSTEM_PROCESSOR) if(CMAKE_CXX_COMPILER_ID) - include(Platform/${CMAKE_SYSTEM_NAME}-${CMAKE_CXX_COMPILER_ID}-CXX-${CMAKE_SYSTEM_PROCESSOR} OPTIONAL RESULT_VARIABLE _INCLUDED_FILE) + include(Platform/${CMAKE_EFFECTIVE_SYSTEM_NAME}-${CMAKE_CXX_COMPILER_ID}-CXX-${CMAKE_SYSTEM_PROCESSOR} OPTIONAL RESULT_VARIABLE _INCLUDED_FILE) endif() if (NOT _INCLUDED_FILE) - include(Platform/${CMAKE_SYSTEM_NAME}-${CMAKE_BASE_NAME}-${CMAKE_SYSTEM_PROCESSOR} OPTIONAL) + include(Platform/${CMAKE_EFFECTIVE_SYSTEM_NAME}-${CMAKE_BASE_NAME}-${CMAKE_SYSTEM_PROCESSOR} OPTIONAL) endif () endif() # load the system- and compiler specific files if(CMAKE_CXX_COMPILER_ID) - include(Platform/${CMAKE_SYSTEM_NAME}-${CMAKE_CXX_COMPILER_ID}-CXX OPTIONAL RESULT_VARIABLE _INCLUDED_FILE) + include(Platform/${CMAKE_EFFECTIVE_SYSTEM_NAME}-${CMAKE_CXX_COMPILER_ID}-CXX OPTIONAL RESULT_VARIABLE _INCLUDED_FILE) endif() if (NOT _INCLUDED_FILE) - include(Platform/${CMAKE_SYSTEM_NAME}-${CMAKE_BASE_NAME} OPTIONAL + include(Platform/${CMAKE_EFFECTIVE_SYSTEM_NAME}-${CMAKE_BASE_NAME} OPTIONAL RESULT_VARIABLE _INCLUDED_FILE) endif () diff --git a/Modules/CMakeDetermineCSharpCompiler.cmake b/Modules/CMakeDetermineCSharpCompiler.cmake index eb825a5..5802b15 100644 --- a/Modules/CMakeDetermineCSharpCompiler.cmake +++ b/Modules/CMakeDetermineCSharpCompiler.cmake @@ -1,7 +1,7 @@ # Distributed under the OSI-approved BSD 3-Clause License. See accompanying # file Copyright.txt or https://cmake.org/licensing for details. -if(NOT ${CMAKE_GENERATOR} MATCHES "Visual Studio ([^89]|[89][0-9])") +if(NOT ${CMAKE_GENERATOR} MATCHES "Visual Studio ([^9]|[9][0-9])") message(FATAL_ERROR "C# is currently only supported for Microsoft Visual Studio 2010 and later.") endif() diff --git a/Modules/CMakeDetermineCUDACompiler.cmake b/Modules/CMakeDetermineCUDACompiler.cmake index f5a3ebd..113b520 100644 --- a/Modules/CMakeDetermineCUDACompiler.cmake +++ b/Modules/CMakeDetermineCUDACompiler.cmake @@ -6,7 +6,7 @@ include(${CMAKE_ROOT}/Modules//CMakeParseImplicitLinkInfo.cmake) if( NOT ( ("${CMAKE_GENERATOR}" MATCHES "Make") OR ("${CMAKE_GENERATOR}" MATCHES "Ninja") OR - ("${CMAKE_GENERATOR}" MATCHES "Visual Studio (1|[89][0-9])") ) ) + ("${CMAKE_GENERATOR}" MATCHES "Visual Studio (1|[9][0-9])") ) ) message(FATAL_ERROR "CUDA language not currently supported by \"${CMAKE_GENERATOR}\" generator") endif() @@ -40,7 +40,6 @@ else() endif() #Allow the user to specify a host compiler -set(CMAKE_CUDA_HOST_COMPILER "" CACHE FILEPATH "Host compiler to be used by nvcc") if(NOT $ENV{CUDAHOSTCXX} STREQUAL "") get_filename_component(CMAKE_CUDA_HOST_COMPILER $ENV{CUDAHOSTCXX} PROGRAM) if(NOT EXISTS ${CMAKE_CUDA_HOST_COMPILER}) diff --git a/Modules/CMakeDetermineCompileFeatures.cmake b/Modules/CMakeDetermineCompileFeatures.cmake index 3ed92be..01a81a1 100644 --- a/Modules/CMakeDetermineCompileFeatures.cmake +++ b/Modules/CMakeDetermineCompileFeatures.cmake @@ -49,6 +49,7 @@ function(cmake_determine_compile_features lang) set(CMAKE_CXX11_COMPILE_FEATURES) set(CMAKE_CXX14_COMPILE_FEATURES) set(CMAKE_CXX17_COMPILE_FEATURES) + set(CMAKE_CXX20_COMPILE_FEATURES) include("${CMAKE_ROOT}/Modules/Internal/FeatureTesting.cmake") @@ -59,6 +60,9 @@ function(cmake_determine_compile_features lang) return() endif() + if (CMAKE_CXX17_COMPILE_FEATURES AND CMAKE_CXX20_COMPILE_FEATURES) + list(REMOVE_ITEM CMAKE_CXX20_COMPILE_FEATURES ${CMAKE_CXX17_COMPILE_FEATURES}) + endif() if (CMAKE_CXX14_COMPILE_FEATURES AND CMAKE_CXX17_COMPILE_FEATURES) list(REMOVE_ITEM CMAKE_CXX17_COMPILE_FEATURES ${CMAKE_CXX14_COMPILE_FEATURES}) endif() @@ -75,6 +79,7 @@ function(cmake_determine_compile_features lang) ${CMAKE_CXX11_COMPILE_FEATURES} ${CMAKE_CXX14_COMPILE_FEATURES} ${CMAKE_CXX17_COMPILE_FEATURES} + ${CMAKE_CXX20_COMPILE_FEATURES} ) endif() @@ -83,6 +88,7 @@ function(cmake_determine_compile_features lang) set(CMAKE_CXX11_COMPILE_FEATURES ${CMAKE_CXX11_COMPILE_FEATURES} PARENT_SCOPE) set(CMAKE_CXX14_COMPILE_FEATURES ${CMAKE_CXX14_COMPILE_FEATURES} PARENT_SCOPE) set(CMAKE_CXX17_COMPILE_FEATURES ${CMAKE_CXX17_COMPILE_FEATURES} PARENT_SCOPE) + set(CMAKE_CXX20_COMPILE_FEATURES ${CMAKE_CXX20_COMPILE_FEATURES} PARENT_SCOPE) message(STATUS "Detecting ${lang} compile features - done") endif() diff --git a/Modules/CMakeDetermineCompilerId.cmake b/Modules/CMakeDetermineCompilerId.cmake index 15c304c..ea5465a 100644 --- a/Modules/CMakeDetermineCompilerId.cmake +++ b/Modules/CMakeDetermineCompilerId.cmake @@ -52,6 +52,22 @@ function(CMAKE_DETERMINE_COMPILER_ID lang flagvar src) endforeach() endif() + # CUDA < 7.5 is missing version macros + if(lang STREQUAL "CUDA" + AND CMAKE_${lang}_COMPILER_ID STREQUAL "NVIDIA" + AND NOT CMAKE_${lang}_COMPILER_VERSION) + execute_process( + COMMAND "${CMAKE_${lang}_COMPILER}" + --version + OUTPUT_VARIABLE output ERROR_VARIABLE output + RESULT_VARIABLE result + TIMEOUT 10 + ) + if(output MATCHES [=[ V([0-9]+)\.([0-9]+)\.([0-9]+)]=]) + set(CMAKE_${lang}_COMPILER_VERSION "${CMAKE_MATCH_1}.${CMAKE_MATCH_2}.${CMAKE_MATCH_3}") + endif() + endif() + if (COMPILER_QNXNTO AND CMAKE_${lang}_COMPILER_ID STREQUAL "GNU") execute_process( COMMAND "${CMAKE_${lang}_COMPILER}" diff --git a/Modules/CMakeDetermineFortranCompiler.cmake b/Modules/CMakeDetermineFortranCompiler.cmake index cf502f6..5ddd64f 100644 --- a/Modules/CMakeDetermineFortranCompiler.cmake +++ b/Modules/CMakeDetermineFortranCompiler.cmake @@ -66,12 +66,20 @@ else() # The order is 95 or newer compilers first, then 90, # then 77 or older compilers, gnu is always last in the group, # so if you paid for a compiler it is picked by default. - set(CMAKE_Fortran_COMPILER_LIST - ftn - ifort ifc af95 af90 efc f95 pathf2003 pathf95 pgf95 pgfortran lf95 xlf95 - fort flang gfortran gfortran-4 g95 f90 pathf90 pgf90 xlf90 epcf90 fort77 - frt pgf77 xlf fl32 af77 g77 f77 nag - ) + if(CMAKE_HOST_WIN32) + set(CMAKE_Fortran_COMPILER_LIST + ifort pgf95 pgfortran lf95 fort + flang gfortran gfortran-4 g95 f90 pgf90 + pgf77 g77 f77 nag + ) + else() + set(CMAKE_Fortran_COMPILER_LIST + ftn + ifort ifc efc pgf95 pgfortran lf95 xlf95 fort + flang gfortran gfortran-4 g95 f90 pgf90 + frt pgf77 xlf g77 f77 nag + ) + endif() # Vendor-specific compiler names. set(_Fortran_COMPILER_NAMES_GNU gfortran gfortran-4 g95 g77) diff --git a/Modules/CMakeFindBinUtils.cmake b/Modules/CMakeFindBinUtils.cmake index ece0547..1b6823c 100644 --- a/Modules/CMakeFindBinUtils.cmake +++ b/Modules/CMakeFindBinUtils.cmake @@ -19,6 +19,25 @@ # on UNIX, cygwin and mingw +if(CMAKE_LINKER) + # we only get here if CMAKE_LINKER was specified using -D or a pre-made CMakeCache.txt + # (e.g. via ctest) or set in CMAKE_TOOLCHAIN_FILE + # find the linker in the PATH if necessary + get_filename_component(_CMAKE_USER_LINKER_PATH "${CMAKE_LINKER}" PATH) + if(NOT _CMAKE_USER_LINKER_PATH) + find_program(CMAKE_LINKER_WITH_PATH NAMES ${CMAKE_LINKER} HINTS ${_CMAKE_TOOLCHAIN_LOCATION}) + if(CMAKE_LINKER_WITH_PATH) + set(CMAKE_LINKER ${CMAKE_LINKER_WITH_PATH}) + get_property(_CMAKE_LINKER_CACHED CACHE CMAKE_LINKER PROPERTY TYPE) + if(_CMAKE_LINKER_CACHED) + set(CMAKE_LINKER "${CMAKE_LINKER}" CACHE STRING "Default Linker" FORCE) + endif() + unset(_CMAKE_LINKER_CACHED) + endif() + unset(CMAKE_LINKER_WITH_PATH CACHE) + endif() +endif() + # if it's the MS C/CXX compiler, search for link if("x${CMAKE_${_CMAKE_PROCESSING_LANGUAGE}_SIMULATE_ID}" STREQUAL "xMSVC" OR "x${CMAKE_${_CMAKE_PROCESSING_LANGUAGE}_COMPILER_ID}" STREQUAL "xMSVC" diff --git a/Modules/CMakeFindPackageMode.cmake b/Modules/CMakeFindPackageMode.cmake index 7c41d49..ec3652c 100644 --- a/Modules/CMakeFindPackageMode.cmake +++ b/Modules/CMakeFindPackageMode.cmake @@ -65,6 +65,8 @@ if("${CMAKE_SYSTEM_NAME}" MATCHES Darwin AND "${COMPILER_ID}" MATCHES GNU) set(CMAKE_${LANGUAGE}_OSX_DEPLOYMENT_TARGET_FLAG "") endif() +include(CMakeSystemSpecificInitialize) + # Also load the system specific file, which sets up e.g. the search paths. # This makes the FIND_XXX() calls work much better include(CMakeSystemSpecificInformation) diff --git a/Modules/CMakeFortranCompiler.cmake.in b/Modules/CMakeFortranCompiler.cmake.in index 2e34cbb..9b951fc 100644 --- a/Modules/CMakeFortranCompiler.cmake.in +++ b/Modules/CMakeFortranCompiler.cmake.in @@ -31,7 +31,7 @@ if(CMAKE_COMPILER_IS_MINGW) set(MINGW 1) endif() set(CMAKE_Fortran_COMPILER_ID_RUN 1) -set(CMAKE_Fortran_SOURCE_FILE_EXTENSIONS f;F;f77;F77;f90;F90;for;For;FOR;f95;F95) +set(CMAKE_Fortran_SOURCE_FILE_EXTENSIONS f;F;fpp;FPP;f77;F77;f90;F90;for;For;FOR;f95;F95) set(CMAKE_Fortran_IGNORE_EXTENSIONS h;H;o;O;obj;OBJ;def;DEF;rc;RC) set(CMAKE_Fortran_LINKER_PREFERENCE 20) if(UNIX) diff --git a/Modules/CMakeFortranInformation.cmake b/Modules/CMakeFortranInformation.cmake index 5f028e4..cceac83 100644 --- a/Modules/CMakeFortranInformation.cmake +++ b/Modules/CMakeFortranInformation.cmake @@ -22,10 +22,10 @@ if(CMAKE_COMPILER_IS_GNUG77) set(CMAKE_BASE_NAME g77) endif() if(CMAKE_Fortran_COMPILER_ID) - include(Platform/${CMAKE_SYSTEM_NAME}-${CMAKE_Fortran_COMPILER_ID}-Fortran OPTIONAL RESULT_VARIABLE _INCLUDED_FILE) + include(Platform/${CMAKE_EFFECTIVE_SYSTEM_NAME}-${CMAKE_Fortran_COMPILER_ID}-Fortran OPTIONAL RESULT_VARIABLE _INCLUDED_FILE) endif() if (NOT _INCLUDED_FILE) - include(Platform/${CMAKE_SYSTEM_NAME}-${CMAKE_BASE_NAME} OPTIONAL + include(Platform/${CMAKE_EFFECTIVE_SYSTEM_NAME}-${CMAKE_BASE_NAME} OPTIONAL RESULT_VARIABLE _INCLUDED_FILE) endif () diff --git a/Modules/CMakeLanguageInformation.cmake b/Modules/CMakeLanguageInformation.cmake index 18c8624..674ab86 100644 --- a/Modules/CMakeLanguageInformation.cmake +++ b/Modules/CMakeLanguageInformation.cmake @@ -9,10 +9,10 @@ macro(__cmake_include_compiler_wrapper lang) set(_INCLUDED_WRAPPER_FILE 0) if (CMAKE_${lang}_COMPILER_ID) - include(Platform/${CMAKE_SYSTEM_NAME}-${CMAKE_${lang}_COMPILER_WRAPPER}-${CMAKE_${lang}_COMPILER_ID}-${lang} OPTIONAL RESULT_VARIABLE _INCLUDED_WRAPPER_FILE) + include(Platform/${CMAKE_EFFECTIVE_SYSTEM_NAME}-${CMAKE_${lang}_COMPILER_WRAPPER}-${CMAKE_${lang}_COMPILER_ID}-${lang} OPTIONAL RESULT_VARIABLE _INCLUDED_WRAPPER_FILE) endif() if (NOT _INCLUDED_WRAPPER_FILE) - include(Platform/${CMAKE_SYSTEM_NAME}-${CMAKE_${lang}_COMPILER_WRAPPER}-${lang} OPTIONAL RESULT_VARIABLE _INCLUDED_WRAPPER_FILE) + include(Platform/${CMAKE_EFFECTIVE_SYSTEM_NAME}-${CMAKE_${lang}_COMPILER_WRAPPER}-${lang} OPTIONAL RESULT_VARIABLE _INCLUDED_WRAPPER_FILE) endif () # No platform - wrapper - lang information so maybe there's just wrapper - lang information diff --git a/Modules/CMakeSwiftInformation.cmake b/Modules/CMakeSwiftInformation.cmake index d9b408d..07ba6d0 100644 --- a/Modules/CMakeSwiftInformation.cmake +++ b/Modules/CMakeSwiftInformation.cmake @@ -14,9 +14,9 @@ endif() if(CMAKE_Swift_COMPILER_ID) # load a hardware specific file, mostly useful for embedded compilers if(CMAKE_SYSTEM_PROCESSOR) - include(Platform/${CMAKE_SYSTEM_NAME}-${CMAKE_Swift_COMPILER_ID}-Swift-${CMAKE_SYSTEM_PROCESSOR} OPTIONAL) + include(Platform/${CMAKE_EFFECTIVE_SYSTEM_NAME}-${CMAKE_Swift_COMPILER_ID}-Swift-${CMAKE_SYSTEM_PROCESSOR} OPTIONAL) endif() - include(Platform/${CMAKE_SYSTEM_NAME}-${CMAKE_Swift_COMPILER_ID}-Swift OPTIONAL) + include(Platform/${CMAKE_EFFECTIVE_SYSTEM_NAME}-${CMAKE_Swift_COMPILER_ID}-Swift OPTIONAL) endif() # for most systems a module is the same as a shared library diff --git a/Modules/CMakeSystemSpecificInitialize.cmake b/Modules/CMakeSystemSpecificInitialize.cmake index 6200e9c..de4d7f5 100644 --- a/Modules/CMakeSystemSpecificInitialize.cmake +++ b/Modules/CMakeSystemSpecificInitialize.cmake @@ -5,6 +5,19 @@ # This file is included by cmGlobalGenerator::EnableLanguage. # It is included before the compiler has been determined. +# The CMAKE_EFFECTIVE_SYSTEM_NAME is used to load compiler and compiler +# wrapper configuration files. By default it equals to CMAKE_SYSTEM_NAME +# but could be overridden in the ${CMAKE_SYSTEM_NAME}-Initialize files. +# +# It is useful to share the same aforementioned configuration files and +# avoids duplicating them in case of tightly related platforms. +# +# An example are the platforms supported by Xcode (macOS, iOS, tvOS, +# and watchOS). For all of those the CMAKE_EFFECTIVE_SYSTEM_NAME is +# set to Apple which results in using +# Platfom/Apple-AppleClang-CXX.cmake for the Apple C++ compiler. +set(CMAKE_EFFECTIVE_SYSTEM_NAME "${CMAKE_SYSTEM_NAME}") + include(Platform/${CMAKE_SYSTEM_NAME}-Initialize OPTIONAL) set(CMAKE_SYSTEM_SPECIFIC_INITIALIZE_LOADED 1) diff --git a/Modules/CMakeTestCSharpCompiler.cmake b/Modules/CMakeTestCSharpCompiler.cmake index f3b95fd..6715c30 100644 --- a/Modules/CMakeTestCSharpCompiler.cmake +++ b/Modules/CMakeTestCSharpCompiler.cmake @@ -15,7 +15,7 @@ unset(CMAKE_CSharp_COMPILER_WORKS CACHE) set(test_compile_file "${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeTmp/testCSharpCompiler.cs") # This file is used by EnableLanguage in cmGlobalGenerator to -# determine that that selected C# compiler can actually compile +# determine that the selected C# compiler can actually compile # and link the most basic of programs. If not, a fatal error # is set and cmake stops processing commands and will not generate # any makefiles or projects. diff --git a/Modules/CMakeTestCUDACompiler.cmake b/Modules/CMakeTestCUDACompiler.cmake index df5ec72..f0454da 100644 --- a/Modules/CMakeTestCUDACompiler.cmake +++ b/Modules/CMakeTestCUDACompiler.cmake @@ -15,7 +15,7 @@ include(CMakeTestCompilerCommon) unset(CMAKE_CUDA_COMPILER_WORKS CACHE) # This file is used by EnableLanguage in cmGlobalGenerator to -# determine that that selected cuda compiler can actually compile +# determine that the selected cuda compiler can actually compile # and link the most basic of programs. If not, a fatal error # is set and cmake stops processing commands and will not generate # any makefiles or projects. diff --git a/Modules/CMakeTestCXXCompiler.cmake b/Modules/CMakeTestCXXCompiler.cmake index 7b80dc0..e4d49ae 100644 --- a/Modules/CMakeTestCXXCompiler.cmake +++ b/Modules/CMakeTestCXXCompiler.cmake @@ -16,7 +16,7 @@ include(CMakeTestCompilerCommon) unset(CMAKE_CXX_COMPILER_WORKS CACHE) # This file is used by EnableLanguage in cmGlobalGenerator to -# determine that that selected C++ compiler can actually compile +# determine that the selected C++ compiler can actually compile # and link the most basic of programs. If not, a fatal error # is set and cmake stops processing commands and will not generate # any makefiles or projects. diff --git a/Modules/CMakeTestFortranCompiler.cmake b/Modules/CMakeTestFortranCompiler.cmake index 3c150a8..e9860e9 100644 --- a/Modules/CMakeTestFortranCompiler.cmake +++ b/Modules/CMakeTestFortranCompiler.cmake @@ -16,7 +16,7 @@ include(CMakeTestCompilerCommon) unset(CMAKE_Fortran_COMPILER_WORKS CACHE) # This file is used by EnableLanguage in cmGlobalGenerator to -# determine that that selected Fortran compiler can actually compile +# determine that the selected Fortran compiler can actually compile # and link the most basic of programs. If not, a fatal error # is set and cmake stops processing commands and will not generate # any makefiles or projects. diff --git a/Modules/CMakeTestJavaCompiler.cmake b/Modules/CMakeTestJavaCompiler.cmake index 23fdbdc..3c33573 100644 --- a/Modules/CMakeTestJavaCompiler.cmake +++ b/Modules/CMakeTestJavaCompiler.cmake @@ -3,7 +3,7 @@ # This file is used by EnableLanguage in cmGlobalGenerator to -# determine that that selected Fortran compiler can actually compile +# determine that the selected Fortran compiler can actually compile # and link the most basic of programs. If not, a fatal error # is set and cmake stops processing commands and will not generate # any makefiles or projects. diff --git a/Modules/CMakeTestRCCompiler.cmake b/Modules/CMakeTestRCCompiler.cmake index c510d3a..3123a6c 100644 --- a/Modules/CMakeTestRCCompiler.cmake +++ b/Modules/CMakeTestRCCompiler.cmake @@ -3,7 +3,7 @@ # This file is used by EnableLanguage in cmGlobalGenerator to -# determine that that selected RC compiler can actually compile +# determine that the selected RC compiler can actually compile # and link the most basic of programs. If not, a fatal error # is set and cmake stops processing commands and will not generate # any makefiles or projects. diff --git a/Modules/CMakeTestSwiftCompiler.cmake b/Modules/CMakeTestSwiftCompiler.cmake index bcd5c33..858c1be 100644 --- a/Modules/CMakeTestSwiftCompiler.cmake +++ b/Modules/CMakeTestSwiftCompiler.cmake @@ -16,7 +16,7 @@ include(CMakeTestCompilerCommon) unset(CMAKE_Swift_COMPILER_WORKS CACHE) # This file is used by EnableLanguage in cmGlobalGenerator to -# determine that that selected C++ compiler can actually compile +# determine that the selected C++ compiler can actually compile # and link the most basic of programs. If not, a fatal error # is set and cmake stops processing commands and will not generate # any makefiles or projects. diff --git a/Modules/CPack.cmake b/Modules/CPack.cmake index 9216fc9..3ff8be6 100644 --- a/Modules/CPack.cmake +++ b/Modules/CPack.cmake @@ -100,11 +100,19 @@ # # Short description of the project (only a few words). Default value is:: # -# ${PROJECT_DESCRIPTION} +# ${CMAKE_PROJECT_DESCRIPTION} # # if DESCRIPTION has given to the project() call or # CMake generated string with PROJECT_NAME otherwise. # +# .. variable:: CPACK_PACKAGE_HOMEPAGE_URL +# +# Project homepage URL. Default value is:: +# +# ${CMAKE_PROJECT_HOMEPAGE_URL} +# +# if HOMEPAGE_URL has given to the project(). +# # .. variable:: CPACK_PACKAGE_FILE_NAME # # The name of the package file to generate, not including the @@ -373,6 +381,10 @@ else() _cpack_set_default(CPACK_PACKAGE_DESCRIPTION_SUMMARY "${CMAKE_PROJECT_NAME} built using CMake") endif() +if(CMAKE_PROJECT_HOMEPAGE_URL) + _cpack_set_default(CPACK_PACKAGE_HOMEPAGE_URL + "${CMAKE_PROJECT_HOMEPAGE_URL}") +endif() _cpack_set_default(CPACK_PACKAGE_DESCRIPTION_FILE "${CMAKE_ROOT}/Templates/CPack.GenericDescription.txt") diff --git a/Modules/CPackDeb.cmake b/Modules/CPackDeb.cmake index 35447c9..444f632 100644 --- a/Modules/CPackDeb.cmake +++ b/Modules/CPackDeb.cmake @@ -254,7 +254,7 @@ # upstream documentation or information may be found. # # * Mandatory : NO -# * Default : - +# * Default : :variable:`CMAKE_PROJECT_HOMEPAGE_URL` # # .. note:: # @@ -914,6 +914,11 @@ function(cpack_deb_prepare_package_vars) endif() endif() + # Homepage: (optional) + if(NOT CPACK_DEBIAN_PACKAGE_HOMEPAGE AND CMAKE_PROJECT_HOMEPAGE_URL) + set(CPACK_DEBIAN_PACKAGE_HOMEPAGE "${CMAKE_PROJECT_HOMEPAGE_URL}") + endif() + # Section: (recommended) if(NOT CPACK_DEBIAN_PACKAGE_SECTION) set(CPACK_DEBIAN_PACKAGE_SECTION "devel") diff --git a/Modules/CPackFreeBSD.cmake b/Modules/CPackFreeBSD.cmake index 7fec78a..b681d4f 100644 --- a/Modules/CPackFreeBSD.cmake +++ b/Modules/CPackFreeBSD.cmake @@ -80,7 +80,8 @@ the RPM information (e.g. package license). * Mandatory: YES * Default: - - :variable:`CPACK_DEBIAN_PACKAGE_HOMEPAGE` (this may be set already + - :variable:`CMAKE_PROJECT_HOMEPAGE_URL`, or if that is not set, + :variable:`CPACK_DEBIAN_PACKAGE_HOMEPAGE` (this may be set already for Debian packaging, so we may as well re-use it). .. variable:: CPACK_FREEBSD_PACKAGE_LICENSE @@ -208,6 +209,7 @@ _cpack_freebsd_fallback_var("CPACK_FREEBSD_PACKAGE_DESCRIPTION" # There's really only one homepage for a project, so # re-use the Debian setting if it's there. _cpack_freebsd_fallback_var("CPACK_FREEBSD_PACKAGE_WWW" + "CMAKE_PROJECT_HOMEPAGE_URL" "CPACK_DEBIAN_PACKAGE_HOMEPAGE" "_cpack_freebsd_fallback_www" ) diff --git a/Modules/CPackNSIS.cmake b/Modules/CPackNSIS.cmake index 18d1871..5bc4395 100644 --- a/Modules/CPackNSIS.cmake +++ b/Modules/CPackNSIS.cmake @@ -126,7 +126,7 @@ # .. variable:: CPACK_NSIS_MENU_LINKS # # Specify links in [application] menu. This should contain a list of pair -# "link" "link name". The link may be an URL or a path relative to +# "link" "link name". The link may be a URL or a path relative to # installation prefix. Like:: # # set(CPACK_NSIS_MENU_LINKS diff --git a/Modules/CPackProductBuild.cmake b/Modules/CPackProductBuild.cmake index 4779b95..ee78d8d 100644 --- a/Modules/CPackProductBuild.cmake +++ b/Modules/CPackProductBuild.cmake @@ -47,6 +47,22 @@ # Specify a specific keychain to search for the signing identity. # # +# .. variable:: CPACK_PREFLIGHT_<COMP>_SCRIPT +# +# Full path to a file that will be used as the ``preinstall`` script for the +# named ``<COMP>`` component's package, where ``<COMP>`` is the uppercased +# component name. No ``preinstall`` script is added if this variable is not +# defined for a given component. +# +# +# .. variable:: CPACK_POSTFLIGHT_<COMP>_SCRIPT +# +# Full path to a file that will be used as the ``postinstall`` script for the +# named ``<COMP>`` component's package, where ``<COMP>`` is the uppercased +# component name. No ``postinstall`` script is added if this variable is not +# defined for a given component. +# +# # .. variable:: CPACK_PRODUCTBUILD_RESOURCES_DIR # # If specified the productbuild generator copies files from this directory diff --git a/Modules/CPackRPM.cmake b/Modules/CPackRPM.cmake index bb5181f..87385de 100644 --- a/Modules/CPackRPM.cmake +++ b/Modules/CPackRPM.cmake @@ -191,7 +191,7 @@ # The projects URL. # # * Mandatory : NO -# * Default : - +# * Default : :variable:`CMAKE_PROJECT_HOMEPAGE_URL` # # .. variable:: CPACK_RPM_PACKAGE_DESCRIPTION # CPACK_RPM_<component>_PACKAGE_DESCRIPTION @@ -1787,6 +1787,10 @@ function(cpack_rpm_generate_package) endif() endif() + if(NOT CPACK_RPM_PACKAGE_URL AND CMAKE_PROJECT_HOMEPAGE_URL) + set(CPACK_RPM_PACKAGE_URL "${CMAKE_PROJECT_HOMEPAGE_URL}") + endif() + # CPACK_RPM_PACKAGE_NAME (mandatory) if(NOT CPACK_RPM_PACKAGE_NAME) string(TOLOWER "${CPACK_PACKAGE_NAME}" CPACK_RPM_PACKAGE_NAME) @@ -1984,7 +1988,7 @@ function(cpack_rpm_generate_package) endif() if(DEFINED CPACK_RPM_PACKAGE_${_RPM_SPEC_HEADER}) - # Prefix can be replaced by Prefixes but the old version stil works so we'll ignore it for now + # Prefix can be replaced by Prefixes but the old version still works so we'll ignore it for now # Requires* is a special case because it gets transformed to Requires(pre/post/preun/postun) # Auto* is a special case because the tags can not be queried by querytags rpmbuild flag set(special_case_tags_ PREFIX REQUIRES_PRE REQUIRES_POST REQUIRES_PREUN REQUIRES_POSTUN AUTOPROV AUTOREQ AUTOREQPROV) diff --git a/Modules/CTest.cmake b/Modules/CTest.cmake index a08282e..2ea931d 100644 --- a/Modules/CTest.cmake +++ b/Modules/CTest.cmake @@ -54,7 +54,7 @@ in the ``CTestConfig.cmake`` file. option(BUILD_TESTING "Build the testing tree." ON) # function to turn generator name into a version string -# like vs8 vs9 +# like vs9 or vs10 function(GET_VS_VERSION_STRING generator var) string(REGEX REPLACE "Visual Studio ([0-9][0-9]?)($|.*)" "\\1" NUMBER "${generator}") diff --git a/Modules/CheckCSourceRuns.cmake b/Modules/CheckCSourceRuns.cmake index fa51346..7eb050c 100644 --- a/Modules/CheckCSourceRuns.cmake +++ b/Modules/CheckCSourceRuns.cmake @@ -92,7 +92,8 @@ macro(CHECK_C_SOURCE_RUNS SOURCE VAR) CMAKE_FLAGS -DCOMPILE_DEFINITIONS:STRING=${MACRO_CHECK_FUNCTION_DEFINITIONS} -DCMAKE_SKIP_RPATH:BOOL=${CMAKE_SKIP_RPATH} "${CHECK_C_SOURCE_COMPILES_ADD_INCLUDES}" - COMPILE_OUTPUT_VARIABLE OUTPUT) + COMPILE_OUTPUT_VARIABLE OUTPUT + RUN_OUTPUT_VARIABLE RUN_OUTPUT) # if it did not compile make the return value fail code of 1 if(NOT ${VAR}_COMPILED) set(${VAR}_EXITCODE 1) @@ -104,8 +105,10 @@ macro(CHECK_C_SOURCE_RUNS SOURCE VAR) message(STATUS "Performing Test ${VAR} - Success") endif() file(APPEND ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeOutput.log - "Performing C SOURCE FILE Test ${VAR} succeeded with the following output:\n" + "Performing C SOURCE FILE Test ${VAR} succeeded with the following compile output:\n" "${OUTPUT}\n" + "...and run output:\n" + "${RUN_OUTPUT}\n" "Return value: ${${VAR}}\n" "Source file was:\n${SOURCE}\n") else() @@ -119,8 +122,10 @@ macro(CHECK_C_SOURCE_RUNS SOURCE VAR) message(STATUS "Performing Test ${VAR} - Failed") endif() file(APPEND ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeError.log - "Performing C SOURCE FILE Test ${VAR} failed with the following output:\n" + "Performing C SOURCE FILE Test ${VAR} failed with the following compile output:\n" "${OUTPUT}\n" + "...and run output:\n" + "${RUN_OUTPUT}\n" "Return value: ${${VAR}_EXITCODE}\n" "Source file was:\n${SOURCE}\n") diff --git a/Modules/CheckIncludeFile.cmake b/Modules/CheckIncludeFile.cmake index e5554c4..24bc349 100644 --- a/Modules/CheckIncludeFile.cmake +++ b/Modules/CheckIncludeFile.cmake @@ -27,6 +27,8 @@ # list of macros to define (-DFOO=bar) # ``CMAKE_REQUIRED_INCLUDES`` # list of include directories +# ``CMAKE_REQUIRED_LIBRARIES`` +# A list of libraries to link. See policy :policy:`CMP0075`. # ``CMAKE_REQUIRED_QUIET`` # execute quietly without messages # @@ -55,14 +57,39 @@ macro(CHECK_INCLUDE_FILE INCLUDE VARIABLE) string(APPEND CMAKE_C_FLAGS " ${ARGV2}") endif() + set(_CIF_LINK_LIBRARIES "") + if(CMAKE_REQUIRED_LIBRARIES) + cmake_policy(GET CMP0075 _CIF_CMP0075 + PARENT_SCOPE # undocumented, do not use outside of CMake + ) + if("x${_CIF_CMP0075}x" STREQUAL "xNEWx") + set(_CIF_LINK_LIBRARIES LINK_LIBRARIES ${CMAKE_REQUIRED_LIBRARIES}) + elseif("x${_CIF_CMP0075}x" STREQUAL "xOLDx") + elseif(NOT _CIF_CMP0075_WARNED) + set(_CIF_CMP0075_WARNED 1) + message(AUTHOR_WARNING + "Policy CMP0075 is not set: Include file check macros honor CMAKE_REQUIRED_LIBRARIES. " + "Run \"cmake --help-policy CMP0075\" for policy details. " + "Use the cmake_policy command to set the policy and suppress this warning." + "\n" + "CMAKE_REQUIRED_LIBRARIES is set to:\n" + " ${CMAKE_REQUIRED_LIBRARIES}\n" + "For compatibility with CMake 3.11 and below this check is ignoring it." + ) + endif() + unset(_CIF_CMP0075) + endif() + try_compile(${VARIABLE} ${CMAKE_BINARY_DIR} ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeTmp/CheckIncludeFile.c COMPILE_DEFINITIONS ${CMAKE_REQUIRED_DEFINITIONS} + ${_CIF_LINK_LIBRARIES} CMAKE_FLAGS -DCOMPILE_DEFINITIONS:STRING=${MACRO_CHECK_INCLUDE_FILE_FLAGS} "${CHECK_INCLUDE_FILE_C_INCLUDE_DIRS}" OUTPUT_VARIABLE OUTPUT) + unset(_CIF_LINK_LIBRARIES) if(${ARGC} EQUAL 3) set(CMAKE_C_FLAGS ${CMAKE_C_FLAGS_SAVE}) diff --git a/Modules/CheckIncludeFileCXX.cmake b/Modules/CheckIncludeFileCXX.cmake index 7948bab..f13d983 100644 --- a/Modules/CheckIncludeFileCXX.cmake +++ b/Modules/CheckIncludeFileCXX.cmake @@ -27,6 +27,8 @@ # list of macros to define (-DFOO=bar) # ``CMAKE_REQUIRED_INCLUDES`` # list of include directories +# ``CMAKE_REQUIRED_LIBRARIES`` +# A list of libraries to link. See policy :policy:`CMP0075`. # ``CMAKE_REQUIRED_QUIET`` # execute quietly without messages # @@ -54,14 +56,39 @@ macro(CHECK_INCLUDE_FILE_CXX INCLUDE VARIABLE) string(APPEND CMAKE_CXX_FLAGS " ${ARGV2}") endif() + set(_CIF_LINK_LIBRARIES "") + if(CMAKE_REQUIRED_LIBRARIES) + cmake_policy(GET CMP0075 _CIF_CMP0075 + PARENT_SCOPE # undocumented, do not use outside of CMake + ) + if("x${_CIF_CMP0075}x" STREQUAL "xNEWx") + set(_CIF_LINK_LIBRARIES LINK_LIBRARIES ${CMAKE_REQUIRED_LIBRARIES}) + elseif("x${_CIF_CMP0075}x" STREQUAL "xOLDx") + elseif(NOT _CIF_CMP0075_WARNED) + set(_CIF_CMP0075_WARNED 1) + message(AUTHOR_WARNING + "Policy CMP0075 is not set: Include file check macros honor CMAKE_REQUIRED_LIBRARIES. " + "Run \"cmake --help-policy CMP0075\" for policy details. " + "Use the cmake_policy command to set the policy and suppress this warning." + "\n" + "CMAKE_REQUIRED_LIBRARIES is set to:\n" + " ${CMAKE_REQUIRED_LIBRARIES}\n" + "For compatibility with CMake 3.11 and below this check is ignoring it." + ) + endif() + unset(_CIF_CMP0075) + endif() + try_compile(${VARIABLE} ${CMAKE_BINARY_DIR} ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeTmp/CheckIncludeFile.cxx COMPILE_DEFINITIONS ${CMAKE_REQUIRED_DEFINITIONS} + ${_CIF_LINK_LIBRARIES} CMAKE_FLAGS -DCOMPILE_DEFINITIONS:STRING=${MACRO_CHECK_INCLUDE_FILE_FLAGS} "${CHECK_INCLUDE_FILE_CXX_INCLUDE_DIRS}" OUTPUT_VARIABLE OUTPUT) + unset(_CIF_LINK_LIBRARIES) if(${ARGC} EQUAL 3) set(CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS_SAVE}) diff --git a/Modules/CheckIncludeFiles.cmake b/Modules/CheckIncludeFiles.cmake index 59afdab..c689f05 100644 --- a/Modules/CheckIncludeFiles.cmake +++ b/Modules/CheckIncludeFiles.cmake @@ -33,6 +33,8 @@ # list of macros to define (-DFOO=bar) # ``CMAKE_REQUIRED_INCLUDES`` # list of include directories +# ``CMAKE_REQUIRED_LIBRARIES`` +# A list of libraries to link. See policy :policy:`CMP0075`. # ``CMAKE_REQUIRED_QUIET`` # execute quietly without messages # @@ -95,6 +97,29 @@ macro(CHECK_INCLUDE_FILES INCLUDE VARIABLE) set(_description "include file ${_INCLUDE}") endif() + set(_CIF_LINK_LIBRARIES "") + if(CMAKE_REQUIRED_LIBRARIES) + cmake_policy(GET CMP0075 _CIF_CMP0075 + PARENT_SCOPE # undocumented, do not use outside of CMake + ) + if("x${_CIF_CMP0075}x" STREQUAL "xNEWx") + set(_CIF_LINK_LIBRARIES LINK_LIBRARIES ${CMAKE_REQUIRED_LIBRARIES}) + elseif("x${_CIF_CMP0075}x" STREQUAL "xOLDx") + elseif(NOT _CIF_CMP0075_WARNED) + set(_CIF_CMP0075_WARNED 1) + message(AUTHOR_WARNING + "Policy CMP0075 is not set: Include file check macros honor CMAKE_REQUIRED_LIBRARIES. " + "Run \"cmake --help-policy CMP0075\" for policy details. " + "Use the cmake_policy command to set the policy and suppress this warning." + "\n" + "CMAKE_REQUIRED_LIBRARIES is set to:\n" + " ${CMAKE_REQUIRED_LIBRARIES}\n" + "For compatibility with CMake 3.11 and below this check is ignoring it." + ) + endif() + unset(_CIF_CMP0075) + endif() + if(NOT CMAKE_REQUIRED_QUIET) message(STATUS "Looking for ${_description}") endif() @@ -102,10 +127,12 @@ macro(CHECK_INCLUDE_FILES INCLUDE VARIABLE) ${CMAKE_BINARY_DIR} ${src} COMPILE_DEFINITIONS ${CMAKE_REQUIRED_DEFINITIONS} + ${_CIF_LINK_LIBRARIES} CMAKE_FLAGS -DCOMPILE_DEFINITIONS:STRING=${MACRO_CHECK_INCLUDE_FILES_FLAGS} "${CHECK_INCLUDE_FILES_INCLUDE_DIRS}" OUTPUT_VARIABLE OUTPUT) + unset(_CIF_LINK_LIBRARIES) if(${VARIABLE}) if(NOT CMAKE_REQUIRED_QUIET) message(STATUS "Looking for ${_description} - found") diff --git a/Modules/CheckSymbolExists.cmake b/Modules/CheckSymbolExists.cmake index d9c9ae4..3483121 100644 --- a/Modules/CheckSymbolExists.cmake +++ b/Modules/CheckSymbolExists.cmake @@ -45,6 +45,9 @@ the way the check is run: include_guard(GLOBAL) +cmake_policy(PUSH) +cmake_policy(SET CMP0054 NEW) # if() quoted variables not dereferenced + macro(CHECK_SYMBOL_EXISTS SYMBOL FILES VARIABLE) if(CMAKE_C_COMPILER_LOADED) __CHECK_SYMBOL_EXISTS_IMPL("${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeTmp/CheckSymbolExists.c" "${SYMBOL}" "${FILES}" "${VARIABLE}" ) @@ -116,3 +119,5 @@ macro(__CHECK_SYMBOL_EXISTS_IMPL SOURCEFILE SYMBOL FILES VARIABLE) endif() endif() endmacro() + +cmake_policy(POP) diff --git a/Modules/Compiler/CMakeCommonCompilerMacros.cmake b/Modules/Compiler/CMakeCommonCompilerMacros.cmake index 684fd30..ad464c7 100644 --- a/Modules/Compiler/CMakeCommonCompilerMacros.cmake +++ b/Modules/Compiler/CMakeCommonCompilerMacros.cmake @@ -78,6 +78,9 @@ endmacro() # Define to allow compile features to be automatically determined macro(cmake_record_cxx_compile_features) set(_result 0) + if(_result EQUAL 0 AND DEFINED CMAKE_CXX20_STANDARD_COMPILE_OPTION) + _record_compiler_features_cxx(20) + endif() if(_result EQUAL 0 AND DEFINED CMAKE_CXX17_STANDARD_COMPILE_OPTION) _record_compiler_features_cxx(17) endif() diff --git a/Modules/Compiler/Clang-CXX.cmake b/Modules/Compiler/Clang-CXX.cmake index efc68b3..e99011b 100644 --- a/Modules/Compiler/Clang-CXX.cmake +++ b/Modules/Compiler/Clang-CXX.cmake @@ -32,12 +32,52 @@ if(NOT "x${CMAKE_CXX_SIMULATE_ID}" STREQUAL "xMSVC") set(CMAKE_CXX14_EXTENSION_COMPILE_OPTION "-std=gnu++1y") endif() - if (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 3.5) + set(_clang_version_std17 5.0) + if(CMAKE_SYSTEM_NAME STREQUAL "Android") + set(_clang_version_std17 6.0) + endif() + + if (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS "${_clang_version_std17}") + set(CMAKE_CXX17_STANDARD_COMPILE_OPTION "-std=c++17") + set(CMAKE_CXX17_EXTENSION_COMPILE_OPTION "-std=gnu++17") + elseif (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 3.5) set(CMAKE_CXX17_STANDARD_COMPILE_OPTION "-std=c++1z") set(CMAKE_CXX17_EXTENSION_COMPILE_OPTION "-std=gnu++1z") endif() + + if (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS "${_clang_version_std17}") + set(CMAKE_CXX20_STANDARD_COMPILE_OPTION "-std=c++2a") + set(CMAKE_CXX20_EXTENSION_COMPILE_OPTION "-std=gnu++2a") + endif() + + unset(_clang_version_std17) + + __compiler_check_default_language_standard(CXX 2.1 98) +elseif(CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 3.9 + AND CMAKE_CXX_SIMULATE_VERSION VERSION_GREATER_EQUAL 19.0) + # This version of clang-cl and the MSVC version it simulates have + # support for -std: flags. + set(CMAKE_CXX98_STANDARD_COMPILE_OPTION "") + set(CMAKE_CXX98_EXTENSION_COMPILE_OPTION "") + set(CMAKE_CXX11_STANDARD_COMPILE_OPTION "") + set(CMAKE_CXX11_EXTENSION_COMPILE_OPTION "") + set(CMAKE_CXX14_STANDARD_COMPILE_OPTION "-std:c++14") + set(CMAKE_CXX14_EXTENSION_COMPILE_OPTION "-std:c++14") + if (CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 6.0) + set(CMAKE_CXX17_STANDARD_COMPILE_OPTION "-std:c++17") + set(CMAKE_CXX17_EXTENSION_COMPILE_OPTION "-std:c++17") + set(CMAKE_CXX20_STANDARD_COMPILE_OPTION "-std:c++latest") + set(CMAKE_CXX20_EXTENSION_COMPILE_OPTION "-std:c++latest") + else() + set(CMAKE_CXX17_STANDARD_COMPILE_OPTION "-std:c++latest") + set(CMAKE_CXX17_EXTENSION_COMPILE_OPTION "-std:c++latest") + endif() + + __compiler_check_default_language_standard(CXX 3.9 14) else() - # clang-cl does not know these options because it behaves like cl.exe + # This version of clang-cl, or the MSVC version it simulates, does not have + # language standards. Set these options as empty strings so the feature + # test infrastructure can at least check to see if they are defined. set(CMAKE_CXX98_STANDARD_COMPILE_OPTION "") set(CMAKE_CXX98_EXTENSION_COMPILE_OPTION "") set(CMAKE_CXX11_STANDARD_COMPILE_OPTION "") @@ -46,10 +86,24 @@ else() set(CMAKE_CXX14_EXTENSION_COMPILE_OPTION "") set(CMAKE_CXX17_STANDARD_COMPILE_OPTION "") set(CMAKE_CXX17_EXTENSION_COMPILE_OPTION "") -endif() + set(CMAKE_CXX20_STANDARD_COMPILE_OPTION "") + set(CMAKE_CXX20_EXTENSION_COMPILE_OPTION "") -if(NOT "x${CMAKE_CXX_SIMULATE_ID}" STREQUAL "xMSVC") - __compiler_check_default_language_standard(CXX 2.1 98) -else() + # There is no meaningful default for this set(CMAKE_CXX_STANDARD_DEFAULT "") + + # There are no compiler modes so we only need to test features once. + # Override the default macro for this special case. Pretend that + # all language standards are available so that at least compilation + # can be attempted. + macro(cmake_record_cxx_compile_features) + list(APPEND CMAKE_CXX_COMPILE_FEATURES + cxx_std_98 + cxx_std_11 + cxx_std_14 + cxx_std_17 + cxx_std_20 + ) + _record_compiler_features(CXX "" CMAKE_CXX_COMPILE_FEATURES) + endmacro() endif() diff --git a/Modules/Compiler/GNU-CXX.cmake b/Modules/Compiler/GNU-CXX.cmake index 4f1f30e..0058223 100644 --- a/Modules/Compiler/GNU-CXX.cmake +++ b/Modules/Compiler/GNU-CXX.cmake @@ -33,9 +33,17 @@ elseif (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 4.8) set(CMAKE_CXX14_EXTENSION_COMPILE_OPTION "-std=gnu++1y") endif() -if (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 5.1) +if (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 8.0) + set(CMAKE_CXX17_STANDARD_COMPILE_OPTION "-std=c++17") + set(CMAKE_CXX17_EXTENSION_COMPILE_OPTION "-std=gnu++17") +elseif (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 5.1) set(CMAKE_CXX17_STANDARD_COMPILE_OPTION "-std=c++1z") set(CMAKE_CXX17_EXTENSION_COMPILE_OPTION "-std=gnu++1z") endif() +if (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 8.0) + set(CMAKE_CXX20_STANDARD_COMPILE_OPTION "-std=c++2a") + set(CMAKE_CXX20_EXTENSION_COMPILE_OPTION "-std=gnu++2a") +endif() + __compiler_check_default_language_standard(CXX 3.4 98 6.0 14) diff --git a/Modules/Compiler/MSVC-C-FeatureTests.cmake b/Modules/Compiler/MSVC-C-FeatureTests.cmake new file mode 100644 index 0000000..3f09be2 --- /dev/null +++ b/Modules/Compiler/MSVC-C-FeatureTests.cmake @@ -0,0 +1,8 @@ +set(_cmake_oldestSupported "_MSC_VER >= 1600") + +# Not yet supported: +#set(_cmake_feature_test_c_static_assert "") +#set(_cmake_feature_test_c_restrict "") + +set(_cmake_feature_test_c_variadic_macros "${_cmake_oldestSupported}") +set(_cmake_feature_test_c_function_prototypes "${_cmake_oldestSupported}") diff --git a/Modules/Compiler/MSVC-C.cmake b/Modules/Compiler/MSVC-C.cmake new file mode 100644 index 0000000..22c34f8 --- /dev/null +++ b/Modules/Compiler/MSVC-C.cmake @@ -0,0 +1,25 @@ +# MSVC has no specific options to set C language standards, but set them as +# empty strings anyways so the feature test infrastructure can at least check +# to see if they are defined. +set(CMAKE_C90_STANDARD_COMPILE_OPTION "") +set(CMAKE_C90_EXTENSION_COMPILE_OPTION "") +set(CMAKE_C99_STANDARD_COMPILE_OPTION "") +set(CMAKE_C99_EXTENSION_COMPILE_OPTION "") +set(CMAKE_C11_STANDARD_COMPILE_OPTION "") +set(CMAKE_C11_EXTENSION_COMPILE_OPTION "") + +# There is no meaningful default for this +set(CMAKE_C_STANDARD_DEFAULT "") + +# There are no C compiler modes so we only need to test features once. +# Override the default macro for this special case. Pretend that +# all language standards are available so that at least compilation +# can be attempted. +macro(cmake_record_c_compile_features) + list(APPEND CMAKE_C_COMPILE_FEATURES + c_std_90 + c_std_99 + c_std_11 + ) + _record_compiler_features(C "" CMAKE_C_COMPILE_FEATURES) +endmacro() diff --git a/Modules/Compiler/MSVC-CXX.cmake b/Modules/Compiler/MSVC-CXX.cmake index 789fff5..be259ff 100644 --- a/Modules/Compiler/MSVC-CXX.cmake +++ b/Modules/Compiler/MSVC-CXX.cmake @@ -22,6 +22,10 @@ if ((CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 19.0.24215.1 AND set(CMAKE_CXX17_STANDARD_COMPILE_OPTION "-std:c++latest") set(CMAKE_CXX17_EXTENSION_COMPILE_OPTION "-std:c++latest") endif() + if (CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 19.12.25835) + set(CMAKE_CXX20_STANDARD_COMPILE_OPTION "-std:c++latest") + set(CMAKE_CXX20_EXTENSION_COMPILE_OPTION "-std:c++latest") + endif() __compiler_check_default_language_standard(CXX 19.0 14) @@ -29,6 +33,12 @@ if ((CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 19.0.24215.1 AND # for meta-features for C++14 and above. Override the default macro # to avoid doing unnecessary work. macro(cmake_record_cxx_compile_features) + if (DEFINED CMAKE_CXX20_STANDARD_COMPILE_OPTION) + list(APPEND CMAKE_CXX20_COMPILE_FEATURES cxx_std_20) + endif() + # The main cmake_record_cxx_compile_features macro makes all + # these conditional on CMAKE_CXX##_STANDARD_COMPILE_OPTION, + # but we can skip the conditions because we set them above. list(APPEND CMAKE_CXX17_COMPILE_FEATURES cxx_std_17) list(APPEND CMAKE_CXX14_COMPILE_FEATURES cxx_std_14) list(APPEND CMAKE_CXX98_COMPILE_FEATURES cxx_std_11) # no flag needed for 11 @@ -46,6 +56,8 @@ elseif (CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 16.0) set(CMAKE_CXX14_EXTENSION_COMPILE_OPTION "") set(CMAKE_CXX17_STANDARD_COMPILE_OPTION "") set(CMAKE_CXX17_EXTENSION_COMPILE_OPTION "") + set(CMAKE_CXX20_STANDARD_COMPILE_OPTION "") + set(CMAKE_CXX20_EXTENSION_COMPILE_OPTION "") # There is no meaningful default for this set(CMAKE_CXX_STANDARD_DEFAULT "") @@ -60,6 +72,7 @@ elseif (CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 16.0) cxx_std_11 cxx_std_14 cxx_std_17 + cxx_std_20 ) _record_compiler_features(CXX "" CMAKE_CXX_COMPILE_FEATURES) endmacro() diff --git a/Modules/Compiler/NVIDIA-DetermineCompiler.cmake b/Modules/Compiler/NVIDIA-DetermineCompiler.cmake index cb0beaf..bf9111a 100644 --- a/Modules/Compiler/NVIDIA-DetermineCompiler.cmake +++ b/Modules/Compiler/NVIDIA-DetermineCompiler.cmake @@ -2,9 +2,11 @@ set(_compiler_id_pp_test "defined(__NVCC__)") set(_compiler_id_version_compute " -# define @PREFIX@COMPILER_VERSION_MAJOR @MACRO_DEC@(__CUDACC_VER_MAJOR__) -# define @PREFIX@COMPILER_VERSION_MINOR @MACRO_DEC@(__CUDACC_VER_MINOR__) -# define @PREFIX@COMPILER_VERSION_PATCH @MACRO_DEC@(__CUDACC_VER_BUILD__) +# if defined(__CUDACC_VER_MAJOR__) +# define @PREFIX@COMPILER_VERSION_MAJOR @MACRO_DEC@(__CUDACC_VER_MAJOR__) +# define @PREFIX@COMPILER_VERSION_MINOR @MACRO_DEC@(__CUDACC_VER_MINOR__) +# define @PREFIX@COMPILER_VERSION_PATCH @MACRO_DEC@(__CUDACC_VER_BUILD__) +# endif # if defined(_MSC_VER) /* _MSC_VER = VVRR */ # define @PREFIX@SIMULATE_VERSION_MAJOR @MACRO_DEC@(_MSC_VER / 100) diff --git a/Modules/Compiler/SunPro-C.cmake b/Modules/Compiler/SunPro-C.cmake index 29c2f22..8d0e6d6 100644 --- a/Modules/Compiler/SunPro-C.cmake +++ b/Modules/Compiler/SunPro-C.cmake @@ -18,6 +18,8 @@ string(APPEND CMAKE_C_FLAGS_MINSIZEREL_INIT " -xO2 -xspace -DNDEBUG") string(APPEND CMAKE_C_FLAGS_RELEASE_INIT " -xO3 -DNDEBUG") string(APPEND CMAKE_C_FLAGS_RELWITHDEBINFO_INIT " -g -xO2 -DNDEBUG") +set(CMAKE_DEPFILE_FLAGS_C "-xMD -xMF <DEPFILE>") + # Initialize C link type selection flags. These flags are used when # building a shared library, shared module, or executable that links # to other libraries to select whether to use the static or shared diff --git a/Modules/Compiler/SunPro-CXX.cmake b/Modules/Compiler/SunPro-CXX.cmake index 5cb7edc..14196b7 100644 --- a/Modules/Compiler/SunPro-CXX.cmake +++ b/Modules/Compiler/SunPro-CXX.cmake @@ -18,6 +18,8 @@ string(APPEND CMAKE_CXX_FLAGS_MINSIZEREL_INIT " -xO2 -xspace -DNDEBUG") string(APPEND CMAKE_CXX_FLAGS_RELEASE_INIT " -xO3 -DNDEBUG") string(APPEND CMAKE_CXX_FLAGS_RELWITHDEBINFO_INIT " -g -xO2 -DNDEBUG") +set(CMAKE_DEPFILE_FLAGS_CXX "-xMD -xMF <DEPFILE>") + # Initialize C link type selection flags. These flags are used when # building a shared library, shared module, or executable that links # to other libraries to select whether to use the static or shared diff --git a/Modules/Compiler/XL.cmake b/Modules/Compiler/XL.cmake index e527a04..3361f8f 100644 --- a/Modules/Compiler/XL.cmake +++ b/Modules/Compiler/XL.cmake @@ -30,6 +30,8 @@ macro(__compiler_xl lang) set(CMAKE_${lang}_CREATE_PREPROCESSED_SOURCE "<CMAKE_${lang}_COMPILER> <DEFINES> <INCLUDES> <FLAGS> -E <SOURCE> > <PREPROCESSED_SOURCE>") set(CMAKE_${lang}_CREATE_ASSEMBLY_SOURCE "<CMAKE_${lang}_COMPILER> <DEFINES> <INCLUDES> <FLAGS> -S <SOURCE> -o <ASSEMBLY_SOURCE>") + set(CMAKE_DEPFILE_FLAGS_${lang} "-MF <DEPFILE> -qmakedep=gcc") + # CMAKE_XL_CreateExportList is part of the AIX XL compilers but not the linux ones. # If we found the tool, we'll use it to create exports, otherwise stick with the regular # create shared library compile line. diff --git a/Modules/ExternalData.cmake b/Modules/ExternalData.cmake index 7331fb2..e5dbcd9 100644 --- a/Modules/ExternalData.cmake +++ b/Modules/ExternalData.cmake @@ -1133,7 +1133,7 @@ if("${ExternalData_ACTION}" STREQUAL "fetch") if(file_up_to_date) # Touch the file to convince the build system it is up to date. - execute_process(COMMAND "${CMAKE_COMMAND}" -E touch "${file}") + file(TOUCH "${file}") else() _ExternalData_link_or_copy("${obj}" "${file}") endif() diff --git a/Modules/FindBoost.cmake b/Modules/FindBoost.cmake index 8d44aee..5b5002a 100644 --- a/Modules/FindBoost.cmake +++ b/Modules/FindBoost.cmake @@ -458,20 +458,10 @@ function(_Boost_GUESS_COMPILER_PREFIX _ret) elseif (GHSMULTI) set(_boost_COMPILER "-ghs") elseif("x${CMAKE_CXX_COMPILER_ID}" STREQUAL "xMSVC") - if (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 19.10) + if(MSVC_TOOLSET_VERSION GREATER_EQUAL 141) set(_boost_COMPILER "-vc141;-vc140") - elseif (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 19) - set(_boost_COMPILER "-vc140") - elseif(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 18) - set(_boost_COMPILER "-vc120") - elseif(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 17) - set(_boost_COMPILER "-vc110") - elseif(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 16) - set(_boost_COMPILER "-vc100") - elseif(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 15) - set(_boost_COMPILER "-vc90") - elseif(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 14) - set(_boost_COMPILER "-vc80") + elseif(MSVC_TOOLSET_VERSION GREATER_EQUAL 80) + set(_boost_COMPILER "-vc${MSVC_TOOLSET_VERSION}") elseif(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 13.10) set(_boost_COMPILER "-vc71") elseif(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 13) # Good luck! @@ -1009,21 +999,12 @@ function(_Boost_UPDATE_WINDOWS_LIBRARY_SEARCH_DIRS_WITH_PREBUILT_PATHS component else() set(_arch_suffix 32) endif() - if(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 19.10) + if(MSVC_TOOLSET_VERSION GREATER_EQUAL 141) list(APPEND ${componentlibvar} ${basedir}/lib${_arch_suffix}-msvc-14.1) list(APPEND ${componentlibvar} ${basedir}/lib${_arch_suffix}-msvc-14.0) - elseif(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 19) - list(APPEND ${componentlibvar} ${basedir}/lib${_arch_suffix}-msvc-14.0) - elseif(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 18) - list(APPEND ${componentlibvar} ${basedir}/lib${_arch_suffix}-msvc-12.0) - elseif(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 17) - list(APPEND ${componentlibvar} ${basedir}/lib${_arch_suffix}-msvc-11.0) - elseif(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 16) - list(APPEND ${componentlibvar} ${basedir}/lib${_arch_suffix}-msvc-10.0) - elseif(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 15) - list(APPEND ${componentlibvar} ${basedir}/lib${_arch_suffix}-msvc-9.0) - elseif(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 14) - list(APPEND ${componentlibvar} ${basedir}/lib${_arch_suffix}-msvc-8.0) + elseif(MSVC_TOOLSET_VERSION GREATER_EQUAL 80) + math(EXPR _toolset_major_version "${MSVC_TOOLSET_VERSION} / 10") + list(APPEND ${componentlibvar} ${basedir}/lib${_arch_suffix}-msvc-${_toolset_major_version}.0) endif() set(${componentlibvar} ${${componentlibvar}} PARENT_SCOPE) endif() diff --git a/Modules/FindCUDA.cmake b/Modules/FindCUDA.cmake index 0a31ac2..a0e4aa9 100644 --- a/Modules/FindCUDA.cmake +++ b/Modules/FindCUDA.cmake @@ -175,7 +175,7 @@ # -- Same as CUDA_ADD_EXECUTABLE except that a library is created. # # CUDA_BUILD_CLEAN_TARGET() -# -- Creates a convience target that deletes all the dependency files +# -- Creates a convenience target that deletes all the dependency files # generated. You should make clean after running this target to ensure the # dependency files get regenerated. # @@ -557,6 +557,11 @@ else() set(c_compiler_realpath "") endif() set(CUDA_HOST_COMPILER "${c_compiler_realpath}" CACHE FILEPATH "Host side compiler used by NVCC") + elseif(MSVC AND "${CMAKE_C_COMPILER}" MATCHES "clcache") + # NVCC does not think it will work if it is passed clcache.exe as the host + # compiler, which means that builds with CC=cl.exe won't work. Best to just + # feed it whatever the actual cl.exe is as the host compiler. + set(CUDA_HOST_COMPILER "cl.exe" CACHE FILEPATH "Host side compiler used by NVCC") else() set(CUDA_HOST_COMPILER "${CMAKE_C_COMPILER}" CACHE FILEPATH "Host side compiler used by NVCC") @@ -733,16 +738,20 @@ endif() # CUDA_NVCC_EXECUTABLE -cuda_find_host_program(CUDA_NVCC_EXECUTABLE - NAMES nvcc - PATHS "${CUDA_TOOLKIT_ROOT_DIR}" - ENV CUDA_PATH - ENV CUDA_BIN_PATH - PATH_SUFFIXES bin bin64 - NO_DEFAULT_PATH - ) -# Search default search paths, after we search our own set of paths. -cuda_find_host_program(CUDA_NVCC_EXECUTABLE nvcc) +if(DEFINED ENV{CUDA_NVCC_EXECUTABLE}) + set(CUDA_NVCC_EXECUTABLE "$ENV{CUDA_NVCC_EXECUTABLE}" CACHE FILEPATH "The CUDA compiler") +else() + cuda_find_host_program(CUDA_NVCC_EXECUTABLE + NAMES nvcc + PATHS "${CUDA_TOOLKIT_ROOT_DIR}" + ENV CUDA_PATH + ENV CUDA_BIN_PATH + PATH_SUFFIXES bin bin64 + NO_DEFAULT_PATH + ) + # Search default search paths, after we search our own set of paths. + cuda_find_host_program(CUDA_NVCC_EXECUTABLE nvcc) +endif() mark_as_advanced(CUDA_NVCC_EXECUTABLE) if(CUDA_NVCC_EXECUTABLE AND NOT CUDA_VERSION) @@ -1564,7 +1573,7 @@ macro(CUDA_WRAP_SRCS cuda_target format generated_files) # Bring in the dependencies. Creates a variable CUDA_NVCC_DEPEND ####### cuda_include_nvcc_dependencies(${cmake_dependency_file}) - # Convience string for output ########################################### + # Convenience string for output ######################################### if(CUDA_BUILD_EMULATION) set(cuda_build_type "Emulation") else() @@ -1975,9 +1984,9 @@ endmacro() ############################################################################### ############################################################################### macro(CUDA_BUILD_CLEAN_TARGET) - # Call this after you add all your CUDA targets, and you will get a convience - # target. You should also make clean after running this target to get the - # build system to generate all the code again. + # Call this after you add all your CUDA targets, and you will get a + # convenience target. You should also make clean after running this target + # to get the build system to generate all the code again. set(cuda_clean_target_name clean_cuda_depends) if (CMAKE_GENERATOR MATCHES "Visual Studio") diff --git a/Modules/FindCUDA/select_compute_arch.cmake b/Modules/FindCUDA/select_compute_arch.cmake index b604a17..22c04df 100644 --- a/Modules/FindCUDA/select_compute_arch.cmake +++ b/Modules/FindCUDA/select_compute_arch.cmake @@ -17,29 +17,55 @@ # More info on CUDA architectures: https://en.wikipedia.org/wiki/CUDA # +if(CMAKE_CUDA_COMPILER_LOADED) # CUDA as a language + if(CMAKE_CUDA_COMPILER_ID STREQUAL "NVIDIA") + set(CUDA_VERSION "${CMAKE_CUDA_COMPILER_VERSION}") + endif() +endif() + +# See: https://docs.nvidia.com/cuda/cuda-compiler-driver-nvcc/index.html#gpu-feature-list + # This list will be used for CUDA_ARCH_NAME = All option set(CUDA_KNOWN_GPU_ARCHITECTURES "Fermi" "Kepler" "Maxwell") # This list will be used for CUDA_ARCH_NAME = Common option (enabled by default) set(CUDA_COMMON_GPU_ARCHITECTURES "3.0" "3.5" "5.0") -if (CUDA_VERSION VERSION_GREATER "6.5") +if(CUDA_VERSION VERSION_LESS "7.0") + set(CUDA_LIMIT_GPU_ARCHITECTURE "5.2") +endif() + +# This list is used to filter CUDA archs when autodetecting +set(CUDA_ALL_GPU_ARCHITECTURES "3.0" "3.2" "3.5" "5.0") + +if(CUDA_VERSION VERSION_GREATER_EQUAL "7.0") list(APPEND CUDA_KNOWN_GPU_ARCHITECTURES "Kepler+Tegra" "Kepler+Tesla" "Maxwell+Tegra") list(APPEND CUDA_COMMON_GPU_ARCHITECTURES "5.2") -endif () -if (CUDA_VERSION VERSION_GREATER "7.5") + if(CUDA_VERSION VERSION_LESS "8.0") + list(APPEND CUDA_COMMON_GPU_ARCHITECTURES "5.2+PTX") + set(CUDA_LIMIT_GPU_ARCHITECTURE "6.0") + endif() +endif() + +if(CUDA_VERSION VERSION_GREATER_EQUAL "8.0") list(APPEND CUDA_KNOWN_GPU_ARCHITECTURES "Pascal") list(APPEND CUDA_COMMON_GPU_ARCHITECTURES "6.0" "6.1") -else() - list(APPEND CUDA_COMMON_GPU_ARCHITECTURES "5.2+PTX") + list(APPEND CUDA_ALL_GPU_ARCHITECTURES "6.0" "6.1" "6.2") + + if(CUDA_VERSION VERSION_LESS "9.0") + list(APPEND CUDA_COMMON_GPU_ARCHITECTURES "6.1+PTX") + set(CUDA_LIMIT_GPU_ARCHITECTURE "7.0") + endif() endif () -if (CUDA_VERSION VERSION_GREATER "8.5") +if(CUDA_VERSION VERSION_GREATER_EQUAL "9.0") list(APPEND CUDA_KNOWN_GPU_ARCHITECTURES "Volta") list(APPEND CUDA_COMMON_GPU_ARCHITECTURES "7.0" "7.0+PTX") -else() - list(APPEND CUDA_COMMON_GPU_ARCHITECTURES "6.1+PTX") + + if(CUDA_VERSION VERSION_LESS "10.0") + set(CUDA_LIMIT_GPU_ARCHITECTURE "8.0") + endif() endif() ################################################################################################ @@ -49,7 +75,11 @@ endif() # function(CUDA_DETECT_INSTALLED_GPUS OUT_VARIABLE) if(NOT CUDA_GPU_DETECT_OUTPUT) - set(file ${PROJECT_BINARY_DIR}/detect_cuda_compute_capabilities.cpp) + if(CMAKE_CUDA_COMPILER_LOADED) # CUDA as a language + set(file "${PROJECT_BINARY_DIR}/detect_cuda_compute_capabilities.cu") + else() + set(file "${PROJECT_BINARY_DIR}/detect_cuda_compute_capabilities.cpp") + endif() file(WRITE ${file} "" "#include <cuda_runtime.h>\n" @@ -68,10 +98,15 @@ function(CUDA_DETECT_INSTALLED_GPUS OUT_VARIABLE) " return 0;\n" "}\n") - try_run(run_result compile_result ${PROJECT_BINARY_DIR} ${file} - CMAKE_FLAGS "-DINCLUDE_DIRECTORIES=${CUDA_INCLUDE_DIRS}" - LINK_LIBRARIES ${CUDA_LIBRARIES} - RUN_OUTPUT_VARIABLE compute_capabilities) + if(CMAKE_CUDA_COMPILER_LOADED) # CUDA as a language + try_run(run_result compile_result ${PROJECT_BINARY_DIR} ${file} + RUN_OUTPUT_VARIABLE compute_capabilities) + else() + try_run(run_result compile_result ${PROJECT_BINARY_DIR} ${file} + CMAKE_FLAGS "-DINCLUDE_DIRECTORIES=${CUDA_INCLUDE_DIRS}" + LINK_LIBRARIES ${CUDA_LIBRARIES} + RUN_OUTPUT_VARIABLE compute_capabilities) + endif() if(run_result EQUAL 0) string(REPLACE "2.1" "2.1(2.0)" compute_capabilities "${compute_capabilities}") @@ -84,7 +119,19 @@ function(CUDA_DETECT_INSTALLED_GPUS OUT_VARIABLE) message(STATUS "Automatic GPU detection failed. Building for common architectures.") set(${OUT_VARIABLE} ${CUDA_COMMON_GPU_ARCHITECTURES} PARENT_SCOPE) else() - set(${OUT_VARIABLE} ${CUDA_GPU_DETECT_OUTPUT} PARENT_SCOPE) + # Filter based on CUDA version supported archs + set(CUDA_GPU_DETECT_OUTPUT_FILTERED "") + separate_arguments(CUDA_GPU_DETECT_OUTPUT) + foreach(ITEM IN ITEMS ${CUDA_GPU_DETECT_OUTPUT}) + if(CUDA_LIMIT_GPU_ARCHITECTURE AND ITEM VERSION_GREATER_EQUAL CUDA_LIMIT_GPU_ARCHITECTURE) + list(GET CUDA_COMMON_GPU_ARCHITECTURES -1 NEWITEM) + string(APPEND CUDA_GPU_DETECT_OUTPUT_FILTERED " ${NEWITEM}") + else() + string(APPEND CUDA_GPU_DETECT_OUTPUT_FILTERED " ${ITEM}") + endif() + endforeach() + + set(${OUT_VARIABLE} ${CUDA_GPU_DETECT_OUTPUT_FILTERED} PARENT_SCOPE) endif() endfunction() diff --git a/Modules/FindCURL.cmake b/Modules/FindCURL.cmake index f4bcc36..e66ae92 100644 --- a/Modules/FindCURL.cmake +++ b/Modules/FindCURL.cmake @@ -5,16 +5,30 @@ # FindCURL # -------- # -# Find curl -# # Find the native CURL headers and libraries. # -# :: +# IMPORTED Targets +# ^^^^^^^^^^^^^^^^ +# +# This module defines :prop_tgt:`IMPORTED` target ``CURL::CURL``, if +# curl has been found. +# +# Result Variables +# ^^^^^^^^^^^^^^^^ +# +# This module defines the following variables: # -# CURL_INCLUDE_DIRS - where to find curl/curl.h, etc. -# CURL_LIBRARIES - List of libraries when using curl. -# CURL_FOUND - True if curl found. -# CURL_VERSION_STRING - the version of curl found (since CMake 2.8.8) +# ``CURL_FOUND`` +# True if curl found. +# +# ``CURL_INCLUDE_DIRS`` +# where to find curl/curl.h, etc. +# +# ``CURL_LIBRARIES`` +# List of libraries when using curl. +# +# ``CURL_VERSION_STRING`` +# The version of curl found. # Look for the header file. find_path(CURL_INCLUDE_DIR NAMES curl/curl.h) @@ -52,4 +66,10 @@ FIND_PACKAGE_HANDLE_STANDARD_ARGS(CURL if(CURL_FOUND) set(CURL_LIBRARIES ${CURL_LIBRARY}) set(CURL_INCLUDE_DIRS ${CURL_INCLUDE_DIR}) + + if(NOT TARGET CURL::CURL) + add_library(CURL::CURL UNKNOWN IMPORTED) + set_target_properties(CURL::CURL PROPERTIES INTERFACE_INCLUDE_DIRECTORIES "${CURL_INCLUDE_DIRS}") + set_property(TARGET CURL::CURL APPEND PROPERTY IMPORTED_LOCATION "${CURL_LIBRARY}") + endif() endif() diff --git a/Modules/FindCxxTest.cmake b/Modules/FindCxxTest.cmake index 2aa5f6f..25454fd 100644 --- a/Modules/FindCxxTest.cmake +++ b/Modules/FindCxxTest.cmake @@ -196,7 +196,7 @@ if(NOT DEFINED CXXTEST_TESTGEN_ARGS) set(CXXTEST_TESTGEN_ARGS --error-printer) endif() -find_package(PythonInterp QUIET) +find_package(Python QUIET) find_package(Perl QUIET) find_path(CXXTEST_INCLUDE_DIR cxxtest/TestSuite.h) @@ -206,17 +206,17 @@ find_program(CXXTEST_PYTHON_TESTGEN_EXECUTABLE find_program(CXXTEST_PERL_TESTGEN_EXECUTABLE cxxtestgen.pl PATHS ${CXXTEST_INCLUDE_DIR}) -if(PYTHONINTERP_FOUND OR PERL_FOUND) +if(PYTHON_FOUND OR PERL_FOUND) include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake) - if(PYTHONINTERP_FOUND AND (CXXTEST_USE_PYTHON OR NOT PERL_FOUND OR NOT DEFINED CXXTEST_USE_PYTHON)) + if(PYTHON_FOUND AND (CXXTEST_USE_PYTHON OR NOT PERL_FOUND OR NOT DEFINED CXXTEST_USE_PYTHON)) set(CXXTEST_TESTGEN_EXECUTABLE ${CXXTEST_PYTHON_TESTGEN_EXECUTABLE}) execute_process(COMMAND ${CXXTEST_PYTHON_TESTGEN_EXECUTABLE} --version OUTPUT_VARIABLE _CXXTEST_OUT ERROR_VARIABLE _CXXTEST_OUT RESULT_VARIABLE _CXXTEST_RESULT) if(_CXXTEST_RESULT EQUAL 0) set(CXXTEST_TESTGEN_INTERPRETER "") else() - set(CXXTEST_TESTGEN_INTERPRETER ${PYTHON_EXECUTABLE}) + set(CXXTEST_TESTGEN_INTERPRETER ${Python_EXECUTABLE}) endif() FIND_PACKAGE_HANDLE_STANDARD_ARGS(CxxTest DEFAULT_MSG CXXTEST_INCLUDE_DIR CXXTEST_PYTHON_TESTGEN_EXECUTABLE) diff --git a/Modules/FindDCMTK.cmake b/Modules/FindDCMTK.cmake index f348d3a..39c1a5b 100644 --- a/Modules/FindDCMTK.cmake +++ b/Modules/FindDCMTK.cmake @@ -301,7 +301,7 @@ endif() # Compatibility: This variable is deprecated set(DCMTK_INCLUDE_DIR ${DCMTK_INCLUDE_DIRS}) -include(FindPackageHandleStandardArgs) +include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake) find_package_handle_standard_args(DCMTK REQUIRED_VARS ${DCMTK_INCLUDE_DIR_NAMES} DCMTK_LIBRARIES FAIL_MESSAGE "Please set DCMTK_DIR and re-run configure") @@ -309,20 +309,14 @@ find_package_handle_standard_args(DCMTK # Workaround bug in packaging of DCMTK 3.6.0 on Debian. # See http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=637687 if(DCMTK_FOUND AND UNIX AND NOT APPLE) - include(CheckCXXSourceCompiles) + include(${CMAKE_CURRENT_LIST_DIR}/CheckIncludeFiles.cmake) set(CMAKE_REQUIRED_FLAGS ) set(CMAKE_REQUIRED_DEFINITIONS ) set(CMAKE_REQUIRED_INCLUDES ${DCMTK_INCLUDE_DIRS}) set(CMAKE_REQUIRED_LIBRARIES ${DCMTK_LIBRARIES}) set(CMAKE_REQUIRED_QUIET ${DCMTK_FIND_QUIETLY}) - check_cxx_source_compiles("#include <dcmtk/config/osconfig.h>\n#include <dcmtk/ofstd/ofstream.h>\nint main(int,char*[]){return 0;}" - DCMTK_HAVE_CONFIG_H_OPTIONAL - ) + check_include_files("dcmtk/config/osconfig.h;dcmtk/ofstd/ofstream.h" DCMTK_HAVE_CONFIG_H_OPTIONAL LANGUAGE CXX) if(NOT DCMTK_HAVE_CONFIG_H_OPTIONAL) set(DCMTK_DEFINITIONS "HAVE_CONFIG_H") endif() endif() - -if(NOT DCMTK_FIND_QUIETLY) - message(STATUS "Trying to find DCMTK relying on FindDCMTK.cmake - ok") -endif() diff --git a/Modules/FindGDAL.cmake b/Modules/FindGDAL.cmake index 2b940b0..ff2976e 100644 --- a/Modules/FindGDAL.cmake +++ b/Modules/FindGDAL.cmake @@ -66,11 +66,49 @@ if(UNIX) if(GDAL_CONFIG) exec_program(${GDAL_CONFIG} ARGS --libs OUTPUT_VARIABLE GDAL_CONFIG_LIBS) + if(GDAL_CONFIG_LIBS) - string(REGEX MATCHALL "-l[^ ]+" _gdal_dashl ${GDAL_CONFIG_LIBS}) - string(REPLACE "-l" "" _gdal_lib "${_gdal_dashl}") - string(REGEX MATCHALL "-L[^ ]+" _gdal_dashL ${GDAL_CONFIG_LIBS}) - string(REPLACE "-L" "" _gdal_libpath "${_gdal_dashL}") + # treat the output as a command line and split it up + separate_arguments(args NATIVE_COMMAND "${GDAL_CONFIG_LIBS}") + + # only consider libraries whose name matches this pattern + set(name_pattern "[gG][dD][aA][lL]") + + # consider each entry as a possible library path, name, or parent directory + foreach(arg IN LISTS args) + # library name + if("${arg}" MATCHES "^-l(.*)$") + set(lib "${CMAKE_MATCH_1}") + + # only consider libraries whose name matches the expected pattern + if("${lib}" MATCHES "${name_pattern}") + list(APPEND _gdal_lib "${lib}") + endif() + # library search path + elseif("${arg}" MATCHES "^-L(.*)$") + list(APPEND _gdal_libpath "${CMAKE_MATCH_1}") + # assume this is a full path to a library + elseif(IS_ABSOLUTE "${arg}" AND EXISTS "${arg}") + # extract the file name + get_filename_component(lib "${arg}" NAME) + + # only consider libraries whose name matches the expected pattern + if(NOT "${lib}" MATCHES "${name_pattern}") + continue() + endif() + + # extract the file directory + get_filename_component(dir "${arg}" DIRECTORY) + + # remove library prefixes/suffixes + string(REGEX REPLACE "^(${CMAKE_SHARED_LIBRARY_PREFIX}|${CMAKE_STATIC_LIBRARY_PREFIX})" "" lib "${lib}") + string(REGEX REPLACE "(${CMAKE_SHARED_LIBRARY_SUFFIX}|${CMAKE_STATIC_LIBRARY_SUFFIX})$" "" lib "${lib}") + + # use the file name and directory as hints + list(APPEND _gdal_libpath "${dir}") + list(APPEND _gdal_lib "${lib}") + endif() + endforeach() endif() endif() endif() diff --git a/Modules/FindGTK2.cmake b/Modules/FindGTK2.cmake index 8d0da51..15d1230 100644 --- a/Modules/FindGTK2.cmake +++ b/Modules/FindGTK2.cmake @@ -352,13 +352,9 @@ function(_GTK2_FIND_LIBRARY _var _lib _expand_vc _append_version) if(_expand_vc AND MSVC) # Add vc80/vc90/vc100 midfixes - if(MSVC_VERSION EQUAL 1400) - set(_library ${_library}-vc80) - elseif(MSVC_VERSION EQUAL 1500) - set(_library ${_library}-vc90) - elseif(MSVC_VERSION EQUAL 1600) - set(_library ${_library}-vc100) - elseif(MSVC_VERSION EQUAL 1700) + if(MSVC_TOOLSET_VERSION LESS 110) + set(_library ${_library}-vc${MSVC_TOOLSET_VERSION}) + else() # Up to gtkmm-win 2.22.0-2 there are no vc110 libraries but vc100 can be used set(_library ${_library}-vc100) endif() diff --git a/Modules/FindIce.cmake b/Modules/FindIce.cmake index b37f796..df76e5a 100644 --- a/Modules/FindIce.cmake +++ b/Modules/FindIce.cmake @@ -255,21 +255,15 @@ function(_Ice_FIND) unset(vcvers) if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC") - if (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 19.10) + if(MSVC_TOOLSET_VERSION GREATER_EQUAL 141) set(vcvers "141;140") - elseif (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 19) - set(vcvers "140") - elseif(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 18) - set(vcvers "120") - elseif(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 17) - set(vcvers "110") - elseif(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 16) - set(vcvers "100") - elseif(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 15) - set(vcvers "90") + elseif(MSVC_TOOLSET_VERSION GREATER_EQUAL 100) + set(vcvers "${MSVC_TOOLSET_VERSION}") + elseif(MSVC_TOOLSET_VERSION GREATER_EQUAL 90) + set(vcvers "${MSVC_TOOLSET_VERSION}") set(vcyear "2008") - elseif(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 14) - set(vcvers "80") + elseif(MSVC_TOOLSET_VERSION GREATER_EQUAL 80) + set(vcvers "${MSVC_TOOLSET_VERSION}") set(vcyear "2005") else() # Unknown version set(vcvers Unknown) diff --git a/Modules/FindImageMagick.cmake b/Modules/FindImageMagick.cmake index 881bff1..6d94d3b 100644 --- a/Modules/FindImageMagick.cmake +++ b/Modules/FindImageMagick.cmake @@ -104,6 +104,7 @@ function(FIND_IMAGEMAGICK_API component header) PATH_SUFFIXES ImageMagick ImageMagick-6 ImageMagick-7 DOC "Path to the ImageMagick arch-independent include dir." + NO_DEFAULT_PATH ) find_path(ImageMagick_${component}_ARCH_INCLUDE_DIR NAMES magick/magick-baseconfig.h @@ -116,6 +117,7 @@ function(FIND_IMAGEMAGICK_API component header) PATH_SUFFIXES ImageMagick ImageMagick-6 ImageMagick-7 DOC "Path to the ImageMagick arch-specific include dir." + NO_DEFAULT_PATH ) find_library(ImageMagick_${component}_LIBRARY NAMES ${ARGN} @@ -125,6 +127,7 @@ function(FIND_IMAGEMAGICK_API component header) PATHS "[HKEY_LOCAL_MACHINE\\SOFTWARE\\ImageMagick\\Current;BinPath]/lib" DOC "Path to the ImageMagick Magick++ library." + NO_DEFAULT_PATH ) # old version have only indep dir diff --git a/Modules/FindJPEG.cmake b/Modules/FindJPEG.cmake index e233714..9542f69 100644 --- a/Modules/FindJPEG.cmake +++ b/Modules/FindJPEG.cmake @@ -5,38 +5,127 @@ # FindJPEG # -------- # -# Find JPEG +# Find the JPEG library (libjpeg) # -# Find the native JPEG includes and library This module defines +# Imported targets +# ^^^^^^^^^^^^^^^^ # -# :: +# This module defines the following :prop_tgt:`IMPORTED` targets: # -# JPEG_INCLUDE_DIR, where to find jpeglib.h, etc. -# JPEG_LIBRARIES, the libraries needed to use JPEG. -# JPEG_FOUND, If false, do not try to use JPEG. +# ``JPEG::JPEG`` +# The JPEG library, if found. # -# also defined, but not for general use are +# Result variables +# ^^^^^^^^^^^^^^^^ # -# :: +# This module will set the following variables in your project: # -# JPEG_LIBRARY, where to find the JPEG library. +# ``JPEG_FOUND`` +# If false, do not try to use JPEG. +# ``JPEG_INCLUDE_DIRS`` +# where to find jpeglib.h, etc. +# ``JPEG_LIBRARIES`` +# the libraries needed to use JPEG. +# ``JPEG_VERSION`` +# the version of the JPEG library found +# +# Cache variables +# ^^^^^^^^^^^^^^^ +# +# The following cache variables may also be set: +# +# ``JPEG_INCLUDE_DIRS`` +# where to find jpeglib.h, etc. +# ``JPEG_LIBRARY_RELEASE`` +# where to find the JPEG library (optimized). +# ``JPEG_LIBRARY_DEBUG`` +# where to find the JPEG library (debug). +# +# Obsolete variables +# ^^^^^^^^^^^^^^^^^^ +# +# ``JPEG_INCLUDE_DIR`` +# where to find jpeglib.h, etc. (same as JPEG_INCLUDE_DIRS) +# ``JPEG_LIBRARY`` +# where to find the JPEG library. find_path(JPEG_INCLUDE_DIR jpeglib.h) -set(JPEG_NAMES ${JPEG_NAMES} jpeg libjpeg) -find_library(JPEG_LIBRARY NAMES ${JPEG_NAMES} ) +set(jpeg_names ${JPEG_NAMES} jpeg libjpeg) +foreach(name ${JPEG_NAMES}) + list(APPEND jpeg_names_debug "${name}d") +endforeach() + +if(NOT JPEG_LIBRARY) + find_library(JPEG_LIBRARY_RELEASE NAMES ${jpeg_names}) + find_library(JPEG_LIBRARY_DEBUG NAMES ${jpeg_names_debug}) + include(${CMAKE_CURRENT_LIST_DIR}/SelectLibraryConfigurations.cmake) + select_library_configurations(JPEG) + mark_as_advanced(JPEG_LIBRARY_RELEASE JPEG_LIBRARY_DEBUG) +endif() +unset(jpeg_names) +unset(jpeg_names_debug) + +if(JPEG_INCLUDE_DIR AND EXISTS "${JPEG_INCLUDE_DIR}/jpeglib.h") + file(STRINGS "${JPEG_INCLUDE_DIR}/jpeglib.h" + jpeg_lib_version REGEX "^#define[\t ]+JPEG_LIB_VERSION[\t ]+.*") + + if (NOT jpeg_lib_version) + # libjpeg-turbo sticks JPEG_LIB_VERSION in jconfig.h + find_path(jconfig_dir jconfig.h) + if (jconfig_dir) + file(STRINGS "${jconfig_dir}/jconfig.h" + jpeg_lib_version REGEX "^#define[\t ]+JPEG_LIB_VERSION[\t ]+.*") + endif() + unset(jconfig_dir) + endif() + + string(REGEX REPLACE "^#define[\t ]+JPEG_LIB_VERSION[\t ]+([0-9]+).*" + "\\1" JPEG_VERSION "${jpeg_lib_version}") + unset(jpeg_lib_version) +endif() include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake) -FIND_PACKAGE_HANDLE_STANDARD_ARGS(JPEG DEFAULT_MSG JPEG_LIBRARY JPEG_INCLUDE_DIR) +find_package_handle_standard_args(JPEG + REQUIRED_VARS JPEG_LIBRARY JPEG_INCLUDE_DIR + VERSION_VAR JPEG_VERSION) if(JPEG_FOUND) set(JPEG_LIBRARIES ${JPEG_LIBRARY}) + set(JPEG_INCLUDE_DIRS "${JPEG_INCLUDE_DIR}") + + if(NOT TARGET JPEG::JPEG) + add_library(JPEG::JPEG UNKNOWN IMPORTED) + if(JPEG_INCLUDE_DIRS) + set_target_properties(JPEG::JPEG PROPERTIES + INTERFACE_INCLUDE_DIRECTORIES "${JPEG_INCLUDE_DIRS}") + endif() + if(EXISTS "${JPEG_LIBRARY}") + set_target_properties(JPEG::JPEG PROPERTIES + IMPORTED_LINK_INTERFACE_LANGUAGES "C" + IMPORTED_LOCATION "${JPEG_LIBRARY}") + endif() + if(EXISTS "${JPEG_LIBRARY_RELEASE}") + set_property(TARGET JPEG::JPEG APPEND PROPERTY + IMPORTED_CONFIGURATIONS RELEASE) + set_target_properties(JPEG::JPEG PROPERTIES + IMPORTED_LINK_INTERFACE_LANGUAGES_RELEASE "C" + IMPORTED_LOCATION_RELEASE "${JPEG_LIBRARY_RELEASE}") + endif() + if(EXISTS "${JPEG_LIBRARY_DEBUG}") + set_property(TARGET JPEG::JPEG APPEND PROPERTY + IMPORTED_CONFIGURATIONS DEBUG) + set_target_properties(JPEG::JPEG PROPERTIES + IMPORTED_LINK_INTERFACE_LANGUAGES_DEBUG "C" + IMPORTED_LOCATION_DEBUG "${JPEG_LIBRARY_DEBUG}") + endif() + endif() endif() # Deprecated declarations. -set (NATIVE_JPEG_INCLUDE_PATH ${JPEG_INCLUDE_DIR} ) +set(NATIVE_JPEG_INCLUDE_PATH ${JPEG_INCLUDE_DIR}) if(JPEG_LIBRARY) - get_filename_component (NATIVE_JPEG_LIB_PATH ${JPEG_LIBRARY} PATH) + get_filename_component(NATIVE_JPEG_LIB_PATH ${JPEG_LIBRARY} PATH) endif() -mark_as_advanced(JPEG_LIBRARY JPEG_INCLUDE_DIR ) +mark_as_advanced(JPEG_LIBRARY JPEG_INCLUDE_DIR) diff --git a/Modules/FindJava.cmake b/Modules/FindJava.cmake index 41c05eb..f8e3d98 100644 --- a/Modules/FindJava.cmake +++ b/Modules/FindJava.cmake @@ -18,7 +18,7 @@ # :: # # Runtime = User just want to execute some Java byte-compiled -# Development = Development tools (java, javac, javah and javadoc), includes Runtime component +# Development = Development tools (java, javac, javah, jar and javadoc), includes Runtime component # IdlJ = idl compiler for Java # JarSigner = signer tool for jar # @@ -271,16 +271,16 @@ if(Java_FIND_COMPONENTS) endif() elseif(component STREQUAL "Development") list(APPEND _JAVA_REQUIRED_VARS Java_JAVA_EXECUTABLE Java_JAVAC_EXECUTABLE - Java_JAVADOC_EXECUTABLE) + Java_JAR_EXECUTABLE Java_JAVADOC_EXECUTABLE) if(Java_VERSION VERSION_LESS "10") list(APPEND _JAVA_REQUIRED_VARS Java_JAVAH_EXECUTABLE) if(Java_JAVA_EXECUTABLE AND Java_JAVAC_EXECUTABLE - AND Java_JAVAH_EXECUTABLE AND Java_JAVADOC_EXECUTABLE) + AND Java_JAVAH_EXECUTABLE AND Java_JAR_EXECUTABLE AND Java_JAVADOC_EXECUTABLE) set(Java_Development_FOUND TRUE) endif() else() if(Java_JAVA_EXECUTABLE AND Java_JAVAC_EXECUTABLE - AND Java_JAVADOC_EXECUTABLE) + AND Java_JAR_EXECUTABLE AND Java_JAVADOC_EXECUTABLE) set(Java_Development_FOUND TRUE) endif() endif() diff --git a/Modules/FindLibXml2.cmake b/Modules/FindLibXml2.cmake index 8ac2980..615de49 100644 --- a/Modules/FindLibXml2.cmake +++ b/Modules/FindLibXml2.cmake @@ -7,6 +7,12 @@ # # Find the XML processing library (libxml2). # +# IMPORTED Targets +# ^^^^^^^^^^^^^^^^ +# +# This module defines :prop_tgt:`IMPORTED` target ``LibXml2::LibXml2``, if +# libxml2 has been found. +# # Result variables # ^^^^^^^^^^^^^^^^ # @@ -87,3 +93,9 @@ FIND_PACKAGE_HANDLE_STANDARD_ARGS(LibXml2 VERSION_VAR LIBXML2_VERSION_STRING) mark_as_advanced(LIBXML2_INCLUDE_DIR LIBXML2_LIBRARY LIBXML2_XMLLINT_EXECUTABLE) + +if(LibXml2_FOUND AND NOT TARGET LibXml2::LibXml2) + add_library(LibXml2::LibXml2 UNKNOWN IMPORTED) + set_target_properties(LibXml2::LibXml2 PROPERTIES INTERFACE_INCLUDE_DIRECTORIES "${LIBXML2_INCLUDE_DIRS}") + set_property(TARGET LibXml2::LibXml2 APPEND PROPERTY IMPORTED_LOCATION "${LIBXML2_LIBRARY}") +endif() diff --git a/Modules/FindLua.cmake b/Modules/FindLua.cmake index b59b9b3..7eba206 100644 --- a/Modules/FindLua.cmake +++ b/Modules/FindLua.cmake @@ -122,6 +122,7 @@ endif () if (NOT LUA_VERSION_STRING) foreach (subdir IN LISTS _lua_include_subdirs) unset(LUA_INCLUDE_PREFIX CACHE) + unset(LUA_INCLUDE_PREFIX) find_path(LUA_INCLUDE_PREFIX ${subdir}/lua.h HINTS ENV LUA_DIR diff --git a/Modules/FindMPI.cmake b/Modules/FindMPI.cmake index 4bfbf03..75c4441 100644 --- a/Modules/FindMPI.cmake +++ b/Modules/FindMPI.cmake @@ -352,6 +352,9 @@ function (_MPI_check_compiler LANG QUERY_FLAG OUTPUT_VARIABLE RESULT_VARIABLE) # Ensure that no error output might be passed upwards. if(NOT WRAPPER_RETURN EQUAL 0) unset(WRAPPER_OUTPUT) + else() + # Strip leading whitespace + string(REGEX REPLACE "^ +" "" WRAPPER_OUTPUT "${WRAPPER_OUTPUT}") endif() set(${OUTPUT_VARIABLE} "${WRAPPER_OUTPUT}" PARENT_SCOPE) set(${RESULT_VARIABLE} "${WRAPPER_RETURN}" PARENT_SCOPE) @@ -715,20 +718,20 @@ function (_MPI_interrogate_compiler LANG) # or shared libraries if there aren't any import libraries in use on the system. # Note that we do not consider CMAKE_<TYPE>_LIBRARY_PREFIX intentionally here: The linker will for a given file # decide how to link it based on file type, not based on a prefix like 'lib'. - set(_MPI_LIB_NAME_REGEX "[^\" ]+${CMAKE_STATIC_LIBRARY_SUFFIX}|\"[^\"]+${CMAKE_STATIC_LIBRARY_SUFFIX}\"") + set(_MPI_LIB_SUFFIX_REGEX "${CMAKE_STATIC_LIBRARY_SUFFIX}") if(DEFINED CMAKE_IMPORT_LIBRARY_SUFFIX) if(NOT ("${CMAKE_IMPORT_LIBRARY_SUFFIX}" STREQUAL "${CMAKE_STATIC_LIBRARY_SUFFIX}")) - string(APPEND _MPI_LIB_NAME_REGEX "[^\" ]+${CMAKE_IMPORT_LIBRARY_SUFFIX}|\"[^\"]+${CMAKE_IMPORT_LIBRARY_SUFFIX}\"") + string(APPEND _MPI_SUFFIX_REGEX "|${CMAKE_IMPORT_LIBRARY_SUFFIX}") endif() else() - string(APPEND _MPI_LIB_NAME_REGEX "[^\" ]+${CMAKE_SHARED_LIBRARY_SUFFIX}|\"[^\"]+${CMAKE_SHARED_LIBRARY_SUFFIX}\"") + string(APPEND _MPI_LIB_SUFFIX_REGEX "|${CMAKE_SHARED_LIBRARY_SUFFIX}") endif() + set(_MPI_LIB_NAME_REGEX "(([^\" ]+(${_MPI_LIB_SUFFIX_REGEX}))|(\"[^\"]+(${_MPI_LIB_SUFFIX_REGEX})\"))( +|$)") string(REPLACE "." "\\." _MPI_LIB_NAME_REGEX "${_MPI_LIB_NAME_REGEX}") - string(REGEX MATCHALL "(^| )(${_MPI_LIB_NAME_REGEX})" MPI_LIBNAMES "${MPI_LINK_CMDLINE}") + string(REGEX MATCHALL "${_MPI_LIB_NAME_REGEX}" MPI_LIBNAMES "${MPI_LINK_CMDLINE}") foreach(_MPI_LIB_NAME IN LISTS MPI_LIBNAMES) - string(REGEX REPLACE "^ " "" _MPI_LIB_NAME "${_MPI_LIB_NAME}") - string(REPLACE "\"" "" _MPI_LIB_NAME "${_MPI_LIB_NAME}") + string(REGEX REPLACE "^ +\"?|\"? +$" "" _MPI_LIB_NAME "${_MPI_LIB_NAME}") get_filename_component(_MPI_LIB_PATH "${_MPI_LIB_NAME}" DIRECTORY) if(NOT "${_MPI_LIB_PATH}" STREQUAL "") list(APPEND MPI_LIB_FULLPATHS_WORK "${_MPI_LIB_NAME}") diff --git a/Modules/FindMatlab.cmake b/Modules/FindMatlab.cmake index 8402b23..b03f793 100644 --- a/Modules/FindMatlab.cmake +++ b/Modules/FindMatlab.cmake @@ -5,22 +5,25 @@ # FindMatlab # ---------- # -# Finds Matlab installations and provides Matlab tools and libraries to cmake. +# Finds Matlab or Matlab Compiler Runtime (MCR) and provides Matlab tools, +# libraries and compilers to CMake. # -# This package first intention is to find the libraries associated with Matlab -# in order to be able to build Matlab extensions (mex files). It can also be -# used: +# This package primary purpose is to find the libraries associated with Matlab +# or the MCR in order to be able to build Matlab extensions (mex files). It +# can also be used: # -# * run specific commands in Matlab -# * declare Matlab unit test -# * retrieve various information from Matlab (mex extensions, versions and +# * to run specific commands in Matlab in case Matlab is available +# * for declaring Matlab unit test +# * to retrieve various information from Matlab (mex extensions, versions and # release queries, ...) # # The module supports the following components: # -# * ``MX_LIBRARY``, ``ENG_LIBRARY`` and ``MAT_LIBRARY``: respectively the MX, -# ENG and MAT libraries of Matlab -# * ``MAIN_PROGRAM`` the Matlab binary program. +# * ``MX_LIBRARY``, ``ENG_LIBRARY`` and ``MAT_LIBRARY``: respectively the ``MX``, +# ``ENG`` and ``MAT`` libraries of Matlab +# * ``MAIN_PROGRAM`` the Matlab binary program. Note that this component is not +# available on the MCR version, and will yield an error if the MCR is found +# instead of the regular Matlab installation. # * ``MEX_COMPILER`` the MEX compiler. # * ``SIMULINK`` the Simulink environment. # @@ -30,24 +33,26 @@ # **version**, which should not be confused with the Matlab *release* name # (eg. `R2014`). # The :command:`matlab_get_version_from_release_name` and -# :command:`matlab_get_release_name_from_version` allow a mapping -# from the release name to the version. +# :command:`matlab_get_release_name_from_version` provide a mapping +# between the release name and the version. # # The variable :variable:`Matlab_ROOT_DIR` may be specified in order to give # the path of the desired Matlab version. Otherwise, the behaviour is platform # specific: # -# * Windows: The installed versions of Matlab are retrieved from the +# * Windows: The installed versions of Matlab/MCR are retrieved from the # Windows registry -# * OS X: The installed versions of Matlab are given by the MATLAB -# paths in ``/Application``. If no such application is found, it falls back -# to the one that might be accessible from the PATH. -# * Unix: The desired Matlab should be accessible from the PATH. +# * OS X: The installed versions of Matlab/MCR are given by the MATLAB +# default installation paths in ``/Application``. If no such application is +# found, it falls back to the one that might be accessible from the ``PATH``. +# * Unix: The desired Matlab should be accessible from the ``PATH``. This does +# not work for MCR installation and :variable:`Matlab_ROOT_DIR` should be +# specified on this platform. # # Additional information is provided when :variable:`MATLAB_FIND_DEBUG` is set. -# When a Matlab binary is found automatically and the ``MATLAB_VERSION`` -# is not given, the version is queried from Matlab directly. -# On Windows, it can make a window running Matlab appear. +# When a Matlab/MCR installation is found automatically and the ``MATLAB_VERSION`` +# is not given, the version is queried from Matlab directly (on Windows this +# may pop up a Matlab window) or from the MCR installation. # # The mapping of the release names and the version of Matlab is performed by # defining pairs (name, version). The variable @@ -135,15 +140,15 @@ # parses the registry for all Matlab versions. Available on Windows only. # The part of the registry parsed is dependent on the host processor # :command:`matlab_get_all_valid_matlab_roots_from_registry` -# returns all the possible Matlab paths, according to a previously +# returns all the possible Matlab or MCR paths, according to a previously # given list. Only the existing/accessible paths are kept. This is mainly # useful for the searching all possible Matlab installation. # :command:`matlab_get_mex_suffix` # returns the suffix to be used for the mex files # (platform/architecture dependent) # :command:`matlab_get_version_from_matlab_run` -# returns the version of Matlab, given the full directory of the Matlab -# program. +# returns the version of Matlab/MCR, given the full directory of the Matlab/MCR +# installation path. # # # Known issues @@ -213,7 +218,7 @@ set(_FindMatlab_SELF_DIR "${CMAKE_CURRENT_LIST_DIR}") -include(FindPackageHandleStandardArgs) +include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake) include(CheckCXXCompilerFlag) include(CheckCCompilerFlag) @@ -256,7 +261,7 @@ endif() # .. command:: matlab_get_version_from_release_name # # Returns the version of Matlab (17.58) from a release name (R2017k) -macro (matlab_get_version_from_release_name release_name version_name) +macro(matlab_get_version_from_release_name release_name version_name) string(REGEX MATCHALL "${release_name}=([0-9]+\\.?[0-9]*)" _matched ${MATLAB_VERSIONS_MAPPING}) @@ -264,7 +269,7 @@ macro (matlab_get_version_from_release_name release_name version_name) if(NOT _matched STREQUAL "") set(${version_name} ${CMAKE_MATCH_1}) else() - message(WARNING "The release name ${release_name} is not registered") + message(WARNING "[MATLAB] The release name ${release_name} is not registered") endif() unset(_matched) @@ -278,7 +283,7 @@ endmacro() # .. command:: matlab_get_release_name_from_version # # Returns the release name (R2017k) from the version of Matlab (17.58) -macro (matlab_get_release_name_from_version version release_name) +macro(matlab_get_release_name_from_version version release_name) set(${release_name} "") foreach(_var IN LISTS MATLAB_VERSIONS_MAPPING) @@ -292,7 +297,7 @@ macro (matlab_get_release_name_from_version version release_name) unset(_var) unset(_matched) if(${release_name} STREQUAL "") - message(WARNING "The version ${version} is not registered") + message(WARNING "[MATLAB] The version ${version} is not registered") endif() endmacro() @@ -341,8 +346,9 @@ endmacro() # installed. The found versions are returned in `matlab_versions`. # Set `win64` to `TRUE` if the 64 bit version of Matlab should be looked for # The returned list contains all versions under -# ``HKLM\\SOFTWARE\\Mathworks\\MATLAB`` or an empty list in case an error -# occurred (or nothing found). +# ``HKLM\\SOFTWARE\\Mathworks\\MATLAB`` and +# ``HKLM\\SOFTWARE\\Mathworks\\MATLAB Runtime`` or an empty list in case an +# error occurred (or nothing found). # # .. note:: # @@ -352,51 +358,54 @@ endmacro() function(matlab_extract_all_installed_versions_from_registry win64 matlab_versions) if(NOT CMAKE_HOST_WIN32) - message(FATAL_ERROR "This macro can only be called by a windows host (call to reg.exe") + message(FATAL_ERROR "[MATLAB] This macro can only be called by a windows host (call to reg.exe)") endif() - if(${win64} AND CMAKE_HOST_SYSTEM_PROCESSOR MATCHES "64") set(APPEND_REG "/reg:64") else() set(APPEND_REG "/reg:32") endif() - # /reg:64 should be added on 64 bits capable OSs in order to enable the - # redirection of 64 bits applications - execute_process( - COMMAND reg query HKEY_LOCAL_MACHINE\\SOFTWARE\\Mathworks\\MATLAB /f * /k ${APPEND_REG} - RESULT_VARIABLE resultMatlab - OUTPUT_VARIABLE varMatlab - ERROR_VARIABLE errMatlab - INPUT_FILE NUL - ) + set(matlabs_from_registry) + foreach(_installation_type IN ITEMS "MATLAB" "MATLAB Runtime") - set(matlabs_from_registry) - if(${resultMatlab} EQUAL 0) + # /reg:64 should be added on 64 bits capable OSs in order to enable the + # redirection of 64 bits applications + execute_process( + COMMAND reg query HKEY_LOCAL_MACHINE\\SOFTWARE\\Mathworks\\${_installation_type} /f * /k ${APPEND_REG} + RESULT_VARIABLE resultMatlab + OUTPUT_VARIABLE varMatlab + ERROR_VARIABLE errMatlab + INPUT_FILE NUL + ) - string( - REGEX MATCHALL "MATLAB\\\\([0-9]+(\\.[0-9]+)?)" - matlab_versions_regex ${varMatlab}) - foreach(match IN LISTS matlab_versions_regex) - string( - REGEX MATCH "MATLAB\\\\(([0-9]+)(\\.([0-9]+))?)" - current_match ${match}) + if(${resultMatlab} EQUAL 0) - set(_matlab_current_version ${CMAKE_MATCH_1}) - set(current_matlab_version_major ${CMAKE_MATCH_2}) - set(current_matlab_version_minor ${CMAKE_MATCH_4}) - if(NOT current_matlab_version_minor) - set(current_matlab_version_minor "0") - endif() + string( + REGEX MATCHALL "MATLAB\\\\([0-9]+(\\.[0-9]+)?)" + matlab_versions_regex ${varMatlab}) + + foreach(match IN LISTS matlab_versions_regex) + string( + REGEX MATCH "MATLAB\\\\(([0-9]+)(\\.([0-9]+))?)" + current_match ${match}) + + set(_matlab_current_version ${CMAKE_MATCH_1}) + set(current_matlab_version_major ${CMAKE_MATCH_2}) + set(current_matlab_version_minor ${CMAKE_MATCH_4}) + if(NOT current_matlab_version_minor) + set(current_matlab_version_minor "0") + endif() - list(APPEND matlabs_from_registry ${_matlab_current_version}) - unset(_matlab_current_version) - endforeach(match) + list(APPEND matlabs_from_registry ${_matlab_current_version}) + unset(_matlab_current_version) + endforeach() - endif() + endif() + endforeach() if(matlabs_from_registry) list(REMOVE_DUPLICATES matlabs_from_registry) @@ -441,7 +450,6 @@ macro(extract_matlab_versions_from_registry_brute_force matlab_versions) # list(APPEND matlab_supported_versions MATLAB_ADDITIONAL_VERSIONS) # endif() - # we order from more recent to older if(matlab_supported_versions) list(REMOVE_DUPLICATES matlab_supported_versions) @@ -449,10 +457,7 @@ macro(extract_matlab_versions_from_registry_brute_force matlab_versions) list(REVERSE matlab_supported_versions) endif() - set(${matlab_versions} ${matlab_supported_versions}) - - endmacro() @@ -461,9 +466,11 @@ endmacro() #.rst: # .. command:: matlab_get_all_valid_matlab_roots_from_registry # -# Populates the Matlab root with valid versions of Matlab. -# The returned matlab_roots is organized in pairs -# ``(version_number,matlab_root_path)``. +# Populates the Matlab root with valid versions of Matlab or +# Matlab Runtime (MCR). +# The returned matlab_roots is organized in triplets +# ``(type,version_number,matlab_root_path)``, where ``type`` +# indicates either ``MATLAB`` or ``MCR``. # # :: # @@ -472,17 +479,17 @@ endmacro() # matlab_roots) # # ``matlab_versions`` -# the versions of each of the Matlab installations +# the versions of each of the Matlab or MCR installations # ``matlab_roots`` -# the location of each of the Matlab installations +# the location of each of the Matlab or MCR installations function(matlab_get_all_valid_matlab_roots_from_registry matlab_versions matlab_roots) # The matlab_versions comes either from # extract_matlab_versions_from_registry_brute_force or # matlab_extract_all_installed_versions_from_registry. - set(_matlab_roots_list ) + # check for Matlab installations foreach(_matlab_current_version ${matlab_versions}) get_filename_component( current_MATLAB_ROOT @@ -490,13 +497,27 @@ function(matlab_get_all_valid_matlab_roots_from_registry matlab_versions matlab_ ABSOLUTE) if(EXISTS ${current_MATLAB_ROOT}) - list(APPEND _matlab_roots_list ${_matlab_current_version} ${current_MATLAB_ROOT}) + list(APPEND _matlab_roots_list "MATLAB" ${_matlab_current_version} ${current_MATLAB_ROOT}) + endif() + + endforeach() + + # Check for MCR installations + foreach(_matlab_current_version ${matlab_versions}) + get_filename_component( + current_MATLAB_ROOT + "[HKEY_LOCAL_MACHINE\\SOFTWARE\\MathWorks\\MATLAB Runtime\\${_matlab_current_version};MATLABROOT]" + ABSOLUTE) + + # remove the dot + string(REPLACE "." "" _matlab_current_version_without_dot "${_matlab_current_version}") + + if(EXISTS ${current_MATLAB_ROOT}) + list(APPEND _matlab_roots_list "MCR" ${_matlab_current_version} "${current_MATLAB_ROOT}/v${_matlab_current_version_without_dot}") endif() - endforeach(_matlab_current_version) - unset(_matlab_current_version) + endforeach() set(${matlab_roots} ${_matlab_roots_list} PARENT_SCOPE) - unset(_matlab_roots_list) endfunction() #.rst: @@ -513,7 +534,7 @@ endfunction() # mex_suffix) # # ``matlab_root`` -# the root of the Matlab installation +# the root of the Matlab/MCR installation # ``mex_suffix`` # the variable name in which the suffix will be returned. function(matlab_get_mex_suffix matlab_root mex_suffix) @@ -548,7 +569,9 @@ function(matlab_get_mex_suffix matlab_root mex_suffix) ) endif() endforeach(current_mexext_suffix) - + if(MATLAB_FIND_DEBUG) + message(STATUS "[MATLAB] Determining mex files extensions from '${matlab_root}/bin' with program '${Matlab_MEXEXTENSIONS_PROG}'") + endif() # the program has been found? if((NOT Matlab_MEXEXTENSIONS_PROG) OR (NOT EXISTS ${Matlab_MEXEXTENSIONS_PROG})) @@ -568,12 +591,29 @@ function(matlab_get_mex_suffix matlab_root mex_suffix) set(devnull INPUT_FILE NUL) endif() + # this is the prefered way. If this does not work properly (eg. MCR on Windows), then we use our own knowledge execute_process( COMMAND ${Matlab_MEXEXTENSIONS_PROG} OUTPUT_VARIABLE _matlab_mex_extension + #RESULT_VARIABLE _matlab_mex_extension_call ERROR_VARIABLE _matlab_mex_extension_error ${devnull}) - string(STRIP ${_matlab_mex_extension} _matlab_mex_extension) + + if(NOT "${_matlab_mex_extension_error}" STREQUAL "") + if(WIN32) + # this is only for intel architecture + if(CMAKE_SIZEOF_VOID_P EQUAL 8) + set(_matlab_mex_extension "mexw64") + else() + set(_matlab_mex_extension "mexw32") + endif() + endif() + endif() + + string(STRIP "${_matlab_mex_extension}" _matlab_mex_extension) + if(MATLAB_FIND_DEBUG) + message(STATUS "[MATLAB] '${Matlab_MEXEXTENSIONS_PROG}' : returned '${_matlab_mex_extension_call}', determined extension '${_matlab_mex_extension}' and error string is '${_matlab_mex_extension_error}'") + endif() unset(Matlab_MEXEXTENSIONS_PROG CACHE) set(${mex_suffix} ${_matlab_mex_extension} PARENT_SCOPE) @@ -586,7 +626,8 @@ endfunction() # .. command:: matlab_get_version_from_matlab_run # # This function runs Matlab program specified on arguments and extracts its -# version. +# version. If the path provided for the Matlab installation points to an MCR +# installation, the version is extracted from the installed files. # # :: # @@ -602,7 +643,6 @@ function(matlab_get_version_from_matlab_run matlab_binary_program matlab_list_ve set(${matlab_list_versions} "" PARENT_SCOPE) - if(MATLAB_FIND_DEBUG) message(STATUS "[MATLAB] Determining the version of Matlab from ${matlab_binary_program}") endif() @@ -704,7 +744,9 @@ endfunction() # .. command:: matlab_add_unit_test # # Adds a Matlab unit test to the test set of cmake/ctest. -# This command requires the component ``MAIN_PROGRAM``. +# This command requires the component ``MAIN_PROGRAM`` and hence is not +# available for an MCR installation. +# # The unit test uses the Matlab unittest framework (default, available # starting Matlab 2013b+) except if the option ``NO_UNITTEST_FRAMEWORK`` # is given. @@ -929,7 +971,7 @@ function(matlab_add_mex) TARGET ${${prefix}_NAME} PRE_BUILD COMMAND ${CMAKE_COMMAND} -E copy_if_different ${${prefix}_DOCUMENTATION} $<TARGET_FILE_DIR:${${prefix}_NAME}>/${output_name}.m - COMMENT "Copy ${${prefix}_NAME} documentation file into the output folder" + COMMENT "[MATLAB] Copy ${${prefix}_NAME} documentation file into the output folder" ) endif() # documentation @@ -1005,10 +1047,10 @@ endfunction() # (internal) # Used to get the version of matlab, using caching. This basically transforms the # output of the root list, with possible unknown version, to a version -# -function(_Matlab_get_version_from_root matlab_root matlab_known_version matlab_final_version) +# This can possibly run Matlab for extracting the version. +function(_Matlab_get_version_from_root matlab_root matlab_or_mcr matlab_known_version matlab_final_version) - # if the version is not trivial, we query matlab for that + # if the version is not trivial, we query matlab (if not MCR) for that # we keep track of the location of matlab that induced this version #if(NOT DEFINED Matlab_PROG_VERSION_STRING_AUTO_DETECT) # set(Matlab_PROG_VERSION_STRING_AUTO_DETECT "" CACHE INTERNAL "internal matlab location for the discovered version") @@ -1021,189 +1063,231 @@ function(_Matlab_get_version_from_root matlab_root matlab_known_version matlab_f return() endif() - # - set(_matlab_current_program ${Matlab_MAIN_PROGRAM}) - - # do we already have a matlab program? - if(NOT _matlab_current_program) - - set(_find_matlab_options) - if(matlab_root AND EXISTS ${matlab_root}) - set(_find_matlab_options PATHS ${matlab_root} ${matlab_root}/bin NO_DEFAULT_PATH) + if("${matlab_or_mcr}" STREQUAL "UNKNOWN") + if(MATLAB_FIND_DEBUG) + message(WARNING "[MATLAB] Determining Matlab or MCR") endif() - find_program( - _matlab_current_program - matlab - ${_find_matlab_options} - DOC "Matlab main program" - ) - endif() + if(EXISTS "${matlab_root}/appdata/version.xml") + # we inspect the application version.xml file that contains the product information + file(STRINGS "${matlab_root}/appdata/version.xml" productinfo_string NEWLINE_CONSUME) + string(REGEX MATCH "<installedProductData.*displayedString=\"([a-zA-Z ]+)\".*/>" + product_reg_match + ${productinfo_string} + ) + + # default fallback to Matlab + set(matlab_or_mcr "MATLAB") + if(NOT "${CMAKE_MATCH_1}" STREQUAL "") + string(TOLOWER "${CMAKE_MATCH_1}" product_reg_match) + + if("${product_reg_match}" STREQUAL "matlab runtime") + set(matlab_or_mcr "MCR") + endif() + endif() + endif() - if(NOT _matlab_current_program OR NOT EXISTS ${_matlab_current_program}) - # if not found, clear the dependent variables if(MATLAB_FIND_DEBUG) - message(WARNING "[MATLAB] Cannot find the main matlab program under ${matlab_root}") + message(WARNING "[MATLAB] '${matlab_root}' contains the '${matlab_or_mcr}'") endif() - set(Matlab_PROG_VERSION_STRING_AUTO_DETECT "" CACHE INTERNAL "internal matlab location for the discovered version" FORCE) - set(Matlab_VERSION_STRING_INTERNAL "" CACHE INTERNAL "internal matlab location for the discovered version" FORCE) - unset(_matlab_current_program) - unset(_matlab_current_program CACHE) - return() endif() - # full real path for path comparison - get_filename_component(_matlab_main_real_path_tmp "${_matlab_current_program}" REALPATH) - unset(_matlab_current_program) - unset(_matlab_current_program CACHE) + # UNKNOWN is the default behaviour in case we + # - have an erroneous matlab_root + # - have an initial 'UNKNOWN' + if("${matlab_or_mcr}" STREQUAL "MATLAB" OR "${matlab_or_mcr}" STREQUAL "UNKNOWN") + # MATLAB versions + set(_matlab_current_program ${Matlab_MAIN_PROGRAM}) - # is it the same as the previous one? - if(_matlab_main_real_path_tmp STREQUAL Matlab_PROG_VERSION_STRING_AUTO_DETECT) - set(${matlab_final_version} ${Matlab_VERSION_STRING_INTERNAL} PARENT_SCOPE) - return() - endif() + # do we already have a matlab program? + if(NOT _matlab_current_program) - # update the location of the program - set(Matlab_PROG_VERSION_STRING_AUTO_DETECT ${_matlab_main_real_path_tmp} CACHE INTERNAL "internal matlab location for the discovered version" FORCE) + set(_find_matlab_options) + if(matlab_root AND EXISTS ${matlab_root}) + set(_find_matlab_options PATHS ${matlab_root} ${matlab_root}/bin NO_DEFAULT_PATH) + endif() - set(matlab_list_of_all_versions) - matlab_get_version_from_matlab_run("${Matlab_PROG_VERSION_STRING_AUTO_DETECT}" matlab_list_of_all_versions) + find_program( + _matlab_current_program + matlab + ${_find_matlab_options} + DOC "Matlab main program" + ) + endif() - list(LENGTH matlab_list_of_all_versions list_of_all_versions_length) - if(${list_of_all_versions_length} GREATER 0) - list(GET matlab_list_of_all_versions 0 _matlab_version_tmp) - else() - set(_matlab_version_tmp "unknown") - endif() + if(NOT _matlab_current_program OR NOT EXISTS ${_matlab_current_program}) + # if not found, clear the dependent variables + if(MATLAB_FIND_DEBUG) + message(WARNING "[MATLAB] Cannot find the main matlab program under ${matlab_root}") + endif() + set(Matlab_PROG_VERSION_STRING_AUTO_DETECT "" CACHE INTERNAL "internal matlab location for the discovered version" FORCE) + set(Matlab_VERSION_STRING_INTERNAL "" CACHE INTERNAL "internal matlab location for the discovered version" FORCE) + unset(_matlab_current_program) + unset(_matlab_current_program CACHE) + return() + endif() - # set the version into the cache - set(Matlab_VERSION_STRING_INTERNAL ${_matlab_version_tmp} CACHE INTERNAL "Matlab version (automatically determined)" FORCE) + # full real path for path comparison + get_filename_component(_matlab_main_real_path_tmp "${_matlab_current_program}" REALPATH) + unset(_matlab_current_program) + unset(_matlab_current_program CACHE) - # warning, just in case several versions found (should not happen) - if((${list_of_all_versions_length} GREATER 1) AND MATLAB_FIND_DEBUG) - message(WARNING "[MATLAB] Found several versions, taking the first one (versions found ${matlab_list_of_all_versions})") - endif() + # is it the same as the previous one? + if(_matlab_main_real_path_tmp STREQUAL Matlab_PROG_VERSION_STRING_AUTO_DETECT) + set(${matlab_final_version} ${Matlab_VERSION_STRING_INTERNAL} PARENT_SCOPE) + return() + endif() - # return the updated value - set(${matlab_final_version} ${Matlab_VERSION_STRING_INTERNAL} PARENT_SCOPE) + # update the location of the program + set(Matlab_PROG_VERSION_STRING_AUTO_DETECT + ${_matlab_main_real_path_tmp} + CACHE INTERNAL "internal matlab location for the discovered version" FORCE) -endfunction() + set(matlab_list_of_all_versions) + matlab_get_version_from_matlab_run("${Matlab_PROG_VERSION_STRING_AUTO_DETECT}" matlab_list_of_all_versions) + list(LENGTH matlab_list_of_all_versions list_of_all_versions_length) + if(${list_of_all_versions_length} GREATER 0) + list(GET matlab_list_of_all_versions 0 _matlab_version_tmp) + else() + set(_matlab_version_tmp "unknown") + endif() + # set the version into the cache + set(Matlab_VERSION_STRING_INTERNAL ${_matlab_version_tmp} CACHE INTERNAL "Matlab version (automatically determined)" FORCE) + # warning, just in case several versions found (should not happen) + if((${list_of_all_versions_length} GREATER 1) AND MATLAB_FIND_DEBUG) + message(WARNING "[MATLAB] Found several versions, taking the first one (versions found ${matlab_list_of_all_versions})") + endif() + # return the updated value + set(${matlab_final_version} ${Matlab_VERSION_STRING_INTERNAL} PARENT_SCOPE) + else() + # MCR + # we cannot run anything in order to extract the version. We assume that the file + # VersionInfo.xml exists under the MatlabRoot, we look for it and extract the version from there + set(_matlab_version_tmp "unknown") + file(STRINGS "${matlab_root}/VersionInfo.xml" versioninfo_string NEWLINE_CONSUME) + # parses "<version>9.2.0.538062</version>" + string(REGEX MATCH "<version>(.*)</version>" + version_reg_match + ${versioninfo_string} + ) + + if(NOT "${version_reg_match}" STREQUAL "") + if("${CMAKE_MATCH_1}" MATCHES "(([0-9])\\.([0-9]))[\\.0-9]*") + set(_matlab_version_tmp "${CMAKE_MATCH_1}") + endif() + endif() + set(${matlab_final_version} "${_matlab_version_tmp}" PARENT_SCOPE) + set(Matlab_VERSION_STRING_INTERNAL + "${_matlab_version_tmp}" + CACHE INTERNAL "Matlab (MCR) version (automatically determined)" + FORCE) + endif() # Matlab or MCR +endfunction() -# ################################### -# Exploring the possible Matlab_ROOTS -# this variable will get all Matlab installations found in the current system. -set(_matlab_possible_roots) +# Utility function for finding Matlab or MCR on Win32 +function(_Matlab_find_instances_win32 matlab_roots) + # On WIN32, we look for Matlab installation in the registry + # if unsuccessful, we look for all known revision and filter the existing + # ones. + # testing if we are able to extract the needed information from the registry + set(_matlab_versions_from_registry) + if(CMAKE_SIZEOF_VOID_P EQUAL 8) + set(_matlab_win64 ON) + else() + set(_matlab_win64 OFF) + endif() -if(Matlab_ROOT_DIR) - # if the user specifies a possible root, we keep this one + matlab_extract_all_installed_versions_from_registry(_matlab_win64 _matlab_versions_from_registry) - if(NOT EXISTS ${Matlab_ROOT_DIR}) - # if Matlab_ROOT_DIR specified but erroneous + # the returned list is empty, doing the search on all known versions + if(NOT _matlab_versions_from_registry) if(MATLAB_FIND_DEBUG) - message(WARNING "[MATLAB] the specified path for Matlab_ROOT_DIR does not exist (${Matlab_ROOT_DIR})") - endif() - else() - # NOTFOUND indicates the code below to search for the version automatically - if("${Matlab_VERSION_STRING_INTERNAL}" STREQUAL "") - list(APPEND _matlab_possible_roots "NOTFOUND" ${Matlab_ROOT_DIR}) # empty version - else() - list(APPEND _matlab_possible_roots ${Matlab_VERSION_STRING_INTERNAL} ${Matlab_ROOT_DIR}) # cached version + message(STATUS "[MATLAB] Search for Matlab from the registry unsuccessful, testing all supported versions") endif() + extract_matlab_versions_from_registry_brute_force(_matlab_versions_from_registry) endif() + # filtering the results with the registry keys + matlab_get_all_valid_matlab_roots_from_registry("${_matlab_versions_from_registry}" _matlab_possible_roots) + unset(_matlab_versions_from_registry) -else() - - # if the user does not specify the possible installation root, we look for - # one installation using the appropriate heuristics + set(_matlab_versions_from_registry) + matlab_extract_all_installed_versions_from_registry(CMAKE_CL_64 _matlab_versions_from_registry) - if(WIN32) + # the returned list is empty, doing the search on all known versions + if(NOT _matlab_versions_from_registry) + if(MATLAB_FIND_DEBUG) + message(STATUS "[MATLAB] Search for Matlab from the registry unsuccessful, testing all supported versions") + endif() + extract_matlab_versions_from_registry_brute_force(_matlab_versions_from_registry) + endif() - # On WIN32, we look for Matlab installation in the registry - # if unsuccessful, we look for all known revision and filter the existing - # ones. + # filtering the results with the registry keys + matlab_get_all_valid_matlab_roots_from_registry("${_matlab_versions_from_registry}" _matlab_possible_roots) + set(${matlab_roots} ${_matlab_possible_roots} PARENT_SCOPE) - # testing if we are able to extract the needed information from the registry - set(_matlab_versions_from_registry) +endfunction() - if(CMAKE_SIZEOF_VOID_P EQUAL 8) - set(_matlab_win64 ON) - else() - set(_matlab_win64 OFF) - endif() +# Utility function for finding Matlab or MCR on OSX +function(_Matlab_find_instances_osx matlab_roots) - matlab_extract_all_installed_versions_from_registry(_matlab_win64 _matlab_versions_from_registry) + set(_matlab_possible_roots) + # on mac, we look for the /Application paths + # this corresponds to the behaviour on Windows. On Linux, we do not have + # any other guess. + matlab_get_supported_releases(_matlab_releases) + if(MATLAB_FIND_DEBUG) + message(STATUS "[MATLAB] Matlab supported versions ${_matlab_releases}. If more version should be supported " + "the variable MATLAB_ADDITIONAL_VERSIONS can be set according to the documentation") + endif() - # the returned list is empty, doing the search on all known versions - if(NOT _matlab_versions_from_registry) + foreach(_matlab_current_release IN LISTS _matlab_releases) + matlab_get_version_from_release_name("${_matlab_current_release}" _matlab_current_version) + string(REPLACE "." "" _matlab_current_version_without_dot "${_matlab_current_version}") + set(_matlab_base_path "/Applications/MATLAB_${_matlab_current_release}.app") + # Check Matlab, has precedence over MCR + if(EXISTS ${_matlab_base_path}) if(MATLAB_FIND_DEBUG) - message(STATUS "[MATLAB] Search for Matlab from the registry unsuccessful, testing all supported versions") + message(STATUS "[MATLAB] Found version ${_matlab_current_release} (${_matlab_current_version}) in ${_matlab_base_path}") endif() - - extract_matlab_versions_from_registry_brute_force(_matlab_versions_from_registry) + list(APPEND _matlab_possible_roots "MATLAB" ${_matlab_current_version} ${_matlab_base_path}) endif() - # filtering the results with the registry keys - matlab_get_all_valid_matlab_roots_from_registry("${_matlab_versions_from_registry}" _matlab_possible_roots) - unset(_matlab_versions_from_registry) - - elseif(APPLE) - - # on mac, we look for the /Application paths - # this corresponds to the behaviour on Windows. On Linux, we do not have - # any other guess. - matlab_get_supported_releases(_matlab_releases) - if(MATLAB_FIND_DEBUG) - message(STATUS "[MATLAB] Matlab supported versions ${_matlab_releases}. If more version should be supported " - "the variable MATLAB_ADDITIONAL_VERSIONS can be set according to the documentation") - endif() - - foreach(_matlab_current_release IN LISTS _matlab_releases) - set(_matlab_full_string "/Applications/MATLAB_${_matlab_current_release}.app") - if(EXISTS ${_matlab_full_string}) - set(_matlab_current_version) - matlab_get_version_from_release_name("${_matlab_current_release}" _matlab_current_version) - if(MATLAB_FIND_DEBUG) - message(STATUS "[MATLAB] Found version ${_matlab_current_release} (${_matlab_current_version}) in ${_matlab_full_string}") - endif() - list(APPEND _matlab_possible_roots ${_matlab_current_version} ${_matlab_full_string}) - unset(_matlab_current_version) + # Checks MCR + set(_mcr_path "/Applications/MATLAB/MATLAB_Runtime/v${_matlab_current_version_without_dot}") + if(EXISTS "${_mcr_path}") + if(MATLAB_FIND_DEBUG) + message(STATUS "[MATLAB] Found MCR version ${_matlab_current_release} (${_matlab_current_version}) in ${_mcr_path}") endif() + list(APPEND _matlab_possible_roots "MCR" ${_matlab_current_version} ${_mcr_path}) + endif() - unset(_matlab_full_string) - endforeach(_matlab_current_release) - - unset(_matlab_current_release) - unset(_matlab_releases) - - endif() - -endif() - + endforeach() + set(${matlab_roots} ${_matlab_possible_roots} PARENT_SCOPE) +endfunction() -list(LENGTH _matlab_possible_roots _numbers_of_matlab_roots) -if(_numbers_of_matlab_roots EQUAL 0) - # if we have not found anything, we fall back on the PATH +# Utility function for finding Matlab or MCR from the PATH +function(_Matlab_find_instances_from_path matlab_roots) + set(_matlab_possible_roots) # At this point, we have no other choice than trying to find it from PATH. - # If set by the user, this won't change + # If set by the user, this wont change find_program( _matlab_main_tmp NAMES matlab) - if(_matlab_main_tmp) # we then populate the list of roots, with empty version if(MATLAB_FIND_DEBUG) @@ -1218,17 +1302,88 @@ if(_numbers_of_matlab_roots EQUAL 0) get_filename_component(_matlab_current_location "${_matlab_current_location}" DIRECTORY) get_filename_component(_matlab_current_location "${_matlab_current_location}" DIRECTORY) # Matlab should be in bin - list(APPEND _matlab_possible_roots "NOTFOUND" ${_matlab_current_location}) + # We found the Matlab program + list(APPEND _matlab_possible_roots "MATLAB" "NOTFOUND" ${_matlab_current_location}) + + # we remove this from the CACHE + unset(_matlab_main_tmp CACHE) + else() + find_program( + _matlab_mex_tmp + NAMES mex) + if(_matlab_mex_tmp) + # we then populate the list of roots, with empty version + if(MATLAB_FIND_DEBUG) + message(STATUS "[MATLAB] mex compiler found from PATH: ${_matlab_mex_tmp}") + endif() + + # resolve symlinks + get_filename_component(_mex_current_location "${_matlab_mex_tmp}" REALPATH) + + # get the directory (the command below has to be run twice) + # this will be the matlab root + get_filename_component(_mex_current_location "${_mex_current_location}" DIRECTORY) + get_filename_component(_mex_current_location "${_mex_current_location}" DIRECTORY) # Matlab Runtime mex compiler should be in bin + + # We found the Matlab program + list(APPEND _matlab_possible_roots "MCR" "NOTFOUND" ${_mex_current_location}) + + unset(_matlab_mex_tmp CACHE) + else() + if(MATLAB_FIND_DEBUG) + message(STATUS "[MATLAB] mex compiler not found") + endif() + endif() - unset(_matlab_current_location) endif() - unset(_matlab_main_tmp CACHE) -endif() + set(${matlab_roots} ${_matlab_possible_roots} PARENT_SCOPE) +endfunction() +# ################################### +# Exploring the possible Matlab_ROOTS +# this variable will get all Matlab installations found in the current system. +set(_matlab_possible_roots) + +if(Matlab_ROOT_DIR) + # if the user specifies a possible root, we keep this one + + if(NOT EXISTS "${Matlab_ROOT_DIR}") + # if Matlab_ROOT_DIR specified but erroneous + if(MATLAB_FIND_DEBUG) + message(WARNING "[MATLAB] the specified path for Matlab_ROOT_DIR does not exist (${Matlab_ROOT_DIR})") + endif() + else() + # NOTFOUND indicates the code below to search for the version automatically + if("${Matlab_VERSION_STRING_INTERNAL}" STREQUAL "") + list(APPEND _matlab_possible_roots "UNKNOWN" "NOTFOUND" ${Matlab_ROOT_DIR}) # empty version, empty MCR/Matlab indication + else() + list(APPEND _matlab_possible_roots "UNKNOWN" ${Matlab_VERSION_STRING_INTERNAL} ${Matlab_ROOT_DIR}) # cached version + endif() + endif() +else() + + # if the user does not specify the possible installation root, we look for + # one installation using the appropriate heuristics. + # There is apparently no standard way on Linux. + if(WIN32) + _Matlab_find_instances_win32(_matlab_possible_roots_win32) + list(APPEND _matlab_possible_roots ${_matlab_possible_roots_win32}) + elseif(APPLE) + _Matlab_find_instances_osx(_matlab_possible_roots_osx) + list(APPEND _matlab_possible_roots ${_matlab_possible_roots_osx}) + endif() +endif() + + +list(LENGTH _matlab_possible_roots _numbers_of_matlab_roots) +if(_numbers_of_matlab_roots EQUAL 0) + # if we have not found anything, we fall back on the PATH + _Matlab_find_instances_from_path(_matlab_possible_roots) +endif() if(MATLAB_FIND_DEBUG) @@ -1242,12 +1397,14 @@ endif() # take the first possible Matlab root list(LENGTH _matlab_possible_roots _numbers_of_matlab_roots) set(Matlab_VERSION_STRING "NOTFOUND") +set(Matlab_Or_MCR "UNKNOWN") if(_numbers_of_matlab_roots GREATER 0) - list(GET _matlab_possible_roots 0 Matlab_VERSION_STRING) - list(GET _matlab_possible_roots 1 Matlab_ROOT_DIR) + list(GET _matlab_possible_roots 0 Matlab_Or_MCR) + list(GET _matlab_possible_roots 1 Matlab_VERSION_STRING) + list(GET _matlab_possible_roots 2 Matlab_ROOT_DIR) # adding a warning in case of ambiguity - if(_numbers_of_matlab_roots GREATER 2 AND MATLAB_FIND_DEBUG) + if(_numbers_of_matlab_roots GREATER 3 AND MATLAB_FIND_DEBUG) message(WARNING "[MATLAB] Found several distributions of Matlab. Setting the current version to ${Matlab_VERSION_STRING} (located ${Matlab_ROOT_DIR})." " If this is not the desired behaviour, provide the -DMatlab_ROOT_DIR=... on the command line") endif() @@ -1290,13 +1447,11 @@ set(Matlab_ROOT_DIR ${Matlab_ROOT_DIR} CACHE PATH "Matlab installation root path # Fix the version, in case this one is NOTFOUND _Matlab_get_version_from_root( "${Matlab_ROOT_DIR}" + "${Matlab_Or_MCR}" ${Matlab_VERSION_STRING} Matlab_VERSION_STRING ) - - - if(MATLAB_FIND_DEBUG) message(STATUS "[MATLAB] Current version is ${Matlab_VERSION_STRING} located ${Matlab_ROOT_DIR}") endif() diff --git a/Modules/FindOpenAL.cmake b/Modules/FindOpenAL.cmake index c3d202e..7521d51 100644 --- a/Modules/FindOpenAL.cmake +++ b/Modules/FindOpenAL.cmake @@ -58,7 +58,7 @@ find_path(OPENAL_INCLUDE_DIR al.h HINTS ENV OPENALDIR - PATH_SUFFIXES include/AL include/OpenAL include + PATH_SUFFIXES include/AL include/OpenAL include AL OpenAL PATHS ~/Library/Frameworks /Library/Frameworks diff --git a/Modules/FindOpenMP.cmake b/Modules/FindOpenMP.cmake index 1bf589d..329ace1 100644 --- a/Modules/FindOpenMP.cmake +++ b/Modules/FindOpenMP.cmake @@ -85,6 +85,7 @@ function(_OPENMP_FLAG_CANDIDATES LANG) set(OMP_FLAG_GNU "-fopenmp") set(OMP_FLAG_Clang "-fopenmp=libomp" "-fopenmp=libiomp5" "-fopenmp") + set(OMP_FLAG_AppleClang "-Xclang -fopenmp") set(OMP_FLAG_HP "+Oopenmp") if(WIN32) set(OMP_FLAG_Intel "-Qopenmp") @@ -125,6 +126,7 @@ set(OpenMP_C_CXX_TEST_SOURCE #include <omp.h> int main() { #ifdef _OPENMP + int n = omp_get_max_threads(); return 0; #else breaks_on_purpose @@ -163,7 +165,7 @@ function(_OPENMP_WRITE_SOURCE_FILE LANG SRC_FILE_CONTENT_VAR SRC_FILE_NAME SRC_F set(${SRC_FILE_FULLPATH} "${SRC_FILE}" PARENT_SCOPE) endfunction() -include(${CMAKE_ROOT}/Modules/CMakeParseImplicitLinkInfo.cmake) +include(${CMAKE_CURRENT_LIST_DIR}/CMakeParseImplicitLinkInfo.cmake) function(_OPENMP_GET_FLAGS LANG FLAG_MODE OPENMP_FLAG_VAR OPENMP_LIB_NAMES_VAR) _OPENMP_FLAG_CANDIDATES("${LANG}") @@ -246,6 +248,28 @@ function(_OPENMP_GET_FLAGS LANG FLAG_MODE OPENMP_FLAG_VAR OPENMP_LIB_NAMES_VAR) set("${OPENMP_LIB_NAMES_VAR}" "" PARENT_SCOPE) endif() break() + elseif(CMAKE_${LANG}_COMPILER_ID STREQUAL "AppleClang" + AND CMAKE_${LANG}_COMPILER_VERSION VERSION_GREATER_EQUAL "7.0") + + # Check for separate OpenMP library on AppleClang 7+ + find_library(OpenMP_libomp_LIBRARY + NAMES omp gomp iomp5 + HINTS ${CMAKE_${LANG}_IMPLICIT_LINK_DIRECTORIES} + ) + mark_as_advanced(OpenMP_libomp_LIBRARY) + + if(OpenMP_libomp_LIBRARY) + try_compile( OpenMP_COMPILE_RESULT_${FLAG_MODE}_${OPENMP_PLAIN_FLAG} ${CMAKE_BINARY_DIR} ${_OPENMP_TEST_SRC} + CMAKE_FLAGS "-DCOMPILE_DEFINITIONS:STRING=${OPENMP_FLAGS_TEST}" + LINK_LIBRARIES ${CMAKE_${LANG}_VERBOSE_FLAG} ${OpenMP_libomp_LIBRARY} + OUTPUT_VARIABLE OpenMP_TRY_COMPILE_OUTPUT + ) + if(OpenMP_COMPILE_RESULT_${FLAG_MODE}_${OPENMP_PLAIN_FLAG}) + set("${OPENMP_FLAG_VAR}" "${OPENMP_FLAG}" PARENT_SCOPE) + set("${OPENMP_LIB_NAMES_VAR}" "libomp" PARENT_SCOPE) + break() + endif() + endif() endif() set("${OPENMP_LIB_NAMES_VAR}" "NOTFOUND" PARENT_SCOPE) set("${OPENMP_FLAG_VAR}" "NOTFOUND" PARENT_SCOPE) @@ -414,6 +438,8 @@ endif() unset(_OpenMP_MIN_VERSION) +include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake) + foreach(LANG IN LISTS OpenMP_FINDLIST) if(CMAKE_${LANG}_COMPILER_LOADED) if (NOT OpenMP_${LANG}_SPEC_DATE AND OpenMP_${LANG}_FLAGS) @@ -423,8 +449,6 @@ foreach(LANG IN LISTS OpenMP_FINDLIST) _OPENMP_SET_VERSION_BY_SPEC_DATE("${LANG}") endif() - include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake) - set(OpenMP_${LANG}_FIND_QUIETLY ${OpenMP_FIND_QUIETLY}) set(OpenMP_${LANG}_FIND_REQUIRED ${OpenMP_FIND_REQUIRED}) set(OpenMP_${LANG}_FIND_VERSION ${OpenMP_FIND_VERSION}) diff --git a/Modules/FindOpenSSL.cmake b/Modules/FindOpenSSL.cmake index c358ff1..d5cd8bc 100644 --- a/Modules/FindOpenSSL.cmake +++ b/Modules/FindOpenSSL.cmake @@ -7,6 +7,12 @@ # # Find the OpenSSL encryption library. # +# Optional COMPONENTS +# ^^^^^^^^^^^^^^^^^^^ +# +# This module supports two optional COMPONENTS: ``Crypto`` and ``SSL``. Both +# components have associated imported targets, as described below. +# # Imported Targets # ^^^^^^^^^^^^^^^^ # @@ -23,7 +29,8 @@ # This module will set the following variables in your project: # # ``OPENSSL_FOUND`` -# System has the OpenSSL library. +# System has the OpenSSL library. If no components are requested it only +# requires the crypto library. # ``OPENSSL_INCLUDE_DIR`` # The OpenSSL include directory. # ``OPENSSL_CRYPTO_LIBRARY`` @@ -371,28 +378,47 @@ if(OPENSSL_INCLUDE_DIR AND EXISTS "${OPENSSL_INCLUDE_DIR}/openssl/opensslv.h") endif () endif () -include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake) - set(OPENSSL_LIBRARIES ${OPENSSL_SSL_LIBRARY} ${OPENSSL_CRYPTO_LIBRARY} ) -if (OPENSSL_VERSION) - find_package_handle_standard_args(OpenSSL - REQUIRED_VARS - #OPENSSL_SSL_LIBRARY # FIXME: require based on a component request? - OPENSSL_CRYPTO_LIBRARY - OPENSSL_INCLUDE_DIR - VERSION_VAR - OPENSSL_VERSION - FAIL_MESSAGE - "Could NOT find OpenSSL, try to set the path to OpenSSL root folder in the system variable OPENSSL_ROOT_DIR" - ) -else () - find_package_handle_standard_args(OpenSSL "Could NOT find OpenSSL, try to set the path to OpenSSL root folder in the system variable OPENSSL_ROOT_DIR" - #OPENSSL_SSL_LIBRARY # FIXME: require based on a component request? +foreach(_comp IN LISTS OpenSSL_FIND_COMPONENTS) + if(_comp STREQUAL "Crypto") + if(EXISTS "${OPENSSL_INCLUDE_DIR}" AND + (EXISTS "${OPENSSL_CRYPTO_LIBRARY}" OR + EXISTS "${LIB_EAY_LIBRARY_DEBUG}" OR + EXISTS "${LIB_EAY_LIBRARY_RELEASE}") + ) + set(OpenSSL_${_comp}_FOUND TRUE) + else() + set(OpenSSL_${_comp}_FOUND FALSE) + endif() + elseif(_comp STREQUAL "SSL") + if(EXISTS "${OPENSSL_INCLUDE_DIR}" AND + (EXISTS "${OPENSSL_SSL_LIBRARY}" OR + EXISTS "${SSL_EAY_LIBRARY_DEBUG}" OR + EXISTS "${SSL_EAY_LIBRARY_RELEASE}") + ) + set(OpenSSL_${_comp}_FOUND TRUE) + else() + set(OpenSSL_${_comp}_FOUND FALSE) + endif() + else() + message(WARNING "${_comp} is not a valid OpenSSL component") + set(OpenSSL_${_comp}_FOUND FALSE) + endif() +endforeach() +unset(_comp) + +include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake) +find_package_handle_standard_args(OpenSSL + REQUIRED_VARS OPENSSL_CRYPTO_LIBRARY OPENSSL_INCLUDE_DIR - ) -endif () + VERSION_VAR + OPENSSL_VERSION + HANDLE_COMPONENTS + FAIL_MESSAGE + "Could NOT find OpenSSL, try to set the path to OpenSSL root folder in the system variable OPENSSL_ROOT_DIR" +) mark_as_advanced(OPENSSL_INCLUDE_DIR OPENSSL_LIBRARIES) @@ -425,6 +451,7 @@ if(OPENSSL_FOUND) IMPORTED_LOCATION_DEBUG "${LIB_EAY_LIBRARY_DEBUG}") endif() endif() + if(NOT TARGET OpenSSL::SSL AND (EXISTS "${OPENSSL_SSL_LIBRARY}" OR EXISTS "${SSL_EAY_LIBRARY_DEBUG}" OR diff --git a/Modules/FindPython.cmake b/Modules/FindPython.cmake new file mode 100644 index 0000000..8139e53 --- /dev/null +++ b/Modules/FindPython.cmake @@ -0,0 +1,181 @@ +# Distributed under the OSI-approved BSD 3-Clause License. See accompanying +# file Copyright.txt or https://cmake.org/licensing for details. + +#[=======================================================================[.rst: +FindPython +---------- + +Find Python interpreter, compiler and development environment (include +directories and libraries). + +Three components are supported: + +* ``Interpreter``: search for Python interpreter. +* ``Compiler``: search for Python compiler. Only offered by IronPython. +* ``Development``: search for development artifacts (include directories and + libraries). + +If no ``COMPONENTS`` is specified, ``Interpreter`` is assumed. + +To ensure consistent versions between components ``Interpreter``, ``Compiler`` +and ``Development``, specify all components at the same time:: + + find_package (Python COMPONENTS Interpreter Development) + +This module looks preferably for version 3 of Python. If not found, version 2 +is searched. +To manage concurrent versions 3 and 2 of Python, use :module:`FindPython3` and +:module:`FindPython2` modules rather than this one. + +Imported Targets +^^^^^^^^^^^^^^^^ + +This module defines the following :ref:`Imported Targets <Imported Targets>`: + +``Python::Interpreter`` + Python interpreter. Target defined if component ``Interpreter`` is found. +``Python::Compiler`` + Python compiler. Target defined if component ``Compiler`` is found. +``Python::Python`` + Python library. Target defined if component ``Development`` is found. + +Result Variables +^^^^^^^^^^^^^^^^ + +This module will set the following variables in your project +(see :ref:`Standard Variable Names <CMake Developer Standard Variable Names>`): + +``Python_FOUND`` + System has the Python requested components. +``Python_Interpreter_FOUND`` + System has the Python interpreter. +``Python_EXECUTABLE`` + Path to the Python interpreter. +``Python_INTERPRETER_ID`` + A short string unique to the interpreter. Possible values include: + * Python + * ActivePython + * Anaconda + * Canopy + * IronPython +``Python_STDLIB`` + Standard platform independent installation directory. + + Information returned by + ``distutils.sysconfig.get_python_lib(plat_specific=False,standard_lib=True)``. +``Python_STDARCH`` + Standard platform dependent installation directory. + + Information returned by + ``distutils.sysconfig.get_python_lib(plat_specific=True,standard_lib=True)``. +``Python_SITELIB`` + Third-party platform independent installation directory. + + Information returned by + ``distutils.sysconfig.get_python_lib(plat_specific=False,standard_lib=False)``. +``Python_SITEARCH`` + Third-party platform dependent installation directory. + + Information returned by + ``distutils.sysconfig.get_python_lib(plat_specific=True,standard_lib=False)``. +``Python_Compiler_FOUND`` + System has the Python compiler. +``Python_COMPILER`` + Path to the Python compiler. Only offered by IronPython. +``Python_COMPILER_ID`` + A short string unique to the compiler. Possible values include: + * IronPython +``Python_Development_FOUND`` + System has the Python development artifacts. +``Python_INCLUDE_DIRS`` + The Python include directories. +``Python_LIBRARIES`` + The Python libraries. +``Python_LIBRARY_DIRS`` + The Python library directories. +``Python_RUNTIME_LIBRARY_DIRS`` + The Python runtime library directories. +``Python_VERSION`` + Python version. +``Python_VERSION_MAJOR`` + Python major version. +``Python_VERSION_MINOR`` + Python minor version. +``Python_VERSION_PATCH`` + Python patch version. + +Hints +^^^^^ + +``Python_ROOT_DIR`` + Define the root directory of a Python installation. + +``Python_USE_STATIC_LIBS`` + * If not defined, search for shared libraries and static libraries in that + order. + * If set to TRUE, search **only** for static libraries. + * If set to FALSE, search **only** for shared libraries. + +Commands +^^^^^^^^ + +This module defines the command ``Python_add_library`` which have the same +semantic as :command:`add_library` but take care of Python module naming rules +(only applied if library is of type ``MODULE``) and add dependency to target +``Python::Python``:: + + Python_add_library (my_module MODULE src1.cpp) + +If library type is not specified, ``MODULE`` is assumed. +#]=======================================================================] + + +set (_PYTHON_PREFIX Python) + +if (DEFINED Python_FIND_VERSION) + set (_Python_REQUIRED_VERSION_MAJOR ${Python_FIND_VERSION_MAJOR}) + + include (${CMAKE_CURRENT_LIST_DIR}/FindPython/Support.cmake) +else() + # iterate over versions in quiet and NOT required modes to avoid multiple + # "Found" messages and prematurally failure. + set (_Python_QUIETLY ${Python_FIND_QUIETLY}) + set (_Python_REQUIRED ${Python_FIND_REQUIRED}) + set (Python_FIND_QUIETLY TRUE) + set (Python_FIND_REQUIRED FALSE) + + set (_Python_REQUIRED_VERSIONS 3 2) + set (_Python_REQUIRED_VERSION_LAST 2) + + foreach (_Python_REQUIRED_VERSION_MAJOR IN LISTS _Python_REQUIRED_VERSIONS) + set (Python_FIND_VERSION ${_Python_REQUIRED_VERSION_MAJOR}) + include (${CMAKE_CURRENT_LIST_DIR}/FindPython/Support.cmake) + if (Python_FOUND OR + _Python_REQUIRED_VERSION_MAJOR EQUAL _Python_REQUIRED_VERSION_LAST) + break() + endif() + # clean-up some CACHE variables to ensure look-up restart from scratch + foreach (_Python_ITEM IN LISTS _Python_CACHED_VARS) + unset (${_Python_ITEM} CACHE) + endforeach() + endforeach() + + unset (Python_FIND_VERSION) + + set (Python_FIND_QUIETLY ${_Python_QUIETLY}) + set (Python_FIND_REQUIRED ${_Python_REQUIRED}) + if (Python_FIND_REQUIRED OR NOT Python_FIND_QUIETLY) + # call again validation command to get "Found" or error message + find_package_handle_standard_args (Python HANDLE_COMPONENTS + REQUIRED_VARS ${_Python_REQUIRED_VARS} + VERSION_VAR Python_VERSION) + endif() +endif() + +if (COMMAND __Python_add_library) + macro (Python_add_library) + __Python_add_library (Python ${ARGV}) + endmacro() +endif() + +unset (_PYTHON_PREFIX) diff --git a/Modules/FindPython/Support.cmake b/Modules/FindPython/Support.cmake new file mode 100644 index 0000000..9903a6d --- /dev/null +++ b/Modules/FindPython/Support.cmake @@ -0,0 +1,929 @@ +# Distributed under the OSI-approved BSD 3-Clause License. See accompanying +# file Copyright.txt or https://cmake.org/licensing for details. + +# +# This file is a "template" file used by various FindPython modules. +# + +cmake_policy (VERSION 3.7) + +# +# Initial configuration +# +if (NOT DEFINED _PYTHON_PREFIX) + message (FATAL_ERROR "FindPython: INTERNAL ERROR") +endif() +if (NOT DEFINED _${_PYTHON_PREFIX}_REQUIRED_VERSION_MAJOR) + message (FATAL_ERROR "FindPython: INTERNAL ERROR") +endif() +if (_${_PYTHON_PREFIX}_REQUIRED_VERSION_MAJOR EQUAL 3) + set(_${_PYTHON_PREFIX}_VERSIONS 3.7 3.6 3.5 3.4 3.3 3.2 3.1 3.0) +elseif (_${_PYTHON_PREFIX}_REQUIRED_VERSION_MAJOR EQUAL 2) + set(_${_PYTHON_PREFIX}_VERSIONS 2.7 2.6 2.5 2.4 2.3 2.2 2.1 2.0) +else() + message (FATAL_ERROR "FindPython: INTERNAL ERROR") +endif() + + +# +# helper commands +# +macro (_PYTHON_DISPLAY_FAILURE _PYTHON_MSG) + if (${_PYTHON_PREFIX}_FIND_REQUIRED) + message (FATAL_ERROR "${_PYTHON_MSG}") + else() + if (NOT ${_PYTHON_PREFIX}_FIND_QUIETLY) + message(STATUS "${_PYTHON_MSG}") + endif () + endif() + + set (${_PYTHON_PREFIX}_FOUND FALSE) + string (TOUPPER "${_PYTHON_PREFIX}" _${_PYTHON_PREFIX}_UPPER_PREFIX) + set (${_PYTHON_UPPER_PREFIX}_FOUND FALSE) + return() +endmacro() + + +function (_PYTHON_GET_FRAMEWORKS _PYTHON_PGF_FRAMEWORK_PATHS _PYTHON_VERSION) + set (_PYTHON_FRAMEWORK_PATHS) + foreach (_PYTHON_FRAMEWORK IN LISTS Python_FRAMEWORKS) + list (APPEND _PYTHON_FRAMEWORK_PATHS + "${_PYTHON_FRAMEWORK}/Versions/${_PYTHON_VERSION}") + endforeach() + set (${_PYTHON_PGF_FRAMEWORK_PATHS} ${_PYTHON_FRAMEWORK_PATHS} PARENT_SCOPE) +endfunction() + + +function (_PYTHON_VALIDATE_INTERPRETER) + if (NOT ${_PYTHON_PREFIX}_EXECUTABLE) + return() + endif() + + if (${_PYTHON_PREFIX}_EXECUTABLE MATCHES "python${CMAKE_EXECUTABLE_SUFFIX}$") + # executable found do not have version in name + # ensure major version is OK + execute_process (COMMAND "${${_PYTHON_PREFIX}_EXECUTABLE}" -c + "import sys; sys.stdout.write(str(sys.version_info[0]))" + RESULT_VARIABLE result + OUTPUT_VARIABLE version + ERROR_QUIET + OUTPUT_STRIP_TRAILING_WHITESPACE) + if (result OR NOT version EQUAL _${_PYTHON_PREFIX}_REQUIRED_VERSION_MAJOR) + # interpreter not usable or has wrong major version + set (${_PYTHON_PREFIX}_EXECUTABLE ${_PYTHON_PREFIX}_EXECUTABLE-NOTFOUND CACHE INTERNAL "" FORCE) + return() + endif() + endif() + + if (CMAKE_SIZEOF_VOID_P AND "Development" IN_LIST ${_PYTHON_PREFIX}_FIND_COMPONENTS + AND NOT CMAKE_CROSSCOMPILING) + # In this case, interpreter must have same architecture as environment + execute_process (COMMAND "${${_PYTHON_PREFIX}_EXECUTABLE}" -c + "import sys, struct; sys.stdout.write(str(struct.calcsize(\"P\")))" + RESULT_VARIABLE result + OUTPUT_VARIABLE size + ERROR_QUIET + OUTPUT_STRIP_TRAILING_WHITESPACE) + if (result OR NOT size EQUAL CMAKE_SIZEOF_VOID_P) + # interpreter not usable or has wrong architecture + set (${_PYTHON_PREFIX}_EXECUTABLE ${_PYTHON_PREFIX}_EXECUTABLE-NOTFOUND CACHE INTERNAL "" FORCE) + return() + endif() + endif() +endfunction() + + +function (_PYTHON_FIND_RUNTIME_LIBRARY _PYTHON_LIB) + string (REPLACE "_RUNTIME" "" _PYTHON_LIB "${_PYTHON_LIB}") + # look at runtime part on systems supporting it + if (CMAKE_SYSTEM_NAME STREQUAL "Windows" OR + (CMAKE_SYSTEM_NAME MATCHES "MSYS|CYGWIN" + AND ${_PYTHON_LIB} MATCHES "${CMAKE_IMPORT_LIBRARY_SUFFIX}$")) + set (CMAKE_FIND_LIBRARY_SUFFIXES ${CMAKE_SHARED_LIBRARY_SUFFIX}) + # MSYS has a special syntax for runtime libraries + if (CMAKE_SYSTEM_NAME MATCHES "MSYS") + list (APPEND CMAKE_FIND_LIBRARY_PREFIXES "msys-") + endif() + find_library (${ARGV}) + endif() +endfunction() + + +function (_PYTHON_SET_LIBRARY_DIRS _PYTHON_SLD_RESULT) + unset (_PYTHON_DIRS) + set (_PYTHON_LIBS ${ARGV}) + list (REMOVE_AT _PYTHON_LIBS 0) + foreach (_PYTHON_LIB IN LISTS _PYTHON_LIBS) + if (${_PYTHON_LIB}) + get_filename_component (_PYTHON_DIR "${${_PYTHON_LIB}}" DIRECTORY) + list (APPEND _PYTHON_DIRS "${_PYTHON_DIR}") + endif() + endforeach() + if (_PYTHON_DIRS) + list (REMOVE_DUPLICATES _PYTHON_DIRS) + endif() + set (${_PYTHON_SLD_RESULT} ${_PYTHON_DIRS} PARENT_SCOPE) +endfunction() + + +# If major version is specified, it must be the same as internal major version +if (DEFINED ${_PYTHON_PREFIX}_FIND_VERSION_MAJOR + AND NOT ${_PYTHON_PREFIX}_FIND_VERSION_MAJOR VERSION_EQUAL _${_PYTHON_PREFIX}_REQUIRED_VERSION_MAJOR) + _python_display_failure ("Could NOT find ${_PYTHON_PREFIX}: Wrong major version specified is \"${${_PYTHON_PREFIX}_FIND_VERSION_MAJOR}\", but expected major version is \"${_${_PYTHON_PREFIX}_REQUIRED_VERSION_MAJOR}\"") +endif() + + +# handle components +if (NOT ${_PYTHON_PREFIX}_FIND_COMPONENTS) + set (${_PYTHON_PREFIX}_FIND_COMPONENTS Interpreter) + set (${_PYTHON_PREFIX}_FIND_REQUIRED_Interpreter TRUE) +endif() +foreach (_${_PYTHON_PREFIX}_COMPONENT IN LISTS ${_PYTHON_PREFIX}_FIND_COMPONENTS) + set (${_PYTHON_PREFIX}_${_${_PYTHON_PREFIX}_COMPONENT}_FOUND FALSE) +endforeach() +unset (_${_PYTHON_PREFIX}_FIND_VERSIONS) + +# Set versions to search +## default: search any version +set (_${_PYTHON_PREFIX}_FIND_VERSIONS ${_${_PYTHON_PREFIX}_VERSIONS}) + +if (${_PYTHON_PREFIX}_FIND_VERSION_COUNT GREATER 1) + if (${_PYTHON_PREFIX}_FIND_VERSION_EXACT) + set (_${_PYTHON_PREFIX}_FIND_VERSIONS ${${_PYTHON_PREFIX}_FIND_VERSION_MAJOR}.${${_PYTHON_PREFIX}_FIND_VERSION_MINOR}) + else() + unset (_${_PYTHON_PREFIX}_FIND_VERSIONS) + # add all compatible versions + foreach (_${_PYTHON_PREFIX}_VERSION IN LISTS _${_PYTHON_PREFIX}_VERSIONS) + if (_${_PYTHON_PREFIX}_VERSION VERSION_GREATER_EQUAL ${_PYTHON_PREFIX}_FIND_VERSION) + list (APPEND _${_PYTHON_PREFIX}_FIND_VERSIONS ${_${_PYTHON_PREFIX}_VERSION}) + endif() + endforeach() + endif() +endif() + +# Anaconda distribution: define which architectures can be used +if (CMAKE_SIZEOF_VOID_P) + # In this case, search only for 64bit or 32bit + math (EXPR _${_PYTHON_PREFIX}_ARCH "${CMAKE_SIZEOF_VOID_P} * 8") + set (_${_PYTHON_PREFIX}_ARCH2 ${_${_PYTHON_PREFIX}_ARCH}) +else() + # architecture unknown, search for both 64bit and 32bit + set (_${_PYTHON_PREFIX}_ARCH 64) + set (_${_PYTHON_PREFIX}_ARCH2 32) +endif() + +# IronPython support +if (CMAKE_SIZEOF_VOID_P) + # In this case, search only for 64bit or 32bit + math (EXPR _${_PYTHON_PREFIX}_ARCH "${CMAKE_SIZEOF_VOID_P} * 8") + set (_${_PYTHON_PREFIX}_IRON_PYTHON_NAMES ipy${_${_PYTHON_PREFIX}_ARCH} ipy) +else() + # architecture unknown, search for natural interpreter + set (_${_PYTHON_PREFIX}_IRON_PYTHON_NAMES ipy) +endif() + +# Apple frameworks handling +include (${CMAKE_CURRENT_LIST_DIR}/../CMakeFindFrameworks.cmake) +cmake_find_frameworks (Python) + +# Save CMAKE_FIND_FRAMEWORK +if (DEFINED CMAKE_FIND_FRAMEWORK) + set (_${_PYTHON_PREFIX}_CMAKE_FIND_FRAMEWORK ${CMAKE_FIND_FRAMEWORK}) +else() + unset (_${_PYTHON_PREFIX}_CMAKE_FIND_FRAMEWORK) +endif() +# To avoid picking up the system elements pre-maturely. +set (CMAKE_FIND_FRAMEWORK LAST) + + +unset (${_PYTHON_PREFIX}_VERSION_MAJOR) +unset (${_PYTHON_PREFIX}_VERSION_MINOR) +unset (${_PYTHON_PREFIX}_VERSION_PATCH) + +unset (_${_PYTHON_PREFIX}_REQUIRED_VARS) +unset (_${_PYTHON_PREFIX}_CACHED_VARS) + + +# first step, search for the interpreter +if ("Interpreter" IN_LIST ${_PYTHON_PREFIX}_FIND_COMPONENTS) + if (${_PYTHON_PREFIX}_FIND_REQUIRED_Interpreter) + list (APPEND _${_PYTHON_PREFIX}_REQUIRED_VARS ${_PYTHON_PREFIX}_EXECUTABLE) + list (APPEND _${_PYTHON_PREFIX}_CACHED_VARS ${_PYTHON_PREFIX}_EXECUTABLE) + endif() + + set (_${_PYTHON_PREFIX}_HINTS "${${_PYTHON_PREFIX}_ROOT_DIR}" ENV ${_PYTHON_PREFIX}_ROOT_DIR) + + # look-up for various versions and locations + foreach (_${_PYTHON_PREFIX}_VERSION IN LISTS _${_PYTHON_PREFIX}_FIND_VERSIONS) + string (REPLACE "." "" _${_PYTHON_PREFIX}_VERSION_NO_DOTS ${_${_PYTHON_PREFIX}_VERSION}) + + _python_get_frameworks (_${_PYTHON_PREFIX}_FRAMEWORK_PATHS ${_${_PYTHON_PREFIX}_VERSION}) + + # try using HINTS + find_program (${_PYTHON_PREFIX}_EXECUTABLE + NAMES python${_${_PYTHON_PREFIX}_VERSION} + NAMES_PER_DIR + HINTS ${_${_PYTHON_PREFIX}_HINTS} + PATHS ${_${_PYTHON_PREFIX}_FRAMEWORK_PATHS} + PATH_SUFFIXES bin + NO_SYSTEM_ENVIRONMENT_PATH + NO_CMAKE_SYSTEM_PATH) + # try using registry + if (WIN32) + find_program (${_PYTHON_PREFIX}_EXECUTABLE + NAMES python${_${_PYTHON_PREFIX}_VERSION} python + ${_${_PYTHON_PREFIX}_IRON_PYTHON_NAMES} + NAMES_PER_DIR + HINTS ${_${_PYTHON_PREFIX}_HINTS} + PATHS [HKEY_CURRENT_USER\\SOFTWARE\\Python\\PythonCore\\${_${_PYTHON_PREFIX}_VERSION}\\InstallPath] + [HKEY_CURRENT_USER\\SOFTWARE\\Python\\ContinuumAnalytics\\Anaconda${_${_PYTHON_PREFIX}_VERSION_NO_DOTS}-${_${_PYTHON_PREFIX}_ARCH}\\InstallPath] + [HKEY_CURRENT_USER\\SOFTWARE\\Python\\ContinuumAnalytics\\Anaconda${_${_PYTHON_PREFIX}_VERSION_NO_DOTS}-${_${_PYTHON_PREFIX}_ARCH2}\\InstallPath] + [HKEY_LOCAL_MACHINE\\SOFTWARE\\Python\\PythonCore\\${_${_PYTHON_PREFIX}_VERSION}\\InstallPath] + [HKEY_LOCAL_MACHINE\\SOFTWARE\\Python\\ContinuumAnalytics\\Anaconda${_${_PYTHON_PREFIX}_VERSION_NO_DOTS}-${_${_PYTHON_PREFIX}_ARCH}\\InstallPath] + [HKEY_LOCAL_MACHINE\\SOFTWARE\\Python\\ContinuumAnalytics\\Anaconda${_${_PYTHON_PREFIX}_VERSION_NO_DOTS}-${_${_PYTHON_PREFIX}_ARCH2}\\InstallPath] + [HKEY_LOCAL_MACHINE\\SOFTWARE\\IronPython\\${_${_PYTHON_PREFIX}_VERSION}\\InstallPath] + PATH_SUFFIXES bin + NO_SYSTEM_ENVIRONMENT_PATH + NO_CMAKE_SYSTEM_PATH) + endif() + # try in standard paths + find_program (${_PYTHON_PREFIX}_EXECUTABLE + NAMES python${_${_PYTHON_PREFIX}_VERSION}) + + _python_validate_interpreter () + if (${_PYTHON_PREFIX}_EXECUTABLE) + break() + endif() + endforeach() + + # try more generic names + if (NOT ${_PYTHON_PREFIX}_EXECUTABLE) + find_program (${_PYTHON_PREFIX}_EXECUTABLE + NAMES python${${_PYTHON_PREFIX}_VERSION_MAJOR} python + ${_${_PYTHON_PREFIX}_IRON_PYTHON_NAMES} + HINTS ${_${_PYTHON_PREFIX}_HINTS} + PATH_SUFFIXES bin) + + _python_validate_interpreter () + endif() + + # retrieve exact version of executable found + if (${_PYTHON_PREFIX}_EXECUTABLE) + execute_process (COMMAND "${${_PYTHON_PREFIX}_EXECUTABLE}" -c + "import sys; sys.stdout.write('.'.join([str(x) for x in sys.version_info[:3]]))" + RESULT_VARIABLE _${_PYTHON_PREFIX}_RESULT + OUTPUT_VARIABLE ${_PYTHON_PREFIX}_VERSION + ERROR_QUIET + OUTPUT_STRIP_TRAILING_WHITESPACE) + if (NOT _${_PYTHON_PREFIX}_RESULT) + string (REGEX MATCHALL "[0-9]+" _${_PYTHON_PREFIX}_VERSIONS "${${_PYTHON_PREFIX}_VERSION}") + list (GET _${_PYTHON_PREFIX}_VERSIONS 0 ${_PYTHON_PREFIX}_VERSION_MAJOR) + list (GET _${_PYTHON_PREFIX}_VERSIONS 1 ${_PYTHON_PREFIX}_VERSION_MINOR) + list (GET _${_PYTHON_PREFIX}_VERSIONS 2 ${_PYTHON_PREFIX}_VERSION_PATCH) + else() + # Interpreter is not usable + set (${_PYTHON_PREFIX}_EXECUTABLE ${_PYTHON_PREFIX}_EXECUTABLE-NOTFOUND CACHE INTERNAL "" FORCE) + unset (${_PYTHON_PREFIX}_VERSION) + endif() + endif() + + if (${_PYTHON_PREFIX}_EXECUTABLE + AND ${_PYTHON_PREFIX}_VERSION_MAJOR VERSION_EQUAL _${_PYTHON_PREFIX}_REQUIRED_VERSION_MAJOR) + set (${_PYTHON_PREFIX}_Interpreter_FOUND TRUE) + # Use interpreter version for future searchs to ensure consistency + set (_${_PYTHON_PREFIX}_FIND_VERSIONS ${${_PYTHON_PREFIX}_VERSION_MAJOR}.${${_PYTHON_PREFIX}_VERSION_MINOR}) + endif() + + if (${_PYTHON_PREFIX}_Interpreter_FOUND) + # retrieve interpreter identity + execute_process (COMMAND "${${_PYTHON_PREFIX}_EXECUTABLE}" -V + RESULT_VARIABLE _${_PYTHON_PREFIX}_RESULT + OUTPUT_VARIABLE ${_PYTHON_PREFIX}_INTERPRETER_ID + ERROR_VARIABLE ${_PYTHON_PREFIX}_INTERPRETER_ID) + if (NOT _${_PYTHON_PREFIX}_RESULT) + if (${_PYTHON_PREFIX}_INTERPRETER_ID MATCHES "Anaconda") + set (${_PYTHON_PREFIX}_INTERPRETER_ID "Anaconda") + elseif (${_PYTHON_PREFIX}_INTERPRETER_ID MATCHES "Enthought") + set (${_PYTHON_PREFIX}_INTERPRETER_ID "Canopy") + else() + string (REGEX REPLACE "^([^ ]+).*" "\\1" ${_PYTHON_PREFIX}_INTERPRETER_ID "${${_PYTHON_PREFIX}_INTERPRETER_ID}") + if (${_PYTHON_PREFIX}_INTERPRETER_ID STREQUAL "Python") + # try to get a more precise ID + execute_process (COMMAND "${${_PYTHON_PREFIX}_EXECUTABLE}" -c "import sys; print(sys.copyright)" + RESULT_VARIABLE _${_PYTHON_PREFIX}_RESULT + OUTPUT_VARIABLE ${_PYTHON_PREFIX}_COPYRIGHT + ERROR_QUIET) + if (${_PYTHON_PREFIX}_COPYRIGHT MATCHES "ActiveState") + set (${_PYTHON_PREFIX}_INTERPRETER_ID "ActivePython") + endif() + endif() + endif() + else() + set (${_PYTHON_PREFIX}_INTERPRETER_ID Python) + endif() + else() + unset (${_PYTHON_PREFIX}_INTERPRETER_ID) + endif() + + # retrieve various package installation directories + execute_process (COMMAND "${${_PYTHON_PREFIX}_EXECUTABLE}" -c "import sys; from distutils import sysconfig;sys.stdout.write(';'.join([sysconfig.get_python_lib(plat_specific=False,standard_lib=True),sysconfig.get_python_lib(plat_specific=True,standard_lib=True),sysconfig.get_python_lib(plat_specific=False,standard_lib=False),sysconfig.get_python_lib(plat_specific=True,standard_lib=False)]))" + + RESULT_VARIABLE _${_PYTHON_PREFIX}_RESULT + OUTPUT_VARIABLE _${_PYTHON_PREFIX}_LIBPATHS + ERROR_QUIET) + if (NOT _${_PYTHON_PREFIX}_RESULT) + list (GET _${_PYTHON_PREFIX}_LIBPATHS 0 ${_PYTHON_PREFIX}_STDLIB) + list (GET _${_PYTHON_PREFIX}_LIBPATHS 1 ${_PYTHON_PREFIX}_STDARCH) + list (GET _${_PYTHON_PREFIX}_LIBPATHS 2 ${_PYTHON_PREFIX}_SITELIB) + list (GET _${_PYTHON_PREFIX}_LIBPATHS 3 ${_PYTHON_PREFIX}_SITEARCH) + else() + unset (${_PYTHON_PREFIX}_STDLIB) + unset (${_PYTHON_PREFIX}_STDARCH) + unset (${_PYTHON_PREFIX}_SITELIB) + unset (${_PYTHON_PREFIX}_SITEARCH) + endif() + + mark_as_advanced (${_PYTHON_PREFIX}_EXECUTABLE) +endif() + + +# second step, search for compiler (IronPython) +if ("Compiler" IN_LIST ${_PYTHON_PREFIX}_FIND_COMPONENTS) + if (${_PYTHON_PREFIX}_FIND_REQUIRED_Compiler) + list (APPEND _${_PYTHON_PREFIX}_REQUIRED_VARS ${_PYTHON_PREFIX}_COMPILER) + list (APPEND _${_PYTHON_PREFIX}_CACHED_VARS ${_PYTHON_PREFIX}_COMPILER) + endif() + + # IronPython specific artifacts + # If IronPython interpreter is found, use its path + unset (_${_PYTHON_PREFIX}_IRON_ROOT) + if (${_PYTHON_PREFIX}_Interpreter_FOUND AND ${_PYTHON_PREFIX}_INTERPRETER_ID STREQUAL "IronPython") + get_filename_component (_${_PYTHON_PREFIX}_IRON_ROOT "${${_PYTHON_PREFIX}_EXECUTABLE}" DIRECTORY) + endif() + + # try using root dir and registry + foreach (_${_PYTHON_PREFIX}_VERSION IN LISTS _${_PYTHON_PREFIX}_FIND_VERSIONS) + find_program (${_PYTHON_PREFIX}_COMPILER + NAMES ipyc + HINTS ${_${_PYTHON_PREFIX}_IRON_ROOT} ${_${_PYTHON_PREFIX}_HINTS} + PATHS [HKEY_LOCAL_MACHINE\\SOFTWARE\\IronPython\\${_${_PYTHON_PREFIX}_VERSION}\\InstallPath] + NO_SYSTEM_ENVIRONMENT_PATH + NO_CMAKE_SYSTEM_PATH) + if (${_PYTHON_PREFIX}_COMPILER) + break() + endif() + endforeach() + # try in standard paths + find_program (${_PYTHON_PREFIX}_COMPILER + NAMES ipyc) + + if (${_PYTHON_PREFIX}_COMPILER) + # retrieve python environment version from compiler + set (_${_PYTHON_PREFIX}_VERSION_DIR "${CMAKE_CURRENT_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/PythonCompilerVersion.dir") + file (WRITE "${_${_PYTHON_PREFIX}_VERSION_DIR}/version.py" "import sys; sys.stdout.write('.'.join([str(x) for x in sys.version_info[:3]]))\n") + execute_process (COMMAND "${${_PYTHON_PREFIX}_COMPILER}" /target:exe /embed "${_${_PYTHON_PREFIX}_VERSION_DIR}/version.py" + WORKING_DIRECTORY "${_${_PYTHON_PREFIX}_VERSION_DIR}" + OUTPUT_QUIET + ERROR_QUIET) + execute_process (COMMAND "${_${_PYTHON_PREFIX}_VERSION_DIR}/version" + WORKING_DIRECTORY "${_${_PYTHON_PREFIX}_VERSION_DIR}" + RESULT_VARIABLE _${_PYTHON_PREFIX}_RESULT + OUTPUT_VARIABLE _${_PYTHON_PREFIX}_VERSION + ERROR_QUIET) + if (NOT _${_PYTHON_PREFIX}_RESULT) + string (REGEX MATCHALL "[0-9]+" _${_PYTHON_PREFIX}_VERSIONS "${_${_PYTHON_PREFIX}_VERSION}") + list (GET _${_PYTHON_PREFIX}_VERSIONS 0 _${_PYTHON_PREFIX}_VERSION_MAJOR) + list (GET _${_PYTHON_PREFIX}_VERSIONS 1 _${_PYTHON_PREFIX}_VERSION_MINOR) + list (GET _${_PYTHON_PREFIX}_VERSIONS 2 _${_PYTHON_PREFIX}_VERSION_PATCH) + + if (NOT ${_PYTHON_PREFIX}_Interpreter_FOUND) + # set public version information + set (${_PYTHON_PREFIX}_VERSION ${_${_PYTHON_PREFIX}_VERSION}) + set (${_PYTHON_PREFIX}_VERSION_MAJOR ${_${_PYTHON_PREFIX}_VERSION_MAJOR}) + set (${_PYTHON_PREFIX}_VERSION_MINOR ${_${_PYTHON_PREFIX}_VERSION_MINOR}) + set (${_PYTHON_PREFIX}_VERSION_PATCH ${_${_PYTHON_PREFIX}_VERSION_PATCH}) + endif() + else() + # compiler not usable + set (${_PYTHON_PREFIX}_COMPILER ${_PYTHON_PREFIX}_COMPILER-NOTFOUND CACHE INTERNAL "" FORCE) + endif() + file (REMOVE_RECURSE "${_${_PYTHON_PREFIX}_VERSION_DIR}") + endif() + + if (${_PYTHON_PREFIX}_COMPILER) + if (${_PYTHON_PREFIX}_Interpreter_FOUND) + # Compiler must be compatible with interpreter + if (${_${_PYTHON_PREFIX}_VERSION_MAJOR}.${_${_PYTHON_PREFIX}_VERSION_MINOR} VERSION_EQUAL ${${_PYTHON_PREFIX}_VERSION_MAJOR}.${${_PYTHON_PREFIX}_VERSION_MINOR}) + set (${_PYTHON_PREFIX}_Compiler_FOUND TRUE) + endif() + elseif (${_PYTHON_PREFIX}_VERSION_MAJOR VERSION_EQUAL _${_PYTHON_PREFIX}_REQUIRED_VERSION_MAJOR) + set (${_PYTHON_PREFIX}_Compiler_FOUND TRUE) + # Use compiler version for future searchs to ensure consistency + set (_${_PYTHON_PREFIX}_FIND_VERSIONS ${${_PYTHON_PREFIX}_VERSION_MAJOR}.${${_PYTHON_PREFIX}_VERSION_MINOR}) + endif() + endif() + + if (${_PYTHON_PREFIX}_Compiler_FOUND) + set (${_PYTHON_PREFIX}_COMPILER_ID IronPython) + else() + unset (${_PYTHON_PREFIX}_COMPILER_ID) + endif() + + mark_as_advanced (${_PYTHON_PREFIX}_COMPILER) +endif() + + +# third step, search for the development artifacts +## Development environment is not compatible with IronPython interpreter +if ("Development" IN_LIST ${_PYTHON_PREFIX}_FIND_COMPONENTS + AND NOT ${_PYTHON_PREFIX}_INTERPRETER_ID STREQUAL "IronPython") + if (${_PYTHON_PREFIX}_FIND_REQUIRED_Development) + list (APPEND _${_PYTHON_PREFIX}_REQUIRED_VARS ${_PYTHON_PREFIX}_LIBRARY + ${_PYTHON_PREFIX}_INCLUDE_DIR) + list (APPEND _${_PYTHON_PREFIX}_CACHED_VARS ${_PYTHON_PREFIX}_LIBRARY + ${_PYTHON_PREFIX}_LIBRARY_RELEASE + ${_PYTHON_PREFIX}_RUNTIME_LIBRARY_RELEASE + ${_PYTHON_PREFIX}_LIBRARY_DEBUG + ${_PYTHON_PREFIX}_RUNTIME_LIBRARY_DEBUG + ${_PYTHON_PREFIX}_INCLUDE_DIR) + endif() + + # Support preference of static libs by adjusting CMAKE_FIND_LIBRARY_SUFFIXES + unset (_${_PYTHON_PREFIX}_CMAKE_FIND_LIBRARY_SUFFIXES) + if (DEFINED ${_PYTHON_PREFIX}_USE_STATIC_LIBS AND NOT WIN32) + set(_${_PYTHON_PREFIX}_CMAKE_FIND_LIBRARY_SUFFIXES ${CMAKE_FIND_LIBRARY_SUFFIXES}) + if(${_PYTHON_PREFIX}_USE_STATIC_LIBS) + set (CMAKE_FIND_LIBRARY_SUFFIXES ${CMAKE_STATIC_LIBRARY_SUFFIX}) + else() + list (REMOVE_ITEM CMAKE_FIND_LIBRARY_SUFFIXES ${CMAKE_STATIC_LIBRARY_SUFFIX}) + endif() + else() + endif() + + # if python interpreter is found, use its location and version to ensure consistency + # between interpreter and development environment + unset (_${_PYTHON_PREFIX}_PREFIX) + if (${_PYTHON_PREFIX}_Interpreter_FOUND) + execute_process (COMMAND "${${_PYTHON_PREFIX}_EXECUTABLE}" -c + "import sys; from distutils import sysconfig; sys.stdout.write(sysconfig.PREFIX)" + RESULT_VARIABLE _${_PYTHON_PREFIX}_RESULT + OUTPUT_VARIABLE _${_PYTHON_PREFIX}_PREFIX + ERROR_QUIET + OUTPUT_STRIP_TRAILING_WHITESPACE) + if (_${_PYTHON_PREFIX}_RESULT) + unset (_${_PYTHON_PREFIX}_PREFIX) + endif() + endif() + set (_${_PYTHON_PREFIX}_HINTS "${_${_PYTHON_PREFIX}_PREFIX}" "${${_PYTHON_PREFIX}_ROOT_DIR}" ENV ${_PYTHON_PREFIX}_ROOT_DIR) + + foreach (_${_PYTHON_PREFIX}_VERSION IN LISTS _${_PYTHON_PREFIX}_FIND_VERSIONS) + string (REPLACE "." "" _${_PYTHON_PREFIX}_VERSION_NO_DOTS ${_${_PYTHON_PREFIX}_VERSION}) + + # try to use pythonX.Y-config tool + set (_${_PYTHON_PREFIX}_CONFIG_NAMES) + if (DEFINED CMAKE_LIBRARY_ARCHITECTURE) + set (_${_PYTHON_PREFIX}_CONFIG_NAMES "${CMAKE_LIBRARY_ARCHITECTURE}-python${_${_PYTHON_PREFIX}_VERSION}-config") + endif() + list (APPEND _${_PYTHON_PREFIX}_CONFIG_NAMES "python${_${_PYTHON_PREFIX}_VERSION}-config") + find_program (_${_PYTHON_PREFIX}_CONFIG + NAMES ${_${_PYTHON_PREFIX}_CONFIG_NAMES} + HINTS ${_${_PYTHON_PREFIX}_HINTS} + PATH_SUFFIXES bin) + unset (_${_PYTHON_PREFIX}_CONFIG_NAMES) + + if (NOT _${_PYTHON_PREFIX}_CONFIG) + continue() + endif() + + # retrieve root install directory + execute_process (COMMAND "${_${_PYTHON_PREFIX}_CONFIG}" --prefix + RESULT_VARIABLE _${_PYTHON_PREFIX}_RESULT + OUTPUT_VARIABLE _${_PYTHON_PREFIX}_PREFIX + ERROR_QUIET + OUTPUT_STRIP_TRAILING_WHITESPACE) + if (_${_PYTHON_PREFIX}_RESULT) + # python-config is not usable + unset (_${_PYTHON_PREFIX}_CONFIG CACHE) + continue() + endif() + set (_${_PYTHON_PREFIX}_HINTS "${_${_PYTHON_PREFIX}_PREFIX}" "${${_PYTHON_PREFIX}_ROOT_DIR}" ENV ${_PYTHON_PREFIX}_ROOT_DIR) + + # retrieve library + execute_process (COMMAND "${_${_PYTHON_PREFIX}_CONFIG}" --ldflags + RESULT_VARIABLE _${_PYTHON_PREFIX}_RESULT + OUTPUT_VARIABLE _${_PYTHON_PREFIX}_FLAGS + ERROR_QUIET + OUTPUT_STRIP_TRAILING_WHITESPACE) + if (NOT _${_PYTHON_PREFIX}_RESULT) + # retrieve library directory + string (REGEX MATCHALL "-L[^ ]+" _${_PYTHON_PREFIX}_LIB_DIRS "${_${_PYTHON_PREFIX}_FLAGS}") + string (REPLACE "-L" "" _${_PYTHON_PREFIX}_LIB_DIRS "${_${_PYTHON_PREFIX}_LIB_DIRS}") + list (REMOVE_DUPLICATES _${_PYTHON_PREFIX}_LIB_DIRS) + # retrieve library name + string (REGEX MATCHALL "-lpython[^ ]+" _${_PYTHON_PREFIX}_LIB_NAMES "${_${_PYTHON_PREFIX}_FLAGS}") + string (REPLACE "-l" "" _${_PYTHON_PREFIX}_LIB_NAMES "${_${_PYTHON_PREFIX}_LIB_NAMES}") + list (REMOVE_DUPLICATES _${_PYTHON_PREFIX}_LIB_NAMES) + + find_library (${_PYTHON_PREFIX}_LIBRARY_RELEASE + NAMES ${_${_PYTHON_PREFIX}_LIB_NAMES} + NAMES_PER_DIR + HINTS ${_${_PYTHON_PREFIX}_HINTS} ${_${_PYTHON_PREFIX}_LIB_DIRS} + PATH_SUFFIXES lib + NO_SYSTEM_ENVIRONMENT_PATH + NO_CMAKE_SYSTEM_PATH) + # retrieve runtime library + if (${_PYTHON_PREFIX}_LIBRARY_RELEASE) + get_filename_component (_${_PYTHON_PREFIX}_PATH "${${_PYTHON_PREFIX}_LIBRARY_RELEASE}" DIRECTORY) + _python_find_runtime_library (${_PYTHON_PREFIX}_RUNTIME_LIBRARY_RELEASE + NAMES ${_${_PYTHON_PREFIX}_LIB_NAMES} + NAMES_PER_DIR + HINTS ${_${_PYTHON_PREFIX}_PATH} ${_${_PYTHON_PREFIX}_HINTS} + PATH_SUFFIXES bin + NO_SYSTEM_ENVIRONMENT_PATH + NO_CMAKE_SYSTEM_PATH) + endif() + endif() + + # retrieve include directory + execute_process (COMMAND "${_${_PYTHON_PREFIX}_CONFIG}" --includes + RESULT_VARIABLE _${_PYTHON_PREFIX}_RESULT + OUTPUT_VARIABLE _${_PYTHON_PREFIX}_FLAGS + ERROR_QUIET + OUTPUT_STRIP_TRAILING_WHITESPACE) + if (NOT _${_PYTHON_PREFIX}_RESULT) + # retrieve include directory + string (REGEX MATCHALL "-I[^ ]+" _${_PYTHON_PREFIX}_INCLUDE_DIRS "${_${_PYTHON_PREFIX}_FLAGS}") + string (REPLACE "-I" "" _${_PYTHON_PREFIX}_INCLUDE_DIRS "${_${_PYTHON_PREFIX}_INCLUDE_DIRS}") + list (REMOVE_DUPLICATES _${_PYTHON_PREFIX}_INCLUDE_DIRS) + + find_path (${_PYTHON_PREFIX}_INCLUDE_DIR + NAMES Python.h + HINTS ${_${_PYTHON_PREFIX}_INCLUDE_DIRS} + NO_SYSTEM_ENVIRONMENT_PATH + NO_CMAKE_SYSTEM_PATH) + endif() + + if (${_PYTHON_PREFIX}_LIBRARY_RELEASE AND ${_PYTHON_PREFIX}_INCLUDE_DIR) + break() + endif() + endforeach() + + # Rely on HINTS and standard paths if config tool failed to locate artifacts + if (NOT (${_PYTHON_PREFIX}_LIBRARY_RELEASE OR ${_PYTHON_PREFIX}_LIBRARY_DEBUG) OR NOT ${_PYTHON_PREFIX}_INCLUDE_DIR) + foreach (_${_PYTHON_PREFIX}_VERSION IN LISTS _${_PYTHON_PREFIX}_FIND_VERSIONS) + string (REPLACE "." "" _${_PYTHON_PREFIX}_VERSION_NO_DOTS ${_${_PYTHON_PREFIX}_VERSION}) + + _python_get_frameworks (_${_PYTHON_PREFIX}_FRAMEWORK_PATHS ${_${_PYTHON_PREFIX}_VERSION}) + + # search first in known locations + find_library (${_PYTHON_PREFIX}_LIBRARY_RELEASE + NAMES python${_${_PYTHON_PREFIX}_VERSION_NO_DOTS} + python${_${_PYTHON_PREFIX}_VERSION}mu + python${_${_PYTHON_PREFIX}_VERSION}m + python${_${_PYTHON_PREFIX}_VERSION}u + python${_${_PYTHON_PREFIX}_VERSION} + NAMES_PER_DIR + HINTS ${_${_PYTHON_PREFIX}_HINTS} + PATHS ${_${_PYTHON_PREFIX}_FRAMEWORK_PATHS} + [HKEY_CURRENT_USER\\SOFTWARE\\Python\\PythonCore\\${_${_PYTHON_PREFIX}_VERSION}\\InstallPath] + [HKEY_CURRENT_USER\\SOFTWARE\\Python\\ContinuumAnalytics\\Anaconda${_${_PYTHON_PREFIX}_VERSION_NO_DOTS}-${_${_PYTHON_PREFIX}_ARCH}\\InstallPath] + [HKEY_LOCAL_MACHINE\\SOFTWARE\\Python\\PythonCore\\${_${_PYTHON_PREFIX}_VERSION}\\InstallPath] + [HKEY_LOCAL_MACHINE\\SOFTWARE\\Python\\ContinuumAnalytics\\Anaconda${_${_PYTHON_PREFIX}_VERSION_NO_DOTS}-${_${_PYTHON_PREFIX}_ARCH}\\InstallPath] + PATH_SUFFIXES lib/${CMAKE_LIBRARY_ARCHITECTURE} lib libs + lib/python${_${_PYTHON_PREFIX}_VERSION}/config-${_${_PYTHON_PREFIX}_VERSION}mu + lib/python${_${_PYTHON_PREFIX}_VERSION}/config-${_${_PYTHON_PREFIX}_VERSION}m + lib/python${_${_PYTHON_PREFIX}_VERSION}/config-${_${_PYTHON_PREFIX}_VERSION}u + lib/python${_${_PYTHON_PREFIX}_VERSION}/config-${_${_PYTHON_PREFIX}_VERSION} + lib/python${_${_PYTHON_PREFIX}_VERSION}/config + NO_SYSTEM_ENVIRONMENT_PATH + NO_CMAKE_SYSTEM_PATH) + # search in all default paths + find_library (${_PYTHON_PREFIX}_LIBRARY_RELEASE + NAMES python${_${_PYTHON_PREFIX}_VERSION_NO_DOTS} + python${_${_PYTHON_PREFIX}_VERSION}mu + python${_${_PYTHON_PREFIX}_VERSION}m + python${_${_PYTHON_PREFIX}_VERSION}u + python${_${_PYTHON_PREFIX}_VERSION} + NAMES_PER_DIR + PATH_SUFFIXES lib/${CMAKE_LIBRARY_ARCHITECTURE} lib libs + lib/python${_${_PYTHON_PREFIX}_VERSION}/config-${_${_PYTHON_PREFIX}_VERSION}mu + lib/python${_${_PYTHON_PREFIX}_VERSION}/config-${_${_PYTHON_PREFIX}_VERSION}m + lib/python${_${_PYTHON_PREFIX}_VERSION}/config-${_${_PYTHON_PREFIX}_VERSION}u + lib/python${_${_PYTHON_PREFIX}_VERSION}/config-${_${_PYTHON_PREFIX}_VERSION} + lib/python${_${_PYTHON_PREFIX}_VERSION}/config) + # retrieve runtime library + if (${_PYTHON_PREFIX}_LIBRARY_RELEASE) + get_filename_component (_${_PYTHON_PREFIX}_PATH "${${_PYTHON_PREFIX}_LIBRARY_RELEASE}" DIRECTORY) + _python_find_runtime_library (${_PYTHON_PREFIX}_RUNTIME_LIBRARY_RELEASE + NAMES python${_${_PYTHON_PREFIX}_VERSION_NO_DOTS} + python${_${_PYTHON_PREFIX}_VERSION}mu + python${_${_PYTHON_PREFIX}_VERSION}m + python${_${_PYTHON_PREFIX}_VERSION}u + python${_${_PYTHON_PREFIX}_VERSION} + NAMES_PER_DIR + HINTS "${_${_PYTHON_PREFIX}_PATH}" ${_${_PYTHON_PREFIX}_HINTS} + PATHS ${_${_PYTHON_PREFIX}_FRAMEWORK_PATHS} + [HKEY_CURRENT_USER\\SOFTWARE\\Python\\PythonCore\\${_${_PYTHON_PREFIX}_VERSION}\\InstallPath] + [HKEY_CURRENT_USER\\SOFTWARE\\Python\\ContinuumAnalytics\\Anaconda${_${_PYTHON_PREFIX}_VERSION_NO_DOTS}-${_${_PYTHON_PREFIX}_ARCH}\\InstallPath] + [HKEY_LOCAL_MACHINE\\SOFTWARE\\Python\\PythonCore\\${_${_PYTHON_PREFIX}_VERSION}\\InstallPath] + [HKEY_LOCAL_MACHINE\\SOFTWARE\\Python\\ContinuumAnalytics\\Anaconda${_${_PYTHON_PREFIX}_VERSION_NO_DOTS}-${_${_PYTHON_PREFIX}_ARCH}\\InstallPath] + PATH_SUFFIXES bin) + endif() + + if (WIN32) + # search for debug library + if (${_PYTHON_PREFIX}_LIBRARY_RELEASE) + # use library location as a hint + get_filename_component (_${_PYTHON_PREFIX}_PATH "${${_PYTHON_PREFIX}_LIBRARY_RELEASE}" DIRECTORY) + find_library (${_PYTHON_PREFIX}_LIBRARY_DEBUG + NAMES python${_${_PYTHON_PREFIX}_VERSION_NO_DOTS}_d + NAMES_PER_DIR + HINTS "${_${_PYTHON_PREFIX}_PATH}" ${_${_PYTHON_PREFIX}_HINTS} + NO_DEFAULT_PATH) + else() + # search first in known locations + find_library (${_PYTHON_PREFIX}_LIBRARY_DEBUG + NAMES python${_${_PYTHON_PREFIX}_VERSION_NO_DOTS}_d + NAMES_PER_DIR + HINTS ${_${_PYTHON_PREFIX}_HINTS} + PATHS [HKEY_CURRENT_USER\\SOFTWARE\\Python\\PythonCore\\${_${_PYTHON_PREFIX}_VERSION}\\InstallPath] + [HKEY_CURRENT_USER\\SOFTWARE\\Python\\ContinuumAnalytics\\Anaconda${_${_PYTHON_PREFIX}_VERSION_NO_DOTS}-${_${_PYTHON_PREFIX}_ARCH}\\InstallPath] + [HKEY_LOCAL_MACHINE\\SOFTWARE\\Python\\PythonCore\\${_${_PYTHON_PREFIX}_VERSION}\\InstallPath] + [HKEY_LOCAL_MACHINE\\SOFTWARE\\Python\\ContinuumAnalytics\\Anaconda${_${_PYTHON_PREFIX}_VERSION_NO_DOTS}-${_${_PYTHON_PREFIX}_ARCH}\\InstallPath] + PATH_SUFFIXES lib libs + NO_SYSTEM_ENVIRONMENT_PATH + NO_CMAKE_SYSTEM_PATH) + # search in all default paths + find_library (${_PYTHON_PREFIX}_LIBRARY_DEBUG + NAMES python${_${_PYTHON_PREFIX}_VERSION_NO_DOTS}_d + NAMES_PER_DIR + PATH_SUFFIXES lib libs) + endif() + if (${_PYTHON_PREFIX}_LIBRARY_DEBUG) + get_filename_component (_${_PYTHON_PREFIX}_PATH "${${_PYTHON_PREFIX}_LIBRARY_DEBUG}" DIRECTORY) + _python_find_runtime_library (${_PYTHON_PREFIX}_RUNTIME_LIBRARY_DEBUG + NAMES python${_${_PYTHON_PREFIX}_VERSION_NO_DOTS}_d + NAMES_PER_DIR + HINTS "${_${_PYTHON_PREFIX}_PATH}" ${_${_PYTHON_PREFIX}_HINTS} + PATHS [HKEY_CURRENT_USER\\SOFTWARE\\Python\\PythonCore\\${_${_PYTHON_PREFIX}_VERSION}\\InstallPath] + [HKEY_CURRENT_USER\\SOFTWARE\\Python\\ContinuumAnalytics\\Anaconda${_${_PYTHON_PREFIX}_VERSION_NO_DOTS}-${_${_PYTHON_PREFIX}_ARCH}\\InstallPath] + [HKEY_LOCAL_MACHINE\\SOFTWARE\\Python\\PythonCore\\${_${_PYTHON_PREFIX}_VERSION}\\InstallPath] + [HKEY_LOCAL_MACHINE\\SOFTWARE\\Python\\ContinuumAnalytics\\Anaconda${_${_PYTHON_PREFIX}_VERSION_NO_DOTS}-${_${_PYTHON_PREFIX}_ARCH}\\InstallPath] + PATH_SUFFIXES bin) + endif() + endif() + + # Don't search for include dir until library location is known + if (${_PYTHON_PREFIX}_LIBRARY_RELEASE OR ${_PYTHON_PREFIX}_LIBRARY_DEBUG) + unset (_${_PYTHON_PREFIX}_INCLUDE_HINTS) + foreach (_${_PYTHON_PREFIX}_LIB IN ITEMS ${_PYTHON_PREFIX}_LIBRARY_RELEASE ${_PYTHON_PREFIX}_LIBRARY_DEBUG) + if (${_${_PYTHON_PREFIX}_LIB}) + # Use the library's install prefix as a hint + if (${_${_PYTHON_PREFIX}_LIB} MATCHES "^(.+/Frameworks/Python.framework/Versions/[0-9.]+)") + list (APPEND _${_PYTHON_PREFIX}_INCLUDE_HINTS "${CMAKE_MATCH_1}") + elseif (${_${_PYTHON_PREFIX}_LIB} MATCHES "^(.+)/lib(64|32)?/python[0-9.]+/config") + list (APPEND _${_PYTHON_PREFIX}_INCLUDE_HINTS "${CMAKE_MATCH_1}") + elseif (DEFINED CMAKE_LIBRARY_ARCHITECTURE AND ${_${_PYTHON_PREFIX}_LIB} MATCHES "^(.+)/lib/${CMAKE_LIBRARY_ARCHITECTURE}") + list (APPEND _${_PYTHON_PREFIX}_INCLUDE_HINTS "${CMAKE_MATCH_1}") + else() + # assume library is in a directory under root + get_filename_component (_${_PYTHON_PREFIX}_PREFIX "${${_${_PYTHON_PREFIX}_LIB}}" DIRECTORY) + get_filename_component (_${_PYTHON_PREFIX}_PREFIX "${_${_PYTHON_PREFIX}_PREFIX}" DIRECTORY) + list (APPEND _${_PYTHON_PREFIX}_INCLUDE_HINTS "${_${_PYTHON_PREFIX}_PREFIX}") + endif() + endif() + endforeach() + list (REMOVE_DUPLICATES _${_PYTHON_PREFIX}_INCLUDE_HINTS) + + find_path (${_PYTHON_PREFIX}_INCLUDE_DIR + NAMES Python.h + HINTS ${_${_PYTHON_PREFIX}_INCLUDE_HINTS} ${_${_PYTHON_PREFIX}_HINTS} + PATHS ${_${_PYTHON_PREFIX}_FRAMEWORK_PATHS} + [HKEY_CURRENT_USER\\SOFTWARE\\Python\\PythonCore\\${_${_PYTHON_PREFIX}_VERSION}\\InstallPath] + [HKEY_CURRENT_USER\\SOFTWARE\\Python\\ContinuumAnalytics\\Anaconda${_${_PYTHON_PREFIX}_VERSION_NO_DOTS}-${_${_PYTHON_PREFIX}_ARCH}\\InstallPath] + [HKEY_LOCAL_MACHINE\\SOFTWARE\\Python\\PythonCore\\${_${_PYTHON_PREFIX}_VERSION}\\InstallPath] + [HKEY_LOCAL_MACHINE\\SOFTWARE\\Python\\ContinuumAnalytics\\Anaconda${_${_PYTHON_PREFIX}_VERSION_NO_DOTS}-${_${_PYTHON_PREFIX}_ARCH}\\InstallPath] + PATH_SUFFIXES include/python${_${_PYTHON_PREFIX}_VERSION}mu + include/python${_${_PYTHON_PREFIX}_VERSION}m + include/python${_${_PYTHON_PREFIX}_VERSION}u + include/python${_${_PYTHON_PREFIX}_VERSION} + include + NO_SYSTEM_ENVIRONMENT_PATH + NO_CMAKE_SYSTEM_PATH) + endif() + + if ((${_PYTHON_PREFIX}_LIBRARY_RELEASE OR ${_PYTHON_PREFIX}_LIBRARY_DEBUG) AND ${_PYTHON_PREFIX}_INCLUDE_DIR) + break() + endif() + endforeach() + + # search header file in standard locations + find_path (${_PYTHON_PREFIX}_INCLUDE_DIR + NAMES Python.h) + endif() + + if (${_PYTHON_PREFIX}_INCLUDE_DIR) + # retrieve version from header file + file (STRINGS "${${_PYTHON_PREFIX}_INCLUDE_DIR}/patchlevel.h" _${_PYTHON_PREFIX}_VERSION + REGEX "^#define[ \t]+PY_VERSION[ \t]+\"[^\"]+\"") + string (REGEX REPLACE "^#define[ \t]+PY_VERSION[ \t]+\"([^\"]+)\".*" "\\1" + _${_PYTHON_PREFIX}_VERSION "${_${_PYTHON_PREFIX}_VERSION}") + string (REGEX MATCHALL "[0-9]+" _${_PYTHON_PREFIX}_VERSIONS "${_${_PYTHON_PREFIX}_VERSION}") + list (GET _${_PYTHON_PREFIX}_VERSIONS 0 _${_PYTHON_PREFIX}_VERSION_MAJOR) + list (GET _${_PYTHON_PREFIX}_VERSIONS 1 _${_PYTHON_PREFIX}_VERSION_MINOR) + list (GET _${_PYTHON_PREFIX}_VERSIONS 2 _${_PYTHON_PREFIX}_VERSION_PATCH) + + if (NOT ${_PYTHON_PREFIX}_Interpreter_FOUND AND NOT ${_PYTHON_PREFIX}_Compiler_FOUND) + # set public version information + set (${_PYTHON_PREFIX}_VERSION ${_${_PYTHON_PREFIX}_VERSION}) + set (${_PYTHON_PREFIX}_VERSION_MAJOR ${_${_PYTHON_PREFIX}_VERSION_MAJOR}) + set (${_PYTHON_PREFIX}_VERSION_MINOR ${_${_PYTHON_PREFIX}_VERSION_MINOR}) + set (${_PYTHON_PREFIX}_VERSION_PATCH ${_${_PYTHON_PREFIX}_VERSION_PATCH}) + endif() + endif() + + # define public variables + include (${CMAKE_CURRENT_LIST_DIR}/../SelectLibraryConfigurations.cmake) + select_library_configurations (${_PYTHON_PREFIX}) + if (${_PYTHON_PREFIX}_RUNTIME_LIBRARY_RELEASE) + set (${_PYTHON_PREFIX}_RUNTIME_LIBRARY "${${_PYTHON_PREFIX}_RUNTIME_LIBRARY_RELEASE}") + elseif (${_PYTHON_PREFIX}_RUNTIME_LIBRARY_DEBUG) + set (${_PYTHON_PREFIX}_RUNTIME_LIBRARY "${${_PYTHON_PREFIX}_RUNTIME_LIBRARY_DEBUG}") + else() + set (${_PYTHON_PREFIX}_RUNTIME_LIBRARY "$${_PYTHON_PREFIX}_RUNTIME_LIBRARY-NOTFOUND") + endif() + + _python_set_library_dirs (${_PYTHON_PREFIX}_LIBRARY_DIRS + ${_PYTHON_PREFIX}_LIBRARY_RELEASE ${_PYTHON_PREFIX}_LIBRARY_DEBUG) + if (UNIX) + if (${_PYTHON_PREFIX}_LIBRARY_RELEASE MATCHES "${CMAKE_SHARED_LIBRARY_SUFFIX}$" + OR ${_PYTHON_PREFIX}_LIBRARY_RELEASE MATCHES "${CMAKE_SHARED_LIBRARY_SUFFIX}$") + set (${_PYTHON_PREFIX}_RUNTIME_LIBRARY_DIRS ${${_PYTHON_PREFIX}_LIBRARY_DIRS}) + endif() + else() + _python_set_library_dirs (${_PYTHON_PREFIX}_RUNTIME_LIBRARY_DIRS + ${_PYTHON_PREFIX}_RUNTIME_LIBRARY_RELEASE ${_PYTHON_PREFIX}_RUNTIME_LIBRARY_DEBUG) + endif() + + set (${_PYTHON_PREFIX}_INCLUDE_DIRS "${${_PYTHON_PREFIX}_INCLUDE_DIR}") + + mark_as_advanced (${_PYTHON_PREFIX}_RUNTIME_LIBRARY_RELEASE + ${_PYTHON_PREFIX}_RUNTIME_LIBRARY_DEBUG + ${_PYTHON_PREFIX}_INCLUDE_DIR) + + if ((${_PYTHON_PREFIX}_LIBRARY_RELEASE OR ${_PYTHON_PREFIX}_LIBRARY_DEBUG) + AND ${_PYTHON_PREFIX}_INCLUDE_DIR) + if (${_PYTHON_PREFIX}_Interpreter_FOUND OR ${_PYTHON_PREFIX}_Compiler_FOUND) + # devlopment environment must be compatible with interpreter/compiler + if (${_${_PYTHON_PREFIX}_VERSION_MAJOR}.${_${_PYTHON_PREFIX}_VERSION_MINOR} VERSION_EQUAL ${${_PYTHON_PREFIX}_VERSION_MAJOR}.${${_PYTHON_PREFIX}_VERSION_MINOR}) + set (${_PYTHON_PREFIX}_Development_FOUND TRUE) + endif() + elseif (${_PYTHON_PREFIX}_VERSION_MAJOR VERSION_EQUAL _${_PYTHON_PREFIX}_REQUIRED_VERSION_MAJOR) + set (${_PYTHON_PREFIX}_Development_FOUND TRUE) + endif() + endif() + + # Restore the original find library ordering + if (DEFINED _${_PYTHON_PREFIX}_CMAKE_FIND_LIBRARY_SUFFIXES) + set (CMAKE_FIND_LIBRARY_SUFFIXES ${_${_PYTHON_PREFIX}_CMAKE_FIND_LIBRARY_SUFFIXES}) + endif() +endif() + +# final validation +if (${_PYTHON_PREFIX}_VERSION_MAJOR AND + NOT ${_PYTHON_PREFIX}_VERSION_MAJOR VERSION_EQUAL _${_PYTHON_PREFIX}_REQUIRED_VERSION_MAJOR) + _python_display_failure ("Could NOT find ${_PYTHON_PREFIX}: Found unsuitable major version \"${${_PYTHON_PREFIX}_VERSION_MAJOR}\", but required major version is exact version \"${_${_PYTHON_PREFIX}_REQUIRED_VERSION_MAJOR}\"") +endif() + +include (${CMAKE_CURRENT_LIST_DIR}/../FindPackageHandleStandardArgs.cmake) +find_package_handle_standard_args (${_PYTHON_PREFIX} + REQUIRED_VARS ${_${_PYTHON_PREFIX}_REQUIRED_VARS} + VERSION_VAR ${_PYTHON_PREFIX}_VERSION + HANDLE_COMPONENTS) + +# Create imported targets and helper functions +if ("Interpreter" IN_LIST ${_PYTHON_PREFIX}_FIND_COMPONENTS + AND ${_PYTHON_PREFIX}_Interpreter_FOUND + AND NOT TARGET ${_PYTHON_PREFIX}::Interpreter) + add_executable (${_PYTHON_PREFIX}::Interpreter IMPORTED) + set_property (TARGET ${_PYTHON_PREFIX}::Interpreter + PROPERTY IMPORTED_LOCATION "${${_PYTHON_PREFIX}_EXECUTABLE}") +endif() + +if ("Compiler" IN_LIST ${_PYTHON_PREFIX}_FIND_COMPONENTS + AND ${_PYTHON_PREFIX}_Compiler_FOUND + AND NOT TARGET ${_PYTHON_PREFIX}::Compiler) + add_executable (${_PYTHON_PREFIX}::Compiler IMPORTED) + set_property (TARGET ${_PYTHON_PREFIX}::Compiler + PROPERTY IMPORTED_LOCATION "${${_PYTHON_PREFIX}_COMPILER}") +endif() + +if ("Development" IN_LIST ${_PYTHON_PREFIX}_FIND_COMPONENTS + AND ${_PYTHON_PREFIX}_Development_FOUND AND NOT TARGET ${_PYTHON_PREFIX}::Python) + + if (${_PYTHON_PREFIX}_LIBRARY_RELEASE MATCHES "${CMAKE_SHARED_LIBRARY_SUFFIX}$" + OR ${_PYTHON_PREFIX}_LIBRARY_DEBUG MATCHES "${CMAKE_SHARED_LIBRARY_SUFFIX}$" + OR ${_PYTHON_PREFIX}_RUNTIME_LIBRARY_RELEASE OR ${_PYTHON_PREFIX}_RUNTIME_LIBRARY_DEBUG) + set (_${_PYTHON_PREFIX}_LIBRARY_TYPE SHARED) + else() + set (_${_PYTHON_PREFIX}_LIBRARY_TYPE STATIC) + endif() + + add_library (${_PYTHON_PREFIX}::Python ${_${_PYTHON_PREFIX}_LIBRARY_TYPE} IMPORTED) + + set_property (TARGET ${_PYTHON_PREFIX}::Python + PROPERTY INTERFACE_INCLUDE_DIRECTORIES "${${_PYTHON_PREFIX}_INCLUDE_DIR}") + + if ((${_PYTHON_PREFIX}_LIBRARY_RELEASE AND ${_PYTHON_PREFIX}_RUNTIME_LIBRARY_RELEASE) + OR (${_PYTHON_PREFIX}_LIBRARY_DEBUG AND ${_PYTHON_PREFIX}_RUNTIME_LIBRARY_DEBUG)) + # System manage shared libraries in two parts: import and runtime + if (${_PYTHON_PREFIX}_LIBRARY_RELEASE AND ${_PYTHON_PREFIX}_LIBRARY_DEBUG) + set_property (TARGET ${_PYTHON_PREFIX}::Python PROPERTY IMPORTED_CONFIGURATIONS RELEASE DEBUG) + set_target_properties (${_PYTHON_PREFIX}::Python + PROPERTIES IMPORTED_LINK_INTERFACE_LANGUAGES_RELEASE "C" + IMPORTED_IMPLIB_RELEASE "${${_PYTHON_PREFIX}_LIBRARY_RELEASE}" + IMPORTED_LOCATION_RELEASE "${${_PYTHON_PREFIX}_RUNTIME_LIBRARY_RELEASE}") + set_target_properties (${_PYTHON_PREFIX}::Python + PROPERTIES IMPORTED_LINK_INTERFACE_LANGUAGES_DEBUG "C" + IMPORTED_IMPLIB_DEBUG "${${_PYTHON_PREFIX}_LIBRARY_DEBUG}" + IMPORTED_LOCATION_DEBUG "${${_PYTHON_PREFIX}_RUNTIME_LIBRARY_DEBUG}") + else() + set_target_properties (${_PYTHON_PREFIX}::Python + PROPERTIES IMPORTED_LINK_INTERFACE_LANGUAGES "C" + IMPORTED_IMPLIB "${${_PYTHON_PREFIX}_LIBRARY}" + IMPORTED_LOCATION "${${_PYTHON_PREFIX}_RUNTIME_LIBRARY}") + endif() + else() + if (${_PYTHON_PREFIX}_LIBRARY_RELEASE AND ${_PYTHON_PREFIX}_LIBRARY_DEBUG) + set_property (TARGET ${_PYTHON_PREFIX}::Python PROPERTY IMPORTED_CONFIGURATIONS RELEASE DEBUG) + set_target_properties (${_PYTHON_PREFIX}::Python + PROPERTIES IMPORTED_LINK_INTERFACE_LANGUAGES_RELEASE "C" + IMPORTED_LOCATION_RELEASE "${${_PYTHON_PREFIX}_LIBRARY_RELEASE}") + set_target_properties (${_PYTHON_PREFIX}::Python + PROPERTIES IMPORTED_LINK_INTERFACE_LANGUAGES_DEBUG "C" + IMPORTED_LOCATION_DEBUG "${${_PYTHON_PREFIX}_LIBRARY_DEBUG}") + else() + set_target_properties (${_PYTHON_PREFIX}::Python + PROPERTIES IMPORTED_LINK_INTERFACE_LANGUAGES "C" + IMPORTED_LOCATION "${${_PYTHON_PREFIX}_LIBRARY}") + endif() + endif() + + if (_${_PYTHON_PREFIX}_CONFIG AND _${_PYTHON_PREFIX}_LIBRARY_TYPE STREQUAL "STATIC") + # extend link information with dependent libraries + execute_process (COMMAND "${_${_PYTHON_PREFIX}_CONFIG}" --ldflags + RESULT_VARIABLE _${_PYTHON_PREFIX}_RESULT + OUTPUT_VARIABLE _${_PYTHON_PREFIX}_FLAGS + ERROR_QUIET + OUTPUT_STRIP_TRAILING_WHITESPACE) + if (NOT _${_PYTHON_PREFIX}_RESULT) + string (REGEX MATCHALL "-[Ll][^ ]+" _${_PYTHON_PREFIX}_LINK_LIBRARIES "${_${_PYTHON_PREFIX}_FLAGS}") + # remove elements relative to python library itself + list (FILTER _${_PYTHON_PREFIX}_LINK_LIBRARIES EXCLUDE REGEX "-lpython") + foreach (_${_PYTHON_PREFIX}_DIR IN LISTS ${_PYTHON_PREFIX}_LIBRARY_DIRS) + list (FILTER _${_PYTHON_PREFIX}_LINK_LIBRARIES EXCLUDE REGEX "-L${${_PYTHON_PREFIX}_DIR}") + endforeach() + set_property (TARGET ${_PYTHON_PREFIX}::Python + PROPERTY INTERFACE_LINK_LIBRARIES ${_${_PYTHON_PREFIX}_LINK_LIBRARIES}) + endif() + endif() + + # + # PYTHON_ADD_LIBRARY (<name> [STATIC|SHARED|MODULE] src1 src2 ... srcN) + # It is used to build modules for python. + # + function (__${_PYTHON_PREFIX}_ADD_LIBRARY prefix name) + cmake_parse_arguments (PARSE_ARGV 2 PYTHON_ADD_LIBRARY + "STATIC;SHARED;MODULE" "" "") + + unset (type) + if (NOT (PYTHON_ADD_LIBRARY_STATIC + OR PYTHON_ADD_LIBRARY_SHARED + OR PYTHON_ADD_LIBRARY_MODULE)) + set (type MODULE) + endif() + add_library (${name} ${type} ${ARGN}) + target_link_libraries (${name} PRIVATE ${prefix}::Python) + + # customize library name to follow module name rules + get_property (type TARGET ${name} PROPERTY TYPE) + if (type STREQUAL "MODULE_LIBRARY") + set_property (TARGET ${name} PROPERTY PREFIX "") + if(CMAKE_SYSTEM_NAME STREQUAL "Windows") + set_property (TARGET ${name} PROPERTY SUFFIX ".pyd") + endif() + endif() + endfunction() +endif() + +# final clean-up + +# Restore CMAKE_FIND_FRAMEWORK +if (DEFINED _${_PYTHON_PREFIX}_CMAKE_FIND_FRAMEWORK) + set (CMAKE_FIND_FRAMEWORK ${_${_PYTHON_PREFIX}_CMAKE_FIND_FRAMEWORK}) + unset (_${_PYTHON_PREFIX}_CMAKE_FIND_FRAMEWORK) +else() + unset (CMAKE_FIND_FRAMEWORK) +endif() + +unset (_${_PYTHON_PREFIX}_CONFIG CACHE) diff --git a/Modules/FindPython2.cmake b/Modules/FindPython2.cmake new file mode 100644 index 0000000..22e9a8f --- /dev/null +++ b/Modules/FindPython2.cmake @@ -0,0 +1,146 @@ +# Distributed under the OSI-approved BSD 3-Clause License. See accompanying +# file Copyright.txt or https://cmake.org/licensing for details. + +#[=======================================================================[.rst: +FindPython2 +----------- + +Find Python 2 interpreter, compiler and development environment (include +directories and libraries). + +Three components are supported: + +* ``Interpreter``: search for Python 2 interpreter +* ``Compiler``: search for Python 2 compiler. Only offered by IronPython. +* ``Development``: search for development artifacts (include directories and + libraries) + +If no ``COMPONENTS`` is specified, ``Interpreter`` is assumed. + +To ensure consistent versions between components ``Interpreter``, ``Compiler`` +and ``Development``, specify all components at the same time:: + + find_package (Python2 COMPONENTS Interpreter Development) + +This module looks only for version 2 of Python. This module can be used +concurrently with :module:`FindPython3` module to use both Python versions. + +The :module:`FindPython` module can be used if Python version does not matter +for you. + +Imported Targets +^^^^^^^^^^^^^^^^ + +This module defines the following :ref:`Imported Targets <Imported Targets>`: + +``Python2::Interpreter`` + Python 2 interpreter. Target defined if component ``Interpreter`` is found. +``Python2::Compiler`` + Python 2 compiler. Target defined if component ``Compiler`` is found. +``Python2::Python`` + Python 2 library. Target defined if component ``Development`` is found. + +Result Variables +^^^^^^^^^^^^^^^^ + +This module will set the following variables in your project +(see :ref:`Standard Variable Names <CMake Developer Standard Variable Names>`): + +``Python2_FOUND`` + System has the Python 2 requested components. +``Python2_Interpreter_FOUND`` + System has the Python 2 interpreter. +``Python2_EXECUTABLE`` + Path to the Python 2 interpreter. +``Python2_INTERPRETER_ID`` + A short string unique to the interpreter. Possible values include: + * Python + * ActivePython + * Anaconda + * Canopy + * IronPython +``Python2_STDLIB`` + Standard platform independent installation directory. + + Information returned by + ``distutils.sysconfig.get_python_lib(plat_specific=False,standard_lib=True)``. +``Python2_STDARCH`` + Standard platform dependent installation directory. + + Information returned by + ``distutils.sysconfig.get_python_lib(plat_specific=True,standard_lib=True)``. +``Python2_SITELIB`` + Third-party platform independent installation directory. + + Information returned by + ``distutils.sysconfig.get_python_lib(plat_specific=False,standard_lib=False)``. +``Python2_SITEARCH`` + Third-party platform dependent installation directory. + + Information returned by + ``distutils.sysconfig.get_python_lib(plat_specific=True,standard_lib=False)``. +``Python2_Compiler_FOUND`` + System has the Python 2 compiler. +``Python2_COMPILER`` + Path to the Python 2 compiler. Only offered by IronPython. +``Python2_COMPILER_ID`` + A short string unique to the compiler. Possible values include: + * IronPython +``Python2_Development_FOUND`` + System has the Python 2 development artifacts. +``Python2_INCLUDE_DIRS`` + The Python 2 include directories. +``Python2_LIBRARIES`` + The Python 2 libraries. +``Python2_LIBRARY_DIRS`` + The Python 2 library directories. +``Python2_RUNTIME_LIBRARY_DIRS`` + The Python 2 runtime library directories. +``Python2_VERSION`` + Python 2 version. +``Python2_VERSION_MAJOR`` + Python 2 major version. +``Python2_VERSION_MINOR`` + Python 2 minor version. +``Python2_VERSION_PATCH`` + Python 2 patch version. + +Hints +^^^^^ + +``Python2_ROOT_DIR`` + Define the root directory of a Python 2 installation. + +``Python2_USE_STATIC_LIBS`` + * If not defined, search for shared libraries and static libraries in that + order. + * If set to TRUE, search **only** for static libraries. + * If set to FALSE, search **only** for shared libraries. + +Commands +^^^^^^^^ + +This module defines the command ``Python2_add_library`` which have the same +semantic as :command:`add_library` but take care of Python module naming rules +(only applied if library is of type ``MODULE``) and add dependency to target +``Python2::Python``:: + + Python2_add_library (my_module MODULE src1.cpp) + +If library type is not specified, ``MODULE`` is assumed. +#]=======================================================================] + + +set (_PYTHON_PREFIX Python2) + +set (_Python2_REQUIRED_VERSION_MAJOR 2) + +include (${CMAKE_CURRENT_LIST_DIR}/FindPython/Support.cmake) + +if (COMMAND __Python2_add_library) + macro (Python2_add_library) + __Python2_add_library (Python2 ${ARGV}) + endmacro() +endif() + +unset (_PYTHON_PREFIX) diff --git a/Modules/FindPython3.cmake b/Modules/FindPython3.cmake new file mode 100644 index 0000000..99c159b --- /dev/null +++ b/Modules/FindPython3.cmake @@ -0,0 +1,146 @@ +# Distributed under the OSI-approved BSD 3-Clause License. See accompanying +# file Copyright.txt or https://cmake.org/licensing for details. + +#[=======================================================================[.rst: +FindPython3 +----------- + +Find Python 3 interpreter, compiler and development environment (include +directories and libraries). + +Three components are supported: + +* ``Interpreter``: search for Python 3 interpreter +* ``Compiler``: search for Python 3 compiler. Only offered by IronPython. +* ``Development``: search for development artifacts (include directories and + libraries) + +If no ``COMPONENTS`` is specified, ``Interpreter`` is assumed. + +To ensure consistent versions between components ``Interpreter``, ``Compiler`` +and ``Development``, specify all components at the same time:: + + find_package (Python3 COMPONENTS Interpreter Development) + +This module looks only for version 3 of Python. This module can be used +concurrently with :module:`FindPython2` module to use both Python versions. + +The :module:`FindPython` module can be used if Python version does not matter +for you. + +Imported Targets +^^^^^^^^^^^^^^^^ + +This module defines the following :ref:`Imported Targets <Imported Targets>`: + +``Python3::Interpreter`` + Python 3 interpreter. Target defined if component ``Interpreter`` is found. +``Python3::Compiler`` + Python 3 compiler. Target defined if component ``Compiler`` is found. +``Python3::Python`` + Python 3 library. Target defined if component ``Development`` is found. + +Result Variables +^^^^^^^^^^^^^^^^ + +This module will set the following variables in your project +(see :ref:`Standard Variable Names <CMake Developer Standard Variable Names>`): + +``Python3_FOUND`` + System has the Python 3 requested components. +``Python3_Interpreter_FOUND`` + System has the Python 3 interpreter. +``Python3_EXECUTABLE`` + Path to the Python 3 interpreter. +``Python3_INTERPRETER_ID`` + A short string unique to the interpreter. Possible values include: + * Python + * ActivePython + * Anaconda + * Canopy + * IronPython +``Python3_STDLIB`` + Standard platform independent installation directory. + + Information returned by + ``distutils.sysconfig.get_python_lib(plat_specific=False,standard_lib=True)``. +``Python3_STDARCH`` + Standard platform dependent installation directory. + + Information returned by + ``distutils.sysconfig.get_python_lib(plat_specific=True,standard_lib=True)``. +``Python3_SITELIB`` + Third-party platform independent installation directory. + + Information returned by + ``distutils.sysconfig.get_python_lib(plat_specific=False,standard_lib=False)``. +``Python3_SITEARCH`` + Third-party platform dependent installation directory. + + Information returned by + ``distutils.sysconfig.get_python_lib(plat_specific=True,standard_lib=False)``. +``Python3_Compiler_FOUND`` + System has the Python 3 compiler. +``Python3_COMPILER`` + Path to the Python 3 compiler. Only offered by IronPython. +``Python3_COMPILER_ID`` + A short string unique to the compiler. Possible values include: + * IronPython +``Python3_Development_FOUND`` + System has the Python 3 development artifacts. +``Python3_INCLUDE_DIRS`` + The Python 3 include directories. +``Python3_LIBRARIES`` + The Python 3 libraries. +``Python3_LIBRARY_DIRS`` + The Python 3 library directories. +``Python3_RUNTIME_LIBRARY_DIRS`` + The Python 3 runtime library directories. +``Python3_VERSION`` + Python 3 version. +``Python3_VERSION_MAJOR`` + Python 3 major version. +``Python3_VERSION_MINOR`` + Python 3 minor version. +``Python3_VERSION_PATCH`` + Python 3 patch version. + +Hints +^^^^^ + +``Python3_ROOT_DIR`` + Define the root directory of a Python 3 installation. + +``Python3_USE_STATIC_LIBS`` + * If not defined, search for shared libraries and static libraries in that + order. + * If set to TRUE, search **only** for static libraries. + * If set to FALSE, search **only** for shared libraries. + +Commands +^^^^^^^^ + +This module defines the command ``Python3_add_library`` which have the same +semantic as :command:`add_library` but take care of Python module naming rules +(only applied if library is of type ``MODULE``) and add dependency to target +``Python3::Python``:: + + Python3_add_library (my_module MODULE src1.cpp) + +If library type is not specified, ``MODULE`` is assumed. +#]=======================================================================] + + +set (_PYTHON_PREFIX Python3) + +set (_Python3_REQUIRED_VERSION_MAJOR 3) + +include (${CMAKE_CURRENT_LIST_DIR}/FindPython/Support.cmake) + +if (COMMAND __Python3_add_library) + macro (Python3_add_library) + __Python3_add_library (Python3 ${ARGV}) + endmacro() +endif() + +unset (_PYTHON_PREFIX) diff --git a/Modules/FindPythonInterp.cmake b/Modules/FindPythonInterp.cmake index 3ef8e9f..bd64762 100644 --- a/Modules/FindPythonInterp.cmake +++ b/Modules/FindPythonInterp.cmake @@ -7,6 +7,10 @@ # # Find python interpreter # +# .. deprecated:: 3.12 +# +# Use :module:`FindPython3`, :module:`FindPython2` or :module:`FindPython` instead. +# # This module finds if Python interpreter is installed and determines # where the executables are. This code sets the following variables: # diff --git a/Modules/FindPythonLibs.cmake b/Modules/FindPythonLibs.cmake index 341d5d9..1a0cc2e 100644 --- a/Modules/FindPythonLibs.cmake +++ b/Modules/FindPythonLibs.cmake @@ -7,6 +7,10 @@ # # Find python libraries # +# .. deprecated:: 3.12 +# +# Use :module:`FindPython3`, :module:`FindPython2` or :module:`FindPython` instead. +# # This module finds if Python is installed and determines where the # include files and libraries are. It also determines what the name of # the library is. This code sets the following variables: diff --git a/Modules/FindVulkan.cmake b/Modules/FindVulkan.cmake index 1f4c8ad..4c60ed7 100644 --- a/Modules/FindVulkan.cmake +++ b/Modules/FindVulkan.cmake @@ -65,7 +65,7 @@ endif() set(Vulkan_LIBRARIES ${Vulkan_LIBRARY}) set(Vulkan_INCLUDE_DIRS ${Vulkan_INCLUDE_DIR}) -include(FindPackageHandleStandardArgs) +include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake) find_package_handle_standard_args(Vulkan DEFAULT_MSG Vulkan_LIBRARY Vulkan_INCLUDE_DIR) diff --git a/Modules/FindZLIB.cmake b/Modules/FindZLIB.cmake index 4065999..a5c04ac 100644 --- a/Modules/FindZLIB.cmake +++ b/Modules/FindZLIB.cmake @@ -75,8 +75,8 @@ endforeach() # Allow ZLIB_LIBRARY to be set manually, as the location of the zlib library if(NOT ZLIB_LIBRARY) foreach(search ${_ZLIB_SEARCHES}) - find_library(ZLIB_LIBRARY_RELEASE NAMES ${ZLIB_NAMES} ${${search}} PATH_SUFFIXES lib) - find_library(ZLIB_LIBRARY_DEBUG NAMES ${ZLIB_NAMES_DEBUG} ${${search}} PATH_SUFFIXES lib) + find_library(ZLIB_LIBRARY_RELEASE NAMES ${ZLIB_NAMES} NAMES_PER_DIR ${${search}} PATH_SUFFIXES lib) + find_library(ZLIB_LIBRARY_DEBUG NAMES ${ZLIB_NAMES_DEBUG} NAMES_PER_DIR ${${search}} PATH_SUFFIXES lib) endforeach() include(${CMAKE_CURRENT_LIST_DIR}/SelectLibraryConfigurations.cmake) diff --git a/Modules/FindwxWidgets.cmake b/Modules/FindwxWidgets.cmake index e21ec38..f2d6285 100644 --- a/Modules/FindwxWidgets.cmake +++ b/Modules/FindwxWidgets.cmake @@ -498,19 +498,7 @@ if(wxWidgets_FIND_STYLE STREQUAL "win32") set(_WX_TOOL gcc) elseif(MSVC) set(_WX_TOOL vc) - if(MSVC_VERSION EQUAL 1910) - set(_WX_TOOLVER 141) - elseif(MSVC_VERSION EQUAL 1900) - set(_WX_TOOLVER 140) - elseif(MSVC_VERSION EQUAL 1800) - set(_WX_TOOLVER 120) - elseif(MSVC_VERSION EQUAL 1700) - set(_WX_TOOLVER 110) - elseif(MSVC_VERSION EQUAL 1600) - set(_WX_TOOLVER 100) - elseif(MSVC_VERSION EQUAL 1500) - set(_WX_TOOLVER 90) - endif() + set(_WX_TOOLVER ${MSVC_TOOLSET_VERSION}) if(CMAKE_SIZEOF_VOID_P EQUAL 8) set(_WX_ARCH _x64) endif() @@ -837,7 +825,7 @@ else() # extract linkdirs (-L) for rpath (i.e., LINK_DIRECTORIES) string(REGEX MATCHALL "-L[^;]+" wxWidgets_LIBRARY_DIRS "${wxWidgets_LIBRARIES}") - string(REPLACE "-L" "" + string(REGEX REPLACE "-L([^;]+)" "\\1" wxWidgets_LIBRARY_DIRS "${wxWidgets_LIBRARY_DIRS}") DBG_MSG_V("wxWidgets_LIBRARIES=${wxWidgets_LIBRARIES}") @@ -875,6 +863,26 @@ else() set(wxWidgets_INCLUDE_DIRS ${_tmp_path}) separate_arguments(wxWidgets_INCLUDE_DIRS) list(REMOVE_ITEM wxWidgets_INCLUDE_DIRS "") + + set(_tmp_path "") + foreach(_path ${wxWidgets_LIBRARY_DIRS}) + execute_process( + COMMAND cygpath -w ${_path} + OUTPUT_VARIABLE _native_path + RESULT_VARIABLE _retv + OUTPUT_STRIP_TRAILING_WHITESPACE + ERROR_QUIET + ) + if(_retv EQUAL 0) + file(TO_CMAKE_PATH ${_native_path} _native_path) + DBG_MSG_V("Path ${_path} converted to ${_native_path}") + string(APPEND _tmp_path " ${_native_path}") + endif() + endforeach() + DBG_MSG("Setting wxWidgets_LIBRARY_DIRS = ${_tmp_path}") + set(wxWidgets_LIBRARY_DIRS ${_tmp_path}) + separate_arguments(wxWidgets_LIBRARY_DIRS) + list(REMOVE_ITEM wxWidgets_LIBRARY_DIRS "") endif() unset(_cygpath_exe CACHE) endif() @@ -917,14 +925,16 @@ unset(_wx_lib_missing) # Check if a specific version was requested by find_package(). if(wxWidgets_FOUND) - find_file(_filename wx/version.h PATHS ${wxWidgets_INCLUDE_DIRS} NO_DEFAULT_PATH) - dbg_msg("_filename: ${_filename}") + unset(_wx_filename) + find_file(_wx_filename wx/version.h PATHS ${wxWidgets_INCLUDE_DIRS} NO_DEFAULT_PATH) + dbg_msg("_wx_filename: ${_wx_filename}") - if(NOT _filename) + if(NOT _wx_filename) message(FATAL_ERROR "wxWidgets wx/version.h file not found in ${wxWidgets_INCLUDE_DIRS}.") endif() - file(READ ${_filename} _wx_version_h) + file(READ "${_wx_filename}" _wx_version_h) + unset(_wx_filename CACHE) string(REGEX REPLACE "^(.*\n)?#define +wxMAJOR_VERSION +([0-9]+).*" "\\2" wxWidgets_VERSION_MAJOR "${_wx_version_h}" ) diff --git a/Modules/GenerateExportHeader.cmake b/Modules/GenerateExportHeader.cmake index 17a3357..e6dcd00 100644 --- a/Modules/GenerateExportHeader.cmake +++ b/Modules/GenerateExportHeader.cmake @@ -185,6 +185,7 @@ # :prop_tgt:`CXX_VISIBILITY_PRESET <<LANG>_VISIBILITY_PRESET>` and # :prop_tgt:`VISIBILITY_INLINES_HIDDEN` instead. +include(CheckCCompilerFlag) include(CheckCXXCompilerFlag) # TODO: Install this macro separately? @@ -194,6 +195,13 @@ macro(_check_cxx_compiler_attribute _ATTRIBUTE _RESULT) ) endmacro() +# TODO: Install this macro separately? +macro(_check_c_compiler_attribute _ATTRIBUTE _RESULT) + check_c_source_compiles("${_ATTRIBUTE} int somefunc() { return 0; } + int main() { return somefunc();}" ${_RESULT} + ) +endmacro() + macro(_test_compiler_hidden_visibility) if(CMAKE_COMPILER_IS_GNUCXX AND CMAKE_CXX_COMPILER_VERSION VERSION_LESS "4.2") @@ -213,9 +221,15 @@ macro(_test_compiler_hidden_visibility) AND NOT CMAKE_CXX_COMPILER_ID MATCHES XL AND NOT CMAKE_CXX_COMPILER_ID MATCHES PGI AND NOT CMAKE_CXX_COMPILER_ID MATCHES Watcom) - check_cxx_compiler_flag(-fvisibility=hidden COMPILER_HAS_HIDDEN_VISIBILITY) - check_cxx_compiler_flag(-fvisibility-inlines-hidden - COMPILER_HAS_HIDDEN_INLINE_VISIBILITY) + if (CMAKE_CXX_COMPILER_LOADED) + check_cxx_compiler_flag(-fvisibility=hidden COMPILER_HAS_HIDDEN_VISIBILITY) + check_cxx_compiler_flag(-fvisibility-inlines-hidden + COMPILER_HAS_HIDDEN_INLINE_VISIBILITY) + else() + check_c_compiler_flag(-fvisibility=hidden COMPILER_HAS_HIDDEN_VISIBILITY) + check_c_compiler_flag(-fvisibility-inlines-hidden + COMPILER_HAS_HIDDEN_INLINE_VISIBILITY) + endif() endif() endmacro() @@ -232,14 +246,27 @@ macro(_test_compiler_has_deprecated) set(COMPILER_HAS_DEPRECATED "" CACHE INTERNAL "Compiler support for a deprecated attribute") else() - _check_cxx_compiler_attribute("__attribute__((__deprecated__))" - COMPILER_HAS_DEPRECATED_ATTR) - if(COMPILER_HAS_DEPRECATED_ATTR) - set(COMPILER_HAS_DEPRECATED "${COMPILER_HAS_DEPRECATED_ATTR}" - CACHE INTERNAL "Compiler support for a deprecated attribute") + if (CMAKE_CXX_COMPILER_LOADED) + _check_cxx_compiler_attribute("__attribute__((__deprecated__))" + COMPILER_HAS_DEPRECATED_ATTR) + if(COMPILER_HAS_DEPRECATED_ATTR) + set(COMPILER_HAS_DEPRECATED "${COMPILER_HAS_DEPRECATED_ATTR}" + CACHE INTERNAL "Compiler support for a deprecated attribute") + else() + _check_cxx_compiler_attribute("__declspec(deprecated)" + COMPILER_HAS_DEPRECATED) + endif() else() - _check_cxx_compiler_attribute("__declspec(deprecated)" - COMPILER_HAS_DEPRECATED) + _check_c_compiler_attribute("__attribute__((__deprecated__))" + COMPILER_HAS_DEPRECATED_ATTR) + if(COMPILER_HAS_DEPRECATED_ATTR) + set(COMPILER_HAS_DEPRECATED "${COMPILER_HAS_DEPRECATED_ATTR}" + CACHE INTERNAL "Compiler support for a deprecated attribute") + else() + _check_c_compiler_attribute("__declspec(deprecated)" + COMPILER_HAS_DEPRECATED) + endif() + endif() endif() endmacro() diff --git a/Modules/InstallRequiredSystemLibraries.cmake b/Modules/InstallRequiredSystemLibraries.cmake index eb17fd7..0fd76c0 100644 --- a/Modules/InstallRequiredSystemLibraries.cmake +++ b/Modules/InstallRequiredSystemLibraries.cmake @@ -121,9 +121,7 @@ if(MSVC) ) endif() - if(MSVC_VERSION EQUAL 1400) - set(MSVC_REDIST_NAME VC80) - + if(MSVC_TOOLSET_VERSION EQUAL 80) # Find the runtime library redistribution directory. get_filename_component(msvc_install_dir "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\8.0;InstallDir]" ABSOLUTE) @@ -163,9 +161,7 @@ if(MSVC) endif() endif() - if(MSVC_VERSION EQUAL 1500) - set(MSVC_REDIST_NAME VC90) - + if(MSVC_TOOLSET_VERSION EQUAL 90) # Find the runtime library redistribution directory. get_filename_component(msvc_install_dir "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\9.0;InstallDir]" ABSOLUTE) @@ -209,34 +205,31 @@ if(MSVC) endif() set(MSVC_REDIST_NAME "") - set(_MSVCRT_DLL_VERSION "") - set(_MSVCRT_IDE_VERSION "") + set(_MSVC_DLL_VERSION "") + set(_MSVC_IDE_VERSION "") if(MSVC_VERSION GREATER_EQUAL 2000) message(WARNING "MSVC ${MSVC_VERSION} not yet supported.") - elseif(MSVC_VERSION GREATER_EQUAL 1911) - set(MSVC_REDIST_NAME VC141) - set(_MSVCRT_DLL_VERSION 140) - set(_MSVCRT_IDE_VERSION 15) - elseif(MSVC_VERSION EQUAL 1910) - set(MSVC_REDIST_NAME VC150) - set(_MSVCRT_DLL_VERSION 140) - set(_MSVCRT_IDE_VERSION 15) - elseif(MSVC_VERSION EQUAL 1900) - set(MSVC_REDIST_NAME VC140) - set(_MSVCRT_DLL_VERSION 140) - set(_MSVCRT_IDE_VERSION 14) - elseif(MSVC_VERSION EQUAL 1800) - set(MSVC_REDIST_NAME VC120) - set(_MSVCRT_DLL_VERSION 120) - set(_MSVCRT_IDE_VERSION 12) - elseif(MSVC_VERSION EQUAL 1700) - set(MSVC_REDIST_NAME VC110) - set(_MSVCRT_DLL_VERSION 110) - set(_MSVCRT_IDE_VERSION 11) - elseif(MSVC_VERSION EQUAL 1600) - set(MSVC_REDIST_NAME VC100) - set(_MSVCRT_DLL_VERSION 100) - set(_MSVCRT_IDE_VERSION 10) + elseif(MSVC_TOOLSET_VERSION) + set(MSVC_REDIST_NAME VC${MSVC_TOOLSET_VERSION}) + if(MSVC_VERSION EQUAL 1910) + # VS2017 named this differently prior to update 3. + set(MSVC_REDIST_NAME VC150) + endif() + + math(EXPR _MSVC_DLL_VERSION "${MSVC_TOOLSET_VERSION} / 10 * 10") + + if(MSVC_TOOLSET_VERSION EQUAL 141) + set(_MSVC_IDE_VERSION 15) + else() + math(EXPR _MSVC_IDE_VERSION "${MSVC_TOOLSET_VERSION} / 10") + endif() + endif() + + set(_MSVCRT_DLL_VERSION "") + set(_MSVCRT_IDE_VERSION "") + if(_MSVC_IDE_VERSION GREATER_EQUAL 10) + set(_MSVCRT_DLL_VERSION "${_MSVC_DLL_VERSION}") + set(_MSVCRT_IDE_VERSION "${_MSVC_IDE_VERSION}") endif() if(_MSVCRT_DLL_VERSION) @@ -433,23 +426,9 @@ if(MSVC) set(_MFC_DLL_VERSION "") set(_MFC_IDE_VERSION "") - if(MSVC_VERSION GREATER_EQUAL 2000) - # Version not yet supported. - elseif(MSVC_VERSION GREATER_EQUAL 1910) - set(_MFC_DLL_VERSION 140) - set(_MFC_IDE_VERSION 15) - elseif(MSVC_VERSION EQUAL 1900) - set(_MFC_DLL_VERSION 140) - set(_MFC_IDE_VERSION 14) - elseif(MSVC_VERSION EQUAL 1800) - set(_MFC_DLL_VERSION 120) - set(_MFC_IDE_VERSION 12) - elseif(MSVC_VERSION EQUAL 1700) - set(_MFC_DLL_VERSION 110) - set(_MFC_IDE_VERSION 11) - elseif(MSVC_VERSION EQUAL 1600) - set(_MFC_DLL_VERSION 100) - set(_MFC_IDE_VERSION 10) + if(_MSVC_IDE_VERSION GREATER_EQUAL 10) + set(_MFC_DLL_VERSION ${_MSVC_DLL_VERSION}) + set(_MFC_IDE_VERSION ${_MSVC_IDE_VERSION}) endif() if(_MFC_DLL_VERSION) @@ -528,32 +507,8 @@ if(MSVC) # MSVC 8 was the first version with OpenMP # Furthermore, there is no debug version of this if(CMAKE_INSTALL_OPENMP_LIBRARIES AND _IRSL_HAVE_MSVC) - set(_MSOMP_DLL_VERSION "") - set(_MSOMP_IDE_VERSION "") - if(MSVC_VERSION GREATER_EQUAL 2000) - # Version not yet supported. - elseif(MSVC_VERSION GREATER_EQUAL 1910) - set(_MSOMP_DLL_VERSION 140) - set(_MSOMP_IDE_VERSION 15) - elseif(MSVC_VERSION EQUAL 1900) - set(_MSOMP_DLL_VERSION 140) - set(_MSOMP_IDE_VERSION 14) - elseif(MSVC_VERSION EQUAL 1800) - set(_MSOMP_DLL_VERSION 120) - set(_MSOMP_IDE_VERSION 12) - elseif(MSVC_VERSION EQUAL 1700) - set(_MSOMP_DLL_VERSION 110) - set(_MSOMP_IDE_VERSION 11) - elseif(MSVC_VERSION EQUAL 1600) - set(_MSOMP_DLL_VERSION 100) - set(_MSOMP_IDE_VERSION 10) - elseif(MSVC_VERSION EQUAL 1500) - set(_MSOMP_DLL_VERSION 90) - set(_MSOMP_IDE_VERSION 9) - elseif(MSVC_VERSION EQUAL 1400) - set(_MSOMP_DLL_VERSION 80) - set(_MSOMP_IDE_VERSION 8) - endif() + set(_MSOMP_DLL_VERSION ${_MSVC_DLL_VERSION}) + set(_MSOMP_IDE_VERSION ${_MSVC_IDE_VERSION}) if(_MSOMP_DLL_VERSION) set(v "${_MSOMP_DLL_VERSION}") diff --git a/Modules/MatlabTestsRedirect.cmake b/Modules/MatlabTestsRedirect.cmake index 64d580d..fc36fc3 100644 --- a/Modules/MatlabTestsRedirect.cmake +++ b/Modules/MatlabTestsRedirect.cmake @@ -55,11 +55,12 @@ endif() if(no_unittest_framework) - set(unittest_to_run "try, ${unittest_file_to_run_name}, catch err, disp('An exception has been thrown during the execution'), disp(err), disp(err.stack), exit(1), end, exit(0)") + set(unittest_to_run "${unittest_file_to_run_name}") endif() +set(command_to_run "try, ${unittest_to_run}, catch err, disp('An exception has been thrown during the execution'), disp(err), disp(err.stack), exit(1), end, exit(0)") set(Matlab_SCRIPT_TO_RUN - "addpath(${concat_string}); ${cmd_to_run_before_test}; ${unittest_to_run}" + "addpath(${concat_string}); ${cmd_to_run_before_test}; ${command_to_run}" ) # if the working directory is not specified then default # to the output_directory because the log file will go there diff --git a/Modules/Platform/Android-Clang-CXX.cmake b/Modules/Platform/Android-Clang-CXX.cmake index 7111836..85d5088 100644 --- a/Modules/Platform/Android-Clang-CXX.cmake +++ b/Modules/Platform/Android-Clang-CXX.cmake @@ -1,2 +1,9 @@ include(Platform/Android-Clang) __android_compiler_clang(CXX) +if(_ANDROID_STL_NOSTDLIBXX) + if(CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 6) + string(APPEND CMAKE_CXX_STANDARD_LIBRARIES " -nostdlib++") + else() + string(APPEND CMAKE_CXX_STANDARD_LIBRARIES " -nodefaultlibs -lgcc -lc -lm -ldl") + endif() +endif() diff --git a/Modules/Platform/Android-Determine.cmake b/Modules/Platform/Android-Determine.cmake index add1dc1..e623902 100644 --- a/Modules/Platform/Android-Determine.cmake +++ b/Modules/Platform/Android-Determine.cmake @@ -261,7 +261,40 @@ if(NOT CMAKE_ANDROID_ARCH_ABI) else() # https://developer.android.com/ndk/guides/application_mk.html # Default is the oldest ARM ABI. - set(CMAKE_ANDROID_ARCH_ABI "armeabi") + + # Lookup the available ABIs among all toolchains. + set(_ANDROID_ABIS "") + file(GLOB _ANDROID_CONFIG_MKS + "${CMAKE_ANDROID_NDK}/build/core/toolchains/*/config.mk" + "${CMAKE_ANDROID_NDK}/toolchains/*/config.mk" + ) + foreach(config_mk IN LISTS _ANDROID_CONFIG_MKS) + file(STRINGS "${config_mk}" _ANDROID_TOOL_ABIS REGEX "^TOOLCHAIN_ABIS :=") + string(REPLACE "TOOLCHAIN_ABIS :=" "" _ANDROID_TOOL_ABIS "${_ANDROID_TOOL_ABIS}") + separate_arguments(_ANDROID_TOOL_ABIS UNIX_COMMAND "${_ANDROID_TOOL_ABIS}") + list(APPEND _ANDROID_ABIS ${_ANDROID_TOOL_ABIS}) + unset(_ANDROID_TOOL_ABIS) + endforeach() + unset(_ANDROID_CONFIG_MKS) + + # Choose the oldest among the available arm ABIs. + if(_ANDROID_ABIS) + list(REMOVE_DUPLICATES _ANDROID_ABIS) + cmake_policy(PUSH) + cmake_policy(SET CMP0057 NEW) + foreach(abi armeabi armeabi-v7a arm64-v8a) + if("${abi}" IN_LIST _ANDROID_ABIS) + set(CMAKE_ANDROID_ARCH_ABI "${abi}") + break() + endif() + endforeach() + cmake_policy(POP) + endif() + unset(_ANDROID_ABIS) + + if(NOT CMAKE_ANDROID_ARCH_ABI) + set(CMAKE_ANDROID_ARCH_ABI "armeabi") + endif() endif() endif() set(CMAKE_ANDROID_ARCH "${_ANDROID_ABI_${CMAKE_ANDROID_ARCH_ABI}_ARCH}") diff --git a/Modules/Platform/Android-GNU-CXX.cmake b/Modules/Platform/Android-GNU-CXX.cmake index 41279d1..d30d0ff 100644 --- a/Modules/Platform/Android-GNU-CXX.cmake +++ b/Modules/Platform/Android-GNU-CXX.cmake @@ -1,2 +1,5 @@ include(Platform/Android-GNU) __android_compiler_gnu(CXX) +if(_ANDROID_STL_NOSTDLIBXX) + string(APPEND CMAKE_CXX_STANDARD_LIBRARIES " -nodefaultlibs -lgcc -lc -lm -ldl") +endif() diff --git a/Modules/Platform/Android/ndk-stl-c++.cmake b/Modules/Platform/Android/ndk-stl-c++.cmake index a12411c..1cafd1f 100644 --- a/Modules/Platform/Android/ndk-stl-c++.cmake +++ b/Modules/Platform/Android/ndk-stl-c++.cmake @@ -1,6 +1,7 @@ # <ndk>/sources/cxx-stl/llvm-libc++/Android.mk set(_ANDROID_STL_RTTI 1) set(_ANDROID_STL_EXCEPTIONS 1) +set(_ANDROID_STL_NOSTDLIBXX 1) macro(__android_stl_cxx lang filename) # Add the include directory. if(EXISTS "${CMAKE_ANDROID_NDK}/sources/cxx-stl/llvm-libc++/libcxx/include/cstddef") diff --git a/Modules/Platform/Android/ndk-stl-gabi++.cmake b/Modules/Platform/Android/ndk-stl-gabi++.cmake index 850a47a..d3b9e45 100644 --- a/Modules/Platform/Android/ndk-stl-gabi++.cmake +++ b/Modules/Platform/Android/ndk-stl-gabi++.cmake @@ -1,6 +1,7 @@ # <ndk>/sources/cxx-stl/gabi++/Android.mk set(_ANDROID_STL_RTTI 1) set(_ANDROID_STL_EXCEPTIONS 1) +set(_ANDROID_STL_NOSTDLIBXX 1) macro(__android_stl_gabixx lang filename) __android_stl_inc(${lang} "${CMAKE_ANDROID_NDK}/sources/cxx-stl/gabi++/include" 1) __android_stl_lib(${lang} "${CMAKE_ANDROID_NDK}/sources/cxx-stl/gabi++/libs/${CMAKE_ANDROID_ARCH_ABI}/${filename}" 1) diff --git a/Modules/Platform/Android/ndk-stl-gnustl.cmake b/Modules/Platform/Android/ndk-stl-gnustl.cmake index b3226ee..46cedc6 100644 --- a/Modules/Platform/Android/ndk-stl-gnustl.cmake +++ b/Modules/Platform/Android/ndk-stl-gnustl.cmake @@ -1,6 +1,7 @@ # <ndk>/sources/cxx-stl/gnu-libstdc++/Android.mk set(_ANDROID_STL_RTTI 1) set(_ANDROID_STL_EXCEPTIONS 1) +set(_ANDROID_STL_NOSTDLIBXX 1) macro(__android_stl_gnustl lang filename) __android_stl_inc(${lang} "${CMAKE_ANDROID_NDK}/sources/cxx-stl/gnu-libstdc++/${CMAKE_${lang}_ANDROID_TOOLCHAIN_VERSION}/include" 1) __android_stl_inc(${lang} "${CMAKE_ANDROID_NDK}/sources/cxx-stl/gnu-libstdc++/${CMAKE_${lang}_ANDROID_TOOLCHAIN_VERSION}/libs/${CMAKE_ANDROID_ARCH_ABI}/include" 1) diff --git a/Modules/Platform/Android/ndk-stl-none.cmake b/Modules/Platform/Android/ndk-stl-none.cmake index 9049c91..45122f7 100644 --- a/Modules/Platform/Android/ndk-stl-none.cmake +++ b/Modules/Platform/Android/ndk-stl-none.cmake @@ -1,2 +1,3 @@ +set(_ANDROID_STL_NOSTDLIBXX 1) macro(__android_stl lang) endmacro() diff --git a/Modules/Platform/Android/ndk-stl-stlport.cmake b/Modules/Platform/Android/ndk-stl-stlport.cmake index eab6b94..efad33b 100644 --- a/Modules/Platform/Android/ndk-stl-stlport.cmake +++ b/Modules/Platform/Android/ndk-stl-stlport.cmake @@ -1,6 +1,7 @@ # <ndk>/sources/cxx-stl/stlport/Android.mk set(_ANDROID_STL_RTTI 1) set(_ANDROID_STL_EXCEPTIONS 1) +set(_ANDROID_STL_NOSTDLIBXX 0) macro(__android_stl_stlport lang filename) __android_stl_inc(${lang} "${CMAKE_ANDROID_NDK}/sources/cxx-stl/stlport/stlport" 1) __android_stl_lib(${lang} "${CMAKE_ANDROID_NDK}/sources/cxx-stl/stlport/libs/${CMAKE_ANDROID_ARCH_ABI}/${filename}" 1) diff --git a/Modules/Platform/Android/ndk-stl-system.cmake b/Modules/Platform/Android/ndk-stl-system.cmake index dd554fe..7d86a40 100644 --- a/Modules/Platform/Android/ndk-stl-system.cmake +++ b/Modules/Platform/Android/ndk-stl-system.cmake @@ -1,6 +1,7 @@ # <ndk>/android-ndk-r11c/sources/cxx-stl/system/Android.mk set(_ANDROID_STL_RTTI 0) set(_ANDROID_STL_EXCEPTIONS 0) +set(_ANDROID_STL_NOSTDLIBXX 0) macro(__android_stl lang) __android_stl_inc(${lang} "${CMAKE_ANDROID_NDK}/sources/cxx-stl/system/include" 1) endmacro() diff --git a/Modules/Platform/Darwin-Absoft-Fortran.cmake b/Modules/Platform/Apple-Absoft-Fortran.cmake index 8caa202..8caa202 100644 --- a/Modules/Platform/Darwin-Absoft-Fortran.cmake +++ b/Modules/Platform/Apple-Absoft-Fortran.cmake diff --git a/Modules/Platform/Darwin-AppleClang-C.cmake b/Modules/Platform/Apple-AppleClang-C.cmake index 3216b29..f45ccf4 100644 --- a/Modules/Platform/Darwin-AppleClang-C.cmake +++ b/Modules/Platform/Apple-AppleClang-C.cmake @@ -1,4 +1,4 @@ -include(Platform/Darwin-Clang-C) +include(Platform/Apple-Clang-C) if(NOT CMAKE_C_COMPILER_VERSION VERSION_LESS 4.2) set(CMAKE_C_SYSTEM_FRAMEWORK_SEARCH_FLAG "-iframework ") else() diff --git a/Modules/Platform/Darwin-AppleClang-CXX.cmake b/Modules/Platform/Apple-AppleClang-CXX.cmake index 3fedf8c..1128204 100644 --- a/Modules/Platform/Darwin-AppleClang-CXX.cmake +++ b/Modules/Platform/Apple-AppleClang-CXX.cmake @@ -1,4 +1,4 @@ -include(Platform/Darwin-Clang-CXX) +include(Platform/Apple-Clang-CXX) if(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 4.2) set(CMAKE_CXX_SYSTEM_FRAMEWORK_SEARCH_FLAG "-iframework ") else() diff --git a/Modules/Platform/Apple-Clang-C.cmake b/Modules/Platform/Apple-Clang-C.cmake new file mode 100644 index 0000000..4d0dc82 --- /dev/null +++ b/Modules/Platform/Apple-Clang-C.cmake @@ -0,0 +1,2 @@ +include(Platform/Apple-Clang) +__apple_compiler_clang(C) diff --git a/Modules/Platform/Apple-Clang-CXX.cmake b/Modules/Platform/Apple-Clang-CXX.cmake new file mode 100644 index 0000000..6c1ddc1 --- /dev/null +++ b/Modules/Platform/Apple-Clang-CXX.cmake @@ -0,0 +1,2 @@ +include(Platform/Apple-Clang) +__apple_compiler_clang(CXX) diff --git a/Modules/Platform/Darwin-Clang.cmake b/Modules/Platform/Apple-Clang.cmake index f8a07ec..0681bfb 100644 --- a/Modules/Platform/Darwin-Clang.cmake +++ b/Modules/Platform/Apple-Clang.cmake @@ -3,12 +3,9 @@ # This module is shared by multiple languages; use include blocker. -if(__DARWIN_COMPILER_CLANG) - return() -endif() -set(__DARWIN_COMPILER_CLANG 1) +include_guard() -macro(__darwin_compiler_clang lang) +macro(__apple_compiler_clang lang) set(CMAKE_${lang}_VERBOSE_FLAG "-v -Wl,-v") # also tell linker to print verbose output set(CMAKE_SHARED_LIBRARY_CREATE_${lang}_FLAGS "-dynamiclib -Wl,-headerpad_max_install_names") set(CMAKE_SHARED_MODULE_CREATE_${lang}_FLAGS "-bundle -Wl,-headerpad_max_install_names") diff --git a/Modules/Platform/Darwin-GNU-C.cmake b/Modules/Platform/Apple-GNU-C.cmake index efdfd00..5481c99 100644 --- a/Modules/Platform/Darwin-GNU-C.cmake +++ b/Modules/Platform/Apple-GNU-C.cmake @@ -1,4 +1,4 @@ -include(Platform/Darwin-GNU) -__darwin_compiler_gnu(C) +include(Platform/Apple-GNU) +__apple_compiler_gnu(C) cmake_gnu_set_sysroot_flag(C) cmake_gnu_set_osx_deployment_target_flag(C) diff --git a/Modules/Platform/Darwin-GNU-CXX.cmake b/Modules/Platform/Apple-GNU-CXX.cmake index e3c2ea7..727f726 100644 --- a/Modules/Platform/Darwin-GNU-CXX.cmake +++ b/Modules/Platform/Apple-GNU-CXX.cmake @@ -1,4 +1,4 @@ -include(Platform/Darwin-GNU) -__darwin_compiler_gnu(CXX) +include(Platform/Apple-GNU) +__apple_compiler_gnu(CXX) cmake_gnu_set_sysroot_flag(CXX) cmake_gnu_set_osx_deployment_target_flag(CXX) diff --git a/Modules/Platform/Darwin-GNU-Fortran.cmake b/Modules/Platform/Apple-GNU-Fortran.cmake index 568d79b..2f53603 100644 --- a/Modules/Platform/Darwin-GNU-Fortran.cmake +++ b/Modules/Platform/Apple-GNU-Fortran.cmake @@ -1,8 +1,8 @@ # Distributed under the OSI-approved BSD 3-Clause License. See accompanying # file Copyright.txt or https://cmake.org/licensing for details. -include(Platform/Darwin-GNU) -__darwin_compiler_gnu(Fortran) +include(Platform/Apple-GNU) +__apple_compiler_gnu(Fortran) cmake_gnu_set_sysroot_flag(Fortran) cmake_gnu_set_osx_deployment_target_flag(Fortran) diff --git a/Modules/Platform/Darwin-GNU.cmake b/Modules/Platform/Apple-GNU.cmake index 9f9ef01..0eb8168 100644 --- a/Modules/Platform/Darwin-GNU.cmake +++ b/Modules/Platform/Apple-GNU.cmake @@ -3,12 +3,9 @@ # This module is shared by multiple languages; use include blocker. -if(__DARWIN_COMPILER_GNU) - return() -endif() -set(__DARWIN_COMPILER_GNU 1) +include_guard() -macro(__darwin_compiler_gnu lang) +macro(__apple_compiler_gnu lang) set(CMAKE_${lang}_VERBOSE_FLAG "-v -Wl,-v") # also tell linker to print verbose output # GNU does not have -shared on OS X set(CMAKE_SHARED_LIBRARY_CREATE_${lang}_FLAGS "-dynamiclib -Wl,-headerpad_max_install_names") diff --git a/Modules/Platform/Apple-Intel-C.cmake b/Modules/Platform/Apple-Intel-C.cmake new file mode 100644 index 0000000..95bb270 --- /dev/null +++ b/Modules/Platform/Apple-Intel-C.cmake @@ -0,0 +1,2 @@ +include(Platform/Apple-Intel) +__apple_compiler_intel(C) diff --git a/Modules/Platform/Apple-Intel-CXX.cmake b/Modules/Platform/Apple-Intel-CXX.cmake new file mode 100644 index 0000000..b87e512 --- /dev/null +++ b/Modules/Platform/Apple-Intel-CXX.cmake @@ -0,0 +1,2 @@ +include(Platform/Apple-Intel) +__apple_compiler_intel(CXX) diff --git a/Modules/Platform/Darwin-Intel-Fortran.cmake b/Modules/Platform/Apple-Intel-Fortran.cmake index 2299da9..e54e237 100644 --- a/Modules/Platform/Darwin-Intel-Fortran.cmake +++ b/Modules/Platform/Apple-Intel-Fortran.cmake @@ -1,8 +1,8 @@ # Distributed under the OSI-approved BSD 3-Clause License. See accompanying # file Copyright.txt or https://cmake.org/licensing for details. -include(Platform/Darwin-Intel) -__darwin_compiler_intel(Fortran) +include(Platform/Apple-Intel) +__apple_compiler_intel(Fortran) set(CMAKE_Fortran_OSX_COMPATIBILITY_VERSION_FLAG "-compatibility_version ") set(CMAKE_Fortran_OSX_CURRENT_VERSION_FLAG "-current_version ") diff --git a/Modules/Platform/Darwin-Intel.cmake b/Modules/Platform/Apple-Intel.cmake index dd33cec..2d4f7e5 100644 --- a/Modules/Platform/Darwin-Intel.cmake +++ b/Modules/Platform/Apple-Intel.cmake @@ -3,12 +3,9 @@ # This module is shared by multiple languages; use include blocker. -if(__DARWIN_COMPILER_INTEL) - return() -endif() -set(__DARWIN_COMPILER_INTEL 1) +include_guard() -macro(__darwin_compiler_intel lang) +macro(__apple_compiler_intel lang) set(CMAKE_${lang}_VERBOSE_FLAG "-v -Wl,-v") # also tell linker to print verbose output set(CMAKE_SHARED_LIBRARY_CREATE_${lang}_FLAGS "-dynamiclib -Wl,-headerpad_max_install_names") set(CMAKE_SHARED_MODULE_CREATE_${lang}_FLAGS "-bundle -Wl,-headerpad_max_install_names") diff --git a/Modules/Platform/Darwin-NAG-Fortran.cmake b/Modules/Platform/Apple-NAG-Fortran.cmake index 8d3e741..8d3e741 100644 --- a/Modules/Platform/Darwin-NAG-Fortran.cmake +++ b/Modules/Platform/Apple-NAG-Fortran.cmake diff --git a/Modules/Platform/Darwin-NVIDIA-CUDA.cmake b/Modules/Platform/Apple-NVIDIA-CUDA.cmake index bec3948..bec3948 100644 --- a/Modules/Platform/Darwin-NVIDIA-CUDA.cmake +++ b/Modules/Platform/Apple-NVIDIA-CUDA.cmake diff --git a/Modules/Platform/Apple-PGI-C.cmake b/Modules/Platform/Apple-PGI-C.cmake new file mode 100644 index 0000000..1e11724 --- /dev/null +++ b/Modules/Platform/Apple-PGI-C.cmake @@ -0,0 +1,2 @@ +include(Platform/Apple-PGI) +__apple_compiler_pgi(C) diff --git a/Modules/Platform/Apple-PGI-CXX.cmake b/Modules/Platform/Apple-PGI-CXX.cmake new file mode 100644 index 0000000..aa5daf7 --- /dev/null +++ b/Modules/Platform/Apple-PGI-CXX.cmake @@ -0,0 +1,2 @@ +include(Platform/Apple-PGI) +__apple_compiler_pgi(CXX) diff --git a/Modules/Platform/Apple-PGI-Fortran.cmake b/Modules/Platform/Apple-PGI-Fortran.cmake new file mode 100644 index 0000000..1e3e4b1 --- /dev/null +++ b/Modules/Platform/Apple-PGI-Fortran.cmake @@ -0,0 +1,2 @@ +include(Platform/Apple-PGI) +__apple_compiler_pgi(Fortran) diff --git a/Modules/Platform/Darwin-PGI.cmake b/Modules/Platform/Apple-PGI.cmake index 04479a8..8d343b7 100644 --- a/Modules/Platform/Darwin-PGI.cmake +++ b/Modules/Platform/Apple-PGI.cmake @@ -2,12 +2,9 @@ # file Copyright.txt or https://cmake.org/licensing for details. # This module is shared by multiple languages; use include blocker. -if(__DARWIN_COMPILER_PGI) - return() -endif() -set(__DARWIN_COMPILER_PGI 1) +include_guard() -macro(__darwin_compiler_pgi lang) +macro(__apple_compiler_pgi lang) set(CMAKE_${lang}_OSX_COMPATIBILITY_VERSION_FLAG "-Wl,-compatibility_version,") set(CMAKE_${lang}_OSX_CURRENT_VERSION_FLAG "-Wl,-current_version,") set(CMAKE_SHARED_LIBRARY_SONAME_${lang}_FLAG "-Wl,-install_name") diff --git a/Modules/Platform/Apple-VisualAge-C.cmake b/Modules/Platform/Apple-VisualAge-C.cmake new file mode 100644 index 0000000..7fa6032 --- /dev/null +++ b/Modules/Platform/Apple-VisualAge-C.cmake @@ -0,0 +1 @@ +include(Platform/Apple-XL-C) diff --git a/Modules/Platform/Apple-VisualAge-CXX.cmake b/Modules/Platform/Apple-VisualAge-CXX.cmake new file mode 100644 index 0000000..12dd347 --- /dev/null +++ b/Modules/Platform/Apple-VisualAge-CXX.cmake @@ -0,0 +1 @@ +include(Platform/Apple-XL-CXX) diff --git a/Modules/Platform/Darwin-XL-C.cmake b/Modules/Platform/Apple-XL-C.cmake index 2aeb132..2aeb132 100644 --- a/Modules/Platform/Darwin-XL-C.cmake +++ b/Modules/Platform/Apple-XL-C.cmake diff --git a/Modules/Platform/Darwin-XL-CXX.cmake b/Modules/Platform/Apple-XL-CXX.cmake index f8e1906..f8e1906 100644 --- a/Modules/Platform/Darwin-XL-CXX.cmake +++ b/Modules/Platform/Apple-XL-CXX.cmake diff --git a/Modules/Platform/Darwin-Clang-C.cmake b/Modules/Platform/Darwin-Clang-C.cmake deleted file mode 100644 index 0a1502e..0000000 --- a/Modules/Platform/Darwin-Clang-C.cmake +++ /dev/null @@ -1,2 +0,0 @@ -include(Platform/Darwin-Clang) -__darwin_compiler_clang(C) diff --git a/Modules/Platform/Darwin-Clang-CXX.cmake b/Modules/Platform/Darwin-Clang-CXX.cmake deleted file mode 100644 index f8e8d88..0000000 --- a/Modules/Platform/Darwin-Clang-CXX.cmake +++ /dev/null @@ -1,2 +0,0 @@ -include(Platform/Darwin-Clang) -__darwin_compiler_clang(CXX) diff --git a/Modules/Platform/Darwin-Initialize.cmake b/Modules/Platform/Darwin-Initialize.cmake index b539e45..3db77aa 100644 --- a/Modules/Platform/Darwin-Initialize.cmake +++ b/Modules/Platform/Darwin-Initialize.cmake @@ -20,6 +20,10 @@ execute_process(COMMAND sw_vers -productVersion set(CMAKE_OSX_ARCHITECTURES "$ENV{CMAKE_OSX_ARCHITECTURES}" CACHE STRING "Build architectures for OSX") +# macOS, iOS, tvOS, and watchOS should lookup compilers from +# Platform/Apple-${CMAKE_CXX_COMPILER_ID}-<LANG> +set(CMAKE_EFFECTIVE_SYSTEM_NAME "Apple") + #---------------------------------------------------------------------------- # _CURRENT_OSX_VERSION - as a two-component string: 10.5, 10.6, ... # diff --git a/Modules/Platform/Darwin-Intel-C.cmake b/Modules/Platform/Darwin-Intel-C.cmake deleted file mode 100644 index 81c630f..0000000 --- a/Modules/Platform/Darwin-Intel-C.cmake +++ /dev/null @@ -1,2 +0,0 @@ -include(Platform/Darwin-Intel) -__darwin_compiler_intel(C) diff --git a/Modules/Platform/Darwin-Intel-CXX.cmake b/Modules/Platform/Darwin-Intel-CXX.cmake deleted file mode 100644 index 90ae53b..0000000 --- a/Modules/Platform/Darwin-Intel-CXX.cmake +++ /dev/null @@ -1,2 +0,0 @@ -include(Platform/Darwin-Intel) -__darwin_compiler_intel(CXX) diff --git a/Modules/Platform/Darwin-PGI-C.cmake b/Modules/Platform/Darwin-PGI-C.cmake deleted file mode 100644 index 790919b..0000000 --- a/Modules/Platform/Darwin-PGI-C.cmake +++ /dev/null @@ -1,2 +0,0 @@ -include(Platform/Darwin-PGI) -__darwin_compiler_pgi(C) diff --git a/Modules/Platform/Darwin-PGI-CXX.cmake b/Modules/Platform/Darwin-PGI-CXX.cmake deleted file mode 100644 index ceaed71..0000000 --- a/Modules/Platform/Darwin-PGI-CXX.cmake +++ /dev/null @@ -1,2 +0,0 @@ -include(Platform/Darwin-PGI) -__darwin_compiler_pgi(CXX) diff --git a/Modules/Platform/Darwin-PGI-Fortran.cmake b/Modules/Platform/Darwin-PGI-Fortran.cmake deleted file mode 100644 index 146807b..0000000 --- a/Modules/Platform/Darwin-PGI-Fortran.cmake +++ /dev/null @@ -1,2 +0,0 @@ -include(Platform/Darwin-PGI) -__darwin_compiler_pgi(Fortran) diff --git a/Modules/Platform/Darwin-VisualAge-C.cmake b/Modules/Platform/Darwin-VisualAge-C.cmake deleted file mode 100644 index 859914f..0000000 --- a/Modules/Platform/Darwin-VisualAge-C.cmake +++ /dev/null @@ -1 +0,0 @@ -include(Platform/Darwin-XL-C) diff --git a/Modules/Platform/Darwin-VisualAge-CXX.cmake b/Modules/Platform/Darwin-VisualAge-CXX.cmake deleted file mode 100644 index 46c1005..0000000 --- a/Modules/Platform/Darwin-VisualAge-CXX.cmake +++ /dev/null @@ -1 +0,0 @@ -include(Platform/Darwin-XL-CXX) diff --git a/Modules/Platform/Windows-MSVC.cmake b/Modules/Platform/Windows-MSVC.cmake index 0737c12..ae180ed 100644 --- a/Modules/Platform/Windows-MSVC.cmake +++ b/Modules/Platform/Windows-MSVC.cmake @@ -71,6 +71,31 @@ if(NOT MSVC_VERSION) message(FATAL_ERROR "MSVC compiler version not detected properly: ${_compiler_version}") endif() + if(MSVC_VERSION GREATER_EQUAL 1910) + # VS 2017 or greater + set(MSVC_TOOLSET_VERSION 141) + elseif(MSVC_VERSION EQUAL 1900) + # VS 2015 + set(MSVC_TOOLSET_VERSION 140) + elseif(MSVC_VERSION EQUAL 1800) + # VS 2013 + set(MSVC_TOOLSET_VERSION 120) + elseif(MSVC_VERSION EQUAL 1700) + # VS 2012 + set(MSVC_TOOLSET_VERSION 110) + elseif(MSVC_VERSION EQUAL 1600) + # VS 2010 + set(MSVC_TOOLSET_VERSION 100) + elseif(MSVC_VERSION EQUAL 1500) + # VS 2008 + set(MSVC_TOOLSET_VERSION 90) + elseif(MSVC_VERSION EQUAL 1400) + # VS 2005 + set(MSVC_TOOLSET_VERSION 80) + else() + # We don't support MSVC_TOOLSET_VERSION for earlier compiler. + endif() + set(MSVC10) set(MSVC11) set(MSVC12) @@ -293,6 +318,34 @@ macro(__windows_compiler_msvc lang) set(CMAKE_${lang}_LINK_EXECUTABLE "${_CMAKE_VS_LINK_EXE}<CMAKE_LINKER> ${CMAKE_CL_NOLOGO} <OBJECTS> ${CMAKE_START_TEMP_FILE} /out:<TARGET> /implib:<TARGET_IMPLIB> /pdb:<TARGET_PDB> /version:<TARGET_VERSION_MAJOR>.<TARGET_VERSION_MINOR>${_PLATFORM_LINK_FLAGS} <CMAKE_${lang}_LINK_FLAGS> <LINK_FLAGS> <LINK_LIBRARIES>${CMAKE_END_TEMP_FILE}") + if("x${CMAKE_${lang}_COMPILER_ID}" STREQUAL "xMSVC") + set(_CMAKE_${lang}_IPO_SUPPORTED_BY_CMAKE YES) + set(_CMAKE_${lang}_IPO_MAY_BE_SUPPORTED_BY_COMPILER YES) + + set(CMAKE_${lang}_COMPILE_OPTIONS_IPO "/GL") + set(CMAKE_${lang}_LINK_OPTIONS_IPO "/INCREMENTAL:NO" "/LTCG") + string(REPLACE "<LINK_FLAGS> " "/LTCG <LINK_FLAGS> " + CMAKE_${lang}_CREATE_STATIC_LIBRARY_IPO "${CMAKE_${lang}_CREATE_STATIC_LIBRARY}") + elseif("x${CMAKE_${lang}_COMPILER_ID}" STREQUAL "xClang" OR + "x${CMAKE_${lang}_COMPILER_ID}" STREQUAL "xFlang") + set(_CMAKE_${lang}_IPO_SUPPORTED_BY_CMAKE YES) + set(_CMAKE_${lang}_IPO_MAY_BE_SUPPORTED_BY_COMPILER YES) + + # '-flto=thin' available since Clang 3.9 and Xcode 8 + # * http://clang.llvm.org/docs/ThinLTO.html#clang-llvm + # * https://trac.macports.org/wiki/XcodeVersionInfo + set(_CMAKE_LTO_THIN TRUE) + if(CMAKE_${lang}_COMPILER_VERSION VERSION_LESS 3.9) + set(_CMAKE_LTO_THIN FALSE) + endif() + + if(_CMAKE_LTO_THIN) + set(CMAKE_${lang}_COMPILE_OPTIONS_IPO "-flto=thin") + else() + set(CMAKE_${lang}_COMPILE_OPTIONS_IPO "-flto") + endif() + endif() + if("x${lang}" STREQUAL "xC" OR "x${lang}" STREQUAL "xCXX") if(CMAKE_VS_PLATFORM_TOOLSET MATCHES "v[0-9]+_clang_.*") diff --git a/Modules/Platform/Windows-NVIDIA-CUDA.cmake b/Modules/Platform/Windows-NVIDIA-CUDA.cmake index 970c2c6..0c11e55 100644 --- a/Modules/Platform/Windows-NVIDIA-CUDA.cmake +++ b/Modules/Platform/Windows-NVIDIA-CUDA.cmake @@ -36,12 +36,27 @@ else() set(_CMAKE_CUDA_EXTRA_DEVICE_LINK_FLAGS "") endif() +# Add implicit host link directories that contain device libraries +# to the device link line. +set(__IMPLICT_DLINK_DIRS ${CMAKE_CUDA_IMPLICIT_LINK_DIRECTORIES}) +if(__IMPLICT_DLINK_DIRS) + list(REMOVE_ITEM __IMPLICT_DLINK_DIRS ${CMAKE_CUDA_HOST_IMPLICIT_LINK_DIRECTORIES}) +endif() +set(__IMPLICT_DLINK_FLAGS ) +foreach(dir ${__IMPLICT_DLINK_DIRS}) + if(EXISTS "${dir}/cublas_device.lib") + string(APPEND __IMPLICT_DLINK_FLAGS " -L\"${dir}\"") + endif() +endforeach() +unset(__IMPLICT_DLINK_DIRS) + set(CMAKE_CUDA_DEVICE_LINK_LIBRARY - "<CMAKE_CUDA_COMPILER> <CMAKE_CUDA_LINK_FLAGS> <LANGUAGE_COMPILE_FLAGS> ${_CMAKE_CUDA_EXTRA_DEVICE_LINK_FLAGS} -shared -dlink <OBJECTS> -o <TARGET> <LINK_LIBRARIES> -Xcompiler=-Fd<TARGET_COMPILE_PDB>,-FS") + "<CMAKE_CUDA_COMPILER> <CMAKE_CUDA_LINK_FLAGS> <LANGUAGE_COMPILE_FLAGS> ${_CMAKE_CUDA_EXTRA_DEVICE_LINK_FLAGS} -shared -dlink <OBJECTS> -o <TARGET> <LINK_LIBRARIES> -Xcompiler=-Fd<TARGET_COMPILE_PDB>,-FS${__IMPLICT_DLINK_FLAGS}") set(CMAKE_CUDA_DEVICE_LINK_EXECUTABLE - "<CMAKE_CUDA_COMPILER> <FLAGS> <CMAKE_CUDA_LINK_FLAGS> ${_CMAKE_CUDA_EXTRA_DEVICE_LINK_FLAGS} -shared -dlink <OBJECTS> -o <TARGET> <LINK_LIBRARIES> -Xcompiler=-Fd<TARGET_COMPILE_PDB>,-FS") + "<CMAKE_CUDA_COMPILER> <FLAGS> <CMAKE_CUDA_LINK_FLAGS> ${_CMAKE_CUDA_EXTRA_DEVICE_LINK_FLAGS} -shared -dlink <OBJECTS> -o <TARGET> <LINK_LIBRARIES> -Xcompiler=-Fd<TARGET_COMPILE_PDB>,-FS${__IMPLICT_DLINK_FLAGS}") unset(_CMAKE_CUDA_EXTRA_DEVICE_LINK_FLAGS) +unset(__IMPLICT_DLINK_FLAGS) string(REPLACE "/D" "-D" _PLATFORM_DEFINES_CUDA "${_PLATFORM_DEFINES}${_PLATFORM_DEFINES_CXX}") diff --git a/Modules/Platform/Windows-df.cmake b/Modules/Platform/Windows-df.cmake index c59be45..f948914 100644 --- a/Modules/Platform/Windows-df.cmake +++ b/Modules/Platform/Windows-df.cmake @@ -30,9 +30,6 @@ set(CMAKE_Fortran_LINK_EXECUTABLE set(CMAKE_CREATE_WIN32_EXE /winapp) set(CMAKE_CREATE_CONSOLE_EXE ) -if(CMAKE_GENERATOR MATCHES "Visual Studio 8") - set (CMAKE_NO_BUILD_TYPE 1) -endif() # does the compiler support pdbtype and is it the newer compiler set(CMAKE_BUILD_TYPE_INIT Debug) diff --git a/Modules/TestBigEndian.cmake b/Modules/TestBigEndian.cmake index cc627d0..9a4bce5 100644 --- a/Modules/TestBigEndian.cmake +++ b/Modules/TestBigEndian.cmake @@ -14,6 +14,8 @@ # TEST_BIG_ENDIAN(VARIABLE) # VARIABLE - variable to store the result to +include(CheckTypeSize) + macro(TEST_BIG_ENDIAN VARIABLE) if(NOT DEFINED HAVE_${VARIABLE}) message(STATUS "Check if the system is big endian") @@ -27,8 +29,6 @@ macro(TEST_BIG_ENDIAN VARIABLE) message(FATAL_ERROR "TEST_BIG_ENDIAN needs either C or CXX language enabled") endif() - include(CheckTypeSize) - CHECK_TYPE_SIZE("unsigned short" CMAKE_SIZEOF_UNSIGNED_SHORT LANGUAGE ${_test_language}) if(CMAKE_SIZEOF_UNSIGNED_SHORT EQUAL 2) message(STATUS "Using unsigned short") diff --git a/Modules/UseJava.cmake b/Modules/UseJava.cmake index d7b720e..6e2c511 100644 --- a/Modules/UseJava.cmake +++ b/Modules/UseJava.cmake @@ -36,7 +36,7 @@ # The default OUTPUT_DIR can also be changed by setting the variable # CMAKE_JAVA_TARGET_OUTPUT_DIR. # -# Optionaly, using option GENERATE_NATIVE_HEADERS, native header files can be generated +# Optionally, using option GENERATE_NATIVE_HEADERS, native header files can be generated # for methods declared as native. These files provide the connective glue that allow your # Java and C code to interact. An INTERFACE target will be created for an easy usage # of generated files. Sub-option DESTINATION can be used to specify output directory for diff --git a/Modules/UseSWIG.cmake b/Modules/UseSWIG.cmake index 959893f..8713cd8 100644 --- a/Modules/UseSWIG.cmake +++ b/Modules/UseSWIG.cmake @@ -5,7 +5,10 @@ UseSWIG ------- -Defines the following macros for use with SWIG: +This file provides support for ``SWIG``. It is assumed that :module:`FindSWIG` +module has already been loaded. + +Defines the following command for use with ``SWIG``: .. command:: swig_add_library @@ -14,20 +17,71 @@ Defines the following macros for use with SWIG: swig_add_library(<name> [TYPE <SHARED|MODULE|STATIC|USE_BUILD_SHARED_LIBS>] LANGUAGE <language> + [NO_PROXY] + [OUTPUT_DIR <directory>] + [OUTFILE_DIR <directory>] SOURCES <file>... - ) - - The variable ``SWIG_MODULE_<name>_REAL_NAME`` will be set to the name - of the swig module target library. - -.. command:: swig_link_libraries - - Link libraries to swig module:: - - swig_link_libraries(<name> [ libraries ]) - -Source file properties on module files can be set before the invocation -of the ``swig_add_library`` macro to specify special behavior of SWIG: + ) + + Targets created with the ``swig_add_library`` command have the same + capabilities as targets created with the :command:`add_library` command, so + those targets can be used with any command expecting a target (e.g. + :command:`target_link_libraries`). + + .. note:: + + For multi-config generators, this module does not support + configuration-specific files generated by ``SWIG``. All build + configurations must result in the same generated source file. + + ``TYPE`` + ``SHARED``, ``MODULE`` and ``STATIC`` have the same semantic as for the + :command:`add_library` command. If ``USE_BUILD_SHARED_LIBS`` is specified, + the library type will be ``STATIC`` or ``SHARED`` based on whether the + current value of the :variable:`BUILD_SHARED_LIBS` variable is ``ON``. If + no type is specified, ``MODULE`` will be used. + + ``LANGUAGE`` + Specify the target language. + + ``NO_PROXY`` + Prevent the generation of the wrapper layer (swig ``-noproxy`` option). + + ``OUTPUT_DIR`` + Specify where to write the language specific files (swig ``-outdir`` + option). If not given, the ``CMAKE_SWIG_OUTDIR`` variable will be used. + If neither is specified, the default depends on the value of the + ``UseSWIG_MODULE_VERSION`` variable as follows: + + * If ``UseSWIG_MODULE_VERSION`` is 1 or is undefined, output is written to + the :variable:`CMAKE_CURRENT_BINARY_DIR` directory. + * If ``UseSWIG_MODULE_VERSION`` is 2, a dedicated directory will be used. + The path of this directory can be retrieved from the + ``SWIG_SUPPORT_FILES_DIRECTORY`` target property. + + ``OUTFILE_DIR`` + Specify an output directory name where the generated source file will be + placed (swig -o option). If not specified, the ``SWIG_OUTFILE_DIR`` variable + will be used. If neither is specified, ``OUTPUT_DIR`` or + ``CMAKE_SWIG_OUTDIR`` is used instead. + + ``SOURCES`` + List of sources for the library. Files with extension ``.i`` will be + identified as sources for the ``SWIG`` tool. Other files will be handled in + the standard way. + +.. note:: + + If ``UseSWIG_MODULE_VERSION`` is set to 2, it is **strongly** recommended + to use a dedicated directory unique to the target when either the + ``OUTPUT_DIR`` option or the ``CMAKE_SWIG_OUTDIR`` variable are specified. + The output directory contents are erased as part of the target build, so + to prevent interference between targets or losing other important files, each + target should have its own dedicated output directory. + +Source file properties on module files **must** be set before the invocation +of the ``swig_add_library`` command to specify special behavior of SWIG and +ensure generated files will receive the required settings. ``CPLUSPLUS`` Call SWIG in c++ mode. For example: @@ -37,9 +91,18 @@ of the ``swig_add_library`` macro to specify special behavior of SWIG: set_property(SOURCE mymod.i PROPERTY CPLUSPLUS ON) swig_add_library(mymod LANGUAGE python SOURCES mymod.i) -``SWIG_FLAGS`` - Add custom flags to the SWIG executable. +``INCLUDE_DIRECTORIES``, ``COMPILE_DEFINITIONS`` and ``COMPILE_OPTIONS`` + Add custom flags to SWIG compiler and have same semantic as properties + :prop_sf:`INCLUDE_DIRECTORIES`, :prop_sf:`COMPILE_DEFINITIONS` and + :prop_sf:`COMPILE_OPTIONS`. + +``GENERATED_INCLUDE_DIRECTORIES``, ``GENERATED_COMPILE_DEFINITIONS`` and ``GENERATED_COMPILE_OPTIONS`` + Add custom flags to the C/C++ generated source. They will fill, respectively, + properties :prop_sf:`INCLUDE_DIRECTORIES`, :prop_sf:`COMPILE_DEFINITIONS` and + :prop_sf:`COMPILE_OPTIONS` of generated C/C++ file. +``DEPENDS`` + Specify additional dependencies to the source file. ``SWIG_MODULE_NAME`` Specify the actual import name of the module in the target language. @@ -50,7 +113,59 @@ of the ``swig_add_library`` macro to specify special behavior of SWIG: set_property(SOURCE mymod.i PROPERTY SWIG_MODULE_NAME mymod_realname) -Some variables can be set to specify special behavior of SWIG: +Target library properties can be set to apply same configuration to all SWIG +input files. + +``SWIG_INCLUDE_DIRECTORIES``, ``SWIG_COMPILE_DEFINITIONS`` and ``SWIG_COMPILE_OPTIONS`` + These properties will be applied to all SWIG input files and have same + semantic as target properties :prop_tgt:`INCLUDE_DIRECTORIES`, + :prop_tgt:`COMPILE_DEFINITIONS` and :prop_tgt:`COMPILE_OPTIONS`. + + .. code-block:: cmake + + swig_add_library(mymod LANGUAGE python SOURCES mymod.i) + set_property(TARGET mymod PROPERTY SWIG_COMPILE_DEFINITIONS MY_DEF1 MY_DEF2) + set_property(TARGET mymod PROPERTY SWIG_COMPILE_OPTIONS -bla -blb) + +``SWIG_GENERATED_INCLUDE_DIRECTORIES``, ``SWIG_GENERATED_COMPILE_DEFINITIONS`` and ``SWIG_GENERATED_COMPILE_OPTIONS`` + These properties will populate, respectively, properties + :prop_sf:`INCLUDE_DIRECTORIES`, :prop_sf:`COMPILE_DEFINITIONS` and + :prop_sf:`COMPILE_FLAGS` of all generated C/C++ files. + +``SWIG_DEPENDS`` + Add dependencies to all SWIG input files. + +The following target properties are output properties and can be used to get +information about support files generated by ``SWIG`` interface compilation. + +``SWIG_SUPPORT_FILES`` + This output property list of wrapper files generated during SWIG compilation. + + .. code-block:: cmake + + swig_add_library(mymod LANGUAGE python SOURCES mymod.i) + get_property(support_files TARGET mymod PROPERTY SWIG_SUPPORT_FILES) + + .. note:: + + Only most principal support files are listed. In case some advanced + features of ``SWIG`` are used (for example ``%template``), associated + support files may not be listed. Prefer to use the + ``SWIG_SUPPORT_FILES_DIRECTORY`` property to handle support files. + +``SWIG_SUPPORT_FILES_DIRECTORY`` + This output property specifies the directory where support files will be + generated. + +Some variables can be set to customize the behavior of ``swig_add_library`` +as well as ``SWIG``: + +``UseSWIG_MODULE_VERSION`` + Specify different behaviors for ``UseSWIG`` module. + + * Set to 1 or undefined: Legacy behavior is applied. + * Set to 2: A new strategy is applied regarding support files: the output + directory of support files is erased before ``SWIG`` interface compilation. ``CMAKE_SWIG_FLAGS`` Add flags to all swig calls. @@ -66,34 +181,50 @@ Some variables can be set to specify special behavior of SWIG: Specify extra dependencies for the generated module for ``<name>``. #]=======================================================================] + +cmake_policy (VERSION 3.11) + set(SWIG_CXX_EXTENSION "cxx") set(SWIG_EXTRA_LIBRARIES "") set(SWIG_PYTHON_EXTRA_FILE_EXTENSIONS ".py") set(SWIG_JAVA_EXTRA_FILE_EXTENSIONS ".java" "JNI.java") +## +## PRIVATE functions +## +function (__SWIG_COMPUTE_TIMESTAMP name language infile workingdir __timestamp) + get_filename_component(filename "${infile}" NAME_WE) + set(${__timestamp} + "${workingdir}/${filename}${language}.stamp" PARENT_SCOPE) + # get_filename_component(filename "${infile}" ABSOLUTE) + # string(UUID uuid NAMESPACE 9735D882-D2F8-4E1D-88C9-A0A4F1F6ECA4 + # NAME ${name}-${language}-${filename} TYPE SHA1) + # set(${__timestamp} "${workingdir}/${uuid}.stamp" PARENT_SCOPE) +endfunction() + # # For given swig module initialize variables associated with it # macro(SWIG_MODULE_INITIALIZE name language) - string(TOUPPER "${language}" swig_uppercase_language) - string(TOLOWER "${language}" swig_lowercase_language) - set(SWIG_MODULE_${name}_LANGUAGE "${swig_uppercase_language}") - set(SWIG_MODULE_${name}_SWIG_LANGUAGE_FLAG "${swig_lowercase_language}") + string(TOUPPER "${language}" SWIG_MODULE_${name}_LANGUAGE) + string(TOLOWER "${language}" SWIG_MODULE_${name}_SWIG_LANGUAGE_FLAG) - set(SWIG_MODULE_${name}_REAL_NAME "${name}") - if (";${CMAKE_SWIG_FLAGS};" MATCHES ";-noproxy;") + set(SWIG_MODULE_${name}_EXTRA_FLAGS) + if (NOT DEFINED SWIG_MODULE_${name}_NOPROXY) + set (SWIG_MODULE_${name}_NOPROXY FALSE) + endif() + if ("-noproxy" IN_LIST CMAKE_SWIG_FLAGS) set (SWIG_MODULE_${name}_NOPROXY TRUE) endif () - if("x${SWIG_MODULE_${name}_LANGUAGE}" STREQUAL "xUNKNOWN") + + if (SWIG_MODULE_${name}_NOPROXY AND NOT "-noproxy" IN_LIST CMAKE_SWIG_FLAGS) + list (APPEND SWIG_MODULE_${name}_EXTRA_FLAGS "-noproxy") + endif() + if(SWIG_MODULE_${name}_LANGUAGE STREQUAL "UNKNOWN") message(FATAL_ERROR "SWIG Error: Language \"${language}\" not found") - elseif("x${SWIG_MODULE_${name}_LANGUAGE}" STREQUAL "xPYTHON" AND NOT SWIG_MODULE_${name}_NOPROXY) - # swig will produce a module.py containing an 'import _modulename' statement, - # which implies having a corresponding _modulename.so (*NIX), _modulename.pyd (Win32), - # unless the -noproxy flag is used - set(SWIG_MODULE_${name}_REAL_NAME "_${name}") - elseif("x${SWIG_MODULE_${name}_LANGUAGE}" STREQUAL "xPERL") - set(SWIG_MODULE_${name}_EXTRA_FLAGS "-shadow") + elseif(SWIG_MODULE_${name}_LANGUAGE STREQUAL "PERL") + list(APPEND SWIG_MODULE_${name}_EXTRA_FLAGS "-shadow") endif() endmacro() @@ -102,79 +233,108 @@ endmacro() # will be generated. This is internal swig macro. # -macro(SWIG_GET_EXTRA_OUTPUT_FILES language outfiles generatedpath infile) - set(${outfiles} "") - get_source_file_property(SWIG_GET_EXTRA_OUTPUT_FILES_module_basename - ${infile} SWIG_MODULE_NAME) - if(SWIG_GET_EXTRA_OUTPUT_FILES_module_basename STREQUAL "NOTFOUND") +function(SWIG_GET_EXTRA_OUTPUT_FILES language outfiles generatedpath infile) + set(files) + get_source_file_property(module_basename + "${infile}" SWIG_MODULE_NAME) + if(NOT swig_module_basename) # try to get module name from "%module foo" syntax - if ( EXISTS ${infile} ) - file ( STRINGS ${infile} _MODULE_NAME REGEX "[ ]*%module[ ]*[a-zA-Z0-9_]+.*" ) + if ( EXISTS "${infile}" ) + file ( STRINGS "${infile}" module_basename REGEX "[ ]*%module[ ]*[a-zA-Z0-9_]+.*" ) endif () - if ( _MODULE_NAME ) - string ( REGEX REPLACE "[ ]*%module[ ]*([a-zA-Z0-9_]+).*" "\\1" _MODULE_NAME "${_MODULE_NAME}" ) - set(SWIG_GET_EXTRA_OUTPUT_FILES_module_basename "${_MODULE_NAME}") + if ( module_basename ) + string ( REGEX REPLACE "[ ]*%module[ ]*([a-zA-Z0-9_]+).*" "\\1" module_basename "${module_basename}" ) else () # try to get module name from "%module (options=...) foo" syntax - if ( EXISTS ${infile} ) - file ( STRINGS ${infile} _MODULE_NAME REGEX "[ ]*%module[ ]*\\(.*\\)[ ]*[a-zA-Z0-9_]+.*" ) + if ( EXISTS "${infile}" ) + file ( STRINGS "${infile}" module_basename REGEX "[ ]*%module[ ]*\\(.*\\)[ ]*[a-zA-Z0-9_]+.*" ) endif () - if ( _MODULE_NAME ) - string ( REGEX REPLACE "[ ]*%module[ ]*\\(.*\\)[ ]*([a-zA-Z0-9_]+).*" "\\1" _MODULE_NAME "${_MODULE_NAME}" ) - set(SWIG_GET_EXTRA_OUTPUT_FILES_module_basename "${_MODULE_NAME}") + if ( module_basename ) + string ( REGEX REPLACE "[ ]*%module[ ]*\\(.*\\)[ ]*([a-zA-Z0-9_]+).*" "\\1" module_basename "${module_basename}" ) else () # fallback to file basename - get_filename_component(SWIG_GET_EXTRA_OUTPUT_FILES_module_basename ${infile} NAME_WE) + get_filename_component(module_basename "${infile}" NAME_WE) endif () endif () endif() foreach(it ${SWIG_${language}_EXTRA_FILE_EXTENSIONS}) - set(extra_file "${generatedpath}/${SWIG_GET_EXTRA_OUTPUT_FILES_module_basename}${it}") - list(APPEND ${outfiles} ${extra_file}) - # Treat extra outputs as plain files regardless of language. - set_property(SOURCE "${extra_file}" PROPERTY LANGUAGE "") + set(extra_file "${generatedpath}/${module_basename}${it}") + list(APPEND files "${extra_file}") endforeach() -endmacro() + # Treat extra outputs as plain files regardless of language. + set_source_files_properties(${files} PROPERTIES LANGUAGE "") + + set (${outfiles} ${files} PARENT_SCOPE) +endfunction() # # Take swig (*.i) file and add proper custom commands for it # -macro(SWIG_ADD_SOURCE_TO_MODULE name outfiles infile) - set(swig_full_infile ${infile}) +function(SWIG_ADD_SOURCE_TO_MODULE name outfiles infile) get_filename_component(swig_source_file_name_we "${infile}" NAME_WE) - get_source_file_property(swig_source_file_generated ${infile} GENERATED) - get_source_file_property(swig_source_file_cplusplus ${infile} CPLUSPLUS) - get_source_file_property(swig_source_file_flags ${infile} SWIG_FLAGS) - if("${swig_source_file_flags}" STREQUAL "NOTFOUND") - set(swig_source_file_flags "") - endif() - get_filename_component(swig_source_file_fullname "${infile}" ABSOLUTE) + get_source_file_property(swig_source_file_cplusplus "${infile}" CPLUSPLUS) # If CMAKE_SWIG_OUTDIR was specified then pass it to -outdir if(CMAKE_SWIG_OUTDIR) - set(swig_outdir ${CMAKE_SWIG_OUTDIR}) + set(outdir ${CMAKE_SWIG_OUTDIR}) else() - set(swig_outdir ${CMAKE_CURRENT_BINARY_DIR}) + set(outdir ${CMAKE_CURRENT_BINARY_DIR}) endif() if(SWIG_OUTFILE_DIR) - set(swig_outfile_dir ${SWIG_OUTFILE_DIR}) + set(outfiledir ${SWIG_OUTFILE_DIR}) + else() + set(outfiledir ${outdir}) + endif() + + if(SWIG_WORKING_DIR) + set (workingdir "${SWIG_WORKING_DIR}") else() - set(swig_outfile_dir ${swig_outdir}) + set(workingdir "${outdir}") + endif() + + set (swig_source_file_flags ${CMAKE_SWIG_FLAGS}) + # handle various swig compile flags properties + get_source_file_property (include_directories "${infile}" INCLUDE_DIRECTORIES) + if (include_directories) + list (APPEND swig_source_file_flags "$<$<BOOL:${include_directories}>:-I$<JOIN:${include_directories},$<SEMICOLON>-I>>") + endif() + set (property "$<TARGET_PROPERTY:${name},SWIG_INCLUDE_DIRECTORIES>") + list (APPEND swig_source_file_flags "$<$<BOOL:${property}>:-I$<JOIN:${property},$<SEMICOLON>-I>>") + + set (property "$<TARGET_PROPERTY:${name},SWIG_COMPILE_DEFINITIONS>") + list (APPEND swig_source_file_flags "$<$<BOOL:${property}>:-D$<JOIN:${property},$<SEMICOLON>-D>>") + get_source_file_property (compile_definitions "${infile}" COMPILE_DEFINITIONS) + if (compile_definitions) + list (APPEND swig_source_file_flags "$<$<BOOL:${compile_definitions}>:-D$<JOIN:${compile_definitions},$<SEMICOLON>-D>>") + endif() + + list (APPEND swig_source_file_flags "$<TARGET_PROPERTY:${name},SWIG_COMPILE_OPTIONS>") + get_source_file_property (compile_options "${infile}" COMPILE_OPTIONS) + if (compile_options) + list (APPEND swig_source_file_flags ${compile_options}) endif() + # legacy support + get_source_file_property (swig_flags "${infile}" SWIG_FLAGS) + if (swig_flags) + list (APPEND swig_source_file_flags ${swig_flags}) + endif() + + get_filename_component(swig_source_file_fullname "${infile}" ABSOLUTE) + if (NOT SWIG_MODULE_${name}_NOPROXY) SWIG_GET_EXTRA_OUTPUT_FILES(${SWIG_MODULE_${name}_LANGUAGE} swig_extra_generated_files - "${swig_outdir}" + "${outdir}" "${swig_source_file_fullname}") endif() set(swig_generated_file_fullname - "${swig_outfile_dir}/${swig_source_file_name_we}") + "${outfiledir}/${swig_source_file_name_we}") # add the language into the name of the file (i.e. TCL_wrap) # this allows for the same .i file to be wrapped into different languages string(APPEND swig_generated_file_fullname @@ -188,45 +348,55 @@ macro(SWIG_ADD_SOURCE_TO_MODULE name outfiles infile) ".c") endif() - #message("Full path to source file: ${swig_source_file_fullname}") - #message("Full path to the output file: ${swig_generated_file_fullname}") - get_directory_property(cmake_include_directories INCLUDE_DIRECTORIES) - list(REMOVE_DUPLICATES cmake_include_directories) - set(swig_include_dirs) - foreach(it ${cmake_include_directories}) - set(swig_include_dirs ${swig_include_dirs} "-I${it}") - endforeach() + get_directory_property (cmake_include_directories INCLUDE_DIRECTORIES) + list (REMOVE_DUPLICATES cmake_include_directories) + set (swig_include_dirs) + if (cmake_include_directories) + set (swig_include_dirs "$<$<BOOL:${cmake_include_directories}>:-I$<JOIN:${cmake_include_directories},$<SEMICOLON>-I>>") + endif() set(swig_special_flags) # default is c, so add c++ flag if it is c++ if(swig_source_file_cplusplus) - set(swig_special_flags ${swig_special_flags} "-c++") + list (APPEND swig_special_flags "-c++") endif() - if("x${SWIG_MODULE_${name}_LANGUAGE}" STREQUAL "xCSHARP") - if(NOT ";${swig_source_file_flags};${CMAKE_SWIG_FLAGS};" MATCHES ";-dllimport;") + + set (swig_extra_flags) + if(SWIG_MODULE_${name}_LANGUAGE STREQUAL "CSHARP") + if(NOT ("-dllimport" IN_LIST swig_source_file_flags OR "-dllimport" IN_LIST SWIG_MODULE_${name}_EXTRA_FLAGS)) # This makes sure that the name used in the generated DllImport # matches the library name created by CMake - set(SWIG_MODULE_${name}_EXTRA_FLAGS "-dllimport;${name}") + list (APPEND SWIG_MODULE_${name}_EXTRA_FLAGS "-dllimport" "${name}") endif() endif() - set(swig_extra_flags) - if(SWIG_MODULE_${name}_EXTRA_FLAGS) - set(swig_extra_flags ${swig_extra_flags} ${SWIG_MODULE_${name}_EXTRA_FLAGS}) + list (APPEND swig_extra_flags ${SWIG_MODULE_${name}_EXTRA_FLAGS}) + + # dependencies + set (swig_dependencies ${SWIG_MODULE_${name}_EXTRA_DEPS} $<TARGET_PROPERTY:${name},SWIG_DEPENDS>) + get_source_file_property(file_depends "${infile}" DEPENDS) + if (file_depends) + list (APPEND swig_dependencies ${file_depends}) endif() + + if (UseSWIG_MODULE_VERSION VERSION_GREATER 1) + # as part of custom command, start by removing old generated files + # to ensure obsolete files do not stay + set (swig_cleanup_command COMMAND "${CMAKE_COMMAND}" -E remove_directory "${outdir}") + else() + unset (swig_cleanup_command) + endif() + # IMPLICIT_DEPENDS below can not handle situations where a dependent file is # removed. We need an extra step with timestamp and custom target, see #16830 # As this is needed only for Makefile generator do it conditionally if(CMAKE_GENERATOR MATCHES "Make") - get_filename_component(swig_generated_timestamp - "${swig_generated_file_fullname}" NAME_WE) - set(swig_gen_target gen_${name}_${swig_generated_timestamp}) - set(swig_generated_timestamp - "${swig_outdir}/${swig_generated_timestamp}.stamp") - set(swig_custom_output ${swig_generated_timestamp}) + __swig_compute_timestamp(${name} ${SWIG_MODULE_${name}_LANGUAGE} + "${infile}" "${workingdir}" swig_generated_timestamp) + set(swig_custom_output "${swig_generated_timestamp}") set(swig_custom_products BYPRODUCTS "${swig_generated_file_fullname}" ${swig_extra_generated_files}) set(swig_timestamp_command - COMMAND ${CMAKE_COMMAND} -E touch ${swig_generated_timestamp}) + COMMAND ${CMAKE_COMMAND} -E touch "${swig_generated_timestamp}") else() set(swig_custom_output "${swig_generated_file_fullname}" ${swig_extra_generated_files}) @@ -236,34 +406,42 @@ macro(SWIG_ADD_SOURCE_TO_MODULE name outfiles infile) add_custom_command( OUTPUT ${swig_custom_output} ${swig_custom_products} - # Let's create the ${swig_outdir} at execution time, in case dir contains $(OutDir) - COMMAND ${CMAKE_COMMAND} -E make_directory ${swig_outdir} + ${swig_cleanup_command} + # Let's create the ${outdir} at execution time, in case dir contains $(OutDir) + COMMAND "${CMAKE_COMMAND}" -E make_directory ${outdir} ${outfiledir} ${swig_timestamp_command} - COMMAND "${SWIG_EXECUTABLE}" - ARGS "-${SWIG_MODULE_${name}_SWIG_LANGUAGE_FLAG}" - ${swig_source_file_flags} - ${CMAKE_SWIG_FLAGS} - -outdir ${swig_outdir} + COMMAND "${CMAKE_COMMAND}" -E env "SWIG_LIB=${SWIG_DIR}" "${SWIG_EXECUTABLE}" + "-${SWIG_MODULE_${name}_SWIG_LANGUAGE_FLAG}" + "${swig_source_file_flags}" + -outdir "${outdir}" ${swig_special_flags} ${swig_extra_flags} - ${swig_include_dirs} + "${swig_include_dirs}" -o "${swig_generated_file_fullname}" "${swig_source_file_fullname}" MAIN_DEPENDENCY "${swig_source_file_fullname}" - DEPENDS ${SWIG_MODULE_${name}_EXTRA_DEPS} + DEPENDS ${swig_dependencies} IMPLICIT_DEPENDS CXX "${swig_source_file_fullname}" - COMMENT "Swig source") - if(CMAKE_GENERATOR MATCHES "Make") - add_custom_target(${swig_gen_target} DEPENDS ${swig_generated_timestamp}) - endif() - unset(swig_generated_timestamp) - unset(swig_custom_output) - unset(swig_custom_products) - unset(swig_timestamp_command) + COMMENT "Swig source" + COMMAND_EXPAND_LISTS) set_source_files_properties("${swig_generated_file_fullname}" ${swig_extra_generated_files} PROPERTIES GENERATED 1) - set(${outfiles} "${swig_generated_file_fullname}" ${swig_extra_generated_files}) -endmacro() + + ## add all properties for generated file to various properties + get_property (include_directories SOURCE "${infile}" PROPERTY GENERATED_INCLUDE_DIRECTORIES) + set_property (SOURCE "${swig_generated_file_fullname}" PROPERTY INCLUDE_DIRECTORIES ${include_directories} $<TARGET_PROPERTY:${name},SWIG_GENERATED_INCLUDE_DIRECTORIES>) + + get_property (compile_definitions SOURCE "${infile}" PROPERTY GENERATED_COMPILE_DEFINITIONS) + set_property (SOURCE "${swig_generated_file_fullname}" PROPERTY COMPILE_DEFINITIONS $<TARGET_PROPERTY:${name},SWIG_GENERATED_COMPILE_DEFINITIONS> ${compile_definitions}) + + get_property (compile_options SOURCE "${infile}" PROPERTY GENERATED_COMPILE_OPTIONS) + set_property (SOURCE "${swig_generated_file_fullname}" PROPERTY COMPILE_OPTIONS $<TARGET_PROPERTY:${name},SWIG_GENERATED_COMPILE_OPTIONS> ${compile_options}) + + set(${outfiles} "${swig_generated_file_fullname}" ${swig_extra_generated_files} PARENT_SCOPE) + + # legacy support + set (swig_generated_file_fullname "${swig_generated_file_fullname}" PARENT_SCOPE) +endfunction() # # Create Swig module @@ -277,13 +455,26 @@ macro(SWIG_ADD_MODULE name language) endmacro() -macro(SWIG_ADD_LIBRARY name) - set(options "") +function(SWIG_ADD_LIBRARY name) + set(options NO_PROXY) set(oneValueArgs LANGUAGE - TYPE) + TYPE + OUTPUT_DIR + OUTFILE_DIR) set(multiValueArgs SOURCES) cmake_parse_arguments(_SAM "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN}) + if (TARGET ${name}) + # a target with same name is already defined. + # call NOW add_library command to raise the most useful error message + add_library(${name}) + return() + endif() + + if (_SAM_UNPARSED_ARGUMENTS) + message(FATAL_ERROR "SWIG_ADD_LIBRARY: ${_SAM_UNPARSED_ARGUMENTS}: unexpected arguments") + endif() + if(NOT DEFINED _SAM_LANGUAGE) message(FATAL_ERROR "SWIG_ADD_LIBRARY: Missing LANGUAGE argument") endif() @@ -294,66 +485,123 @@ macro(SWIG_ADD_LIBRARY name) if(NOT DEFINED _SAM_TYPE) set(_SAM_TYPE MODULE) - elseif("${_SAM_TYPE}" STREQUAL "USE_BUILD_SHARED_LIBS") + elseif(_SAM_TYPE STREQUAL "USE_BUILD_SHARED_LIBS") unset(_SAM_TYPE) endif() - swig_module_initialize(${name} ${_SAM_LANGUAGE}) + if (NOT DEFINED UseSWIG_MODULE_VERSION) + set (UseSWIG_MODULE_VERSION 1) + elseif (NOT UseSWIG_MODULE_VERSION MATCHES "^(1|2)$") + message (FATAL_ERROR "UseSWIG_MODULE_VERSION: ${UseSWIG_MODULE_VERSION}: invalid value. 1 or 2 is expected.") + endif() - set(swig_dot_i_sources) - set(swig_other_sources) - foreach(it ${_SAM_SOURCES}) - if(${it} MATCHES "\\.i$") - set(swig_dot_i_sources ${swig_dot_i_sources} "${it}") + set (workingdir "${CMAKE_CURRENT_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/${name}.dir") + # set special variable to pass extra information to command SWIG_ADD_SOURCE_TO_MODULE + # which cannot be changed due to legacy compatibility + set (SWIG_WORKING_DIR "${workingdir}") + + set (outputdir "${_SAM_OUTPUT_DIR}") + if (NOT _SAM_OUTPUT_DIR) + if (CMAKE_SWIG_OUTDIR) + set (outputdir "${CMAKE_SWIG_OUTDIR}") else() - set(swig_other_sources ${swig_other_sources} "${it}") + if (UseSWIG_MODULE_VERSION VERSION_GREATER 1) + set (outputdir "${workingdir}/${_SAM_LANGUAGE}.files") + else() + set (outputdir "${CMAKE_CURRENT_BINARY_DIR}") + endif() endif() - endforeach() + endif() + + set (outfiledir "${_SAM_OUTFILE_DIR}") + if(NOT _SAM_OUTFILE_DIR) + if (SWIG_OUTFILE_DIR) + set (outfiledir "${SWIG_OUTFILE_DIR}") + else() + if (_SAM_OUTPUT_DIR OR CMAKE_SWIG_OUTDIR) + set (outfiledir "${outputdir}") + else() + set (outfiledir "${workingdir}") + endif() + endif() + endif() + # set again, locally, predefined variables to ensure compatibility + # with command SWIG_ADD_SOURCE_TO_MODULE + set(CMAKE_SWIG_OUTDIR "${outputdir}") + set(SWIG_OUTFILE_DIR "${outfiledir}") + + set (SWIG_MODULE_${name}_NOPROXY ${_SAM_NO_PROXY}) + swig_module_initialize(${name} ${_SAM_LANGUAGE}) + + set(swig_dot_i_sources ${_SAM_SOURCES}) + list(FILTER swig_dot_i_sources INCLUDE REGEX "\\.i$") + if (NOT swig_dot_i_sources) + message(FATAL_ERROR "SWIG_ADD_LIBRARY: no SWIG interface files specified") + endif() + set(swig_other_sources ${_SAM_SOURCES}) + list(REMOVE_ITEM swig_other_sources ${swig_dot_i_sources}) set(swig_generated_sources) - set(swig_generated_targets) - foreach(it ${swig_dot_i_sources}) - SWIG_ADD_SOURCE_TO_MODULE(${name} swig_generated_source ${it}) - set(swig_generated_sources ${swig_generated_sources} "${swig_generated_source}") - list(APPEND swig_generated_targets "${swig_gen_target}") + set(swig_generated_timestamps) + foreach(swig_it IN LISTS swig_dot_i_sources) + SWIG_ADD_SOURCE_TO_MODULE(${name} swig_generated_source "${swig_it}") + list (APPEND swig_generated_sources "${swig_generated_source}") + if(CMAKE_GENERATOR MATCHES "Make") + __swig_compute_timestamp(${name} ${SWIG_MODULE_${name}_LANGUAGE} "${swig_it}" + "${workingdir}" swig_timestamp) + list (APPEND swig_generated_timestamps "${swig_timestamp}") + endif() endforeach() - get_directory_property(swig_extra_clean_files ADDITIONAL_MAKE_CLEAN_FILES) - set_directory_properties(PROPERTIES - ADDITIONAL_MAKE_CLEAN_FILES "${swig_extra_clean_files};${swig_generated_sources}") - add_library(${SWIG_MODULE_${name}_REAL_NAME} + set_property (DIRECTORY APPEND PROPERTY + ADDITIONAL_MAKE_CLEAN_FILES ${swig_generated_sources} ${swig_generated_timestamps}) + if (UseSWIG_MODULE_VERSION VERSION_GREATER 1) + set_property (DIRECTORY APPEND PROPERTY ADDITIONAL_MAKE_CLEAN_FILES "${outputdir}") + endif() + + add_library(${name} ${_SAM_TYPE} ${swig_generated_sources} ${swig_other_sources}) if(CMAKE_GENERATOR MATCHES "Make") # see IMPLICIT_DEPENDS above - add_dependencies(${SWIG_MODULE_${name}_REAL_NAME} ${swig_generated_targets}) + add_custom_target(${name}_swig_compilation DEPENDS ${swig_generated_timestamps}) + add_dependencies(${name} ${name}_swig_compilation) endif() - if("${_SAM_TYPE}" STREQUAL "MODULE") - set_target_properties(${SWIG_MODULE_${name}_REAL_NAME} PROPERTIES NO_SONAME ON) + if(_SAM_TYPE STREQUAL "MODULE") + set_target_properties(${name} PROPERTIES NO_SONAME ON) endif() string(TOLOWER "${_SAM_LANGUAGE}" swig_lowercase_language) - if ("${swig_lowercase_language}" STREQUAL "octave") - set_target_properties(${SWIG_MODULE_${name}_REAL_NAME} PROPERTIES PREFIX "") - set_target_properties(${SWIG_MODULE_${name}_REAL_NAME} PROPERTIES SUFFIX ".oct") - elseif ("${swig_lowercase_language}" STREQUAL "go") - set_target_properties(${SWIG_MODULE_${name}_REAL_NAME} PROPERTIES PREFIX "") - elseif ("${swig_lowercase_language}" STREQUAL "java") + if (swig_lowercase_language STREQUAL "octave") + set_target_properties(${name} PROPERTIES PREFIX "") + set_target_properties(${name} PROPERTIES SUFFIX ".oct") + elseif (swig_lowercase_language STREQUAL "go") + set_target_properties(${name} PROPERTIES PREFIX "") + elseif (swig_lowercase_language STREQUAL "java") + # In java you want: + # System.loadLibrary("LIBRARY"); + # then JNI will look for a library whose name is platform dependent, namely + # MacOS : libLIBRARY.jnilib + # Windows: LIBRARY.dll + # Linux : libLIBRARY.so if (APPLE) - # In java you want: - # System.loadLibrary("LIBRARY"); - # then JNI will look for a library whose name is platform dependent, namely - # MacOS : libLIBRARY.jnilib - # Windows: LIBRARY.dll - # Linux : libLIBRARY.so - set_target_properties (${SWIG_MODULE_${name}_REAL_NAME} PROPERTIES SUFFIX ".jnilib") - endif () - elseif ("${swig_lowercase_language}" STREQUAL "lua") - if("${_SAM_TYPE}" STREQUAL "MODULE") - set_target_properties(${SWIG_MODULE_${name}_REAL_NAME} PROPERTIES PREFIX "") + set_target_properties (${name} PROPERTIES SUFFIX ".jnilib") + endif() + if ((WIN32 AND MINGW) OR CYGWIN OR CMAKE_SYSTEM_NAME STREQUAL MSYS) + set_target_properties(${name} PROPERTIES PREFIX "") + endif() + elseif (swig_lowercase_language STREQUAL "lua") + if(_SAM_TYPE STREQUAL "MODULE") + set_target_properties(${name} PROPERTIES PREFIX "") + endif() + elseif (swig_lowercase_language STREQUAL "python") + if (SWIG_MODULE_${name}_NOPROXY) + set_target_properties(${name} PROPERTIES PREFIX "") + else() + # swig will produce a module.py containing an 'import _modulename' statement, + # which implies having a corresponding _modulename.so (*NIX), _modulename.pyd (Win32), + # unless the -noproxy flag is used + set_target_properties(${name} PROPERTIES PREFIX "_") endif() - elseif ("${swig_lowercase_language}" STREQUAL "python") - # this is only needed for the python case where a _modulename.so is generated - set_target_properties(${SWIG_MODULE_${name}_REAL_NAME} PROPERTIES PREFIX "") # Python extension modules on Windows must have the extension ".pyd" # instead of ".dll" as of Python 2.5. Older python versions do support # this suffix. @@ -363,34 +611,68 @@ macro(SWIG_ADD_LIBRARY name) # .pyd is now the only filename extension that will be searched for. # </quote> if(WIN32 AND NOT CYGWIN) - set_target_properties(${SWIG_MODULE_${name}_REAL_NAME} PROPERTIES SUFFIX ".pyd") + set_target_properties(${name} PROPERTIES SUFFIX ".pyd") endif() - elseif ("${swig_lowercase_language}" STREQUAL "r") - set_target_properties(${SWIG_MODULE_${name}_REAL_NAME} PROPERTIES PREFIX "") - elseif ("${swig_lowercase_language}" STREQUAL "ruby") + elseif (swig_lowercase_language STREQUAL "r") + set_target_properties(${name} PROPERTIES PREFIX "") + elseif (swig_lowercase_language STREQUAL "ruby") # In ruby you want: # require 'LIBRARY' # then ruby will look for a library whose name is platform dependent, namely # MacOS : LIBRARY.bundle # Windows: LIBRARY.dll # Linux : LIBRARY.so - set_target_properties (${SWIG_MODULE_${name}_REAL_NAME} PROPERTIES PREFIX "") + set_target_properties (${name} PROPERTIES PREFIX "") + if (APPLE) + set_target_properties (${name} PROPERTIES SUFFIX ".bundle") + endif () + elseif (swig_lowercase_language STREQUAL "perl") + # assume empty prefix because we expect the module to be dynamically loaded + set_target_properties (${name} PROPERTIES PREFIX "") if (APPLE) - set_target_properties (${SWIG_MODULE_${name}_REAL_NAME} PROPERTIES SUFFIX ".bundle") + set_target_properties (${name} PROPERTIES SUFFIX ".dylib") endif () else() # assume empty prefix because we expect the module to be dynamically loaded - set_target_properties (${SWIG_MODULE_${name}_REAL_NAME} PROPERTIES PREFIX "") + set_target_properties (${name} PROPERTIES PREFIX "") endif () -endmacro() + + # target property SWIG_SUPPORT_FILES_DIRECTORY specify output directory of support files + set_property (TARGET ${name} PROPERTY SWIG_SUPPORT_FILES_DIRECTORY "${outputdir}") + # target property SWIG_SUPPORT_FILES lists principal proxy support files + if (NOT SWIG_MODULE_${name}_NOPROXY) + string(TOUPPER "${_SAM_LANGUAGE}" swig_uppercase_language) + set(swig_all_support_files) + foreach (swig_it IN LISTS SWIG_${swig_uppercase_language}_EXTRA_FILE_EXTENSIONS) + set (swig_support_files ${swig_generated_sources}) + list (FILTER swig_support_files INCLUDE REGEX ".*${swig_it}$") + list(APPEND swig_all_support_files ${swig_support_files}) + endforeach() + if (swig_all_support_files) + list(REMOVE_DUPLICATES swig_all_support_files) + endif() + set_property (TARGET ${name} PROPERTY SWIG_SUPPORT_FILES ${swig_all_support_files}) + endif() + + # to ensure legacy behavior, export some variables + set (SWIG_MODULE_${name}_LANGUAGE "${SWIG_MODULE_${name}_LANGUAGE}" PARENT_SCOPE) + set (SWIG_MODULE_${name}_SWIG_LANGUAGE_FLAG "${SWIG_MODULE_${name}_SWIG_LANGUAGE_FLAG}" PARENT_SCOPE) + set (SWIG_MODULE_${name}_REAL_NAME "${name}" PARENT_SCOPE) + set (SWIG_MODULE_${name}_NOPROXY "${SWIG_MODULE_${name}_NOPROXY}" PARENT_SCOPE) + set (SWIG_MODULE_${name}_EXTRA_FLAGS "${SWIG_MODULE_${name}_EXTRA_FLAGS}" PARENT_SCOPE) + # the last one is a bit crazy but it is documented, so... + # NOTA: works as expected if only ONE input file is specified + set (swig_generated_file_fullname "${swig_generated_file_fullname}" PARENT_SCOPE) +endfunction() # # Like TARGET_LINK_LIBRARIES but for swig modules # -macro(SWIG_LINK_LIBRARIES name) +function(SWIG_LINK_LIBRARIES name) + message(DEPRECATION "SWIG_LINK_LIBRARIES is deprecated. Use TARGET_LINK_LIBRARIES instead.") if(SWIG_MODULE_${name}_REAL_NAME) - target_link_libraries(${SWIG_MODULE_${name}_REAL_NAME} ${ARGN}) + target_link_libraries(${name} ${ARGN}) else() message(SEND_ERROR "Cannot find Swig library \"${name}\".") endif() -endmacro() +endfunction() diff --git a/Modules/WriteCompilerDetectionHeader.cmake b/Modules/WriteCompilerDetectionHeader.cmake index e7f9912..3718e9d 100644 --- a/Modules/WriteCompilerDetectionHeader.cmake +++ b/Modules/WriteCompilerDetectionHeader.cmake @@ -17,6 +17,7 @@ # [OUTPUT_FILES_VAR <output_files_var> OUTPUT_DIR <output_dir>] # COMPILERS <compiler> [...] # FEATURES <feature> [...] +# [BARE_FEATURES <feature> [...]] # [VERSION <version>] # [PROLOG <prolog>] # [EPILOG <epilog>] @@ -83,10 +84,14 @@ # See the :manual:`cmake-compile-features(7)` manual for information on # compile features. # +# ``BARE_FEATURES`` will define the compatibility macros with the name used in +# newer versions of the language standard, so the code can use the new feature +# name unconditionally. +# # ``ALLOW_UNKNOWN_COMPILERS`` and ``ALLOW_UNKNOWN_COMPILER_VERSIONS`` cause # the module to generate conditions that treat unknown compilers as simply # lacking all features. Without these options the default behavior is to -# generate a ``#error`` for unknown compilers. +# generate a ``#error`` for unknown compilers and versions. # # Feature Test Macros # =================== @@ -148,20 +153,24 @@ # ``ClimbingStats_CONSTEXPR`` macro will expand to ``constexpr`` # if ``cxx_constexpr`` is supported. # -# The following features generate corresponding symbol defines: +# If ``BARE_FEATURES cxx_final`` was given as argument the ``final`` keyword +# will be defined for old compilers, too. +# +# The following features generate corresponding symbol defines and if they +# are available as ``BARE_FEATURES``: # -# ========================== =================================== ================= -# Feature Define Symbol -# ========================== =================================== ================= -# ``c_restrict`` ``<PREFIX>_RESTRICT`` ``restrict`` -# ``cxx_constexpr`` ``<PREFIX>_CONSTEXPR`` ``constexpr`` +# ========================== =================================== ================= ====== +# Feature Define Symbol bare +# ========================== =================================== ================= ====== +# ``c_restrict`` ``<PREFIX>_RESTRICT`` ``restrict`` yes +# ``cxx_constexpr`` ``<PREFIX>_CONSTEXPR`` ``constexpr`` yes # ``cxx_deleted_functions`` ``<PREFIX>_DELETED_FUNCTION`` ``= delete`` # ``cxx_extern_templates`` ``<PREFIX>_EXTERN_TEMPLATE`` ``extern`` -# ``cxx_final`` ``<PREFIX>_FINAL`` ``final`` -# ``cxx_noexcept`` ``<PREFIX>_NOEXCEPT`` ``noexcept`` +# ``cxx_final`` ``<PREFIX>_FINAL`` ``final`` yes +# ``cxx_noexcept`` ``<PREFIX>_NOEXCEPT`` ``noexcept`` yes # ``cxx_noexcept`` ``<PREFIX>_NOEXCEPT_EXPR(X)`` ``noexcept(X)`` -# ``cxx_override`` ``<PREFIX>_OVERRIDE`` ``override`` -# ========================== =================================== ================= +# ``cxx_override`` ``<PREFIX>_OVERRIDE`` ``override`` yes +# ========================== =================================== ================= ====== # # Compatibility Implementation Macros # =================================== @@ -195,18 +204,18 @@ # decorator or a compiler-specific decorator such as ``__alignof__`` # used by GNU compilers. # -# ============================= ================================ ===================== -# Feature Define Symbol -# ============================= ================================ ===================== +# ============================= ================================ ===================== ====== +# Feature Define Symbol bare +# ============================= ================================ ===================== ====== # ``cxx_alignas`` ``<PREFIX>_ALIGNAS`` ``alignas`` # ``cxx_alignof`` ``<PREFIX>_ALIGNOF`` ``alignof`` -# ``cxx_nullptr`` ``<PREFIX>_NULLPTR`` ``nullptr`` +# ``cxx_nullptr`` ``<PREFIX>_NULLPTR`` ``nullptr`` yes # ``cxx_static_assert`` ``<PREFIX>_STATIC_ASSERT`` ``static_assert`` # ``cxx_static_assert`` ``<PREFIX>_STATIC_ASSERT_MSG`` ``static_assert`` # ``cxx_attribute_deprecated`` ``<PREFIX>_DEPRECATED`` ``[[deprecated]]`` # ``cxx_attribute_deprecated`` ``<PREFIX>_DEPRECATED_MSG`` ``[[deprecated]]`` # ``cxx_thread_local`` ``<PREFIX>_THREAD_LOCAL`` ``thread_local`` -# ============================= ================================ ===================== +# ============================= ================================ ===================== ====== # # A use-case which arises with such deprecation macros is the deprecation # of an entire library. In that case, all public API in the library may @@ -252,6 +261,37 @@ macro(_simpledefine FEATURE_NAME FEATURE_TESTNAME FEATURE_STRING FEATURE_DEFAULT endif() endmacro() +macro(_simplebaredefine FEATURE_NAME FEATURE_STRING FEATURE_DEFAULT_STRING) + if (feature STREQUAL "${FEATURE_NAME}") + string(APPEND file_content " +# if !(defined(${def_name}) && ${def_name}) +# define ${FEATURE_STRING} ${FEATURE_DEFAULT_STRING} +# endif +\n") + endif() +endmacro() + +function(_check_feature_lists C_FEATURE_VAR CXX_FEATURE_VAR) + foreach(feature ${ARGN}) + if (feature MATCHES "^c_std_") + # ignored + elseif (feature MATCHES "^cxx_std_") + # ignored + elseif (feature MATCHES "^cxx_") + list(APPEND _langs CXX) + list(APPEND ${CXX_FEATURE_VAR} ${feature}) + elseif (feature MATCHES "^c_") + list(APPEND _langs C) + list(APPEND ${C_FEATURE_VAR} ${feature}) + else() + message(FATAL_ERROR "Unsupported feature ${feature}.") + endif() + endforeach() + set(${C_FEATURE_VAR} ${${C_FEATURE_VAR}} PARENT_SCOPE) + set(${CXX_FEATURE_VAR} ${${CXX_FEATURE_VAR}} PARENT_SCOPE) + set(_langs ${_langs} PARENT_SCOPE) +endfunction() + function(write_compiler_detection_header file_keyword file_arg prefix_keyword prefix_arg @@ -264,13 +304,13 @@ function(write_compiler_detection_header endif() set(options ALLOW_UNKNOWN_COMPILERS ALLOW_UNKNOWN_COMPILER_VERSIONS) set(oneValueArgs VERSION EPILOG PROLOG OUTPUT_FILES_VAR OUTPUT_DIR) - set(multiValueArgs COMPILERS FEATURES) + set(multiValueArgs COMPILERS FEATURES BARE_FEATURES) cmake_parse_arguments(_WCD "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN}) if (NOT _WCD_COMPILERS) message(FATAL_ERROR "Invalid arguments. write_compiler_detection_header requires at least one compiler.") endif() - if (NOT _WCD_FEATURES) + if (NOT _WCD_FEATURES AND NOT _WCD_BARE_FEATURES) message(FATAL_ERROR "Invalid arguments. write_compiler_detection_header requires at least one feature.") endif() @@ -377,21 +417,8 @@ function(write_compiler_detection_header )\n") endif() - foreach(feature ${_WCD_FEATURES}) - if (feature MATCHES "^c_std_") - # ignored - elseif (feature MATCHES "^cxx_std_") - # ignored - elseif (feature MATCHES "^cxx_") - list(APPEND _langs CXX) - list(APPEND CXX_features ${feature}) - elseif (feature MATCHES "^c_") - list(APPEND _langs C) - list(APPEND C_features ${feature}) - else() - message(FATAL_ERROR "Unsupported feature ${feature}.") - endif() - endforeach() + _check_feature_lists(C_features CXX_features ${_WCD_FEATURES}) + _check_feature_lists(C_bare_features CXX_bare_features ${_WCD_BARE_FEATURES}) list(REMOVE_DUPLICATES _langs) if(_WCD_OUTPUT_FILES_VAR) @@ -557,7 +584,18 @@ template<> struct ${prefix_arg}StaticAssert<true>{}; # endif \n") endif() - _simpledefine(cxx_nullptr NULLPTR nullptr 0) + if (feature STREQUAL cxx_nullptr) + set(def_value "${prefix_arg}_NULLPTR") + string(APPEND file_content " +# if defined(${def_name}) && ${def_name} +# define ${def_value} nullptr +# elif ${prefix_arg}_COMPILER_IS_GNU +# define ${def_value} __null +# else +# define ${def_value} 0 +# endif +\n") + endif() if (feature STREQUAL cxx_thread_local) set(def_value "${prefix_arg}_THREAD_LOCAL") string(APPEND file_content " @@ -595,6 +633,29 @@ template<> struct ${prefix_arg}StaticAssert<true>{}; endif() endforeach() + foreach(feature ${${_lang}_bare_features}) + string(TOUPPER ${feature} feature_upper) + set(feature_PP "COMPILER_${feature_upper}") + set(def_name ${prefix_arg}_${feature_PP}) + _simplebaredefine(c_restrict restrict "") + _simplebaredefine(cxx_constexpr constexpr "") + _simplebaredefine(cxx_final final "") + _simplebaredefine(cxx_override override "") + if (feature STREQUAL cxx_nullptr) + set(def_value "nullptr") + string(APPEND file_content " +# if !(defined(${def_name}) && ${def_name}) +# if ${prefix_arg}_COMPILER_IS_GNU +# define ${def_value} __null +# else +# define ${def_value} 0 +# endif +# endif +\n") + endif() + _simplebaredefine(cxx_noexcept noexcept "") + endforeach() + string(APPEND file_content "#endif\n") endforeach() diff --git a/Source/CMakeLists.txt b/Source/CMakeLists.txt index a0010a2..d9e07e5 100644 --- a/Source/CMakeLists.txt +++ b/Source/CMakeLists.txt @@ -131,6 +131,8 @@ set(SRCS LexerParser/cmListFileLexer.c LexerParser/cmListFileLexer.in.l + cmAffinity.cxx + cmAffinity.h cmArchiveWrite.cxx cmBase32.cxx cmCacheManager.cxx @@ -244,6 +246,8 @@ set(SRCS cmGlobalGeneratorFactory.h cmGlobalUnixMakefileGenerator3.cxx cmGlobalUnixMakefileGenerator3.h + cmGlobVerificationManager.cxx + cmGlobVerificationManager.h cmGraphAdjacencyList.h cmGraphVizWriter.cxx cmGraphVizWriter.h @@ -371,6 +375,8 @@ set(SRCS cmCommand.h cmCommands.cxx cmCommands.h + cmAddCompileDefinitionsCommand.cxx + cmAddCompileDefinitionsCommand.h cmAddCompileOptionsCommand.cxx cmAddCompileOptionsCommand.h cmAddCustomCommandCommand.cxx @@ -553,6 +559,7 @@ set(SRCS cmSiteNameCommand.h cmSourceGroupCommand.cxx cmSourceGroupCommand.h + cmStringReplaceHelper.cxx cmStringCommand.cxx cmStringCommand.h cmSubdirCommand.cxx diff --git a/Source/CMakeVersion.cmake b/Source/CMakeVersion.cmake index b69c125..785cb92 100644 --- a/Source/CMakeVersion.cmake +++ b/Source/CMakeVersion.cmake @@ -1,5 +1,5 @@ # CMake version number components. set(CMake_VERSION_MAJOR 3) set(CMake_VERSION_MINOR 11) -set(CMake_VERSION_PATCH 1) -#set(CMake_VERSION_RC 0) +set(CMake_VERSION_PATCH 20180426) +#set(CMake_VERSION_RC 1) diff --git a/Source/CMakeVersionCompute.cmake b/Source/CMakeVersionCompute.cmake index 79264ed..72a5800 100644 --- a/Source/CMakeVersionCompute.cmake +++ b/Source/CMakeVersionCompute.cmake @@ -32,7 +32,12 @@ endif() # components in the RC file are 16-bit integers so we may have to # split the patch component. if(CMake_VERSION_PATCH MATCHES "^([0-9]+)([0-9][0-9][0-9][0-9])$") - set(CMake_RCVERSION ${CMake_VERSION_MAJOR},${CMake_VERSION_MINOR},${CMAKE_MATCH_1},${CMAKE_MATCH_2}) + set(CMake_RCVERSION_YEAR "${CMAKE_MATCH_1}") + set(CMake_RCVERSION_MONTH_DAY "${CMAKE_MATCH_2}") + string(REGEX REPLACE "^0+" "" CMake_RCVERSION_MONTH_DAY "${CMake_RCVERSION_MONTH_DAY}") + set(CMake_RCVERSION ${CMake_VERSION_MAJOR},${CMake_VERSION_MINOR},${CMake_RCVERSION_YEAR},${CMake_RCVERSION_MONTH_DAY}) + unset(CMake_RCVERSION_MONTH_DAY) + unset(CMake_RCVERSION_YEAR) else() set(CMake_RCVERSION ${CMake_VERSION_MAJOR},${CMake_VERSION_MINOR},${CMake_VERSION_PATCH}) endif() diff --git a/Source/CPack/cmCPackArchiveGenerator.cxx b/Source/CPack/cmCPackArchiveGenerator.cxx index 9ff547a..00fbdab 100644 --- a/Source/CPack/cmCPackArchiveGenerator.cxx +++ b/Source/CPack/cmCPackArchiveGenerator.cxx @@ -9,6 +9,7 @@ #include "cmSystemTools.h" #include "cmWorkingDirectory.h" +#include <cstring> #include <ostream> #include <utility> #include <vector> @@ -51,6 +52,7 @@ int cmCPackArchiveGenerator::InitializeInternal() this->SetOptionIfNotSet("CPACK_INCLUDE_TOPLEVEL_DIRECTORY", "1"); return this->Superclass::InitializeInternal(); } + int cmCPackArchiveGenerator::addOneComponentToArchive( cmArchiveWrite& archive, cmCPackComponent* component) { @@ -61,6 +63,13 @@ int cmCPackArchiveGenerator::addOneComponentToArchive( localToplevel += "/" + component->Name; // Change to local toplevel cmWorkingDirectory workdir(localToplevel); + if (workdir.Failed()) { + cmCPackLogger(cmCPackLog::LOG_ERROR, + "Failed to change working directory to " + << localToplevel << " : " + << std::strerror(workdir.GetLastResult()) << std::endl); + return 0; + } std::string filePrefix; if (this->IsOn("CPACK_COMPONENT_INCLUDE_TOPLEVEL_DIRECTORY")) { filePrefix = this->GetOption("CPACK_PACKAGE_FILE_NAME"); @@ -237,6 +246,13 @@ int cmCPackArchiveGenerator::PackageFiles() // CASE 3 : NON COMPONENT package. DECLARE_AND_OPEN_ARCHIVE(packageFileNames[0], archive); cmWorkingDirectory workdir(toplevel); + if (workdir.Failed()) { + cmCPackLogger(cmCPackLog::LOG_ERROR, + "Failed to change working directory to " + << toplevel << " : " + << std::strerror(workdir.GetLastResult()) << std::endl); + return 0; + } for (std::string const& file : files) { // Get the relative path to the file std::string rp = cmSystemTools::RelativePath(toplevel, file); diff --git a/Source/CPack/cmCPackGenerator.cxx b/Source/CPack/cmCPackGenerator.cxx index d838b30..64aba10 100644 --- a/Source/CPack/cmCPackGenerator.cxx +++ b/Source/CPack/cmCPackGenerator.cxx @@ -6,6 +6,7 @@ #include "cmsys/Glob.hxx" #include "cmsys/RegularExpression.hxx" #include <algorithm> +#include <cstring> #include <memory> // IWYU pragma: keep #include <utility> @@ -404,6 +405,13 @@ int cmCPackGenerator::InstallProjectViaInstalledDirectories( cmCPackLogger(cmCPackLog::LOG_DEBUG, "Change dir to: " << goToDir << std::endl); cmWorkingDirectory workdir(goToDir); + if (workdir.Failed()) { + cmCPackLogger( + cmCPackLog::LOG_ERROR, "Failed to change working directory to " + << goToDir << " : " << std::strerror(workdir.GetLastResult()) + << std::endl); + return 0; + } for (auto const& symlinked : symlinkedFiles) { cmCPackLogger(cmCPackLog::LOG_DEBUG, "Will create a symlink: " << symlinked.second << "--> " << symlinked.first @@ -994,7 +1002,8 @@ int cmCPackGenerator::DoPackage() { // scope that enables package generators to run internal scripts with // latest CMake policies enabled cmMakefile::ScopePushPop pp{ this->MakefileMap }; - this->MakefileMap->SetPolicyVersion(cmVersion::GetCMakeVersion()); + this->MakefileMap->SetPolicyVersion(cmVersion::GetCMakeVersion(), + std::string()); if (!this->PackageFiles() || cmSystemTools::GetErrorOccuredFlag()) { cmCPackLogger(cmCPackLog::LOG_ERROR, "Problem compressing the directory" diff --git a/Source/CTest/cmCTestBuildAndTestHandler.cxx b/Source/CTest/cmCTestBuildAndTestHandler.cxx index 2e1ea4c..b2c68e7 100644 --- a/Source/CTest/cmCTestBuildAndTestHandler.cxx +++ b/Source/CTest/cmCTestBuildAndTestHandler.cxx @@ -11,6 +11,7 @@ #include "cmsys/Process.h" #include <chrono> +#include <cstring> #include <ratio> #include <stdlib.h> @@ -196,6 +197,16 @@ int cmCTestBuildAndTestHandler::RunCMakeAndTest(std::string* outstring) cmSystemTools::MakeDirectory(this->BinaryDir); } cmWorkingDirectory workdir(this->BinaryDir); + if (workdir.Failed()) { + auto msg = "Failed to change working directory to " + this->BinaryDir + + " : " + std::strerror(workdir.GetLastResult()) + "\n"; + if (outstring) { + *outstring = msg; + } else { + cmCTestLog(this->CTest, ERROR_MESSAGE, msg); + } + return 1; + } if (this->BuildNoCMake) { // Make the generator available for the Build call below. @@ -307,7 +318,16 @@ int cmCTestBuildAndTestHandler::RunCMakeAndTest(std::string* outstring) // run the test from the this->BuildRunDir if set if (!this->BuildRunDir.empty()) { out << "Run test in directory: " << this->BuildRunDir << "\n"; - cmSystemTools::ChangeDirectory(this->BuildRunDir); + if (!workdir.SetDirectory(this->BuildRunDir)) { + out << "Failed to change working directory : " + << std::strerror(workdir.GetLastResult()) << "\n"; + if (outstring) { + *outstring = out.str(); + } else { + cmCTestLog(this->CTest, ERROR_MESSAGE, out.str()); + } + return 1; + } } out << "Running test command: \"" << fullPath << "\""; for (std::string const& testCommandArg : this->TestCommandArgs) { diff --git a/Source/CTest/cmCTestCoverageHandler.cxx b/Source/CTest/cmCTestCoverageHandler.cxx index 9c66e73..bafbe9a 100644 --- a/Source/CTest/cmCTestCoverageHandler.cxx +++ b/Source/CTest/cmCTestCoverageHandler.cxx @@ -23,6 +23,7 @@ #include "cmsys/RegularExpression.hxx" #include <algorithm> #include <chrono> +#include <cstring> #include <iomanip> #include <iterator> #include <sstream> @@ -927,7 +928,8 @@ int cmCTestCoverageHandler::HandleGCovCoverage( std::string gcovCommand = this->CTest->GetCTestConfiguration("CoverageCommand"); if (gcovCommand.empty()) { - cmCTestLog(this->CTest, WARNING, "Could not find gcov." << std::endl); + cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT, + "Could not find gcov." << std::endl, this->Quiet); return 0; } std::string gcovExtraFlags = @@ -975,7 +977,12 @@ int cmCTestCoverageHandler::HandleGCovCoverage( std::string testingDir = this->CTest->GetBinaryDir() + "/Testing"; std::string tempDir = testingDir + "/CoverageInfo"; - cmSystemTools::MakeDirectory(tempDir); + if (!cmSystemTools::MakeDirectory(tempDir)) { + cmCTestLog(this->CTest, ERROR_MESSAGE, + "Unable to make directory: " << tempDir << std::endl); + cont->Error++; + return 0; + } cmWorkingDirectory workdir(tempDir); int gcovStyle = 0; @@ -1376,6 +1383,14 @@ int cmCTestCoverageHandler::HandleLCovCoverage( this->Quiet); std::string fileDir = cmSystemTools::GetFilenamePath(f); cmWorkingDirectory workdir(fileDir); + if (workdir.Failed()) { + cmCTestLog(this->CTest, ERROR_MESSAGE, + "Unable to change working directory to " + << fileDir << " : " + << std::strerror(workdir.GetLastResult()) << std::endl); + cont->Error++; + continue; + } cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT, "Current coverage dir: " << fileDir << std::endl, @@ -1600,6 +1615,12 @@ bool cmCTestCoverageHandler::FindLCovFiles(std::vector<std::string>& files) gl.RecurseThroughSymlinksOff(); std::string buildDir = this->CTest->GetCTestConfiguration("BuildDirectory"); cmWorkingDirectory workdir(buildDir); + if (workdir.Failed()) { + cmCTestLog(this->CTest, ERROR_MESSAGE, + "Unable to change working directory to " << buildDir + << std::endl); + return false; + } // Run profmerge to merge all *.dyn files into dpi files if (!cmSystemTools::RunSingleCommand("profmerge")) { diff --git a/Source/CTest/cmCTestCurl.h b/Source/CTest/cmCTestCurl.h index 427a392..86d9489 100644 --- a/Source/CTest/cmCTestCurl.h +++ b/Source/CTest/cmCTestCurl.h @@ -16,7 +16,7 @@ class cmCTestCurl public: cmCTestCurl(cmCTest*); ~cmCTestCurl(); - bool UploadFile(std::string const& url, std::string const& file, + bool UploadFile(std::string const& local_file, std::string const& url, std::string const& fields, std::string& response); bool HttpRequest(std::string const& url, std::string const& fields, std::string& response); diff --git a/Source/CTest/cmCTestHandlerCommand.cxx b/Source/CTest/cmCTestHandlerCommand.cxx index 5a7baf5..1fff2fa 100644 --- a/Source/CTest/cmCTestHandlerCommand.cxx +++ b/Source/CTest/cmCTestHandlerCommand.cxx @@ -9,6 +9,7 @@ #include "cmWorkingDirectory.h" #include "cmake.h" +#include <cstring> #include <sstream> #include <stdlib.h> @@ -218,6 +219,21 @@ bool cmCTestHandlerCommand::InitialPass(std::vector<std::string> const& args, } cmWorkingDirectory workdir( this->CTest->GetCTestConfiguration("BuildDirectory")); + if (workdir.Failed()) { + this->SetError("failed to change directory to " + + this->CTest->GetCTestConfiguration("BuildDirectory") + + " : " + std::strerror(workdir.GetLastResult())); + if (capureCMakeError) { + this->Makefile->AddDefinition(this->Values[ct_CAPTURE_CMAKE_ERROR], + "-1"); + cmCTestLog(this->CTest, ERROR_MESSAGE, this->GetName() + << " " << this->GetError() << "\n"); + // return success because failure is recorded in CAPTURE_CMAKE_ERROR + return true; + } + return false; + } + int res = handler->ProcessHandler(); if (this->Values[ct_RETURN_VALUE] && *this->Values[ct_RETURN_VALUE]) { std::ostringstream str; diff --git a/Source/CTest/cmCTestMultiProcessHandler.cxx b/Source/CTest/cmCTestMultiProcessHandler.cxx index 50c2d86..14b5caa 100644 --- a/Source/CTest/cmCTestMultiProcessHandler.cxx +++ b/Source/CTest/cmCTestMultiProcessHandler.cxx @@ -2,6 +2,7 @@ file Copyright.txt or https://cmake.org/licensing for details. */ #include "cmCTestMultiProcessHandler.h" +#include "cmAffinity.h" #include "cmCTest.h" #include "cmCTestRunTest.h" #include "cmCTestScriptHandler.h" @@ -19,6 +20,7 @@ #include <algorithm> #include <chrono> +#include <cstring> #include <iomanip> #include <list> #include <math.h> @@ -53,6 +55,8 @@ cmCTestMultiProcessHandler::cmCTestMultiProcessHandler() this->TestLoad = 0; this->Completed = 0; this->RunningCount = 0; + this->ProcessorsAvailable = cmAffinity::GetProcessorsAvailable(); + this->HaveAffinity = this->ProcessorsAvailable.size(); this->StopTimePassed = false; this->HasCycles = false; this->SerialTestRunning = false; @@ -127,6 +131,21 @@ bool cmCTestMultiProcessHandler::StartTestProcess(int test) return false; } + if (this->HaveAffinity && this->Properties[test]->WantAffinity) { + size_t needProcessors = this->GetProcessorsUsed(test); + if (needProcessors > this->ProcessorsAvailable.size()) { + return false; + } + std::vector<size_t> affinity; + affinity.reserve(needProcessors); + for (size_t i = 0; i < needProcessors; ++i) { + auto p = this->ProcessorsAvailable.begin(); + affinity.push_back(*p); + this->ProcessorsAvailable.erase(p); + } + this->Properties[test]->Affinity = std::move(affinity); + } + cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT, "test " << test << "\n", this->Quiet); this->TestRunningMap[test] = true; // mark the test as running @@ -151,13 +170,19 @@ bool cmCTestMultiProcessHandler::StartTestProcess(int test) } } - cmWorkingDirectory workdir(this->Properties[test]->Directory); - - // Lock the resources we'll be using + // Always lock the resources we'll be using, even if we fail to set the + // working directory because FinishTestProcess() will try to unlock them this->LockResources(test); - if (testRun->StartTest(this->Total)) { - return true; + cmWorkingDirectory workdir(this->Properties[test]->Directory); + if (workdir.Failed()) { + testRun->StartFailure("Failed to change working directory to " + + this->Properties[test]->Directory + " : " + + std::strerror(workdir.GetLastResult())); + } else { + if (testRun->StartTest(this->Total)) { + return true; + } } this->FinishTestProcess(testRun, false); @@ -200,6 +225,11 @@ inline size_t cmCTestMultiProcessHandler::GetProcessorsUsed(int test) if (processors > this->ParallelLevel) { processors = this->ParallelLevel; } + // Cap tests that want affinity to the maximum affinity available. + if (this->HaveAffinity && processors > this->HaveAffinity && + this->Properties[test]->WantAffinity) { + processors = this->HaveAffinity; + } return processors; } @@ -398,6 +428,11 @@ void cmCTestMultiProcessHandler::FinishTestProcess(cmCTestRunTest* runner, this->UnlockResources(test); this->RunningCount -= GetProcessorsUsed(test); + for (auto p : properties->Affinity) { + this->ProcessorsAvailable.insert(p); + } + properties->Affinity.clear(); + delete runner; if (started) { this->StartNextTests(); @@ -666,6 +701,8 @@ void cmCTestMultiProcessHandler::PrintTestList() count++; cmCTestTestHandler::cmCTestTestProperties& p = *it.second; + // Don't worry if this fails, we are only showing the test list, not + // running the tests cmWorkingDirectory workdir(p.Directory); cmCTestRunTest testRun(*this); diff --git a/Source/CTest/cmCTestMultiProcessHandler.h b/Source/CTest/cmCTestMultiProcessHandler.h index 7837ff9..19e1a35 100644 --- a/Source/CTest/cmCTestMultiProcessHandler.h +++ b/Source/CTest/cmCTestMultiProcessHandler.h @@ -119,6 +119,8 @@ protected: // Number of tests that are complete size_t Completed; size_t RunningCount; + std::set<size_t> ProcessorsAvailable; + size_t HaveAffinity; bool StopTimePassed; // list of test properties (indices concurrent to the test map) PropertiesMap Properties; diff --git a/Source/CTest/cmCTestRunTest.cxx b/Source/CTest/cmCTestRunTest.cxx index 30ad38c..8d8ebaa 100644 --- a/Source/CTest/cmCTestRunTest.cxx +++ b/Source/CTest/cmCTestRunTest.cxx @@ -14,6 +14,7 @@ #include "cmsys/RegularExpression.hxx" #include <chrono> #include <cmAlgorithms.h> +#include <cstring> #include <iomanip> #include <ratio> #include <sstream> @@ -248,11 +249,7 @@ bool cmCTestRunTest::EndTest(size_t completed, size_t total, bool started) *this->TestHandler->LogFile << "Test time = " << buf << std::endl; } - // Set the working directory to the tests directory to process Dart files. - { - cmWorkingDirectory workdir(this->TestProperties->Directory); - this->DartProcessing(); - } + this->DartProcessing(); // if this is doing MemCheck then all the output needs to be put into // Output since that is what is parsed by cmCTestMemCheckHandler @@ -338,6 +335,13 @@ bool cmCTestRunTest::StartAgain() this->RunAgain = false; // reset // change to tests directory cmWorkingDirectory workdir(this->TestProperties->Directory); + if (workdir.Failed()) { + this->StartFailure("Failed to change working directory to " + + this->TestProperties->Directory + " : " + + std::strerror(workdir.GetLastResult())); + return true; + } + this->StartTest(this->TotalNumberOfTests); return true; } @@ -386,6 +390,37 @@ void cmCTestRunTest::MemCheckPostProcess() handler->PostProcessTest(this->TestResult, this->Index); } +void cmCTestRunTest::StartFailure(std::string const& output) +{ + // Still need to log the Start message so the test summary records our + // attempt to start this test + cmCTestLog(this->CTest, HANDLER_OUTPUT, + std::setw(2 * getNumWidth(this->TotalNumberOfTests) + 8) + << "Start " + << std::setw(getNumWidth(this->TestHandler->GetMaxIndex())) + << this->TestProperties->Index << ": " + << this->TestProperties->Name << std::endl); + + this->ProcessOutput.clear(); + if (!output.empty()) { + *this->TestHandler->LogFile << output << std::endl; + cmCTestLog(this->CTest, ERROR_MESSAGE, output << std::endl); + } + + this->TestResult.Properties = this->TestProperties; + this->TestResult.ExecutionTime = cmDuration::zero(); + this->TestResult.CompressOutput = false; + this->TestResult.ReturnValue = -1; + this->TestResult.CompletionStatus = "Failed to start"; + this->TestResult.Status = cmCTestTestHandler::NOT_RUN; + this->TestResult.TestCount = this->TestProperties->Index; + this->TestResult.Name = this->TestProperties->Name; + this->TestResult.Path = this->TestProperties->Directory; + this->TestResult.Output = output; + this->TestResult.FullCommandLine.clear(); + this->TestProcess = cm::make_unique<cmProcess>(*this); +} + // Starts the execution of a test. Returns once it has started bool cmCTestRunTest::StartTest(size_t total) { @@ -515,7 +550,8 @@ bool cmCTestRunTest::StartTest(size_t total) } return this->ForkProcess(timeout, this->TestProperties->ExplicitTimeout, - &this->TestProperties->Environment); + &this->TestProperties->Environment, + &this->TestProperties->Affinity); } void cmCTestRunTest::ComputeArguments() @@ -591,7 +627,8 @@ void cmCTestRunTest::DartProcessing() } bool cmCTestRunTest::ForkProcess(cmDuration testTimeOut, bool explicitTimeout, - std::vector<std::string>* environment) + std::vector<std::string>* environment, + std::vector<size_t>* affinity) { this->TestProcess = cm::make_unique<cmProcess>(*this); this->TestProcess->SetId(this->Index); @@ -637,7 +674,8 @@ bool cmCTestRunTest::ForkProcess(cmDuration testTimeOut, bool explicitTimeout, cmSystemTools::AppendEnv(*environment); } - return this->TestProcess->StartProcess(this->MultiTestHandler.Loop); + return this->TestProcess->StartProcess(this->MultiTestHandler.Loop, + affinity); } void cmCTestRunTest::WriteLogOutputTop(size_t completed, size_t total) diff --git a/Source/CTest/cmCTestRunTest.h b/Source/CTest/cmCTestRunTest.h index 4d57357..3b1d674 100644 --- a/Source/CTest/cmCTestRunTest.h +++ b/Source/CTest/cmCTestRunTest.h @@ -74,6 +74,8 @@ public: bool StartAgain(); + void StartFailure(std::string const& output); + cmCTest* GetCTest() const { return this->CTest; } void FinalizeTest(); @@ -83,7 +85,8 @@ private: void DartProcessing(); void ExeNotFound(std::string exe); bool ForkProcess(cmDuration testTimeOut, bool explicitTimeout, - std::vector<std::string>* environment); + std::vector<std::string>* environment, + std::vector<size_t>* affinity); void WriteLogOutputTop(size_t completed, size_t total); // Run post processing of the process output for MemCheck void MemCheckPostProcess(); diff --git a/Source/CTest/cmCTestScriptHandler.cxx b/Source/CTest/cmCTestScriptHandler.cxx index e0bffd4..5fff730 100644 --- a/Source/CTest/cmCTestScriptHandler.cxx +++ b/Source/CTest/cmCTestScriptHandler.cxx @@ -527,7 +527,7 @@ int cmCTestScriptHandler::RunConfigurationScript( return result; } - // only run the curent script if we should + // only run the current script if we should if (this->Makefile && this->Makefile->IsOn("CTEST_RUN_CURRENT_SCRIPT") && this->ShouldRunCurrentScript) { return this->RunCurrentScript(); diff --git a/Source/CTest/cmCTestSubmitHandler.cxx b/Source/CTest/cmCTestSubmitHandler.cxx index 08d05c8..3bab81e 100644 --- a/Source/CTest/cmCTestSubmitHandler.cxx +++ b/Source/CTest/cmCTestSubmitHandler.cxx @@ -7,6 +7,7 @@ #include "cm_jsoncpp_value.h" #include "cmsys/Process.h" #include <chrono> +#include <cstring> #include <sstream> #include <stdio.h> #include <stdlib.h> @@ -1532,6 +1533,15 @@ int cmCTestSubmitHandler::ProcessHandler() // change to the build directory so that we can uses a relative path // on windows since scp doesn't support "c:" a drive in the path cmWorkingDirectory workdir(buildDirectory); + if (workdir.Failed()) { + cmCTestLog(this->CTest, ERROR_MESSAGE, + " Failed to change directory to " + << buildDirectory << " : " + << std::strerror(workdir.GetLastResult()) << std::endl); + ofs << " Failed to change directory to " << buildDirectory << " : " + << std::strerror(workdir.GetLastResult()) << std::endl; + return -1; + } if (!this->SubmitUsingSCP(this->CTest->GetCTestConfiguration("ScpCommand"), "Testing/" + this->CTest->GetCurrentTag(), files, @@ -1551,6 +1561,15 @@ int cmCTestSubmitHandler::ProcessHandler() // change to the build directory so that we can uses a relative path // on windows since scp doesn't support "c:" a drive in the path cmWorkingDirectory workdir(buildDirectory); + if (workdir.Failed()) { + cmCTestLog(this->CTest, ERROR_MESSAGE, + " Failed to change directory to " + << buildDirectory << " : " + << std::strerror(workdir.GetLastResult()) << std::endl); + ofs << " Failed to change directory to " << buildDirectory << " : " + << std::strerror(workdir.GetLastResult()) << std::endl; + return -1; + } cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT, " Change directory: " << buildDirectory << std::endl, this->Quiet); diff --git a/Source/CTest/cmCTestTestHandler.cxx b/Source/CTest/cmCTestTestHandler.cxx index 84d8926..cbaf984 100644 --- a/Source/CTest/cmCTestTestHandler.cxx +++ b/Source/CTest/cmCTestTestHandler.cxx @@ -6,6 +6,7 @@ #include <cmsys/Base64.h> #include <cmsys/Directory.hxx> #include <cmsys/RegularExpression.hxx> +#include <cstring> #include <functional> #include <iomanip> #include <iterator> @@ -14,7 +15,6 @@ #include <sstream> #include <stdio.h> #include <stdlib.h> -#include <string.h> #include <time.h> #include "cmAlgorithms.h" @@ -85,6 +85,11 @@ bool cmCTestSubdirCommand::InitialPass(std::vector<std::string> const& args, bool readit = false; { cmWorkingDirectory workdir(fname); + if (workdir.Failed()) { + this->SetError("Failed to change directory to " + fname + " : " + + std::strerror(workdir.GetLastResult())); + return false; + } const char* testFilename; if (cmSystemTools::FileExists("CTestTestfile.cmake")) { // does the CTestTestfile.cmake exist ? @@ -2165,6 +2170,9 @@ bool cmCTestTestHandler::SetTestsProperties( rt.Processors = 1; } } + if (key == "PROCESSOR_AFFINITY") { + rt.WantAffinity = cmSystemTools::IsOn(val.c_str()); + } if (key == "SKIP_RETURN_CODE") { rt.SkipReturnCode = atoi(val.c_str()); if (rt.SkipReturnCode < 0 || rt.SkipReturnCode > 255) { @@ -2336,6 +2344,7 @@ bool cmCTestTestHandler::AddTest(const std::vector<std::string>& args) test.ExplicitTimeout = false; test.Cost = 0; test.Processors = 1; + test.WantAffinity = false; test.SkipReturnCode = -1; test.PreviousRuns = 0; if (this->UseIncludeRegExpFlag && diff --git a/Source/CTest/cmCTestTestHandler.h b/Source/CTest/cmCTestTestHandler.h index f4978b6..d2694a1 100644 --- a/Source/CTest/cmCTestTestHandler.h +++ b/Source/CTest/cmCTestTestHandler.h @@ -130,6 +130,8 @@ public: int Index; // Requested number of process slots int Processors; + bool WantAffinity; + std::vector<size_t> Affinity; // return code of test which will mark test as "not run" int SkipReturnCode; std::vector<std::string> Environment; diff --git a/Source/CTest/cmProcess.cxx b/Source/CTest/cmProcess.cxx index 09ed0a9..5c9b169 100644 --- a/Source/CTest/cmProcess.cxx +++ b/Source/CTest/cmProcess.cxx @@ -83,7 +83,7 @@ void cmProcess::SetCommandArguments(std::vector<std::string> const& args) this->Arguments = args; } -bool cmProcess::StartProcess(uv_loop_t& loop) +bool cmProcess::StartProcess(uv_loop_t& loop, std::vector<size_t>* affinity) { this->ProcessState = cmProcess::State::Error; if (this->Command.empty()) { @@ -138,6 +138,22 @@ bool cmProcess::StartProcess(uv_loop_t& loop) options.stdio_count = 3; // in, out and err options.exit_cb = &cmProcess::OnExitCB; options.stdio = stdio; +#if !defined(CMAKE_USE_SYSTEM_LIBUV) + std::vector<char> cpumask; + if (affinity && !affinity->empty()) { + cpumask.resize(static_cast<size_t>(uv_cpumask_size()), 0); + for (auto p : *affinity) { + cpumask[p] = 1; + } + options.cpumask = cpumask.data(); + options.cpumask_size = cpumask.size(); + } else { + options.cpumask = nullptr; + options.cpumask_size = 0; + } +#else + static_cast<void>(affinity); +#endif status = uv_read_start(pipe_reader, &cmProcess::OnAllocateCB, &cmProcess::OnReadCB); diff --git a/Source/CTest/cmProcess.h b/Source/CTest/cmProcess.h index 20e24b9..b2d87fa 100644 --- a/Source/CTest/cmProcess.h +++ b/Source/CTest/cmProcess.h @@ -36,7 +36,7 @@ public: void ChangeTimeout(cmDuration t); void ResetStartTime(); // Return true if the process starts - bool StartProcess(uv_loop_t& loop); + bool StartProcess(uv_loop_t& loop, std::vector<size_t>* affinity); enum class State { diff --git a/Source/Checks/Curses.cmake b/Source/Checks/Curses.cmake new file mode 100644 index 0000000..46dc770 --- /dev/null +++ b/Source/Checks/Curses.cmake @@ -0,0 +1,41 @@ +message(STATUS "Checking for curses support") + +# Try compiling a simple project using curses. +# Pass in any cache entries that the user may have set. +set(CMakeCheckCurses_ARGS "") +foreach(v + CURSES_INCLUDE_PATH + CURSES_CURSES_LIBRARY + CURSES_NCURSES_LIBRARY + CURSES_EXTRA_LIBRARY + CURSES_FORM_LIBRARY + ) + if(${v}) + list(APPEND CMakeCheckCurses_ARGS -D${v}=${${v}}) + endif() +endforeach() +file(REMOVE_RECURSE "${CMake_BINARY_DIR}/Source/Checks/Curses-build") +try_compile(CMakeCheckCurses_COMPILED + ${CMake_BINARY_DIR}/Source/Checks/Curses-build + ${CMake_SOURCE_DIR}/Source/Checks/Curses + CheckCurses # project name + CheckCurses # target name + CMAKE_FLAGS + "-DCMAKE_C_FLAGS:STRING=${CMAKE_C_FLAGS}" + ${CMakeCheckCurses_ARGS} + OUTPUT_VARIABLE CMakeCheckCurses_OUTPUT + ) + +# Covnert result from cache entry to normal variable. +set(CMakeCheckCurses_COMPILED "${CMakeCheckCurses_COMPILED}") +unset(CMakeCheckCurses_COMPILED CACHE) + +if(CMakeCheckCurses_COMPILED) + message(STATUS "Checking for curses support - Success") + file(APPEND ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeOutput.log + "Checking for curses support passed with the following output:\n${CMakeCheckCurses_OUTPUT}\n\n") +else() + message(STATUS "Checking for curses support - Failed") + file(APPEND ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeError.log + "Checking for curses support failed with the following output:\n${CMakeCheckCurses_OUTPUT}\n\n") +endif() diff --git a/Source/Checks/Curses/CMakeLists.txt b/Source/Checks/Curses/CMakeLists.txt new file mode 100644 index 0000000..17318a3 --- /dev/null +++ b/Source/Checks/Curses/CMakeLists.txt @@ -0,0 +1,25 @@ +cmake_minimum_required(VERSION 3.1) +if(POLICY CMP0060) + cmake_policy(SET CMP0060 NEW) +endif() +project(CheckCurses C) + +set(CURSES_NEED_NCURSES TRUE) +find_package(Curses) +if(NOT CURSES_FOUND) + return() +endif() +include_directories(${CURSES_INCLUDE_DIRS}) +add_executable(CheckCurses CheckCurses.c) +target_link_libraries(CheckCurses ${CURSES_LIBRARIES}) + +foreach(h + CURSES_HAVE_CURSES_H + CURSES_HAVE_NCURSES_H + CURSES_HAVE_NCURSES_NCURSES_H + CURSES_HAVE_NCURSES_CURSES_H + ) + if(${h}) + target_compile_definitions(CheckCurses PRIVATE ${h}) + endif() +endforeach() diff --git a/Source/Checks/Curses/CheckCurses.c b/Source/Checks/Curses/CheckCurses.c new file mode 100644 index 0000000..857ae28 --- /dev/null +++ b/Source/Checks/Curses/CheckCurses.c @@ -0,0 +1,15 @@ +#if defined(CURSES_HAVE_NCURSES_H) +#include <ncurses.h> +#elif defined(CURSES_HAVE_NCURSES_NCURSES_H) +#include <ncurses/ncurses.h> +#elif defined(CURSES_HAVE_NCURSES_CURSES_H) +#include <ncurses/curses.h> +#else +#include <curses.h> +#endif + +int main() +{ + curses_version(); + return 0; +} diff --git a/Source/CursesDialog/cmCursesStandardIncludes.h b/Source/CursesDialog/cmCursesStandardIncludes.h index 332d2af..60bad94 100644 --- a/Source/CursesDialog/cmCursesStandardIncludes.h +++ b/Source/CursesDialog/cmCursesStandardIncludes.h @@ -5,6 +5,11 @@ #include "cmConfigure.h" // IWYU pragma: keep +// Record whether __attribute__ is currently defined. See purpose below. +#ifndef __attribute__ +#define cm_no__attribute__ +#endif + #if defined(__hpux) #define _BOOL_DEFINED #include <sys/time.h> @@ -29,4 +34,12 @@ inline void curses_clear() #undef erase #undef clear +// The curses headers on some platforms (e.g. Solaris) may +// define __attribute__ as a macro. This breaks C++ headers +// in some cases, so undefine it now. +#if defined(cm_no__attribute__) && defined(__attribute__) +#undef __attribute__ +#endif +#undef cm_no__attribute__ + #endif // cmCursesStandardIncludes_h diff --git a/Source/LexerParser/cmFortranParser.cxx b/Source/LexerParser/cmFortranParser.cxx index 2b3452f..00c8a8a 100644 --- a/Source/LexerParser/cmFortranParser.cxx +++ b/Source/LexerParser/cmFortranParser.cxx @@ -1563,7 +1563,7 @@ yyreduce: #line 119 "cmFortranParser.y" /* yacc.c:1646 */ { cmFortranParser* parser = cmFortran_yyget_extra(yyscanner); - cmFortranParser_RuleUse(parser, (yyvsp[-4].string)); + cmFortranParser_RuleSubmodule(parser, (yyvsp[-4].string), (yyvsp[-2].string)); free((yyvsp[-4].string)); free((yyvsp[-2].string)); } @@ -1574,7 +1574,7 @@ yyreduce: #line 125 "cmFortranParser.y" /* yacc.c:1646 */ { cmFortranParser* parser = cmFortran_yyget_extra(yyscanner); - cmFortranParser_RuleUse(parser, (yyvsp[-6].string)); + cmFortranParser_RuleSubmoduleNested(parser, (yyvsp[-6].string), (yyvsp[-4].string), (yyvsp[-2].string)); free((yyvsp[-6].string)); free((yyvsp[-4].string)); free((yyvsp[-2].string)); diff --git a/Source/LexerParser/cmFortranParser.y b/Source/LexerParser/cmFortranParser.y index acfb40a..5e09248 100644 --- a/Source/LexerParser/cmFortranParser.y +++ b/Source/LexerParser/cmFortranParser.y @@ -118,13 +118,13 @@ stmt: } | SUBMODULE LPAREN WORD RPAREN WORD other EOSTMT { cmFortranParser* parser = cmFortran_yyget_extra(yyscanner); - cmFortranParser_RuleUse(parser, $3); + cmFortranParser_RuleSubmodule(parser, $3, $5); free($3); free($5); } | SUBMODULE LPAREN WORD COLON WORD RPAREN WORD other EOSTMT { cmFortranParser* parser = cmFortran_yyget_extra(yyscanner); - cmFortranParser_RuleUse(parser, $3); + cmFortranParser_RuleSubmoduleNested(parser, $3, $5, $7); free($3); free($5); free($7); diff --git a/Source/cmAddCompileDefinitionsCommand.cxx b/Source/cmAddCompileDefinitionsCommand.cxx new file mode 100644 index 0000000..0474819 --- /dev/null +++ b/Source/cmAddCompileDefinitionsCommand.cxx @@ -0,0 +1,20 @@ +/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying + file Copyright.txt or https://cmake.org/licensing for details. */ +#include "cmAddCompileDefinitionsCommand.h" + +#include "cmMakefile.h" + +class cmExecutionStatus; + +bool cmAddCompileDefinitionsCommand::InitialPass( + std::vector<std::string> const& args, cmExecutionStatus&) +{ + if (args.empty()) { + return true; + } + + for (std::string const& i : args) { + this->Makefile->AddCompileDefinition(i); + } + return true; +} diff --git a/Source/cmAddCompileDefinitionsCommand.h b/Source/cmAddCompileDefinitionsCommand.h new file mode 100644 index 0000000..e985dca --- /dev/null +++ b/Source/cmAddCompileDefinitionsCommand.h @@ -0,0 +1,31 @@ +/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying + file Copyright.txt or https://cmake.org/licensing for details. */ +#ifndef cmAddCompileDefinitionsCommand_h +#define cmAddCompileDefinitionsCommand_h + +#include "cmConfigure.h" // IWYU pragma: keep + +#include <string> +#include <vector> + +#include "cmCommand.h" + +class cmExecutionStatus; + +class cmAddCompileDefinitionsCommand : public cmCommand +{ +public: + /** + * This is a virtual constructor for the command. + */ + cmCommand* Clone() override { return new cmAddCompileDefinitionsCommand; } + + /** + * This is called when the command is first encountered in + * the CMakeLists.txt file. + */ + bool InitialPass(std::vector<std::string> const& args, + cmExecutionStatus& status) override; +}; + +#endif diff --git a/Source/cmAffinity.cxx b/Source/cmAffinity.cxx new file mode 100644 index 0000000..bdf1f42 --- /dev/null +++ b/Source/cmAffinity.cxx @@ -0,0 +1,62 @@ +/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying + file Copyright.txt or https://cmake.org/licensing for details. */ +#include "cmAffinity.h" + +#include "cm_uv.h" + +#ifndef CMAKE_USE_SYSTEM_LIBUV +#ifdef _WIN32 +#define CM_HAVE_CPU_AFFINITY +#include <windows.h> +#elif defined(__linux__) || defined(__FreeBSD__) +#define CM_HAVE_CPU_AFFINITY +#include <pthread.h> +#include <sched.h> +#if defined(__FreeBSD__) +#include <pthread_np.h> +#include <sys/cpuset.h> +#include <sys/param.h> +#endif +#if defined(__linux__) +typedef cpu_set_t cm_cpuset_t; +#else +typedef cpuset_t cm_cpuset_t; +#endif +#endif +#endif + +namespace cmAffinity { + +std::set<size_t> GetProcessorsAvailable() +{ + std::set<size_t> processorsAvailable; +#ifdef CM_HAVE_CPU_AFFINITY + int cpumask_size = uv_cpumask_size(); + if (cpumask_size > 0) { +#ifdef _WIN32 + DWORD_PTR procmask; + DWORD_PTR sysmask; + if (GetProcessAffinityMask(GetCurrentProcess(), &procmask, &sysmask) != + 0) { + for (int i = 0; i < cpumask_size; ++i) { + if (procmask & (((DWORD_PTR)1) << i)) { + processorsAvailable.insert(i); + } + } + } +#else + cm_cpuset_t cpuset; + CPU_ZERO(&cpuset); // NOLINT(clang-tidy) + if (pthread_getaffinity_np(pthread_self(), sizeof(cpuset), &cpuset) == 0) { + for (int i = 0; i < cpumask_size; ++i) { + if (CPU_ISSET(i, &cpuset)) { + processorsAvailable.insert(i); + } + } + } +#endif + } +#endif + return processorsAvailable; +} +} diff --git a/Source/cmAffinity.h b/Source/cmAffinity.h new file mode 100644 index 0000000..3775bae --- /dev/null +++ b/Source/cmAffinity.h @@ -0,0 +1,12 @@ +/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying + file Copyright.txt or https://cmake.org/licensing for details. */ +#pragma once +#include "cmConfigure.h" // IWYU pragma: keep + +#include <cstddef> +#include <set> + +namespace cmAffinity { + +std::set<size_t> GetProcessorsAvailable(); +} diff --git a/Source/cmAlgorithms.h b/Source/cmAlgorithms.h index 3380b78..244dc1c 100644 --- a/Source/cmAlgorithms.h +++ b/Source/cmAlgorithms.h @@ -311,7 +311,7 @@ struct RemoveDuplicatesAPI<Range, T*> template <typename Range> typename Range::const_iterator cmRemoveDuplicates(Range& r) { - typedef typename ContainerAlgorithms::RemoveDuplicatesAPI<Range> API; + typedef ContainerAlgorithms::RemoveDuplicatesAPI<Range> API; typedef typename API::value_type T; std::vector<T> unique; unique.reserve(r.size()); diff --git a/Source/cmCMakeMinimumRequired.cxx b/Source/cmCMakeMinimumRequired.cxx index bcc41fc..2b51976 100644 --- a/Source/cmCMakeMinimumRequired.cxx +++ b/Source/cmCMakeMinimumRequired.cxx @@ -42,12 +42,27 @@ bool cmCMakeMinimumRequired::InitialPass(std::vector<std::string> const& args, // Make sure there was a version to check. if (version_string.empty()) { - return this->EnforceUnknownArguments(); + return this->EnforceUnknownArguments(std::string()); + } + + // Separate the <min> version and any trailing ...<max> component. + std::string::size_type const dd = version_string.find("..."); + std::string const version_min = version_string.substr(0, dd); + std::string const version_max = dd != std::string::npos + ? version_string.substr(dd + 3, std::string::npos) + : std::string(); + if (dd != std::string::npos && + (version_min.empty() || version_max.empty())) { + std::ostringstream e; + e << "VERSION \"" << version_string + << "\" does not have a version on both sides of \"...\"."; + this->SetError(e.str()); + return false; } // Save the required version string. this->Makefile->AddDefinition("CMAKE_MINIMUM_REQUIRED_VERSION", - version_string.c_str()); + version_min.c_str()); // Get the current version number. unsigned int current_major = cmVersion::GetMajorVersion(); @@ -61,10 +76,10 @@ bool cmCMakeMinimumRequired::InitialPass(std::vector<std::string> const& args, unsigned int required_minor = 0; unsigned int required_patch = 0; unsigned int required_tweak = 0; - if (sscanf(version_string.c_str(), "%u.%u.%u.%u", &required_major, + if (sscanf(version_min.c_str(), "%u.%u.%u.%u", &required_major, &required_minor, &required_patch, &required_tweak) < 2) { std::ostringstream e; - e << "could not parse VERSION \"" << version_string << "\"."; + e << "could not parse VERSION \"" << version_min << "\"."; this->SetError(e.str()); return false; } @@ -78,7 +93,7 @@ bool cmCMakeMinimumRequired::InitialPass(std::vector<std::string> const& args, current_patch == required_patch && current_tweak < required_tweak)) { // The current version is too low. std::ostringstream e; - e << "CMake " << version_string + e << "CMake " << version_min << " or higher is required. You are running version " << cmVersion::GetCMakeVersion(); this->Makefile->IssueMessage(cmake::FATAL_ERROR, e.str()); @@ -87,7 +102,7 @@ bool cmCMakeMinimumRequired::InitialPass(std::vector<std::string> const& args, } // The version is not from the future, so enforce unknown arguments. - if (!this->EnforceUnknownArguments()) { + if (!this->EnforceUnknownArguments(version_max)) { return false; } @@ -95,22 +110,47 @@ bool cmCMakeMinimumRequired::InitialPass(std::vector<std::string> const& args, this->Makefile->IssueMessage( cmake::AUTHOR_WARNING, "Compatibility with CMake < 2.4 is not supported by CMake >= 3.0."); - this->Makefile->SetPolicyVersion("2.4"); + this->Makefile->SetPolicyVersion("2.4", version_max); } else { - this->Makefile->SetPolicyVersion(version_string.c_str()); + this->Makefile->SetPolicyVersion(version_min, version_max); } return true; } -bool cmCMakeMinimumRequired::EnforceUnknownArguments() +bool cmCMakeMinimumRequired::EnforceUnknownArguments( + std::string const& version_max) { - if (!this->UnknownArguments.empty()) { - std::ostringstream e; - e << "called with unknown argument \"" << this->UnknownArguments[0] - << "\"."; - this->SetError(e.str()); - return false; + if (this->UnknownArguments.empty()) { + return true; } - return true; + + // Consider the max version if at least two components were given. + unsigned int max_major = 0; + unsigned int max_minor = 0; + unsigned int max_patch = 0; + unsigned int max_tweak = 0; + if (sscanf(version_max.c_str(), "%u.%u.%u.%u", &max_major, &max_minor, + &max_patch, &max_tweak) >= 2) { + unsigned int current_major = cmVersion::GetMajorVersion(); + unsigned int current_minor = cmVersion::GetMinorVersion(); + unsigned int current_patch = cmVersion::GetPatchVersion(); + unsigned int current_tweak = cmVersion::GetTweakVersion(); + + if ((current_major < max_major) || + (current_major == max_major && current_minor < max_minor) || + (current_major == max_major && current_minor == max_minor && + current_patch < max_patch) || + (current_major == max_major && current_minor == max_minor && + current_patch == max_patch && current_tweak < max_tweak)) { + // A ...<max> version was given that is larger than the current + // version of CMake, so tolerate unknown arguments. + return true; + } + } + + std::ostringstream e; + e << "called with unknown argument \"" << this->UnknownArguments[0] << "\"."; + this->SetError(e.str()); + return false; } diff --git a/Source/cmCMakeMinimumRequired.h b/Source/cmCMakeMinimumRequired.h index 18d9460..f9b61e1 100644 --- a/Source/cmCMakeMinimumRequired.h +++ b/Source/cmCMakeMinimumRequired.h @@ -34,7 +34,7 @@ public: private: std::vector<std::string> UnknownArguments; - bool EnforceUnknownArguments(); + bool EnforceUnknownArguments(std::string const& version_max); }; #endif diff --git a/Source/cmCMakePolicyCommand.cxx b/Source/cmCMakePolicyCommand.cxx index 3ccc815..adf9ef8 100644 --- a/Source/cmCMakePolicyCommand.cxx +++ b/Source/cmCMakePolicyCommand.cxx @@ -95,7 +95,11 @@ bool cmCMakePolicyCommand::HandleSetMode(std::vector<std::string> const& args) bool cmCMakePolicyCommand::HandleGetMode(std::vector<std::string> const& args) { - if (args.size() != 3) { + bool parent_scope = false; + if (args.size() == 4 && args[3] == "PARENT_SCOPE") { + // Undocumented PARENT_SCOPE option for use within CMake. + parent_scope = true; + } else if (args.size() != 3) { this->SetError("GET must be given exactly 2 additional arguments."); return false; } @@ -115,7 +119,8 @@ bool cmCMakePolicyCommand::HandleGetMode(std::vector<std::string> const& args) } // Lookup the policy setting. - cmPolicies::PolicyStatus status = this->Makefile->GetPolicyStatus(pid); + cmPolicies::PolicyStatus status = + this->Makefile->GetPolicyStatus(pid, parent_scope); switch (status) { case cmPolicies::OLD: // Report that the policy is set to OLD. @@ -156,6 +161,23 @@ bool cmCMakePolicyCommand::HandleVersionMode( this->SetError("VERSION given too many arguments"); return false; } - this->Makefile->SetPolicyVersion(args[1].c_str()); + std::string const& version_string = args[1]; + + // Separate the <min> version and any trailing ...<max> component. + std::string::size_type const dd = version_string.find("..."); + std::string const version_min = version_string.substr(0, dd); + std::string const version_max = dd != std::string::npos + ? version_string.substr(dd + 3, std::string::npos) + : std::string(); + if (dd != std::string::npos && + (version_min.empty() || version_max.empty())) { + std::ostringstream e; + e << "VERSION \"" << version_string + << "\" does not have a version on both sides of \"...\"."; + this->SetError(e.str()); + return false; + } + + this->Makefile->SetPolicyVersion(version_min, version_max); return true; } diff --git a/Source/cmCTest.h b/Source/cmCTest.h index 673a40e..b2f4f25 100644 --- a/Source/cmCTest.h +++ b/Source/cmCTest.h @@ -347,7 +347,7 @@ public: const std::string& cmake_var, bool suppress = false); - /** Make string safe to be send as an URL */ + /** Make string safe to be sent as a URL */ static std::string MakeURLSafe(const std::string&); /** Decode a URL to the original string. */ diff --git a/Source/cmCacheManager.cxx b/Source/cmCacheManager.cxx index fab2445..13407e5 100644 --- a/Source/cmCacheManager.cxx +++ b/Source/cmCacheManager.cxx @@ -8,6 +8,7 @@ #include <sstream> #include <stdio.h> #include <string.h> +#include <string> #include "cmGeneratedFileStream.h" #include "cmMessenger.h" @@ -160,14 +161,14 @@ bool cmCacheManager::LoadCache(const std::string& path, bool internal, currentcwd += "/CMakeCache.txt"; oldcwd += "/CMakeCache.txt"; if (!cmSystemTools::SameFile(oldcwd, currentcwd)) { - std::string message = - std::string("The current CMakeCache.txt directory ") + currentcwd + - std::string(" is different than the directory ") + - std::string(this->GetInitializedCacheValue("CMAKE_CACHEFILE_DIR")) + - std::string(" where CMakeCache.txt was created. This may result " - "in binaries being created in the wrong place. If you " - "are not sure, reedit the CMakeCache.txt"); - cmSystemTools::Error(message.c_str()); + std::ostringstream message; + message << "The current CMakeCache.txt directory " << currentcwd + << " is different than the directory " + << this->GetInitializedCacheValue("CMAKE_CACHEFILE_DIR") + << " where CMakeCache.txt was created. This may result " + "in binaries being created in the wrong place. If you " + "are not sure, reedit the CMakeCache.txt"; + cmSystemTools::Error(message.str().c_str()); } } return true; @@ -243,19 +244,18 @@ bool cmCacheManager::SaveCache(const std::string& path, cmMessenger* messenger) } // before writing the cache, update the version numbers // to the - char temp[1024]; - sprintf(temp, "%d", cmVersion::GetMinorVersion()); - this->AddCacheEntry("CMAKE_CACHE_MINOR_VERSION", temp, - "Minor version of cmake used to create the " + this->AddCacheEntry("CMAKE_CACHE_MAJOR_VERSION", + std::to_string(cmVersion::GetMajorVersion()).c_str(), + "Major version of cmake used to create the " "current loaded cache", cmStateEnums::INTERNAL); - sprintf(temp, "%d", cmVersion::GetMajorVersion()); - this->AddCacheEntry("CMAKE_CACHE_MAJOR_VERSION", temp, - "Major version of cmake used to create the " + this->AddCacheEntry("CMAKE_CACHE_MINOR_VERSION", + std::to_string(cmVersion::GetMinorVersion()).c_str(), + "Minor version of cmake used to create the " "current loaded cache", cmStateEnums::INTERNAL); - sprintf(temp, "%d", cmVersion::GetPatchVersion()); - this->AddCacheEntry("CMAKE_CACHE_PATCH_VERSION", temp, + this->AddCacheEntry("CMAKE_CACHE_PATCH_VERSION", + std::to_string(cmVersion::GetPatchVersion()).c_str(), "Patch version of cmake used to create the " "current loaded cache", cmStateEnums::INTERNAL); diff --git a/Source/cmCommands.cxx b/Source/cmCommands.cxx index a1de8b1..a87b450 100644 --- a/Source/cmCommands.cxx +++ b/Source/cmCommands.cxx @@ -4,6 +4,7 @@ #include "cmPolicies.h" #include "cmState.h" +#include "cmAddCompileDefinitionsCommand.h" #include "cmAddCustomCommandCommand.h" #include "cmAddCustomTargetCommand.h" #include "cmAddDefinitionsCommand.h" @@ -253,6 +254,8 @@ void GetProjectCommands(cmState* state) state->AddBuiltinCommand("try_run", new cmTryRunCommand); #if defined(CMAKE_BUILD_WITH_CMAKE) + state->AddBuiltinCommand("add_compile_definitions", + new cmAddCompileDefinitionsCommand); state->AddBuiltinCommand("add_compile_options", new cmAddCompileOptionsCommand); state->AddBuiltinCommand("aux_source_directory", diff --git a/Source/cmComputeLinkInformation.cxx b/Source/cmComputeLinkInformation.cxx index 8a5a6de..6e6e0be 100644 --- a/Source/cmComputeLinkInformation.cxx +++ b/Source/cmComputeLinkInformation.cxx @@ -240,21 +240,19 @@ because this need be done only for shared libraries without soname-s. cmComputeLinkInformation::cmComputeLinkInformation( const cmGeneratorTarget* target, const std::string& config) -{ // Store context information. - this->Target = target; - this->Makefile = this->Target->Target->GetMakefile(); - this->GlobalGenerator = - this->Target->GetLocalGenerator()->GetGlobalGenerator(); - this->CMakeInstance = this->GlobalGenerator->GetCMakeInstance(); - + : Target(target), + Makefile(target->Target->GetMakefile()), + GlobalGenerator(target->GetLocalGenerator()->GetGlobalGenerator()), + CMakeInstance(this->GlobalGenerator->GetCMakeInstance()) + // The configuration being linked. + , + Config(config) +{ // Check whether to recognize OpenBSD-style library versioned names. this->OpenBSD = this->Makefile->GetState()->GetGlobalPropertyAsBool( "FIND_LIBRARY_USE_OPENBSD_VERSIONING"); - // The configuration being linked. - this->Config = config; - // Allocate internals. this->OrderLinkerSearchPath = new cmOrderDirectories( this->GlobalGenerator, target, "linker search path"); @@ -406,17 +404,18 @@ cmComputeLinkInformation::~cmComputeLinkInformation() } cmComputeLinkInformation::ItemVector const& -cmComputeLinkInformation::GetItems() +cmComputeLinkInformation::GetItems() const { return this->Items; } std::vector<std::string> const& cmComputeLinkInformation::GetDirectories() + const { return this->OrderLinkerSearchPath->GetOrderedDirectories(); } -std::string cmComputeLinkInformation::GetRPathLinkString() +std::string cmComputeLinkInformation::GetRPathLinkString() const { // If there is no separate linker runtime search flag (-rpath-link) // there is no reason to compute a string. @@ -428,18 +427,19 @@ std::string cmComputeLinkInformation::GetRPathLinkString() return cmJoin(this->OrderDependentRPath->GetOrderedDirectories(), ":"); } -std::vector<std::string> const& cmComputeLinkInformation::GetDepends() +std::vector<std::string> const& cmComputeLinkInformation::GetDepends() const { return this->Depends; } std::vector<std::string> const& cmComputeLinkInformation::GetFrameworkPaths() + const { return this->FrameworkPaths; } const std::set<const cmGeneratorTarget*>& -cmComputeLinkInformation::GetSharedLibrariesLinked() +cmComputeLinkInformation::GetSharedLibrariesLinked() const { return this->SharedLibrariesLinked; } @@ -611,6 +611,9 @@ void cmComputeLinkInformation::AddItem(std::string const& item, if (!libName.empty()) { this->AddItem(libName, nullptr); } + } else if (tgt->GetType() == cmStateEnums::OBJECT_LIBRARY) { + // Ignore object library! + // Its object-files should already have been extracted for linking. } else { // Decide whether to use an import library. bool implib = @@ -1023,7 +1026,7 @@ void cmComputeLinkInformation::AddFullItem(std::string const& item) (generator.find("Visual Studio") != std::string::npos || generator.find("Xcode") != std::string::npos)) { std::string file = cmSystemTools::GetFilenameName(item); - if (!this->ExtractAnyLibraryName.find(file.c_str())) { + if (!this->ExtractAnyLibraryName.find(file)) { this->HandleBadFullItem(item, file); return; } @@ -1230,7 +1233,7 @@ void cmComputeLinkInformation::AddUserItem(std::string const& item, void cmComputeLinkInformation::AddFrameworkItem(std::string const& item) { // Try to separate the framework name and path. - if (!this->SplitFramework.find(item.c_str())) { + if (!this->SplitFramework.find(item)) { std::ostringstream e; e << "Could not parse framework path \"" << item << "\" " << "linked by target " << this->Target->GetName() << "."; @@ -1569,7 +1572,7 @@ void cmComputeLinkInformation::LoadImplicitLinkInfo() } std::vector<std::string> const& -cmComputeLinkInformation::GetRuntimeSearchPath() +cmComputeLinkInformation::GetRuntimeSearchPath() const { return this->OrderRuntimeSearchPath->GetOrderedDirectories(); } @@ -1635,7 +1638,7 @@ void cmComputeLinkInformation::AddLibraryRuntimeInfo( if (!is_shared_library) { // On some platforms (AIX) a shared library may look static. if (this->ArchivesMayBeShared) { - if (this->ExtractStaticLibraryName.find(file.c_str())) { + if (this->ExtractStaticLibraryName.find(file)) { // This is the name of a shared library or archive. is_shared_library = true; } @@ -1680,7 +1683,7 @@ static void cmCLI_ExpandListUnique(const char* str, } void cmComputeLinkInformation::GetRPath(std::vector<std::string>& runtimeDirs, - bool for_install) + bool for_install) const { // Select whether to generate runtime search directories. bool outputRuntime = @@ -1794,7 +1797,7 @@ void cmComputeLinkInformation::GetRPath(std::vector<std::string>& runtimeDirs, cmCLI_ExpandListUnique(this->RuntimeAlways.c_str(), runtimeDirs, emitted); } -std::string cmComputeLinkInformation::GetRPathString(bool for_install) +std::string cmComputeLinkInformation::GetRPathString(bool for_install) const { // Get the directories to use. std::vector<std::string> runtimeDirs; @@ -1822,7 +1825,7 @@ std::string cmComputeLinkInformation::GetRPathString(bool for_install) return rpath; } -std::string cmComputeLinkInformation::GetChrpathString() +std::string cmComputeLinkInformation::GetChrpathString() const { if (!this->RuntimeUseChrpath) { return ""; diff --git a/Source/cmComputeLinkInformation.h b/Source/cmComputeLinkInformation.h index f8c6214..65c12da 100644 --- a/Source/cmComputeLinkInformation.h +++ b/Source/cmComputeLinkInformation.h @@ -48,21 +48,21 @@ public: cmGeneratorTarget const* Target; }; typedef std::vector<Item> ItemVector; - ItemVector const& GetItems(); - std::vector<std::string> const& GetDirectories(); - std::vector<std::string> const& GetDepends(); - std::vector<std::string> const& GetFrameworkPaths(); + ItemVector const& GetItems() const; + std::vector<std::string> const& GetDirectories() const; + std::vector<std::string> const& GetDepends() const; + std::vector<std::string> const& GetFrameworkPaths() const; std::string GetLinkLanguage() const { return this->LinkLanguage; } - std::vector<std::string> const& GetRuntimeSearchPath(); + std::vector<std::string> const& GetRuntimeSearchPath() const; std::string const& GetRuntimeFlag() const { return this->RuntimeFlag; } std::string const& GetRuntimeSep() const { return this->RuntimeSep; } - void GetRPath(std::vector<std::string>& runtimeDirs, bool for_install); - std::string GetRPathString(bool for_install); - std::string GetChrpathString(); - std::set<cmGeneratorTarget const*> const& GetSharedLibrariesLinked(); + void GetRPath(std::vector<std::string>& runtimeDirs, bool for_install) const; + std::string GetRPathString(bool for_install) const; + std::string GetChrpathString() const; + std::set<cmGeneratorTarget const*> const& GetSharedLibrariesLinked() const; std::string const& GetRPathLinkFlag() const { return this->RPathLinkFlag; } - std::string GetRPathLinkString(); + std::string GetRPathLinkString() const; std::string GetConfig() const { return this->Config; } private: @@ -78,13 +78,13 @@ private: std::set<cmGeneratorTarget const*> SharedLibrariesLinked; // Context information. - cmGeneratorTarget const* Target; - cmMakefile* Makefile; - cmGlobalGenerator* GlobalGenerator; - cmake* CMakeInstance; + cmGeneratorTarget const* const Target; + cmMakefile* const Makefile; + cmGlobalGenerator* const GlobalGenerator; + cmake* const CMakeInstance; // Configuration information. - std::string Config; + std::string const Config; std::string LinkLanguage; // Modes for dealing with dependent shared libraries. diff --git a/Source/cmComputeTargetDepends.cxx b/Source/cmComputeTargetDepends.cxx index 18767a3..efdd3a5 100644 --- a/Source/cmComputeTargetDepends.cxx +++ b/Source/cmComputeTargetDepends.cxx @@ -211,11 +211,11 @@ void cmComputeTargetDepends::CollectTargetDepends(int depender_index) if (depender->GetType() != cmStateEnums::EXECUTABLE && depender->GetType() != cmStateEnums::STATIC_LIBRARY && depender->GetType() != cmStateEnums::SHARED_LIBRARY && - depender->GetType() != cmStateEnums::MODULE_LIBRARY) { + depender->GetType() != cmStateEnums::MODULE_LIBRARY && + depender->GetType() != cmStateEnums::OBJECT_LIBRARY) { this->GlobalGenerator->GetCMakeInstance()->IssueMessage( cmake::FATAL_ERROR, - "Only executables and non-OBJECT libraries may " - "reference target objects.", + "Only executables and libraries may reference target objects.", depender->GetBacktrace()); return; } diff --git a/Source/cmConfigureFileCommand.h b/Source/cmConfigureFileCommand.h index cff934b..5603c50 100644 --- a/Source/cmConfigureFileCommand.h +++ b/Source/cmConfigureFileCommand.h @@ -32,9 +32,9 @@ private: std::string InputFile; std::string OutputFile; - bool CopyOnly; - bool EscapeQuotes; - bool AtOnly; + bool CopyOnly = false; + bool EscapeQuotes = false; + bool AtOnly = false; }; #endif diff --git a/Source/cmCoreTryCompile.h b/Source/cmCoreTryCompile.h index 6f35a54..ae714a6 100644 --- a/Source/cmCoreTryCompile.h +++ b/Source/cmCoreTryCompile.h @@ -46,7 +46,7 @@ protected: std::string BinaryDirectory; std::string OutputFile; std::string FindErrorMessage; - bool SrcFileSignature; + bool SrcFileSignature = false; private: std::vector<std::string> WarnCMP0067; diff --git a/Source/cmDepends.cxx b/Source/cmDepends.cxx index cdab671..4716e14 100644 --- a/Source/cmDepends.cxx +++ b/Source/cmDepends.cxx @@ -7,7 +7,6 @@ #include "cmLocalGenerator.h" #include "cmMakefile.h" #include "cmSystemTools.h" -#include "cmWorkingDirectory.h" #include "cmsys/FStream.hxx" #include <sstream> @@ -15,8 +14,7 @@ #include <utility> cmDepends::cmDepends(cmLocalGenerator* lg, const char* targetDir) - : CompileDirectory() - , LocalGenerator(lg) + : LocalGenerator(lg) , Verbose(false) , FileComparison(nullptr) , TargetDirectory(targetDir) @@ -73,9 +71,6 @@ bool cmDepends::Finalize(std::ostream& /*unused*/, std::ostream& /*unused*/) bool cmDepends::Check(const char* makeFile, const char* internalFile, std::map<std::string, DependencyVector>& validDeps) { - // Dependency checks must be done in proper working directory. - cmWorkingDirectory workdir(this->CompileDirectory); - // Check whether dependencies must be regenerated. bool okay = true; cmsys::ifstream fin(internalFile); diff --git a/Source/cmDepends.h b/Source/cmDepends.h index a4fee3c..4b9e05a 100644 --- a/Source/cmDepends.h +++ b/Source/cmDepends.h @@ -31,9 +31,6 @@ public: path from the build directory to the target file. */ cmDepends(cmLocalGenerator* lg = nullptr, const char* targetDir = ""); - /** at what level will the compile be done from */ - void SetCompileDirectory(const char* dir) { this->CompileDirectory = dir; } - /** Set the local generator for the directory in which we are scanning dependencies. This is not a full local generator; it has been setup to do relative path conversions for the current @@ -95,9 +92,6 @@ protected: virtual bool Finalize(std::ostream& makeDepends, std::ostream& internalDepends); - // The directory in which the build rule for the target file is executed. - std::string CompileDirectory; - // The local generator. cmLocalGenerator* LocalGenerator; diff --git a/Source/cmDependsC.cxx b/Source/cmDependsC.cxx index 62bc8d9..34c0e94 100644 --- a/Source/cmDependsC.cxx +++ b/Source/cmDependsC.cxx @@ -96,9 +96,16 @@ bool cmDependsC::WriteDependencies(const std::set<std::string>& sources, std::set<std::string> dependencies; bool haveDeps = false; + std::string binDir = this->LocalGenerator->GetBinaryDirectory(); + + // Compute a path to the object file to write to the internal depend file. + // Any existing content of the internal depend file has already been + // loaded in ValidDeps with this path as a key. + std::string obj_i = this->LocalGenerator->ConvertToRelativePath(binDir, obj); + if (this->ValidDeps != nullptr) { std::map<std::string, DependencyVector>::const_iterator tmpIt = - this->ValidDeps->find(obj); + this->ValidDeps->find(obj_i); if (tmpIt != this->ValidDeps->end()) { dependencies.insert(tmpIt->second.begin(), tmpIt->second.end()); haveDeps = true; @@ -222,8 +229,6 @@ bool cmDependsC::WriteDependencies(const std::set<std::string>& sources, // written by the original local generator for this directory // convert the dependencies to paths relative to the home output // directory. We must do the same here. - std::string binDir = this->LocalGenerator->GetBinaryDirectory(); - std::string obj_i = this->LocalGenerator->ConvertToRelativePath(binDir, obj); std::string obj_m = cmSystemTools::ConvertToOutputPath(obj_i); internalDepends << obj_i << std::endl; diff --git a/Source/cmDependsFortran.cxx b/Source/cmDependsFortran.cxx index 1a66ca0..dbea15a 100644 --- a/Source/cmDependsFortran.cxx +++ b/Source/cmDependsFortran.cxx @@ -10,6 +10,7 @@ #include <string.h> #include <utility> +#include "cmAlgorithms.h" #include "cmFortranParser.h" /* Interface to parser object. */ #include "cmGeneratedFileStream.h" #include "cmLocalGenerator.h" @@ -23,6 +24,22 @@ // use lower case and some always use upper case. I do not know if any // use the case from the source code. +static void cmFortranModuleAppendUpperLower(std::string const& mod, + std::string& mod_upper, + std::string& mod_lower) +{ + std::string::size_type ext_len = 0; + if (cmHasLiteralSuffix(mod, ".mod")) { + ext_len = 4; + } else if (cmHasLiteralSuffix(mod, ".smod")) { + ext_len = 5; + } + std::string const& name = mod.substr(0, mod.size() - ext_len); + std::string const& ext = mod.substr(mod.size() - ext_len); + mod_upper += cmSystemTools::UpperCase(name) + ext; + mod_lower += mod; +} + class cmDependsFortranInternals { public: @@ -181,16 +198,13 @@ bool cmDependsFortran::Finalize(std::ostream& makeDepends, for (std::string const& i : provides) { std::string mod_upper = mod_dir; mod_upper += "/"; - mod_upper += cmSystemTools::UpperCase(i); - mod_upper += ".mod"; std::string mod_lower = mod_dir; mod_lower += "/"; - mod_lower += i; - mod_lower += ".mod"; + cmFortranModuleAppendUpperLower(i, mod_upper, mod_lower); std::string stamp = stamp_dir; stamp += "/"; stamp += i; - stamp += ".mod.stamp"; + stamp += ".stamp"; fcStream << "\n"; fcStream << " \"" << this->MaybeConvertToRelativePath(currentBinDir, mod_lower) @@ -270,7 +284,14 @@ void cmDependsFortran::MatchRemoteModules(std::istream& fin, if (line[0] == ' ') { if (doing_provides) { - this->ConsiderModule(line.c_str() + 1, stampDir); + std::string mod = line; + if (!cmHasLiteralSuffix(mod, ".mod") && + !cmHasLiteralSuffix(mod, ".smod")) { + // Support fortran.internal files left by older versions of CMake. + // They do not include the ".mod" extension. + mod += ".mod"; + } + this->ConsiderModule(mod.c_str() + 1, stampDir); } } else if (line == "provides") { doing_provides = true; @@ -292,7 +313,7 @@ void cmDependsFortran::ConsiderModule(const char* name, const char* stampDir) std::string stampFile = stampDir; stampFile += "/"; stampFile += name; - stampFile += ".mod.stamp"; + stampFile += ".stamp"; required->second = stampFile; } } @@ -366,7 +387,6 @@ bool cmDependsFortran::WriteDependenciesReal(const char* obj, // Always use lower case for the mod stamp file name. The // cmake_copy_f90_mod will call back to this class, which will // try various cases for the real mod file name. - std::string m = cmSystemTools::LowerCase(i); std::string modFile = mod_dir; modFile += "/"; modFile += i; @@ -375,8 +395,8 @@ bool cmDependsFortran::WriteDependenciesReal(const char* obj, cmOutputConverter::SHELL); std::string stampFile = stamp_dir; stampFile += "/"; - stampFile += m; - stampFile += ".mod.stamp"; + stampFile += i; + stampFile += ".stamp"; stampFile = this->MaybeConvertToRelativePath(binDir, stampFile); std::string const stampFileForShell = this->LocalGenerator->ConvertToOutputFormat(stampFile, @@ -423,10 +443,9 @@ bool cmDependsFortran::WriteDependenciesReal(const char* obj, bool cmDependsFortran::FindModule(std::string const& name, std::string& module) { // Construct possible names for the module file. - std::string mod_upper = cmSystemTools::UpperCase(name); - std::string mod_lower = name; - mod_upper += ".mod"; - mod_lower += ".mod"; + std::string mod_upper; + std::string mod_lower; + cmFortranModuleAppendUpperLower(name, mod_upper, mod_lower); // Search the include path for the module. std::string fullName; @@ -470,17 +489,19 @@ bool cmDependsFortran::CopyModule(const std::vector<std::string>& args) if (args.size() >= 5) { compilerId = args[4]; } + if (!cmHasLiteralSuffix(mod, ".mod") && !cmHasLiteralSuffix(mod, ".smod")) { + // Support depend.make files left by older versions of CMake. + // They do not include the ".mod" extension. + mod += ".mod"; + } std::string mod_dir = cmSystemTools::GetFilenamePath(mod); if (!mod_dir.empty()) { mod_dir += "/"; } std::string mod_upper = mod_dir; - mod_upper += cmSystemTools::UpperCase(cmSystemTools::GetFilenameName(mod)); std::string mod_lower = mod_dir; - mod_lower += cmSystemTools::LowerCase(cmSystemTools::GetFilenameName(mod)); - mod += ".mod"; - mod_upper += ".mod"; - mod_lower += ".mod"; + cmFortranModuleAppendUpperLower(cmSystemTools::GetFilenameName(mod), + mod_upper, mod_lower); if (cmSystemTools::FileExists(mod_upper, true)) { if (cmDependsFortran::ModulesDiffer(mod_upper.c_str(), stamp.c_str(), compilerId.c_str())) { diff --git a/Source/cmExportBuildAndroidMKGenerator.cxx b/Source/cmExportBuildAndroidMKGenerator.cxx index 817b5d9..0ceac85 100644 --- a/Source/cmExportBuildAndroidMKGenerator.cxx +++ b/Source/cmExportBuildAndroidMKGenerator.cxx @@ -41,7 +41,8 @@ void cmExportBuildAndroidMKGenerator::GenerateExpectedTargetsCode( } void cmExportBuildAndroidMKGenerator::GenerateImportTargetCode( - std::ostream& os, const cmGeneratorTarget* target) + std::ostream& os, cmGeneratorTarget const* target, + cmStateEnums::TargetType /*targetType*/) { std::string targetName = this->Namespace; targetName += target->GetExportName(); diff --git a/Source/cmExportBuildAndroidMKGenerator.h b/Source/cmExportBuildAndroidMKGenerator.h index c80839b..a9b6107 100644 --- a/Source/cmExportBuildAndroidMKGenerator.h +++ b/Source/cmExportBuildAndroidMKGenerator.h @@ -11,6 +11,7 @@ #include "cmExportBuildFileGenerator.h" #include "cmExportFileGenerator.h" +#include "cmStateTypes.h" class cmGeneratorTarget; @@ -47,8 +48,9 @@ protected: void GenerateImportHeaderCode(std::ostream& os, const std::string& config = "") override; void GenerateImportFooterCode(std::ostream& os) override; - void GenerateImportTargetCode(std::ostream& os, - const cmGeneratorTarget* target) override; + void GenerateImportTargetCode( + std::ostream& os, cmGeneratorTarget const* target, + cmStateEnums::TargetType /*targetType*/) override; void GenerateExpectedTargetsCode( std::ostream& os, const std::string& expectedTargets) override; void GenerateImportPropertyCode( diff --git a/Source/cmExportBuildFileGenerator.cxx b/Source/cmExportBuildFileGenerator.cxx index f7aa6e8..72489bf 100644 --- a/Source/cmExportBuildFileGenerator.cxx +++ b/Source/cmExportBuildFileGenerator.cxx @@ -59,7 +59,7 @@ bool cmExportBuildFileGenerator::GenerateMainFile(std::ostream& os) this->LG->GetMakefile()->GetBacktrace()); return false; } - if (te->GetType() == cmStateEnums::INTERFACE_LIBRARY) { + if (this->GetExportTargetType(te) == cmStateEnums::INTERFACE_LIBRARY) { this->GenerateRequiredCMakeVersion(os, "3.0.0"); } } @@ -71,7 +71,7 @@ bool cmExportBuildFileGenerator::GenerateMainFile(std::ostream& os) // Create all the imported targets. for (cmGeneratorTarget* gte : this->Exports) { - this->GenerateImportTargetCode(os, gte); + this->GenerateImportTargetCode(os, gte, this->GetExportTargetType(gte)); gte->Target->AppendBuildInterfaceIncludes(); @@ -97,6 +97,15 @@ bool cmExportBuildFileGenerator::GenerateMainFile(std::ostream& os) properties, missingTargets); this->PopulateInterfaceProperty("INTERFACE_POSITION_INDEPENDENT_CODE", gte, properties); + + std::string errorMessage; + if (!this->PopulateExportProperties(gte, properties, errorMessage)) { + this->LG->GetGlobalGenerator()->GetCMakeInstance()->IssueMessage( + cmake::FATAL_ERROR, errorMessage, + this->LG->GetMakefile()->GetBacktrace()); + return false; + } + const bool newCMP0022Behavior = gte->GetPolicyStatusCMP0022() != cmPolicies::WARN && gte->GetPolicyStatusCMP0022() != cmPolicies::OLD; @@ -128,12 +137,13 @@ void cmExportBuildFileGenerator::GenerateImportTargetsConfig( // Collect import properties for this target. ImportPropertyMap properties; - if (target->GetType() != cmStateEnums::INTERFACE_LIBRARY) { + if (this->GetExportTargetType(target) != cmStateEnums::INTERFACE_LIBRARY) { this->SetImportLocationProperty(config, suffix, target, properties); } if (!properties.empty()) { // Get the rest of the target details. - if (target->GetType() != cmStateEnums::INTERFACE_LIBRARY) { + if (this->GetExportTargetType(target) != + cmStateEnums::INTERFACE_LIBRARY) { this->SetImportDetailProperties(config, suffix, target, properties, missingTargets); this->SetImportLinkInterface(config, suffix, @@ -153,6 +163,21 @@ void cmExportBuildFileGenerator::GenerateImportTargetsConfig( } } +cmStateEnums::TargetType cmExportBuildFileGenerator::GetExportTargetType( + cmGeneratorTarget const* target) const +{ + cmStateEnums::TargetType targetType = target->GetType(); + // An object library exports as an interface library if we cannot + // tell clients where to find the objects. This is sufficient + // to support transitive usage requirements on other targets that + // use the object library. + if (targetType == cmStateEnums::OBJECT_LIBRARY && + !this->LG->GetGlobalGenerator()->HasKnownObjectFileLocation(nullptr)) { + targetType = cmStateEnums::INTERFACE_LIBRARY; + } + return targetType; +} + void cmExportBuildFileGenerator::SetExportSet(cmExportSet* exportSet) { this->ExportSet = exportSet; @@ -199,13 +224,14 @@ void cmExportBuildFileGenerator::SetImportLocationProperty( } // Add the import library for windows DLLs. - if (target->HasImportLibrary() && + if (target->HasImportLibrary(config) && mf->GetDefinition("CMAKE_IMPORT_LIBRARY_SUFFIX")) { std::string prop = "IMPORTED_IMPLIB"; prop += suffix; std::string value = target->GetFullPath(config, cmStateEnums::ImportLibraryArtifact); - target->GetImplibGNUtoMS(value, value, "${CMAKE_IMPORT_LIBRARY_SUFFIX}"); + target->GetImplibGNUtoMS(config, value, value, + "${CMAKE_IMPORT_LIBRARY_SUFFIX}"); properties[prop] = value; } } diff --git a/Source/cmExportBuildFileGenerator.h b/Source/cmExportBuildFileGenerator.h index 6457a77..ada2709 100644 --- a/Source/cmExportBuildFileGenerator.h +++ b/Source/cmExportBuildFileGenerator.h @@ -6,6 +6,7 @@ #include "cmConfigure.h" // IWYU pragma: keep #include "cmExportFileGenerator.h" +#include "cmStateTypes.h" #include <iosfwd> #include <string> @@ -53,6 +54,8 @@ protected: void GenerateImportTargetsConfig( std::ostream& os, const std::string& config, std::string const& suffix, std::vector<std::string>& missingTargets) override; + cmStateEnums::TargetType GetExportTargetType( + cmGeneratorTarget const* target) const; void HandleMissingTarget(std::string& link_libs, std::vector<std::string>& missingTargets, cmGeneratorTarget* depender, diff --git a/Source/cmExportCommand.cxx b/Source/cmExportCommand.cxx index c8a727d..655ebe8 100644 --- a/Source/cmExportCommand.cxx +++ b/Source/cmExportCommand.cxx @@ -146,17 +146,6 @@ bool cmExportCommand::InitialPass(std::vector<std::string> const& args, } if (cmTarget* target = gg->FindTarget(currentTarget)) { - if (target->GetType() == cmStateEnums::OBJECT_LIBRARY) { - std::string reason; - if (!this->Makefile->GetGlobalGenerator() - ->HasKnownObjectFileLocation(&reason)) { - std::ostringstream e; - e << "given OBJECT library \"" << currentTarget - << "\" which may not be exported" << reason << "."; - this->SetError(e.str()); - return false; - } - } if (target->GetType() == cmStateEnums::UTILITY) { this->SetError("given custom target \"" + currentTarget + "\" which may not be exported."); diff --git a/Source/cmExportFileGenerator.cxx b/Source/cmExportFileGenerator.cxx index 434abdc..8894d44 100644 --- a/Source/cmExportFileGenerator.cxx +++ b/Source/cmExportFileGenerator.cxx @@ -11,6 +11,8 @@ #include "cmMakefile.h" #include "cmOutputConverter.h" #include "cmPolicies.h" +#include "cmProperty.h" +#include "cmPropertyMap.h" #include "cmStateTypes.h" #include "cmSystemTools.h" #include "cmTarget.h" @@ -775,6 +777,20 @@ void cmExportFileGenerator::SetImportDetailProperties( properties[prop] = m.str(); } } + + // Add information if this target is a managed target + if (target->GetManagedType(config) != + cmGeneratorTarget::ManagedType::Native) { + std::string prop = "IMPORTED_COMMON_LANGUAGE_RUNTIME"; + prop += suffix; + std::string propval; + if (auto* p = target->GetProperty("COMMON_LANGUAGE_RUNTIME")) { + propval = p; + } + // TODO: make sure propval is set to non-empty string for + // CSharp targets (i.e. force ManagedType::Managed). + properties[prop] = propval; + } } template <typename T> @@ -901,8 +917,10 @@ void cmExportFileGenerator::GenerateExpectedTargetsCode( "\n\n"; /* clang-format on */ } + void cmExportFileGenerator::GenerateImportTargetCode( - std::ostream& os, const cmGeneratorTarget* target) + std::ostream& os, cmGeneratorTarget const* target, + cmStateEnums::TargetType targetType) { // Construct the imported target name. std::string targetName = this->Namespace; @@ -911,7 +929,7 @@ void cmExportFileGenerator::GenerateImportTargetCode( // Create the imported target. os << "# Create imported target " << targetName << "\n"; - switch (target->GetType()) { + switch (targetType) { case cmStateEnums::EXECUTABLE: os << "add_executable(" << targetName << " IMPORTED)\n"; break; @@ -1095,3 +1113,41 @@ void cmExportFileGenerator::GenerateImportedFileChecksCode( os << ")\n\n"; } + +bool cmExportFileGenerator::PopulateExportProperties( + cmGeneratorTarget* gte, ImportPropertyMap& properties, + std::string& errorMessage) +{ + auto& targetProperties = gte->Target->GetProperties(); + const auto& exportProperties = targetProperties.find("EXPORT_PROPERTIES"); + if (exportProperties != targetProperties.end()) { + std::vector<std::string> propsToExport; + cmSystemTools::ExpandListArgument(exportProperties->second.GetValue(), + propsToExport); + for (auto& prop : propsToExport) { + /* Black list reserved properties */ + if (cmSystemTools::StringStartsWith(prop, "IMPORTED_") || + cmSystemTools::StringStartsWith(prop, "INTERFACE_")) { + std::ostringstream e; + e << "Target \"" << gte->Target->GetName() << "\" contains property \"" + << prop << "\" in EXPORT_PROPERTIES but IMPORTED_* and INTERFACE_* " + << "properties are reserved."; + errorMessage = e.str(); + return false; + } + auto propertyValue = targetProperties.GetPropertyValue(prop); + std::string evaluatedValue = cmGeneratorExpression::Preprocess( + propertyValue, cmGeneratorExpression::StripAllGeneratorExpressions); + if (evaluatedValue != propertyValue) { + std::ostringstream e; + e << "Target \"" << gte->Target->GetName() << "\" contains property \"" + << prop << "\" in EXPORT_PROPERTIES but this property contains a " + << "generator expression. This is not allowed."; + errorMessage = e.str(); + return false; + } + properties[prop] = propertyValue; + } + } + return true; +} diff --git a/Source/cmExportFileGenerator.h b/Source/cmExportFileGenerator.h index 985c8f6..954e6c5 100644 --- a/Source/cmExportFileGenerator.h +++ b/Source/cmExportFileGenerator.h @@ -6,6 +6,7 @@ #include "cmConfigure.h" // IWYU pragma: keep #include "cmGeneratorExpression.h" +#include "cmStateTypes.h" #include "cmVersion.h" #include "cmVersionConfig.h" @@ -76,7 +77,8 @@ protected: virtual void GenerateImportFooterCode(std::ostream& os); void GenerateImportVersionCode(std::ostream& os); virtual void GenerateImportTargetCode(std::ostream& os, - cmGeneratorTarget const* target); + cmGeneratorTarget const* target, + cmStateEnums::TargetType targetType); virtual void GenerateImportPropertyCode(std::ostream& os, const std::string& config, cmGeneratorTarget const* target, @@ -166,6 +168,10 @@ protected: virtual void GenerateRequiredCMakeVersion(std::ostream& os, const char* versionString); + bool PopulateExportProperties(cmGeneratorTarget* gte, + ImportPropertyMap& properties, + std::string& errorMessage); + // The namespace in which the exports are placed in the generated file. std::string Namespace; diff --git a/Source/cmExportInstallAndroidMKGenerator.cxx b/Source/cmExportInstallAndroidMKGenerator.cxx index fe565e6..9bc8089 100644 --- a/Source/cmExportInstallAndroidMKGenerator.cxx +++ b/Source/cmExportInstallAndroidMKGenerator.cxx @@ -55,7 +55,8 @@ void cmExportInstallAndroidMKGenerator::GenerateImportFooterCode(std::ostream&) } void cmExportInstallAndroidMKGenerator::GenerateImportTargetCode( - std::ostream& os, const cmGeneratorTarget* target) + std::ostream& os, cmGeneratorTarget const* target, + cmStateEnums::TargetType /*targetType*/) { std::string targetName = this->Namespace; targetName += target->GetExportName(); diff --git a/Source/cmExportInstallAndroidMKGenerator.h b/Source/cmExportInstallAndroidMKGenerator.h index 91554ee..8883ffa 100644 --- a/Source/cmExportInstallAndroidMKGenerator.h +++ b/Source/cmExportInstallAndroidMKGenerator.h @@ -12,6 +12,7 @@ #include "cmExportFileGenerator.h" #include "cmExportInstallFileGenerator.h" +#include "cmStateTypes.h" class cmGeneratorTarget; class cmInstallExportGenerator; @@ -41,8 +42,9 @@ protected: void GenerateImportHeaderCode(std::ostream& os, const std::string& config = "") override; void GenerateImportFooterCode(std::ostream& os) override; - void GenerateImportTargetCode(std::ostream& os, - const cmGeneratorTarget* target) override; + void GenerateImportTargetCode( + std::ostream& os, cmGeneratorTarget const* target, + cmStateEnums::TargetType /*targetType*/) override; void GenerateExpectedTargetsCode( std::ostream& os, const std::string& expectedTargets) override; void GenerateImportPropertyCode( diff --git a/Source/cmExportInstallFileGenerator.cxx b/Source/cmExportInstallFileGenerator.cxx index 954b561..63d04a6 100644 --- a/Source/cmExportInstallFileGenerator.cxx +++ b/Source/cmExportInstallFileGenerator.cxx @@ -75,11 +75,12 @@ bool cmExportInstallFileGenerator::GenerateMainFile(std::ostream& os) // Create all the imported targets. for (cmTargetExport* te : allTargets) { cmGeneratorTarget* gt = te->Target; + cmStateEnums::TargetType targetType = this->GetExportTargetType(te); requiresConfigFiles = - requiresConfigFiles || gt->GetType() != cmStateEnums::INTERFACE_LIBRARY; + requiresConfigFiles || targetType != cmStateEnums::INTERFACE_LIBRARY; - this->GenerateImportTargetCode(os, gt); + this->GenerateImportTargetCode(os, gt, targetType); ImportPropertyMap properties; @@ -103,6 +104,12 @@ bool cmExportInstallFileGenerator::GenerateMainFile(std::ostream& os) cmGeneratorExpression::InstallInterface, properties, missingTargets); + std::string errorMessage; + if (!this->PopulateExportProperties(gt, properties, errorMessage)) { + cmSystemTools::Error(errorMessage.c_str()); + return false; + } + const bool newCMP0022Behavior = gt->GetPolicyStatusCMP0022() != cmPolicies::WARN && gt->GetPolicyStatusCMP0022() != cmPolicies::OLD; @@ -114,7 +121,7 @@ bool cmExportInstallFileGenerator::GenerateMainFile(std::ostream& os) require2_8_12 = true; } } - if (gt->GetType() == cmStateEnums::INTERFACE_LIBRARY) { + if (targetType == cmStateEnums::INTERFACE_LIBRARY) { require3_0_0 = true; } if (gt->GetProperty("INTERFACE_SOURCES")) { @@ -308,7 +315,7 @@ void cmExportInstallFileGenerator::GenerateImportTargetsConfig( // Add each target in the set to the export. for (cmTargetExport* te : *this->IEGen->GetExportSet()->GetTargetExports()) { // Collect import properties for this target. - if (te->Target->GetType() == cmStateEnums::INTERFACE_LIBRARY) { + if (this->GetExportTargetType(te) == cmStateEnums::INTERFACE_LIBRARY) { continue; } @@ -426,6 +433,19 @@ void cmExportInstallFileGenerator::SetImportLocationProperty( } } +cmStateEnums::TargetType cmExportInstallFileGenerator::GetExportTargetType( + cmTargetExport const* targetExport) const +{ + cmStateEnums::TargetType targetType = targetExport->Target->GetType(); + // An OBJECT library installed with no OBJECTS DESTINATION + // is transformed to an INTERFACE library. + if (targetType == cmStateEnums::OBJECT_LIBRARY && + targetExport->ObjectsGenerator == nullptr) { + targetType = cmStateEnums::INTERFACE_LIBRARY; + } + return targetType; +} + void cmExportInstallFileGenerator::HandleMissingTarget( std::string& link_libs, std::vector<std::string>& missingTargets, cmGeneratorTarget* depender, cmGeneratorTarget* dependee) diff --git a/Source/cmExportInstallFileGenerator.h b/Source/cmExportInstallFileGenerator.h index cda8433..ea607fb 100644 --- a/Source/cmExportInstallFileGenerator.h +++ b/Source/cmExportInstallFileGenerator.h @@ -6,6 +6,7 @@ #include "cmConfigure.h" // IWYU pragma: keep #include "cmExportFileGenerator.h" +#include "cmStateTypes.h" #include <iosfwd> #include <map> @@ -17,6 +18,7 @@ class cmGeneratorTarget; class cmGlobalGenerator; class cmInstallExportGenerator; class cmInstallTargetGenerator; +class cmTargetExport; /** \class cmExportInstallFileGenerator * \brief Generate a file exporting targets from an install tree. @@ -57,6 +59,8 @@ protected: void GenerateImportTargetsConfig( std::ostream& os, const std::string& config, std::string const& suffix, std::vector<std::string>& missingTargets) override; + cmStateEnums::TargetType GetExportTargetType( + cmTargetExport const* targetExport) const; void HandleMissingTarget(std::string& link_libs, std::vector<std::string>& missingTargets, cmGeneratorTarget* depender, diff --git a/Source/cmExportLibraryDependenciesCommand.h b/Source/cmExportLibraryDependenciesCommand.h index bf5e9bc..8414866 100644 --- a/Source/cmExportLibraryDependenciesCommand.h +++ b/Source/cmExportLibraryDependenciesCommand.h @@ -27,7 +27,7 @@ public: private: std::string Filename; - bool Append; + bool Append = false; void ConstFinalPass() const; }; diff --git a/Source/cmExportTryCompileFileGenerator.cxx b/Source/cmExportTryCompileFileGenerator.cxx index ae8cd37..87648cb 100644 --- a/Source/cmExportTryCompileFileGenerator.cxx +++ b/Source/cmExportTryCompileFileGenerator.cxx @@ -33,7 +33,7 @@ bool cmExportTryCompileFileGenerator::GenerateMainFile(std::ostream& os) this->Exports.pop_back(); if (emitted.insert(te).second) { emittedDeps.insert(te); - this->GenerateImportTargetCode(os, te); + this->GenerateImportTargetCode(os, te, te->GetType()); ImportPropertyMap properties; diff --git a/Source/cmExternalMakefileProjectGenerator.h b/Source/cmExternalMakefileProjectGenerator.h index 5cc6442..d48abca 100644 --- a/Source/cmExternalMakefileProjectGenerator.h +++ b/Source/cmExternalMakefileProjectGenerator.h @@ -62,7 +62,7 @@ protected: ///! Contains the names of the global generators support by this generator. std::vector<std::string> SupportedGlobalGenerators; ///! the global generator which creates the makefiles - const cmGlobalGenerator* GlobalGenerator; + const cmGlobalGenerator* GlobalGenerator = nullptr; std::string Name; }; diff --git a/Source/cmExtraCodeLiteGenerator.cxx b/Source/cmExtraCodeLiteGenerator.cxx index 4dbaa3f..c7c780c 100644 --- a/Source/cmExtraCodeLiteGenerator.cxx +++ b/Source/cmExtraCodeLiteGenerator.cxx @@ -408,7 +408,6 @@ void cmExtraCodeLiteGenerator::CreateProjectSourceEntries( const std::string& projectPath, const cmMakefile* mf, const std::string& projectType, const std::string& targetName) { - cmXMLWriter& xml(*_xml); FindMatchingHeaderfiles(cFiles, otherFiles); // Create 2 virtual folders: src and include @@ -469,10 +468,14 @@ void cmExtraCodeLiteGenerator::CreateProjectSourceEntries( xml.EndElement(); // ResourceCompiler xml.StartElement("General"); - std::string outputPath = mf->GetSafeDefinition("EXECUTABLE_OUTPUT_PATH"); + std::string outputPath = + mf->GetSafeDefinition("CMAKE_RUNTIME_OUTPUT_DIRECTORY"); + if (outputPath.empty()) { + outputPath = mf->GetSafeDefinition("EXECUTABLE_OUTPUT_PATH"); + } std::string relapath; if (!outputPath.empty()) { - relapath = cmSystemTools::RelativePath(this->WorkspacePath, outputPath); + relapath = cmSystemTools::RelativePath(projectPath, outputPath); xml.Attribute("OutputFile", relapath + "/$(ProjectName)"); } else { xml.Attribute("OutputFile", "$(IntermediateDirectory)/$(ProjectName)"); @@ -635,7 +638,7 @@ std::string cmExtraCodeLiteGenerator::GetBuildCommand( if (generator == "NMake Makefiles" || generator == "Ninja") { ss << make; } else if (generator == "MinGW Makefiles" || generator == "Unix Makefiles") { - ss << make << " -j " << this->CpuCount; + ss << make << " -f$(ProjectPath)/Makefile -j " << this->CpuCount; } if (!targetName.empty()) { ss << " " << targetName; diff --git a/Source/cmFileCommand.cxx b/Source/cmFileCommand.cxx index d3dcc01..6c1a869 100644 --- a/Source/cmFileCommand.cxx +++ b/Source/cmFileCommand.cxx @@ -160,6 +160,12 @@ bool cmFileCommand::InitialPass(std::vector<std::string> const& args, if (subCommand == "TO_NATIVE_PATH") { return this->HandleCMakePathCommand(args, true); } + if (subCommand == "TOUCH") { + return this->HandleTouchCommand(args, true); + } + if (subCommand == "TOUCH_NOCREATE") { + return this->HandleTouchCommand(args, false); + } if (subCommand == "TIMESTAMP") { return this->HandleTimestampCommand(args); } @@ -751,9 +757,13 @@ bool cmFileCommand::HandleGlobCommand(std::vector<std::string> const& args, } } - std::string output; - bool first = true; - for (; i != args.end(); ++i) { + std::vector<std::string> files; + bool configureDepends = false; + bool warnConfigureLate = false; + bool warnFollowedSymlinks = false; + const cmake::WorkingMode workingMode = + this->Makefile->GetCMakeInstance()->GetWorkingMode(); + while (i != args.end()) { if (*i == "LIST_DIRECTORIES") { ++i; if (i != args.end()) { @@ -771,103 +781,139 @@ bool cmFileCommand::HandleGlobCommand(std::vector<std::string> const& args, this->SetError("LIST_DIRECTORIES missing bool value."); return false; } - continue; - } - - if (recurse && (*i == "FOLLOW_SYMLINKS")) { + ++i; + if (i == args.end()) { + this->SetError("GLOB requires a glob expression after the bool."); + return false; + } + } else if (*i == "FOLLOW_SYMLINKS") { + if (!recurse) { + this->SetError("FOLLOW_SYMLINKS is not a valid parameter for GLOB."); + return false; + } explicitFollowSymlinks = true; g.RecurseThroughSymlinksOn(); ++i; if (i == args.end()) { this->SetError( - "GLOB_RECURSE requires a glob expression after FOLLOW_SYMLINKS"); + "GLOB_RECURSE requires a glob expression after FOLLOW_SYMLINKS."); return false; } - } - - if (*i == "RELATIVE") { + } else if (*i == "RELATIVE") { ++i; // skip RELATIVE if (i == args.end()) { - this->SetError("GLOB requires a directory after the RELATIVE tag"); + this->SetError("GLOB requires a directory after the RELATIVE tag."); return false; } g.SetRelative(i->c_str()); ++i; if (i == args.end()) { - this->SetError("GLOB requires a glob expression after the directory"); + this->SetError("GLOB requires a glob expression after the directory."); return false; } - } - - cmsys::Glob::GlobMessages globMessages; - if (!cmsys::SystemTools::FileIsFullPath(*i)) { - std::string expr = this->Makefile->GetCurrentSourceDirectory(); - // Handle script mode - if (!expr.empty()) { - expr += "/" + *i; - g.FindFiles(expr, &globMessages); - } else { - g.FindFiles(*i, &globMessages); + } else if (*i == "CONFIGURE_DEPENDS") { + // Generated build system depends on glob results + if (!configureDepends && warnConfigureLate) { + this->Makefile->IssueMessage( + cmake::AUTHOR_WARNING, + "CONFIGURE_DEPENDS flag was given after a glob expression was " + "already evaluated."); + } + if (workingMode != cmake::NORMAL_MODE) { + this->Makefile->IssueMessage( + cmake::FATAL_ERROR, + "CONFIGURE_DEPENDS is invalid for script and find package modes."); + return false; + } + configureDepends = true; + ++i; + if (i == args.end()) { + this->SetError( + "GLOB requires a glob expression after CONFIGURE_DEPENDS."); + return false; } } else { - g.FindFiles(*i, &globMessages); - } - - if (!globMessages.empty()) { - bool shouldExit = false; - for (cmsys::Glob::Message const& globMessage : globMessages) { - if (globMessage.type == cmsys::Glob::cyclicRecursion) { - this->Makefile->IssueMessage( - cmake::AUTHOR_WARNING, - "Cyclic recursion detected while globbing for '" + *i + "':\n" + - globMessage.content); + std::string expr = *i; + if (!cmsys::SystemTools::FileIsFullPath(*i)) { + expr = this->Makefile->GetCurrentSourceDirectory(); + // Handle script mode + if (!expr.empty()) { + expr += "/" + *i; } else { - this->Makefile->IssueMessage( - cmake::FATAL_ERROR, "Error has occurred while globbing for '" + - *i + "' - " + globMessage.content); - shouldExit = true; + expr = *i; } } - if (shouldExit) { - return false; + + cmsys::Glob::GlobMessages globMessages; + g.FindFiles(expr, &globMessages); + + if (!globMessages.empty()) { + bool shouldExit = false; + for (cmsys::Glob::Message const& globMessage : globMessages) { + if (globMessage.type == cmsys::Glob::cyclicRecursion) { + this->Makefile->IssueMessage( + cmake::AUTHOR_WARNING, + "Cyclic recursion detected while globbing for '" + *i + "':\n" + + globMessage.content); + } else { + this->Makefile->IssueMessage( + cmake::FATAL_ERROR, "Error has occurred while globbing for '" + + *i + "' - " + globMessage.content); + shouldExit = true; + } + } + if (shouldExit) { + return false; + } } - } - std::vector<std::string>::size_type cc; - std::vector<std::string>& files = g.GetFiles(); - std::sort(files.begin(), files.end()); - for (cc = 0; cc < files.size(); cc++) { - if (!first) { - output += ";"; + if (recurse && !explicitFollowSymlinks && + g.GetFollowedSymlinkCount() != 0) { + warnFollowedSymlinks = true; + } + + std::vector<std::string>& foundFiles = g.GetFiles(); + files.insert(files.end(), foundFiles.begin(), foundFiles.end()); + + if (configureDepends) { + std::sort(foundFiles.begin(), foundFiles.end()); + foundFiles.erase(std::unique(foundFiles.begin(), foundFiles.end()), + foundFiles.end()); + this->Makefile->GetCMakeInstance()->AddGlobCacheEntry( + recurse, (recurse ? g.GetRecurseListDirs() : g.GetListDirs()), + (recurse ? g.GetRecurseThroughSymlinks() : false), + (g.GetRelative() ? g.GetRelative() : ""), expr, foundFiles, variable, + this->Makefile->GetBacktrace()); + } else { + warnConfigureLate = true; } - output += files[cc]; - first = false; + ++i; } } - if (recurse && !explicitFollowSymlinks) { - switch (status) { - case cmPolicies::REQUIRED_IF_USED: - case cmPolicies::REQUIRED_ALWAYS: - case cmPolicies::NEW: - // Correct behavior, yay! - break; - case cmPolicies::OLD: - // Probably not really the expected behavior, but the author explicitly - // asked for the old behavior... no warning. - case cmPolicies::WARN: - // Possibly unexpected old behavior *and* we actually traversed - // symlinks without being explicitly asked to: warn the author. - if (g.GetFollowedSymlinkCount() != 0) { - this->Makefile->IssueMessage( - cmake::AUTHOR_WARNING, - cmPolicies::GetPolicyWarning(cmPolicies::CMP0009)); - } - break; - } + switch (status) { + case cmPolicies::REQUIRED_IF_USED: + case cmPolicies::REQUIRED_ALWAYS: + case cmPolicies::NEW: + // Correct behavior, yay! + break; + case cmPolicies::OLD: + // Probably not really the expected behavior, but the author explicitly + // asked for the old behavior... no warning. + case cmPolicies::WARN: + // Possibly unexpected old behavior *and* we actually traversed + // symlinks without being explicitly asked to: warn the author. + if (warnFollowedSymlinks) { + this->Makefile->IssueMessage( + cmake::AUTHOR_WARNING, + cmPolicies::GetPolicyWarning(cmPolicies::CMP0009)); + } + break; } - this->Makefile->AddDefinition(variable, output.c_str()); + std::sort(files.begin(), files.end()); + files.erase(std::unique(files.begin(), files.end()), files.end()); + this->Makefile->AddDefinition(variable, cmJoin(files, ";").c_str()); return true; } @@ -905,6 +951,38 @@ bool cmFileCommand::HandleMakeDirectoryCommand( return true; } +bool cmFileCommand::HandleTouchCommand(std::vector<std::string> const& args, + bool create) +{ + // File command has at least one argument + assert(args.size() > 1); + + std::vector<std::string>::const_iterator i = args.begin(); + + i++; // Get rid of subcommand + + for (; i != args.end(); ++i) { + std::string tfile = *i; + if (!cmsys::SystemTools::FileIsFullPath(tfile)) { + tfile = this->Makefile->GetCurrentSourceDirectory(); + tfile += "/" + *i; + } + if (!this->Makefile->CanIWriteThisFile(tfile)) { + std::string e = + "attempted to touch a file: " + tfile + " in a source directory."; + this->SetError(e); + cmSystemTools::SetFatalErrorOccured(); + return false; + } + if (!cmSystemTools::Touch(tfile, create)) { + std::string error = "problem touching file: " + tfile; + this->SetError(error); + return false; + } + } + return true; +} + bool cmFileCommand::HandleDifferentCommand( std::vector<std::string> const& args) { @@ -1051,14 +1129,26 @@ protected: if (permissions) { #ifdef WIN32 if (Makefile->IsOn("CMAKE_CROSSCOMPILING")) { + // Store the mode in an NTFS alternate stream. std::string mode_t_adt_filename = std::string(toFile) + ":cmake_mode_t"; + // Writing to an NTFS alternate stream changes the modification + // time, so we need to save and restore its original value. + cmSystemToolsFileTime* file_time_orig = cmSystemTools::FileTimeNew(); + cmSystemTools::FileTimeGet(toFile, file_time_orig); + cmsys::ofstream permissionStream(mode_t_adt_filename.c_str()); if (permissionStream) { permissionStream << std::oct << permissions << std::endl; } + + permissionStream.close(); + + cmSystemTools::FileTimeSet(toFile, file_time_orig); + + cmSystemTools::FileTimeDelete(file_time_orig); } #endif diff --git a/Source/cmFileCommand.h b/Source/cmFileCommand.h index 17269f3..719dca2 100644 --- a/Source/cmFileCommand.h +++ b/Source/cmFileCommand.h @@ -39,6 +39,7 @@ protected: bool HandleHashCommand(std::vector<std::string> const& args); bool HandleStringsCommand(std::vector<std::string> const& args); bool HandleGlobCommand(std::vector<std::string> const& args, bool recurse); + bool HandleTouchCommand(std::vector<std::string> const& args, bool create); bool HandleMakeDirectoryCommand(std::vector<std::string> const& args); bool HandleRelativePathCommand(std::vector<std::string> const& args); diff --git a/Source/cmFileTimeComparison.h b/Source/cmFileTimeComparison.h index b1f8ed6..114989b 100644 --- a/Source/cmFileTimeComparison.h +++ b/Source/cmFileTimeComparison.h @@ -8,9 +8,9 @@ class cmFileTimeComparisonInternal; /** \class cmFileTimeComparison - * \brief Helper class for performing globbing searches. + * \brief Helper class for comparing file modification times. * - * Finds all files that match a given globbing expression. + * Compare file modification times or test if file modification times differ. */ class cmFileTimeComparison { diff --git a/Source/cmFindBase.cxx b/Source/cmFindBase.cxx index 417cdd2..865595b 100644 --- a/Source/cmFindBase.cxx +++ b/Source/cmFindBase.cxx @@ -67,8 +67,6 @@ bool cmFindBase::ParseArguments(std::vector<std::string> const& argsIn) } this->AlreadyInCache = false; - this->SelectDefaultNoPackageRootPath(); - // Find the current root path mode. this->SelectDefaultRootPathMode(); @@ -206,16 +204,12 @@ void cmFindBase::FillPackageRootPath() { cmSearchPath& paths = this->LabeledPaths[PathLabel::PackageRoot]; - // Add package specific search prefixes - // NOTE: This should be using const_reverse_iterator but HP aCC and - // Oracle sunCC both currently have standard library issues - // with the reverse iterator APIs. - for (std::deque<std::string>::reverse_iterator pkg = - this->Makefile->FindPackageModuleStack.rbegin(); - pkg != this->Makefile->FindPackageModuleStack.rend(); ++pkg) { - std::string varName = *pkg + "_ROOT"; - paths.AddCMakePrefixPath(varName); - paths.AddEnvPrefixPath(varName); + // Add the PACKAGE_ROOT_PATH from each enclosing find_package call. + for (std::deque<std::vector<std::string>>::const_reverse_iterator pkgPaths = + this->Makefile->FindPackageRootPathStack.rbegin(); + pkgPaths != this->Makefile->FindPackageRootPathStack.rend(); + ++pkgPaths) { + paths.AddPrefixPaths(*pkgPaths); } paths.AddSuffixes(this->SearchPathSuffixes); @@ -225,8 +219,8 @@ void cmFindBase::FillCMakeVariablePath() { cmSearchPath& paths = this->LabeledPaths[PathLabel::CMake]; - // Add CMake varibles of the same name as the previous environment - // varibles CMAKE_*_PATH to be used most of the time with -D + // Add CMake variables of the same name as the previous environment + // variables CMAKE_*_PATH to be used most of the time with -D // command line options std::string var = "CMAKE_"; var += this->CMakePathName; diff --git a/Source/cmFindCommon.cxx b/Source/cmFindCommon.cxx index 4a467f3..64108d7 100644 --- a/Source/cmFindCommon.cxx +++ b/Source/cmFindCommon.cxx @@ -88,13 +88,6 @@ void cmFindCommon::InitializeSearchPathGroups() std::make_pair(PathLabel::Guess, cmSearchPath(this))); } -void cmFindCommon::SelectDefaultNoPackageRootPath() -{ - if (!this->Makefile->IsOn("__UNDOCUMENTED_CMAKE_FIND_PACKAGE_ROOT")) { - this->NoPackageRootPath = true; - } -} - void cmFindCommon::SelectDefaultRootPathMode() { // Check the policy variable for this find command type. diff --git a/Source/cmFindCommon.h b/Source/cmFindCommon.h index b237f1b..89ff174 100644 --- a/Source/cmFindCommon.h +++ b/Source/cmFindCommon.h @@ -84,9 +84,6 @@ protected: /** Compute final search path list (reroot + trailing slash). */ void ComputeFinalPaths(); - /** Decide whether to enable the PACKAGE_ROOT search entries. */ - void SelectDefaultNoPackageRootPath(); - /** Compute the current default root path mode. */ void SelectDefaultRootPathMode(); diff --git a/Source/cmFindPackageCommand.cxx b/Source/cmFindPackageCommand.cxx index 2f3a85b..46854f7 100644 --- a/Source/cmFindPackageCommand.cxx +++ b/Source/cmFindPackageCommand.cxx @@ -21,6 +21,7 @@ #include "cmAlgorithms.h" #include "cmMakefile.h" +#include "cmPolicies.h" #include "cmSearchPath.h" #include "cmState.h" #include "cmStateTypes.h" @@ -209,8 +210,6 @@ bool cmFindPackageCommand::InitialPass(std::vector<std::string> const& args, this->SortDirection = strcmp(sd, "ASC") == 0 ? Asc : Dec; } - this->SelectDefaultNoPackageRootPath(); - // Find the current root path mode. this->SelectDefaultRootPathMode(); @@ -454,6 +453,38 @@ bool cmFindPackageCommand::InitialPass(std::vector<std::string> const& args, return true; } + { + // Allocate a PACKAGE_ROOT_PATH for the current find_package call. + this->Makefile->FindPackageRootPathStack.emplace_back(); + std::vector<std::string>& rootPaths = + *this->Makefile->FindPackageRootPathStack.rbegin(); + + // Add root paths from <PackageName>_ROOT CMake and environment variables, + // subject to CMP0074. + switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0074)) { + case cmPolicies::WARN: + this->Makefile->MaybeWarnCMP0074(this->Name); + CM_FALLTHROUGH; + case cmPolicies::OLD: + // OLD behavior is to ignore the <pkg>_ROOT variables. + break; + case cmPolicies::REQUIRED_IF_USED: + case cmPolicies::REQUIRED_ALWAYS: + this->Makefile->IssueMessage( + cmake::FATAL_ERROR, + cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0074)); + break; + case cmPolicies::NEW: { + // NEW behavior is to honor the <pkg>_ROOT variables. + std::string const rootVar = this->Name + "_ROOT"; + if (const char* pkgRoot = this->Makefile->GetDefinition(rootVar)) { + cmSystemTools::ExpandListArgument(pkgRoot, rootPaths, false); + } + cmSystemTools::GetPath(rootPaths, rootVar.c_str()); + } break; + } + } + this->SetModuleVariables(components); // See if there is a Find<package>.cmake module. @@ -589,9 +620,6 @@ void cmFindPackageCommand::SetModuleVariables(const std::string& components) exact += "_FIND_VERSION_EXACT"; this->AddFindDefinition(exact, this->VersionExact ? "1" : "0"); } - - // Push on to the package stack - this->Makefile->FindPackageModuleStack.push_back(this->Name); } void cmFindPackageCommand::AddFindDefinition(const std::string& var, @@ -1076,7 +1104,7 @@ void cmFindPackageCommand::AppendSuccessInformation() this->RestoreFindDefinitions(); // Pop the package stack - this->Makefile->FindPackageModuleStack.pop_back(); + this->Makefile->FindPackageRootPathStack.pop_back(); } void cmFindPackageCommand::ComputePrefixes() @@ -1116,16 +1144,14 @@ void cmFindPackageCommand::FillPrefixesPackageRoot() { cmSearchPath& paths = this->LabeledPaths[PathLabel::PackageRoot]; - // Add package specific search prefixes - // NOTE: This should be using const_reverse_iterator but HP aCC and - // Oracle sunCC both currently have standard library issues - // with the reverse iterator APIs. - for (std::deque<std::string>::reverse_iterator pkg = - this->Makefile->FindPackageModuleStack.rbegin(); - pkg != this->Makefile->FindPackageModuleStack.rend(); ++pkg) { - std::string varName = *pkg + "_ROOT"; - paths.AddCMakePath(varName); - paths.AddEnvPath(varName); + // Add the PACKAGE_ROOT_PATH from each enclosing find_package call. + for (std::deque<std::vector<std::string>>::const_reverse_iterator pkgPaths = + this->Makefile->FindPackageRootPathStack.rbegin(); + pkgPaths != this->Makefile->FindPackageRootPathStack.rend(); + ++pkgPaths) { + for (std::string const& path : *pkgPaths) { + paths.AddPath(path); + } } } @@ -2039,7 +2065,7 @@ bool cmFindPackageCommand::SearchPrefix(std::string const& prefix_in) common.push_back("lib"); common.push_back("share"); - // PREFIX/(lib/ARCH|lib|share)/cmake/(Foo|foo|FOO).*/ + // PREFIX/(lib/ARCH|lib*|share)/cmake/(Foo|foo|FOO).*/ { cmFindPackageFileList lister(this); lister / cmFileListGeneratorFixed(prefix) / @@ -2052,7 +2078,7 @@ bool cmFindPackageCommand::SearchPrefix(std::string const& prefix_in) } } - // PREFIX/(lib/ARCH|lib|share)/(Foo|foo|FOO).*/ + // PREFIX/(lib/ARCH|lib*|share)/(Foo|foo|FOO).*/ { cmFindPackageFileList lister(this); lister / cmFileListGeneratorFixed(prefix) / @@ -2064,7 +2090,7 @@ bool cmFindPackageCommand::SearchPrefix(std::string const& prefix_in) } } - // PREFIX/(lib/ARCH|lib|share)/(Foo|foo|FOO).*/(cmake|CMake)/ + // PREFIX/(lib/ARCH|lib*|share)/(Foo|foo|FOO).*/(cmake|CMake)/ { cmFindPackageFileList lister(this); lister / cmFileListGeneratorFixed(prefix) / @@ -2077,7 +2103,7 @@ bool cmFindPackageCommand::SearchPrefix(std::string const& prefix_in) } } - // PREFIX/(Foo|foo|FOO).*/(lib/ARCH|lib|share)/cmake/(Foo|foo|FOO).*/ + // PREFIX/(Foo|foo|FOO).*/(lib/ARCH|lib*|share)/cmake/(Foo|foo|FOO).*/ { cmFindPackageFileList lister(this); lister / cmFileListGeneratorFixed(prefix) / @@ -2092,7 +2118,7 @@ bool cmFindPackageCommand::SearchPrefix(std::string const& prefix_in) } } - // PREFIX/(Foo|foo|FOO).*/(lib/ARCH|lib|share)/(Foo|foo|FOO).*/ + // PREFIX/(Foo|foo|FOO).*/(lib/ARCH|lib*|share)/(Foo|foo|FOO).*/ { cmFindPackageFileList lister(this); lister / cmFileListGeneratorFixed(prefix) / @@ -2106,7 +2132,7 @@ bool cmFindPackageCommand::SearchPrefix(std::string const& prefix_in) } } - // PREFIX/(Foo|foo|FOO).*/(lib/ARCH|lib|share)/(Foo|foo|FOO).*/(cmake|CMake)/ + // PREFIX/(Foo|foo|FOO).*/(lib/ARCH|lib*|share)/(Foo|foo|FOO).*/(cmake|CMake)/ { cmFindPackageFileList lister(this); lister / cmFileListGeneratorFixed(prefix) / diff --git a/Source/cmFortranParser.h b/Source/cmFortranParser.h index 3f5ad87..efcd100 100644 --- a/Source/cmFortranParser.h +++ b/Source/cmFortranParser.h @@ -39,11 +39,19 @@ int cmFortranParser_GetOldStartcond(cmFortranParser* parser); /* Callbacks for parser. */ void cmFortranParser_Error(cmFortranParser* parser, const char* message); -void cmFortranParser_RuleUse(cmFortranParser* parser, const char* name); +void cmFortranParser_RuleUse(cmFortranParser* parser, const char* module_name); void cmFortranParser_RuleLineDirective(cmFortranParser* parser, const char* filename); void cmFortranParser_RuleInclude(cmFortranParser* parser, const char* name); -void cmFortranParser_RuleModule(cmFortranParser* parser, const char* name); +void cmFortranParser_RuleModule(cmFortranParser* parser, + const char* module_name); +void cmFortranParser_RuleSubmodule(cmFortranParser* parser, + const char* module_name, + const char* submodule_name); +void cmFortranParser_RuleSubmoduleNested(cmFortranParser* parser, + const char* module_name, + const char* submodule_name, + const char* nested_submodule_name); void cmFortranParser_RuleDefine(cmFortranParser* parser, const char* name); void cmFortranParser_RuleUndef(cmFortranParser* parser, const char* name); void cmFortranParser_RuleIfdef(cmFortranParser* parser, const char* name); diff --git a/Source/cmFortranParserImpl.cxx b/Source/cmFortranParserImpl.cxx index dd4f16b..01cbb78 100644 --- a/Source/cmFortranParserImpl.cxx +++ b/Source/cmFortranParserImpl.cxx @@ -168,11 +168,16 @@ void cmFortranParser_Error(cmFortranParser* parser, const char* msg) parser->Error = msg ? msg : "unknown error"; } -void cmFortranParser_RuleUse(cmFortranParser* parser, const char* name) +void cmFortranParser_RuleUse(cmFortranParser* parser, const char* module_name) { - if (!parser->InPPFalseBranch) { - parser->Info.Requires.insert(cmSystemTools::LowerCase(name)); + if (parser->InPPFalseBranch) { + return; } + + // syntax: "use module_name" + // requires: "module_name.mod" + std::string const& mod_name = cmSystemTools::LowerCase(module_name); + parser->Info.Requires.insert(mod_name + ".mod"); } void cmFortranParser_RuleLineDirective(cmFortranParser* parser, @@ -225,11 +230,63 @@ void cmFortranParser_RuleInclude(cmFortranParser* parser, const char* name) } } -void cmFortranParser_RuleModule(cmFortranParser* parser, const char* name) +void cmFortranParser_RuleModule(cmFortranParser* parser, + const char* module_name) { - if (!parser->InPPFalseBranch && !parser->InInterface) { - parser->Info.Provides.insert(cmSystemTools::LowerCase(name)); + if (parser->InPPFalseBranch) { + return; } + + if (!parser->InInterface) { + // syntax: "module module_name" + // provides: "module_name.mod" + std::string const& mod_name = cmSystemTools::LowerCase(module_name); + parser->Info.Provides.insert(mod_name + ".mod"); + } +} + +void cmFortranParser_RuleSubmodule(cmFortranParser* parser, + const char* module_name, + const char* submodule_name) +{ + if (parser->InPPFalseBranch) { + return; + } + + // syntax: "submodule (module_name) submodule_name" + // requires: "module_name.mod" + // provides: "module_name@submodule_name.smod" + // + // FIXME: Some compilers split the submodule part of a module into a + // separate "module_name.smod" file. Whether it is generated or + // not depends on conditions more subtle than we currently detect. + // For now we depend directly on "module_name.mod". + + std::string const& mod_name = cmSystemTools::LowerCase(module_name); + std::string const& sub_name = cmSystemTools::LowerCase(submodule_name); + parser->Info.Requires.insert(mod_name + ".mod"); + parser->Info.Provides.insert(mod_name + "@" + sub_name + ".smod"); +} + +void cmFortranParser_RuleSubmoduleNested(cmFortranParser* parser, + const char* module_name, + const char* submodule_name, + const char* nested_submodule_name) +{ + if (parser->InPPFalseBranch) { + return; + } + + // syntax: "submodule (module_name:submodule_name) nested_submodule_name" + // requires: "module_name@submodule_name.smod" + // provides: "module_name@nested_submodule_name.smod" + + std::string const& mod_name = cmSystemTools::LowerCase(module_name); + std::string const& sub_name = cmSystemTools::LowerCase(submodule_name); + std::string const& nest_name = + cmSystemTools::LowerCase(nested_submodule_name); + parser->Info.Requires.insert(mod_name + "@" + sub_name + ".smod"); + parser->Info.Provides.insert(mod_name + "@" + nest_name + ".smod"); } void cmFortranParser_RuleDefine(cmFortranParser* parser, const char* macro) diff --git a/Source/cmGeneratorExpressionDAGChecker.cxx b/Source/cmGeneratorExpressionDAGChecker.cxx index f0eafb4..face282 100644 --- a/Source/cmGeneratorExpressionDAGChecker.cxx +++ b/Source/cmGeneratorExpressionDAGChecker.cxx @@ -154,6 +154,18 @@ bool cmGeneratorExpressionDAGChecker::GetTransitivePropertiesOnly() return top->TransitivePropertiesOnly; } +bool cmGeneratorExpressionDAGChecker::EvaluatingGenexExpression() +{ + const cmGeneratorExpressionDAGChecker* top = this; + const cmGeneratorExpressionDAGChecker* parent = this->Parent; + while (parent) { + top = parent; + parent = parent->Parent; + } + + return top->Property == "TARGET_GENEX_EVAL" || top->Property == "GENEX_EVAL"; +} + bool cmGeneratorExpressionDAGChecker::EvaluatingLinkLibraries(const char* tgt) { const cmGeneratorExpressionDAGChecker* top = this; diff --git a/Source/cmGeneratorExpressionDAGChecker.h b/Source/cmGeneratorExpressionDAGChecker.h index 3f73fca..a3a8f69 100644 --- a/Source/cmGeneratorExpressionDAGChecker.h +++ b/Source/cmGeneratorExpressionDAGChecker.h @@ -61,6 +61,7 @@ struct cmGeneratorExpressionDAGChecker void ReportError(cmGeneratorExpressionContext* context, const std::string& expr); + bool EvaluatingGenexExpression(); bool EvaluatingLinkLibraries(const char* tgt = nullptr); #define DECLARE_TRANSITIVE_PROPERTY_METHOD(METHOD) bool METHOD() const; diff --git a/Source/cmGeneratorExpressionEvaluator.h b/Source/cmGeneratorExpressionEvaluator.h index 92dac79..0561799 100644 --- a/Source/cmGeneratorExpressionEvaluator.h +++ b/Source/cmGeneratorExpressionEvaluator.h @@ -7,6 +7,7 @@ #include <stddef.h> #include <string> +#include <utility> #include <vector> struct cmGeneratorExpressionContext; @@ -64,17 +65,16 @@ private: struct GeneratorExpressionContent : public cmGeneratorExpressionEvaluator { GeneratorExpressionContent(const char* startContent, size_t length); - void SetIdentifier( - std::vector<cmGeneratorExpressionEvaluator*> const& identifier) + + void SetIdentifier(std::vector<cmGeneratorExpressionEvaluator*> identifier) { - this->IdentifierChildren = identifier; + this->IdentifierChildren = std::move(identifier); } void SetParameters( - std::vector<std::vector<cmGeneratorExpressionEvaluator*>> const& - parameters) + std::vector<std::vector<cmGeneratorExpressionEvaluator*>> parameters) { - this->ParamChildren = parameters; + this->ParamChildren = std::move(parameters); } Type GetType() const override diff --git a/Source/cmGeneratorExpressionNode.cxx b/Source/cmGeneratorExpressionNode.cxx index c1f1ee4..399e894 100644 --- a/Source/cmGeneratorExpressionNode.cxx +++ b/Source/cmGeneratorExpressionNode.cxx @@ -275,6 +275,203 @@ static const struct EqualNode : public cmGeneratorExpressionNode } } equalNode; +static const struct InListNode : public cmGeneratorExpressionNode +{ + InListNode() {} + + int NumExpectedParameters() const override { return 2; } + + std::string Evaluate( + const std::vector<std::string>& parameters, + cmGeneratorExpressionContext* /*context*/, + const GeneratorExpressionContent* /*content*/, + cmGeneratorExpressionDAGChecker* /*dagChecker*/) const override + { + std::vector<std::string> values; + cmSystemTools::ExpandListArgument(parameters[1], values); + if (values.empty()) { + return "0"; + } + + return std::find(values.cbegin(), values.cend(), parameters.front()) == + values.cend() + ? "0" + : "1"; + } +} inListNode; + +static const struct TargetExistsNode : public cmGeneratorExpressionNode +{ + TargetExistsNode() {} + + int NumExpectedParameters() const override { return 1; } + + std::string Evaluate( + const std::vector<std::string>& parameters, + cmGeneratorExpressionContext* context, + const GeneratorExpressionContent* content, + cmGeneratorExpressionDAGChecker* /*dagChecker*/) const override + { + if (parameters.size() != 1) { + reportError(context, content->GetOriginalExpression(), + "$<TARGET_EXISTS:...> expression requires one parameter"); + return std::string(); + } + + std::string targetName = parameters.front(); + if (targetName.empty() || + !cmGeneratorExpression::IsValidTargetName(targetName)) { + reportError(context, content->GetOriginalExpression(), + "$<TARGET_EXISTS:tgt> expression requires a non-empty " + "valid target name."); + return std::string(); + } + + return context->LG->GetMakefile()->FindTargetToUse(targetName) ? "1" : "0"; + } +} targetExistsNode; + +static const struct TargetNameIfExistsNode : public cmGeneratorExpressionNode +{ + TargetNameIfExistsNode() {} + + int NumExpectedParameters() const override { return 1; } + + std::string Evaluate( + const std::vector<std::string>& parameters, + cmGeneratorExpressionContext* context, + const GeneratorExpressionContent* content, + cmGeneratorExpressionDAGChecker* /*dagChecker*/) const override + { + if (parameters.size() != 1) { + reportError(context, content->GetOriginalExpression(), + "$<TARGET_NAME_IF_EXISTS:...> expression requires one " + "parameter"); + return std::string(); + } + + std::string targetName = parameters.front(); + if (targetName.empty() || + !cmGeneratorExpression::IsValidTargetName(targetName)) { + reportError(context, content->GetOriginalExpression(), + "$<TARGET_NAME_IF_EXISTS:tgt> expression requires a " + "non-empty valid target name."); + return std::string(); + } + + return context->LG->GetMakefile()->FindTargetToUse(targetName) + ? targetName + : std::string(); + } +} targetNameIfExistsNode; + +struct GenexEvaluator : public cmGeneratorExpressionNode +{ + GenexEvaluator() {} + +protected: + std::string EvaluateExpression( + const std::string& genexOperator, const std::string& expression, + cmGeneratorExpressionContext* context, + const GeneratorExpressionContent* content, + cmGeneratorExpressionDAGChecker* dagCheckerParent) const + { + if (context->HeadTarget) { + cmGeneratorExpressionDAGChecker dagChecker( + context->Backtrace, context->HeadTarget->GetName(), genexOperator, + content, dagCheckerParent); + switch (dagChecker.Check()) { + case cmGeneratorExpressionDAGChecker::SELF_REFERENCE: + case cmGeneratorExpressionDAGChecker::CYCLIC_REFERENCE: { + dagChecker.ReportError(context, content->GetOriginalExpression()); + return std::string(); + } + case cmGeneratorExpressionDAGChecker::ALREADY_SEEN: + case cmGeneratorExpressionDAGChecker::DAG: + break; + } + + return this->EvaluateDependentExpression( + expression, context->LG, context, context->HeadTarget, + context->CurrentTarget, &dagChecker); + } + + return this->EvaluateDependentExpression( + expression, context->LG, context, context->HeadTarget, + context->CurrentTarget, dagCheckerParent); + } +}; + +static const struct TargetGenexEvalNode : public GenexEvaluator +{ + TargetGenexEvalNode() {} + + int NumExpectedParameters() const override { return 2; } + + bool AcceptsArbitraryContentParameter() const override { return true; } + + std::string Evaluate( + const std::vector<std::string>& parameters, + cmGeneratorExpressionContext* context, + const GeneratorExpressionContent* content, + cmGeneratorExpressionDAGChecker* dagCheckerParent) const override + { + const std::string& targetName = parameters.front(); + if (targetName.empty() || + !cmGeneratorExpression::IsValidTargetName(targetName)) { + reportError(context, content->GetOriginalExpression(), + "$<TARGET_GENEX_EVAL:tgt, ...> expression requires a " + "non-empty valid target name."); + return std::string(); + } + + const auto* target = context->LG->FindGeneratorTargetToUse(targetName); + if (!target) { + std::ostringstream e; + e << "$<TARGET_GENEX_EVAL:tgt, ...> target \"" << targetName + << "\" not found."; + reportError(context, content->GetOriginalExpression(), e.str()); + return std::string(); + } + + const std::string& expression = parameters[1]; + if (expression.empty()) { + return expression; + } + + cmGeneratorExpressionContext targetContext( + context->LG, context->Config, context->Quiet, target, target, + context->EvaluateForBuildsystem, context->Backtrace, context->Language); + + return this->EvaluateExpression("TARGET_GENEX_EVAL", expression, + &targetContext, content, dagCheckerParent); + } +} targetGenexEvalNode; + +static const struct GenexEvalNode : public GenexEvaluator +{ + GenexEvalNode() {} + + int NumExpectedParameters() const override { return 1; } + + bool AcceptsArbitraryContentParameter() const override { return true; } + + std::string Evaluate( + const std::vector<std::string>& parameters, + cmGeneratorExpressionContext* context, + const GeneratorExpressionContent* content, + cmGeneratorExpressionDAGChecker* dagCheckerParent) const override + { + const std::string& expression = parameters[0]; + if (expression.empty()) { + return expression; + } + + return this->EvaluateExpression("GENEX_EVAL", expression, context, content, + dagCheckerParent); + } +} genexEvalNode; + static const struct LowerCaseNode : public cmGeneratorExpressionNode { LowerCaseNode() {} @@ -1034,7 +1231,9 @@ static const struct TargetPropertyNode : public cmGeneratorExpressionNode const char* prop = target->GetProperty(propertyName); if (dagCheckerParent) { - if (dagCheckerParent->EvaluatingLinkLibraries()) { + if (dagCheckerParent->EvaluatingGenexExpression()) { + // No check required. + } else if (dagCheckerParent->EvaluatingLinkLibraries()) { #define TRANSITIVE_PROPERTY_COMPARE(PROPERTY) \ (#PROPERTY == propertyName || "INTERFACE_" #PROPERTY == propertyName) || if (CM_FOR_EACH_TRANSITIVE_PROPERTY_NAME( @@ -1585,7 +1784,8 @@ struct TargetFilesystemArtifactResultCreator<ArtifactLinkerTag> "executables with ENABLE_EXPORTS."); return std::string(); } - cmStateEnums::ArtifactType artifact = target->HasImportLibrary() + cmStateEnums::ArtifactType artifact = + target->HasImportLibrary(context->Config) ? cmStateEnums::ImportLibraryArtifact : cmStateEnums::RuntimeBinaryArtifact; return target->GetFullPath(context->Config, artifact); @@ -1827,6 +2027,7 @@ const cmGeneratorExpressionNode* cmGeneratorExpressionNode::GetNode( nodeMap["TARGET_BUNDLE_CONTENT_DIR"] = &targetBundleContentDirNode; nodeMap["STREQUAL"] = &strEqualNode; nodeMap["EQUAL"] = &equalNode; + nodeMap["IN_LIST"] = &inListNode; nodeMap["LOWER_CASE"] = &lowerCaseNode; nodeMap["UPPER_CASE"] = &upperCaseNode; nodeMap["MAKE_C_IDENTIFIER"] = &makeCIdentifierNode; @@ -1839,6 +2040,10 @@ const cmGeneratorExpressionNode* cmGeneratorExpressionNode::GetNode( nodeMap["TARGET_NAME"] = &targetNameNode; nodeMap["TARGET_OBJECTS"] = &targetObjectsNode; nodeMap["TARGET_POLICY"] = &targetPolicyNode; + nodeMap["TARGET_EXISTS"] = &targetExistsNode; + nodeMap["TARGET_NAME_IF_EXISTS"] = &targetNameIfExistsNode; + nodeMap["TARGET_GENEX_EVAL"] = &targetGenexEvalNode; + nodeMap["GENEX_EVAL"] = &genexEvalNode; nodeMap["BUILD_INTERFACE"] = &buildInterfaceNode; nodeMap["INSTALL_INTERFACE"] = &installInterfaceNode; nodeMap["INSTALL_PREFIX"] = &installPrefixNode; diff --git a/Source/cmGeneratorExpressionParser.cxx b/Source/cmGeneratorExpressionParser.cxx index 278de04..7b4dc7b 100644 --- a/Source/cmGeneratorExpressionParser.cxx +++ b/Source/cmGeneratorExpressionParser.cxx @@ -6,6 +6,7 @@ #include <assert.h> #include <stddef.h> +#include <utility> cmGeneratorExpressionParser::cmGeneratorExpressionParser( const std::vector<cmGeneratorExpressionToken>& tokens) @@ -92,7 +93,7 @@ void cmGeneratorExpressionParser::ParseGeneratorExpression( assert(this->it != this->Tokens.end()); ++this->it; --this->NestingLevel; - content->SetIdentifier(identifier); + content->SetIdentifier(std::move(identifier)); result.push_back(content); return; } @@ -198,8 +199,8 @@ void cmGeneratorExpressionParser::ParseGeneratorExpression( ((this->it - 1)->Content - startToken->Content) + (this->it - 1)->Length; GeneratorExpressionContent* content = new GeneratorExpressionContent(startToken->Content, contentLength); - content->SetIdentifier(identifier); - content->SetParameters(parameters); + content->SetIdentifier(std::move(identifier)); + content->SetParameters(std::move(parameters)); result.push_back(content); } diff --git a/Source/cmGeneratorTarget.cxx b/Source/cmGeneratorTarget.cxx index 2bb01b2..0cb299c 100644 --- a/Source/cmGeneratorTarget.cxx +++ b/Source/cmGeneratorTarget.cxx @@ -132,8 +132,8 @@ cmGeneratorTarget::cmGeneratorTarget(cmTarget* t, cmLocalGenerator* lg) this->SourceEntries, true); this->DLLPlatform = - (this->Makefile->IsOn("WIN32") || this->Makefile->IsOn("CYGWIN") || - this->Makefile->IsOn("MINGW")); + strcmp(this->Makefile->GetSafeDefinition("CMAKE_IMPORT_LIBRARY_SUFFIX"), + "") != 0; this->PolicyMap = t->PolicyMap; } @@ -240,13 +240,16 @@ const char* cmGeneratorTarget::GetOutputTargetType( case cmStateEnums::MODULE_LIBRARY: switch (artifact) { case cmStateEnums::RuntimeBinaryArtifact: - // Module import libraries are treated as archive targets. + // Module libraries are always treated as library targets. return "LIBRARY"; case cmStateEnums::ImportLibraryArtifact: - // Module libraries are always treated as library targets. + // Module import libraries are treated as archive targets. return "ARCHIVE"; } break; + case cmStateEnums::OBJECT_LIBRARY: + // Object libraries are always treated as object targets. + return "OBJECT"; case cmStateEnums::EXECUTABLE: switch (artifact) { case cmStateEnums::RuntimeBinaryArtifact: @@ -808,6 +811,26 @@ static void AddInterfaceEntries( } } +static void AddObjectEntries( + cmGeneratorTarget const* thisTarget, std::string const& config, + std::vector<cmGeneratorTarget::TargetPropertyEntry*>& entries) +{ + if (cmLinkImplementationLibraries const* impl = + thisTarget->GetLinkImplementationLibraries(config)) { + for (cmLinkImplItem const& lib : impl->Libraries) { + if (lib.Target && + lib.Target->GetType() == cmStateEnums::OBJECT_LIBRARY) { + std::string genex = "$<TARGET_OBJECTS:" + lib + ">"; + cmGeneratorExpression ge(lib.Backtrace); + std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(genex); + cge->SetEvaluateForBuildsystem(true); + entries.push_back( + new cmGeneratorTarget::TargetPropertyEntry(std::move(cge), lib)); + } + } + } +} + static bool processSources( cmGeneratorTarget const* tgt, const std::vector<cmGeneratorTarget::TargetPropertyEntry*>& entries, @@ -848,13 +871,10 @@ static bool processSources( std::ostringstream err; if (!targetName.empty()) { err << "Target \"" << targetName - << "\" contains relative " - "path in its INTERFACE_SOURCES:\n" - " \"" + << "\" contains relative path in its INTERFACE_SOURCES:\n \"" << src << "\""; } else { - err << "Found relative path while evaluating sources of " - "\"" + err << "Found relative path while evaluating sources of \"" << tgt->GetName() << "\":\n \"" << src << "\"\n"; } tgt->GetLocalGenerator()->IssueMessage(cmake::FATAL_ERROR, err.str()); @@ -931,23 +951,32 @@ void cmGeneratorTarget::GetSourceFiles(std::vector<std::string>& files, processSources(this, this->SourceEntries, files, uniqueSrcs, &dagChecker, config, debugSources); + // Collect INTERFACE_SOURCES of all direct link-dependencies. std::vector<cmGeneratorTarget::TargetPropertyEntry*> linkInterfaceSourcesEntries; - AddInterfaceEntries(this, config, "INTERFACE_SOURCES", linkInterfaceSourcesEntries); - std::vector<std::string>::size_type numFilesBefore = files.size(); bool contextDependentInterfaceSources = processSources(this, linkInterfaceSourcesEntries, files, uniqueSrcs, &dagChecker, config, debugSources); + // Collect TARGET_OBJECTS of direct object link-dependencies. + std::vector<cmGeneratorTarget::TargetPropertyEntry*> linkObjectsEntries; + AddObjectEntries(this, config, linkObjectsEntries); + std::vector<std::string>::size_type numFilesBefore2 = files.size(); + bool contextDependentObjects = + processSources(this, linkObjectsEntries, files, uniqueSrcs, &dagChecker, + config, debugSources); + if (!contextDependentDirectSources && - !(contextDependentInterfaceSources && numFilesBefore < files.size())) { + !(contextDependentInterfaceSources && numFilesBefore < files.size()) && + !(contextDependentObjects && numFilesBefore2 < files.size())) { this->LinkImplementationLanguageIsContextDependent = false; } cmDeleteAll(linkInterfaceSourcesEntries); + cmDeleteAll(linkObjectsEntries); } void cmGeneratorTarget::GetSourceFiles(std::vector<cmSourceFile*>& files, @@ -1053,9 +1082,6 @@ void cmGeneratorTarget::ComputeKindedSources(KindedSources& files, kind = SourceKindHeader; } else if (sf->GetPropertyAsBool("EXTERNAL_OBJECT")) { kind = SourceKindExternalObject; - if (this->GetType() == cmStateEnums::OBJECT_LIBRARY) { - badObjLib.push_back(sf); - } } else if (!sf->GetLanguage().empty()) { kind = SourceKindObjectSource; } else if (ext == "def") { @@ -1673,6 +1699,7 @@ bool cmGeneratorTarget::HaveWellDefinedOutputFiles() const return this->GetType() == cmStateEnums::STATIC_LIBRARY || this->GetType() == cmStateEnums::SHARED_LIBRARY || this->GetType() == cmStateEnums::MODULE_LIBRARY || + this->GetType() == cmStateEnums::OBJECT_LIBRARY || this->GetType() == cmStateEnums::EXECUTABLE; } @@ -2001,8 +2028,13 @@ void cmGeneratorTarget::ComputeModuleDefinitionInfo( info.WindowsExportAllSymbols = this->Makefile->IsOn("CMAKE_SUPPORT_WINDOWS_EXPORT_ALL_SYMBOLS") && this->GetPropertyAsBool("WINDOWS_EXPORT_ALL_SYMBOLS"); +#if defined(_WIN32) && defined(CMAKE_BUILD_WITH_CMAKE) info.DefFileGenerated = info.WindowsExportAllSymbols || info.Sources.size() > 1; +#else + // Our __create_def helper is only available on Windows. + info.DefFileGenerated = false; +#endif if (info.DefFileGenerated) { info.DefFile = this->ObjectDirectory /* has slash */ + "exports.def"; } else if (!info.Sources.empty()) { @@ -2592,13 +2624,20 @@ std::vector<std::string> cmGeneratorTarget::GetIncludeDirectories( return includes; } +enum class OptionsParse +{ + None, + Shell +}; + static void processCompileOptionsInternal( cmGeneratorTarget const* tgt, const std::vector<cmGeneratorTarget::TargetPropertyEntry*>& entries, std::vector<std::string>& options, std::unordered_set<std::string>& uniqueOptions, cmGeneratorExpressionDAGChecker* dagChecker, const std::string& config, - bool debugOptions, const char* logName, std::string const& language) + bool debugOptions, const char* logName, std::string const& language, + OptionsParse parse) { for (cmGeneratorTarget::TargetPropertyEntry* entry : entries) { std::vector<std::string> entryOptions; @@ -2609,7 +2648,12 @@ static void processCompileOptionsInternal( std::string usedOptions; for (std::string const& opt : entryOptions) { if (uniqueOptions.insert(opt).second) { - options.push_back(opt); + if (parse == OptionsParse::Shell && + cmHasLiteralPrefix(opt, "SHELL:")) { + cmSystemTools::ParseUnixCommandLine(opt.c_str() + 6, options); + } else { + options.push_back(opt); + } if (debugOptions) { usedOptions += " * " + opt + "\n"; } @@ -2634,7 +2678,7 @@ static void processCompileOptions( { processCompileOptionsInternal(tgt, entries, options, uniqueOptions, dagChecker, config, debugOptions, "options", - language); + language, OptionsParse::Shell); } void cmGeneratorTarget::GetCompileOptions(std::vector<std::string>& result, @@ -2688,7 +2732,7 @@ static void processCompileFeatures( { processCompileOptionsInternal(tgt, entries, options, uniqueOptions, dagChecker, config, debugOptions, "features", - std::string()); + std::string(), OptionsParse::None); } void cmGeneratorTarget::GetCompileFeatures(std::vector<std::string>& result, @@ -2738,7 +2782,7 @@ static void processCompileDefinitions( { processCompileOptionsInternal(tgt, entries, options, uniqueOptions, dagChecker, config, debugOptions, - "definitions", language); + "definitions", language, OptionsParse::None); } void cmGeneratorTarget::GetCompileDefinitions( @@ -4934,6 +4978,16 @@ void cmGeneratorTarget::ComputeImportInfo(std::string const& desired_config, } } + // Get information if target is managed assembly. + { + std::string linkProp = "IMPORTED_COMMON_LANGUAGE_RUNTIME"; + if (auto pc = this->GetProperty(linkProp + suffix)) { + info.Managed = this->CheckManagedType(pc); + } else if (auto p = this->GetProperty(linkProp)) { + info.Managed = this->CheckManagedType(p); + } + } + // Get the cyclic repetition count. if (this->GetType() == cmStateEnums::STATIC_LIBRARY) { std::string linkProp = "IMPORTED_LINK_INTERFACE_MULTIPLICITY"; @@ -5151,6 +5205,18 @@ void cmGeneratorTarget::GetLanguages(std::set<std::string>& languages, } } +bool cmGeneratorTarget::HasLanguage(std::string const& language, + std::string const& config, + bool exclusive) const +{ + std::set<std::string> languages; + this->GetLanguages(languages, config); + // add linker language (if it is different from compiler languages) + languages.insert(this->GetLinkerLanguage(config)); + return (languages.size() == 1 || !exclusive) && + languages.count(language) > 0; +} + void cmGeneratorTarget::ComputeLinkImplementationLanguages( const std::string& config, cmOptionalLinkImplementation& impl) const { @@ -5325,20 +5391,6 @@ cmGeneratorTarget* cmGeneratorTarget::FindTargetToLink( tgt = nullptr; } - if (tgt && tgt->GetType() == cmStateEnums::OBJECT_LIBRARY) { - std::ostringstream e; - e << "Target \"" << this->GetName() << "\" links to " - "OBJECT library \"" - << tgt->GetName() - << "\" but this is not " - "allowed. " - "One may link only to STATIC or SHARED libraries, or to executables " - "with the ENABLE_EXPORTS property set."; - cmake* cm = this->LocalGenerator->GetCMakeInstance(); - cm->IssueMessage(cmake::FATAL_ERROR, e.str(), this->GetBacktrace()); - tgt = nullptr; - } - return tgt; } @@ -5351,16 +5403,17 @@ std::string cmGeneratorTarget::GetPDBDirectory(const std::string& config) const return ""; } -bool cmGeneratorTarget::HasImplibGNUtoMS() const +bool cmGeneratorTarget::HasImplibGNUtoMS(std::string const& config) const { - return this->HasImportLibrary() && this->GetPropertyAsBool("GNUtoMS"); + return this->HasImportLibrary(config) && this->GetPropertyAsBool("GNUtoMS"); } -bool cmGeneratorTarget::GetImplibGNUtoMS(std::string const& gnuName, +bool cmGeneratorTarget::GetImplibGNUtoMS(std::string const& config, + std::string const& gnuName, std::string& out, const char* newExt) const { - if (this->HasImplibGNUtoMS() && gnuName.size() > 6 && + if (this->HasImplibGNUtoMS(config) && gnuName.size() > 6 && gnuName.substr(gnuName.size() - 6) == ".dll.a") { out = gnuName.substr(0, gnuName.size() - 6); out += newExt ? newExt : ".lib"; @@ -5375,11 +5428,14 @@ bool cmGeneratorTarget::IsExecutableWithExports() const this->GetPropertyAsBool("ENABLE_EXPORTS")); } -bool cmGeneratorTarget::HasImportLibrary() const +bool cmGeneratorTarget::HasImportLibrary(std::string const& config) const { return (this->IsDLLPlatform() && (this->GetType() == cmStateEnums::SHARED_LIBRARY || - this->IsExecutableWithExports())); + this->IsExecutableWithExports()) && + // Assemblies which have only managed code do not have + // import libraries. + this->GetManagedType(config) != ManagedType::Managed); } std::string cmGeneratorTarget::GetSupportDirectory() const @@ -5402,6 +5458,7 @@ bool cmGeneratorTarget::IsLinkable() const this->GetType() == cmStateEnums::SHARED_LIBRARY || this->GetType() == cmStateEnums::MODULE_LIBRARY || this->GetType() == cmStateEnums::UNKNOWN_LIBRARY || + this->GetType() == cmStateEnums::OBJECT_LIBRARY || this->GetType() == cmStateEnums::INTERFACE_LIBRARY || this->IsExecutableWithExports()); } @@ -5431,3 +5488,49 @@ bool cmGeneratorTarget::IsCFBundleOnApple() const return (this->GetType() == cmStateEnums::MODULE_LIBRARY && this->Makefile->IsOn("APPLE") && this->GetPropertyAsBool("BUNDLE")); } + +cmGeneratorTarget::ManagedType cmGeneratorTarget::CheckManagedType( + std::string const& propval) const +{ + // The type of the managed assembly (mixed unmanaged C++ and C++/CLI, + // or only C++/CLI) does only depend on whether the property is an empty + // string or contains any value at all. In Visual Studio generators + // this propval is prepended with /clr[:] which results in: + // + // 1. propval does not exist: no /clr flag, unmanaged target, has import + // lib + // 2. empty propval: add /clr as flag, mixed unmanaged/managed + // target, has import lib + // 3. any value (safe,pure): add /clr:[propval] as flag, target with + // managed code only, no import lib + return propval.empty() ? ManagedType::Mixed : ManagedType::Managed; +} + +cmGeneratorTarget::ManagedType cmGeneratorTarget::GetManagedType( + const std::string& config) const +{ + // Only libraries and executables can be managed targets. + if (this->GetType() != cmStateEnums::SHARED_LIBRARY && + this->GetType() != cmStateEnums::STATIC_LIBRARY && + this->GetType() != cmStateEnums::EXECUTABLE) { + return ManagedType::Undefined; + } + + // Check imported target. + if (this->IsImported()) { + if (cmGeneratorTarget::ImportInfo const* info = + this->GetImportInfo(config)) { + return info->Managed; + } + return ManagedType::Undefined; + } + + // Check for explicitly set clr target property. + if (auto* clr = this->GetProperty("COMMON_LANGUAGE_RUNTIME")) { + return this->CheckManagedType(clr); + } + + // TODO: need to check if target is a CSharp target here. + // If yes: return ManagedType::Managed. + return ManagedType::Native; +} diff --git a/Source/cmGeneratorTarget.h b/Source/cmGeneratorTarget.h index 2f6ce33..d4a553a 100644 --- a/Source/cmGeneratorTarget.h +++ b/Source/cmGeneratorTarget.h @@ -364,6 +364,12 @@ public: void GetLanguages(std::set<std::string>& languages, std::string const& config) const; + // Evaluate if the target uses the given language for compilation + // and/or linking. If 'exclusive' is true, 'language' is expected + // to be the only language used for the target. + bool HasLanguage(std::string const& language, std::string const& config, + bool exclusive = true) const; + void GetObjectLibrariesCMP0026( std::vector<cmGeneratorTarget*>& objlibs) const; @@ -566,17 +572,17 @@ public: std::string GetLinkerLanguage(const std::string& config) const; /** Does this target have a GNU implib to convert to MS format? */ - bool HasImplibGNUtoMS() const; + bool HasImplibGNUtoMS(std::string const& config) const; /** Convert the given GNU import library name (.dll.a) to a name with a new extension (.lib or ${CMAKE_IMPORT_LIBRARY_SUFFIX}). */ - bool GetImplibGNUtoMS(std::string const& gnuName, std::string& out, - const char* newExt = nullptr) const; + bool GetImplibGNUtoMS(std::string const& config, std::string const& gnuName, + std::string& out, const char* newExt = nullptr) const; bool IsExecutableWithExports() const; /** Return whether or not the target has a DLL import library. */ - bool HasImportLibrary() const; + bool HasImportLibrary(std::string const& config) const; /** Get a build-tree directory in which to place target support files. */ std::string GetSupportDirectory() const; @@ -597,6 +603,19 @@ public: /** Return whether this target is a CFBundle (plugin) on Apple. */ bool IsCFBundleOnApple() const; + /** Assembly types. The order of the values of this enum is relevant + because of smaller/larger comparison operations! */ + enum ManagedType + { + Undefined = 0, // target is no lib or executable + Native, // target compiles to unmanaged binary. + Mixed, // target compiles to mixed (managed and unmanaged) binary. + Managed // target compiles to managed binary. + }; + + /** Return the type of assembly this target compiles to. */ + ManagedType GetManagedType(const std::string& config) const; + struct SourceFileFlags GetTargetSourceFileFlags( const cmSourceFile* sf) const; @@ -741,10 +760,12 @@ private: { ImportInfo() : NoSOName(false) + , Managed(Native) , Multiplicity(0) { } bool NoSOName; + ManagedType Managed; unsigned int Multiplicity; std::string Location; std::string SOName; @@ -838,6 +859,8 @@ private: bool ComputePDBOutputDir(const std::string& kind, const std::string& config, std::string& out) const; + ManagedType CheckManagedType(std::string const& propval) const; + public: const std::vector<const cmGeneratorTarget*>& GetLinkImplementationClosure( const std::string& config) const; diff --git a/Source/cmGlobVerificationManager.cxx b/Source/cmGlobVerificationManager.cxx new file mode 100644 index 0000000..e23b6ea --- /dev/null +++ b/Source/cmGlobVerificationManager.cxx @@ -0,0 +1,172 @@ +/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying + file Copyright.txt or https://cmake.org/licensing for details. */ +#include "cmGlobVerificationManager.h" + +#include "cmsys/FStream.hxx" +#include <sstream> + +#include "cmGeneratedFileStream.h" +#include "cmListFileCache.h" +#include "cmSystemTools.h" +#include "cmVersion.h" +#include "cmake.h" + +bool cmGlobVerificationManager::SaveVerificationScript(const std::string& path) +{ + if (this->Cache.empty()) { + return true; + } + + std::string scriptFile = path; + scriptFile += cmake::GetCMakeFilesDirectory(); + std::string stampFile = scriptFile; + cmSystemTools::MakeDirectory(scriptFile); + scriptFile += "/VerifyGlobs.cmake"; + stampFile += "/cmake.verify_globs"; + cmGeneratedFileStream verifyScriptFile(scriptFile.c_str()); + verifyScriptFile.SetCopyIfDifferent(true); + if (!verifyScriptFile) { + cmSystemTools::Error("Unable to open verification script file for save. ", + scriptFile.c_str()); + cmSystemTools::ReportLastSystemError(""); + return false; + } + + verifyScriptFile << std::boolalpha; + verifyScriptFile << "# CMAKE generated file: DO NOT EDIT!\n" + << "# Generated by CMake Version " + << cmVersion::GetMajorVersion() << "." + << cmVersion::GetMinorVersion() << "\n"; + + for (auto const& i : this->Cache) { + CacheEntryKey k = std::get<0>(i); + CacheEntryValue v = std::get<1>(i); + + if (!v.Initialized) { + continue; + } + + verifyScriptFile << "\n"; + + for (auto const& bt : v.Backtraces) { + verifyScriptFile << "# " << std::get<0>(bt); + std::get<1>(bt).PrintTitle(verifyScriptFile); + verifyScriptFile << "\n"; + } + + k.PrintGlobCommand(verifyScriptFile, "NEW_GLOB"); + verifyScriptFile << "\n"; + + verifyScriptFile << "set(OLD_GLOB\n"; + for (const std::string& file : v.Files) { + verifyScriptFile << " \"" << file << "\"\n"; + } + verifyScriptFile << " )\n"; + + verifyScriptFile << "if(NOT \"${NEW_GLOB}\" STREQUAL \"${OLD_GLOB}\")\n" + << " message(\"-- GLOB mismatch!\")\n" + << " file(TOUCH_NOCREATE \"" << stampFile << "\")\n" + << "endif()\n"; + } + verifyScriptFile.Close(); + + cmsys::ofstream verifyStampFile(stampFile.c_str()); + if (!verifyStampFile) { + cmSystemTools::Error("Unable to open verification stamp file for write. ", + stampFile.c_str()); + return false; + } + verifyStampFile << "# This file is generated by CMake for checking of the " + "VerifyGlobs.cmake file\n"; + this->VerifyScript = scriptFile; + this->VerifyStamp = stampFile; + return true; +} + +bool cmGlobVerificationManager::DoWriteVerifyTarget() const +{ + return !this->VerifyScript.empty() && !this->VerifyStamp.empty(); +} + +bool cmGlobVerificationManager::CacheEntryKey::operator<( + const CacheEntryKey& r) const +{ + if (this->Recurse < r.Recurse) { + return true; + } + if (this->Recurse > r.Recurse) { + return false; + } + if (this->ListDirectories < r.ListDirectories) { + return true; + } + if (this->ListDirectories > r.ListDirectories) { + return false; + } + if (this->FollowSymlinks < r.FollowSymlinks) { + return true; + } + if (this->FollowSymlinks > r.FollowSymlinks) { + return false; + } + if (this->Relative < r.Relative) { + return true; + } + if (this->Relative > r.Relative) { + return false; + } + if (this->Expression < r.Expression) { + return true; + } + if (this->Expression > r.Expression) { + return false; + } + return false; +} + +void cmGlobVerificationManager::CacheEntryKey::PrintGlobCommand( + std::ostream& out, const std::string& cmdVar) +{ + out << "file(GLOB" << (this->Recurse ? "_RECURSE " : " "); + out << cmdVar << " "; + if (this->Recurse && this->FollowSymlinks) { + out << "FOLLOW_SYMLINKS "; + } + out << "LIST_DIRECTORIES " << this->ListDirectories << " "; + if (!this->Relative.empty()) { + out << "RELATIVE \"" << this->Relative << "\" "; + } + out << "\"" << this->Expression << "\")"; +} + +void cmGlobVerificationManager::AddCacheEntry( + const bool recurse, const bool listDirectories, const bool followSymlinks, + const std::string& relative, const std::string& expression, + const std::vector<std::string>& files, const std::string& variable, + const cmListFileBacktrace& backtrace) +{ + CacheEntryKey key = CacheEntryKey(recurse, listDirectories, followSymlinks, + relative, expression); + CacheEntryValue& value = this->Cache[key]; + if (!value.Initialized) { + value.Files = files; + value.Initialized = true; + value.Backtraces.emplace_back(variable, backtrace); + } else if (value.Initialized && value.Files != files) { + std::ostringstream message; + message << std::boolalpha; + message << "The glob expression\n"; + key.PrintGlobCommand(message, variable); + backtrace.PrintTitle(message); + message << "\nwas already present in the glob cache but the directory\n" + "contents have changed during the configuration run.\n"; + message << "Matching glob expressions:"; + for (auto const& bt : value.Backtraces) { + message << "\n " << std::get<0>(bt); + std::get<1>(bt).PrintTitle(message); + } + cmSystemTools::Error(message.str().c_str()); + } else { + value.Backtraces.emplace_back(variable, backtrace); + } +} diff --git a/Source/cmGlobVerificationManager.h b/Source/cmGlobVerificationManager.h new file mode 100644 index 0000000..4508602 --- /dev/null +++ b/Source/cmGlobVerificationManager.h @@ -0,0 +1,89 @@ +/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying + file Copyright.txt or https://cmake.org/licensing for details. */ +#ifndef cmGlobVerificationManager_h +#define cmGlobVerificationManager_h + +#include "cmConfigure.h" // IWYU pragma: keep + +#include "cmListFileCache.h" + +#include <iosfwd> +#include <map> +#include <string> +#include <utility> +#include <vector> + +/** \class cmGlobVerificationManager + * \brief Class for expressing build-time dependencies on glob expressions. + * + * Generates a CMake script which verifies glob outputs during prebuild. + * + */ +class cmGlobVerificationManager +{ +public: + cmGlobVerificationManager() {} + +protected: + ///! Save verification script for given makefile. + ///! Saves to output <path>/<CMakeFilesDirectory>/VerifyGlobs.cmake + bool SaveVerificationScript(const std::string& path); + + ///! Add an entry into the glob cache + void AddCacheEntry(bool recurse, bool listDirectories, bool followSymlinks, + const std::string& relative, + const std::string& expression, + const std::vector<std::string>& files, + const std::string& variable, + const cmListFileBacktrace& bt); + + ///! Check targets should be written in generated build system. + bool DoWriteVerifyTarget() const; + + ///! Get the paths to the generated script and stamp files + std::string const& GetVerifyScript() const { return this->VerifyScript; } + std::string const& GetVerifyStamp() const { return this->VerifyStamp; } + +private: + struct CacheEntryKey + { + const bool Recurse; + const bool ListDirectories; + const bool FollowSymlinks; + const std::string Relative; + const std::string Expression; + CacheEntryKey(const bool rec, const bool l, const bool s, + const std::string& rel, const std::string& e) + : Recurse(rec) + , ListDirectories(l) + , FollowSymlinks(s) + , Relative(rel) + , Expression(e) + { + } + bool operator<(const CacheEntryKey& r) const; + void PrintGlobCommand(std::ostream& out, const std::string& cmdVar); + }; + + struct CacheEntryValue + { + bool Initialized; + std::vector<std::string> Files; + std::vector<std::pair<std::string, cmListFileBacktrace>> Backtraces; + CacheEntryValue() + : Initialized(false) + { + } + }; + + typedef std::map<CacheEntryKey, CacheEntryValue> CacheEntryMap; + CacheEntryMap Cache; + std::string VerifyScript; + std::string VerifyStamp; + + // Only cmState should be able to add cache values. + // cmGlobVerificationManager should never be used directly. + friend class cmState; // allow access to add cache values +}; + +#endif diff --git a/Source/cmGlobalGenerator.cxx b/Source/cmGlobalGenerator.cxx index c805b98..cf277d5 100644 --- a/Source/cmGlobalGenerator.cxx +++ b/Source/cmGlobalGenerator.cxx @@ -6,11 +6,11 @@ #include "cmsys/FStream.hxx" #include <algorithm> #include <assert.h> +#include <cstring> #include <iterator> #include <sstream> #include <stdio.h> #include <stdlib.h> -#include <string.h> #if defined(_WIN32) && !defined(__CYGWIN__) #include <windows.h> @@ -1806,6 +1806,8 @@ int cmGlobalGenerator::Build(const std::string& /*unused*/, cmSystemTools::OutputOption outputflag, std::vector<std::string> const& nativeOptions) { + bool hideconsole = cmSystemTools::GetRunCommandHideConsole(); + /** * Run an executable command and put the stdout in output. */ @@ -1813,9 +1815,17 @@ int cmGlobalGenerator::Build(const std::string& /*unused*/, output += "Change Dir: "; output += bindir; output += "\n"; + if (workdir.Failed()) { + cmSystemTools::SetRunCommandHideConsole(hideconsole); + cmSystemTools::Error("Failed to change directory: ", + std::strerror(workdir.GetLastResult())); + output += "Failed to change directory: "; + output += std::strerror(workdir.GetLastResult()); + output += "\n"; + return 1; + } int retVal; - bool hideconsole = cmSystemTools::GetRunCommandHideConsole(); cmSystemTools::SetRunCommandHideConsole(true); std::string outputBuffer; std::string* outputPtr = &outputBuffer; @@ -1883,6 +1893,13 @@ int cmGlobalGenerator::Build(const std::string& /*unused*/, retVal = 1; } + // The OpenWatcom tools do not return an error code when a link + // library is not found! + if (this->CMakeInstance->GetState()->UseWatcomWMake() && retVal == 0 && + output.find("W1008: cannot open") != std::string::npos) { + retVal = 1; + } + return retVal; } diff --git a/Source/cmGlobalNinjaGenerator.cxx b/Source/cmGlobalNinjaGenerator.cxx index b251f86..c19a61c 100644 --- a/Source/cmGlobalNinjaGenerator.cxx +++ b/Source/cmGlobalNinjaGenerator.cxx @@ -101,31 +101,6 @@ std::string cmGlobalNinjaGenerator::EncodeRuleName(std::string const& name) return encoded; } -static bool IsIdentChar(char c) -{ - return ('a' <= c && c <= 'z') || - ('+' <= c && c <= '9') || // +,-./ and numbers - ('A' <= c && c <= 'Z') || (c == '_') || (c == '$') || (c == '\\') || - (c == ' ') || (c == ':'); -} - -std::string cmGlobalNinjaGenerator::EncodeIdent(const std::string& ident, - std::ostream& vars) -{ - if (std::find_if(ident.begin(), ident.end(), - [](char c) { return !IsIdentChar(c); }) != ident.end()) { - static unsigned VarNum = 0; - std::ostringstream names; - names << "ident" << VarNum++; - vars << names.str() << " = " << ident << "\n"; - return "$" + names.str(); - } - std::string result = ident; - cmSystemTools::ReplaceString(result, " ", "$ "); - cmSystemTools::ReplaceString(result, ":", "$:"); - return result; -} - std::string cmGlobalNinjaGenerator::EncodeLiteral(const std::string& lit) { std::string result = lit; @@ -143,7 +118,10 @@ std::string cmGlobalNinjaGenerator::EncodePath(const std::string& path) else std::replace(result.begin(), result.end(), '/', '\\'); #endif - return EncodeLiteral(result); + result = EncodeLiteral(result); + cmSystemTools::ReplaceString(result, " ", "$ "); + cmSystemTools::ReplaceString(result, ":", "$:"); + return result; } void cmGlobalNinjaGenerator::WriteBuild( @@ -177,14 +155,14 @@ void cmGlobalNinjaGenerator::WriteBuild( // Write explicit dependencies. for (std::string const& explicitDep : explicitDeps) { - arguments += " " + EncodeIdent(EncodePath(explicitDep), os); + arguments += " " + EncodePath(explicitDep); } // Write implicit dependencies. if (!implicitDeps.empty()) { arguments += " |"; for (std::string const& implicitDep : implicitDeps) { - arguments += " " + EncodeIdent(EncodePath(implicitDep), os); + arguments += " " + EncodePath(implicitDep); } } @@ -192,7 +170,7 @@ void cmGlobalNinjaGenerator::WriteBuild( if (!orderOnlyDeps.empty()) { arguments += " ||"; for (std::string const& orderOnlyDep : orderOnlyDeps) { - arguments += " " + EncodeIdent(EncodePath(orderOnlyDep), os); + arguments += " " + EncodePath(orderOnlyDep); } } @@ -203,7 +181,7 @@ void cmGlobalNinjaGenerator::WriteBuild( // Write outputs files. build += "build"; for (std::string const& output : outputs) { - build += " " + EncodeIdent(EncodePath(output), os); + build += " " + EncodePath(output); if (this->ComputingUnknownDependencies) { this->CombinedBuildOutputs.insert(output); } @@ -211,7 +189,7 @@ void cmGlobalNinjaGenerator::WriteBuild( if (!implicitOuts.empty()) { build += " |"; for (std::string const& implicitOut : implicitOuts) { - build += " " + EncodeIdent(EncodePath(implicitOut), os); + build += " " + EncodePath(implicitOut); } } build += ":"; @@ -475,6 +453,7 @@ cmGlobalNinjaGenerator::cmGlobalNinjaGenerator(cmake* cm) , PolicyCMP0058(cmPolicies::WARN) , NinjaSupportsConsolePool(false) , NinjaSupportsImplicitOuts(false) + , NinjaSupportsManifestRestat(false) , NinjaSupportsDyndeps(0) { #ifdef _WIN32 @@ -597,6 +576,9 @@ void cmGlobalNinjaGenerator::CheckNinjaFeatures() this->NinjaSupportsImplicitOuts = !cmSystemTools::VersionCompare( cmSystemTools::OP_LESS, this->NinjaVersion.c_str(), this->RequiredNinjaVersionForImplicitOuts().c_str()); + this->NinjaSupportsManifestRestat = !cmSystemTools::VersionCompare( + cmSystemTools::OP_LESS, this->NinjaVersion.c_str(), + RequiredNinjaVersionForManifestRestat().c_str()); { // Our ninja branch adds ".dyndep-#" to its version number, // where '#' is a feature-specific version number. Extract it. @@ -949,12 +931,14 @@ void cmGlobalNinjaGenerator::AddDependencyToAll(const std::string& input) void cmGlobalNinjaGenerator::WriteAssumedSourceDependencies() { for (auto const& asd : this->AssumedSourceDependencies) { - cmNinjaDeps deps; - std::copy(asd.second.begin(), asd.second.end(), std::back_inserter(deps)); + cmNinjaDeps orderOnlyDeps; + std::copy(asd.second.begin(), asd.second.end(), + std::back_inserter(orderOnlyDeps)); WriteCustomCommandBuild(/*command=*/"", /*description=*/"", "Assume dependencies for generated source file.", /*depfile*/ "", /*uses_terminal*/ false, - /*restat*/ true, cmNinjaDeps(1, asd.first), deps); + /*restat*/ true, cmNinjaDeps(1, asd.first), + cmNinjaDeps(), orderOnlyDeps); } } @@ -1223,11 +1207,13 @@ void cmGlobalNinjaGenerator::WriteUnknownExplicitDependencies(std::ostream& os) for (std::string const& file : files) { knownDependencies.insert(this->ConvertToNinjaPath(file)); } - // get list files which are implicit dependencies as well and will be phony - // for rebuild manifest - std::vector<std::string> const& lf = lg->GetMakefile()->GetListFiles(); - for (std::string const& j : lf) { - knownDependencies.insert(this->ConvertToNinjaPath(j)); + if (!this->GlobalSettingIsOn("CMAKE_SUPPRESS_REGENERATION")) { + // get list files which are implicit dependencies as well and will be + // phony for rebuild manifest + std::vector<std::string> const& lf = lg->GetMakefile()->GetListFiles(); + for (std::string const& j : lf) { + knownDependencies.insert(this->ConvertToNinjaPath(j)); + } } std::vector<cmGeneratorExpressionEvaluationFile*> const& ef = lg->GetMakefile()->GetEvaluationFiles(); @@ -1335,6 +1321,9 @@ void cmGlobalNinjaGenerator::WriteTargetAll(std::ostream& os) void cmGlobalNinjaGenerator::WriteTargetRebuildManifest(std::ostream& os) { + if (this->GlobalSettingIsOn("CMAKE_SUPPRESS_REGENERATION")) { + return; + } cmLocalGenerator* lg = this->LocalGenerators[0]; std::ostringstream cmd; @@ -1356,6 +1345,7 @@ void cmGlobalNinjaGenerator::WriteTargetRebuildManifest(std::ostream& os) /*generator=*/true); cmNinjaDeps implicitDeps; + cmNinjaDeps explicitDeps; for (cmLocalGenerator* localGen : this->LocalGenerators) { std::vector<std::string> const& lf = localGen->GetMakefile()->GetListFiles(); @@ -1365,10 +1355,6 @@ void cmGlobalNinjaGenerator::WriteTargetRebuildManifest(std::ostream& os) } implicitDeps.push_back(this->CMakeCacheFile); - std::sort(implicitDeps.begin(), implicitDeps.end()); - implicitDeps.erase(std::unique(implicitDeps.begin(), implicitDeps.end()), - implicitDeps.end()); - cmNinjaVars variables; // Use 'console' pool to get non buffered output of the CMake re-run call // Available since Ninja 1.5 @@ -1376,16 +1362,81 @@ void cmGlobalNinjaGenerator::WriteTargetRebuildManifest(std::ostream& os) variables["pool"] = "console"; } + cmake* cm = this->GetCMakeInstance(); + if (this->SupportsManifestRestat() && cm->DoWriteGlobVerifyTarget()) { + std::ostringstream verify_cmd; + verify_cmd << lg->ConvertToOutputFormat(cmSystemTools::GetCMakeCommand(), + cmOutputConverter::SHELL) + << " -P " + << lg->ConvertToOutputFormat(cm->GetGlobVerifyScript(), + cmOutputConverter::SHELL); + + WriteRule(*this->RulesFileStream, "VERIFY_GLOBS", verify_cmd.str(), + "Re-checking globbed directories...", + "Rule for re-checking globbed directories.", + /*depfile=*/"", + /*deptype=*/"", + /*rspfile=*/"", + /*rspcontent*/ "", + /*restat=*/"", + /*generator=*/true); + + std::string verifyForce = cm->GetGlobVerifyScript() + "_force"; + cmNinjaDeps verifyForceDeps(1, this->NinjaOutputPath(verifyForce)); + + this->WritePhonyBuild(os, "Phony target to force glob verification run.", + verifyForceDeps, cmNinjaDeps()); + + variables["restat"] = "1"; + std::string const verifyScriptFile = + this->NinjaOutputPath(cm->GetGlobVerifyScript()); + std::string const verifyStampFile = + this->NinjaOutputPath(cm->GetGlobVerifyStamp()); + this->WriteBuild(os, + "Re-run CMake to check if globbed directories changed.", + "VERIFY_GLOBS", + /*outputs=*/cmNinjaDeps(1, verifyStampFile), + /*implicitOuts=*/cmNinjaDeps(), + /*explicitDeps=*/cmNinjaDeps(), + /*implicitDeps=*/verifyForceDeps, + /*orderOnlyDeps=*/cmNinjaDeps(), variables); + + variables.erase("restat"); + implicitDeps.push_back(verifyScriptFile); + explicitDeps.push_back(verifyStampFile); + } else if (!this->SupportsManifestRestat() && + cm->DoWriteGlobVerifyTarget()) { + std::ostringstream msg; + msg << "The detected version of Ninja:\n" + << " " << this->NinjaVersion << "\n" + << "is less than the version of Ninja required by CMake for adding " + "restat dependencies to the build.ninja manifest regeneration " + "target:\n" + << " " << this->RequiredNinjaVersionForManifestRestat() << "\n"; + msg << "Any pre-check scripts, such as those generated for file(GLOB " + "CONFIGURE_DEPENDS), will not be run by Ninja."; + this->GetCMakeInstance()->IssueMessage(cmake::AUTHOR_WARNING, msg.str()); + } + + std::sort(implicitDeps.begin(), implicitDeps.end()); + implicitDeps.erase(std::unique(implicitDeps.begin(), implicitDeps.end()), + implicitDeps.end()); + std::string const ninjaBuildFile = this->NinjaOutputPath(NINJA_BUILD_FILE); this->WriteBuild(os, "Re-run CMake if any of its inputs changed.", "RERUN_CMAKE", /*outputs=*/cmNinjaDeps(1, ninjaBuildFile), - /*implicitOuts=*/cmNinjaDeps(), - /*explicitDeps=*/cmNinjaDeps(), implicitDeps, + /*implicitOuts=*/cmNinjaDeps(), explicitDeps, implicitDeps, /*orderOnlyDeps=*/cmNinjaDeps(), variables); + cmNinjaDeps missingInputs; + std::set_difference(std::make_move_iterator(implicitDeps.begin()), + std::make_move_iterator(implicitDeps.end()), + CustomCommandOutputs.begin(), CustomCommandOutputs.end(), + std::back_inserter(missingInputs)); + this->WritePhonyBuild(os, "A missing CMake input file is not an error.", - implicitDeps, cmNinjaDeps()); + missingInputs, cmNinjaDeps()); } std::string cmGlobalNinjaGenerator::ninjaCmd() const @@ -1408,6 +1459,11 @@ bool cmGlobalNinjaGenerator::SupportsImplicitOuts() const return this->NinjaSupportsImplicitOuts; } +bool cmGlobalNinjaGenerator::SupportsManifestRestat() const +{ + return this->NinjaSupportsManifestRestat; +} + void cmGlobalNinjaGenerator::WriteTargetClean(std::ostream& os) { WriteRule(*this->RulesFileStream, "CLEAN", ninjaCmd() + " -t clean", @@ -1758,7 +1814,7 @@ bool cmGlobalNinjaGenerator::WriteDyndepFile( Json::Value tm = Json::objectValue; for (cmFortranObjectInfo const& object : objects) { for (std::string const& p : object.Provides) { - std::string const mod = module_dir + p + ".mod"; + std::string const mod = module_dir + p; mod_files[p] = mod; tm[p] = mod; } diff --git a/Source/cmGlobalNinjaGenerator.h b/Source/cmGlobalNinjaGenerator.h index 7f80d08..bfff3d9 100644 --- a/Source/cmGlobalNinjaGenerator.h +++ b/Source/cmGlobalNinjaGenerator.h @@ -73,7 +73,6 @@ public: static void WriteDivider(std::ostream& os); static std::string EncodeRuleName(std::string const& name); - static std::string EncodeIdent(const std::string& ident, std::ostream& vars); static std::string EncodeLiteral(const std::string& lit); std::string EncodePath(const std::string& path); @@ -346,8 +345,10 @@ public: static std::string RequiredNinjaVersion() { return "1.3"; } static std::string RequiredNinjaVersionForConsolePool() { return "1.5"; } static std::string RequiredNinjaVersionForImplicitOuts() { return "1.7"; } + static std::string RequiredNinjaVersionForManifestRestat() { return "1.8"; } bool SupportsConsolePool() const; bool SupportsImplicitOuts() const; + bool SupportsManifestRestat() const; std::string NinjaOutputPath(std::string const& path) const; bool HasOutputPathPrefix() const { return !this->OutputPathPrefix.empty(); } @@ -460,6 +461,7 @@ private: std::string NinjaVersion; bool NinjaSupportsConsolePool; bool NinjaSupportsImplicitOuts; + bool NinjaSupportsManifestRestat; unsigned long NinjaSupportsDyndeps; private: diff --git a/Source/cmGlobalUnixMakefileGenerator3.cxx b/Source/cmGlobalUnixMakefileGenerator3.cxx index d990a6c..c07f10f 100644 --- a/Source/cmGlobalUnixMakefileGenerator3.cxx +++ b/Source/cmGlobalUnixMakefileGenerator3.cxx @@ -241,6 +241,10 @@ void cmGlobalUnixMakefileGenerator3::WriteMainMakefile2() lg->WriteMakeRule(makefileStream, "The main recursive preinstall target", "preinstall", depends, no_commands, true); + // Write an empty clean: + lg->WriteMakeRule(makefileStream, "The main recursive clean target", "clean", + depends, no_commands, true); + // Write out the "special" stuff lg->WriteSpecialTargetsTop(makefileStream); @@ -256,6 +260,10 @@ void cmGlobalUnixMakefileGenerator3::WriteMainMakefile2() void cmGlobalUnixMakefileGenerator3::WriteMainCMakefile() { + if (this->GlobalSettingIsOn("CMAKE_SUPPRESS_REGENERATION")) { + return; + } + // Open the output file. This should not be copy-if-different // because the check-build-system step compares the makefile time to // see if the build system must be regenerated. @@ -293,6 +301,13 @@ void cmGlobalUnixMakefileGenerator3::WriteMainCMakefile() lfiles.insert(lfiles.end(), lg->GetMakefile()->GetListFiles().begin(), lg->GetMakefile()->GetListFiles().end()); } + + cmake* cm = this->GetCMakeInstance(); + if (cm->DoWriteGlobVerifyTarget()) { + lfiles.push_back(cm->GetGlobVerifyScript()); + lfiles.push_back(cm->GetGlobVerifyStamp()); + } + // Sort the list and remove duplicates. std::sort(lfiles.begin(), lfiles.end(), std::less<std::string>()); #if !defined(__VMS) // The Compaq STL on VMS crashes, so accept duplicates. @@ -525,7 +540,10 @@ void cmGlobalUnixMakefileGenerator3::WriteConvenienceRules( std::vector<std::string> depends; std::vector<std::string> commands; - depends.push_back("cmake_check_build_system"); + bool regenerate = !this->GlobalSettingIsOn("CMAKE_SUPPRESS_REGENERATION"); + if (regenerate) { + depends.push_back("cmake_check_build_system"); + } // write the target convenience rules for (cmLocalGenerator* localGen : this->LocalGenerators) { @@ -558,7 +576,9 @@ void cmGlobalUnixMakefileGenerator3::WriteConvenienceRules( tmp += "Makefile2"; commands.push_back(lg->GetRecursiveMakeCall(tmp.c_str(), name)); depends.clear(); - depends.push_back("cmake_check_build_system"); + if (regenerate) { + depends.push_back("cmake_check_build_system"); + } lg->WriteMakeRule(ruleFileStream, "Build rule for target.", name, depends, commands, true); @@ -609,7 +629,10 @@ void cmGlobalUnixMakefileGenerator3::WriteConvenienceRules2( // write the directory level rules for this local gen this->WriteDirectoryRules2(ruleFileStream, lg); - depends.push_back("cmake_check_build_system"); + bool regenerate = !this->GlobalSettingIsOn("CMAKE_SUPPRESS_REGENERATION"); + if (regenerate) { + depends.push_back("cmake_check_build_system"); + } // for each target Generate the rule files for each target. const std::vector<cmGeneratorTarget*>& targets = lg->GetGeneratorTargets(); @@ -715,7 +738,9 @@ void cmGlobalUnixMakefileGenerator3::WriteConvenienceRules2( commands.push_back(progCmd.str()); } depends.clear(); - depends.push_back("cmake_check_build_system"); + if (regenerate) { + depends.push_back("cmake_check_build_system"); + } localName = lg->GetRelativeTargetDirectory(gtarget); localName += "/rule"; lg->WriteMakeRule(ruleFileStream, @@ -768,7 +793,7 @@ void cmGlobalUnixMakefileGenerator3::WriteConvenienceRules2( } } -// Build a map that contains a the set of targets used by each local +// Build a map that contains the set of targets used by each local // generator directory level. void cmGlobalUnixMakefileGenerator3::InitializeProgressMarks() { @@ -898,7 +923,9 @@ void cmGlobalUnixMakefileGenerator3::WriteHelpRule( "for this Makefile:"); lg->AppendEcho(commands, "... all (the default if no target is provided)"); lg->AppendEcho(commands, "... clean"); - lg->AppendEcho(commands, "... depend"); + if (!this->GlobalSettingIsOn("CMAKE_SUPPRESS_REGENERATION")) { + lg->AppendEcho(commands, "... depend"); + } // Keep track of targets already listed. std::set<std::string> emittedTargets; diff --git a/Source/cmGlobalVisualStudio10Generator.cxx b/Source/cmGlobalVisualStudio10Generator.cxx index 73a5dae..205e0d0 100644 --- a/Source/cmGlobalVisualStudio10Generator.cxx +++ b/Source/cmGlobalVisualStudio10Generator.cxx @@ -636,126 +636,89 @@ bool cmGlobalVisualStudio10Generator::FindVCTargetsPath(cmMakefile* mf) cmsys::ofstream fout(vcxprojAbs.c_str()); cmXMLWriter xw(fout); - /* clang-format off */ - xw.StartDocument(); - xw.StartElement("Project"); - xw.Attribute("DefaultTargets", "Build"); - xw.Attribute("ToolsVersion", "4.0"); - xw.Attribute("xmlns", - "http://schemas.microsoft.com/developer/msbuild/2003"); - if (this->IsNsightTegra()) { - xw.StartElement("PropertyGroup"); - xw.Attribute("Label", "NsightTegraProject"); - xw.StartElement("NsightTegraProjectRevisionNumber"); - xw.Content("6"); - xw.EndElement(); // NsightTegraProjectRevisionNumber - xw.EndElement(); // PropertyGroup - } - xw.StartElement("ItemGroup"); - xw.Attribute("Label", "ProjectConfigurations"); - xw.StartElement("ProjectConfiguration"); - xw.Attribute("Include", "Debug|" + this->GetPlatformName()); - xw.StartElement("Configuration"); - xw.Content("Debug"); - xw.EndElement(); // Configuration - xw.StartElement("Platform"); - xw.Content(this->GetPlatformName()); - xw.EndElement(); // Platform - xw.EndElement(); // ProjectConfiguration - xw.EndElement(); // ItemGroup - xw.StartElement("PropertyGroup"); - xw.Attribute("Label", "Globals"); - xw.StartElement("ProjectGuid"); - xw.Content("{F3FC6D86-508D-3FB1-96D2-995F08B142EC}"); - xw.EndElement(); // ProjectGuid - xw.StartElement("Keyword"); - xw.Content("Win32Proj"); - xw.EndElement(); // Keyword - xw.StartElement("Platform"); - xw.Content(this->GetPlatformName()); - xw.EndElement(); // Platform - if (this->GetSystemName() == "WindowsPhone") { - xw.StartElement("ApplicationType"); - xw.Content("Windows Phone"); - xw.EndElement(); // ApplicationType - xw.StartElement("ApplicationTypeRevision"); - xw.Content(this->GetSystemVersion()); - xw.EndElement(); // ApplicationTypeRevision - } else if (this->GetSystemName() == "WindowsStore") { - xw.StartElement("ApplicationType"); - xw.Content("Windows Store"); - xw.EndElement(); // ApplicationType - xw.StartElement("ApplicationTypeRevision"); - xw.Content(this->GetSystemVersion()); - xw.EndElement(); // ApplicationTypeRevision - } - if (!this->WindowsTargetPlatformVersion.empty()) { - xw.StartElement("WindowsTargetPlatformVersion"); - xw.Content(this->WindowsTargetPlatformVersion); - xw.EndElement(); // WindowsTargetPlatformVersion - } - if (this->GetPlatformName() == "ARM64") { - xw.StartElement("WindowsSDKDesktopARM64Support"); - xw.Content("true"); - xw.EndElement(); // WindowsSDK64DesktopARMSupport - } - else if (this->GetPlatformName() == "ARM") { - xw.StartElement("WindowsSDKDesktopARMSupport"); - xw.Content("true"); - xw.EndElement(); // WindowsSDKDesktopARMSupport - } - xw.EndElement(); // PropertyGroup - xw.StartElement("Import"); - xw.Attribute("Project", - "$(VCTargetsPath)\\Microsoft.Cpp.Default.props"); - xw.EndElement(); // Import + cmXMLDocument doc(xw); + cmXMLElement eprj(doc, "Project"); + eprj.Attribute("DefaultTargets", "Build"); + eprj.Attribute("ToolsVersion", "4.0"); + eprj.Attribute("xmlns", + "http://schemas.microsoft.com/developer/msbuild/2003"); + if (this->IsNsightTegra()) { + cmXMLElement epg(eprj, "PropertyGroup"); + epg.Attribute("Label", "NsightTegraProject"); + cmXMLElement(epg, "NsightTegraProjectRevisionNumber").Content("6"); + } + { + cmXMLElement eig(eprj, "ItemGroup"); + eig.Attribute("Label", "ProjectConfigurations"); + cmXMLElement epc(eig, "ProjectConfiguration"); + epc.Attribute("Include", "Debug|" + this->GetPlatformName()); + cmXMLElement(epc, "Configuration").Content("Debug"); + cmXMLElement(epc, "Platform").Content(this->GetPlatformName()); + } + { + cmXMLElement epg(eprj, "PropertyGroup"); + epg.Attribute("Label", "Globals"); + cmXMLElement(epg, "ProjectGuid") + .Content("{F3FC6D86-508D-3FB1-96D2-995F08B142EC}"); + cmXMLElement(epg, "Keyword").Content("Win32Proj"); + cmXMLElement(epg, "Platform").Content(this->GetPlatformName()); + if (this->GetSystemName() == "WindowsPhone") { + cmXMLElement(epg, "ApplicationType").Content("Windows Phone"); + cmXMLElement(epg, "ApplicationTypeRevision") + .Content(this->GetSystemVersion()); + } else if (this->GetSystemName() == "WindowsStore") { + cmXMLElement(epg, "ApplicationType").Content("Windows Store"); + cmXMLElement(epg, "ApplicationTypeRevision") + .Content(this->GetSystemVersion()); + } + if (!this->WindowsTargetPlatformVersion.empty()) { + cmXMLElement(epg, "WindowsTargetPlatformVersion") + .Content(this->WindowsTargetPlatformVersion); + } + if (this->GetPlatformName() == "ARM64") { + cmXMLElement(epg, "WindowsSDKDesktopARM64Support").Content("true"); + } else if (this->GetPlatformName() == "ARM") { + cmXMLElement(epg, "WindowsSDKDesktopARMSupport").Content("true"); + } + } + cmXMLElement(eprj, "Import") + .Attribute("Project", "$(VCTargetsPath)\\Microsoft.Cpp.Default.props"); if (!this->GeneratorToolsetHostArchitecture.empty()) { - xw.StartElement("PropertyGroup"); - xw.StartElement("PreferredToolArchitecture"); - xw.Content(this->GeneratorToolsetHostArchitecture); - xw.EndElement(); // PreferredToolArchitecture - xw.EndElement(); // PropertyGroup + cmXMLElement epg(eprj, "PropertyGroup"); + cmXMLElement(epg, "PreferredToolArchitecture") + .Content(this->GeneratorToolsetHostArchitecture); } - xw.StartElement("PropertyGroup"); - xw.Attribute("Label", "Configuration"); - xw.StartElement("ConfigurationType"); + { + cmXMLElement epg(eprj, "PropertyGroup"); + epg.Attribute("Label", "Configuration"); + { + cmXMLElement ect(epg, "ConfigurationType"); + if (this->IsNsightTegra()) { + // Tegra-Android platform does not understand "Utility". + ect.Content("StaticLibrary"); + } else { + ect.Content("Utility"); + } + } + cmXMLElement(epg, "CharacterSet").Content("MultiByte"); if (this->IsNsightTegra()) { - // Tegra-Android platform does not understand "Utility". - xw.Content("StaticLibrary"); + cmXMLElement(epg, "NdkToolchainVersion") + .Content(this->GetPlatformToolsetString()); } else { - xw.Content("Utility"); + cmXMLElement(epg, "PlatformToolset") + .Content(this->GetPlatformToolsetString()); } - xw.EndElement(); // ConfigurationType - xw.StartElement("CharacterSet"); - xw.Content("MultiByte"); - xw.EndElement(); // CharacterSet - if (this->IsNsightTegra()) { - xw.StartElement("NdkToolchainVersion"); - xw.Content(this->GetPlatformToolsetString()); - xw.EndElement(); // NdkToolchainVersion - } else { - xw.StartElement("PlatformToolset"); - xw.Content(this->GetPlatformToolsetString()); - xw.EndElement(); // PlatformToolset - } - xw.EndElement(); // PropertyGroup - xw.StartElement("Import"); - xw.Attribute("Project", "$(VCTargetsPath)\\Microsoft.Cpp.props"); - xw.EndElement(); // Import - xw.StartElement("ItemDefinitionGroup"); - xw.StartElement("PostBuildEvent"); - xw.StartElement("Command"); - xw.Content("echo VCTargetsPath=$(VCTargetsPath)"); - xw.EndElement(); // Command - xw.EndElement(); // PostBuildEvent - xw.EndElement(); // ItemDefinitionGroup - xw.StartElement("Import"); - xw.Attribute("Project", - "$(VCTargetsPath)\\Microsoft.Cpp.targets"); - xw.EndElement(); // Import - xw.EndElement(); // Project - xw.EndDocument(); - /* clang-format on */ + } + cmXMLElement(eprj, "Import") + .Attribute("Project", "$(VCTargetsPath)\\Microsoft.Cpp.props"); + { + cmXMLElement eidg(eprj, "ItemDefinitionGroup"); + cmXMLElement epbe(eidg, "PostBuildEvent"); + cmXMLElement(epbe, "Command") + .Content("echo VCTargetsPath=$(VCTargetsPath)"); + } + cmXMLElement(eprj, "Import") + .Attribute("Project", "$(VCTargetsPath)\\Microsoft.Cpp.targets"); } std::vector<std::string> cmd; diff --git a/Source/cmGlobalVisualStudio7Generator.cxx b/Source/cmGlobalVisualStudio7Generator.cxx index c915dc5..7ff007f 100644 --- a/Source/cmGlobalVisualStudio7Generator.cxx +++ b/Source/cmGlobalVisualStudio7Generator.cxx @@ -294,19 +294,6 @@ void cmGlobalVisualStudio7Generator::Generate() if (!cmSystemTools::GetErrorOccuredFlag()) { this->CallVisualStudioMacro(MacroReload); } - - if (this->Version == VS8 && !this->CMakeInstance->GetIsInTryCompile()) { - const char* cmakeWarnVS8 = - this->CMakeInstance->GetState()->GetCacheEntryValue("CMAKE_WARN_VS8"); - if (!cmakeWarnVS8 || !cmSystemTools::IsOff(cmakeWarnVS8)) { - this->CMakeInstance->IssueMessage( - cmake::WARNING, - "The \"Visual Studio 8 2005\" generator is deprecated " - "and will be removed in a future version of CMake." - "\n" - "Add CMAKE_WARN_VS8=OFF to the cache to disable this warning."); - } - } } void cmGlobalVisualStudio7Generator::OutputSLNFile( diff --git a/Source/cmGlobalVisualStudio8Generator.cxx b/Source/cmGlobalVisualStudio8Generator.cxx index ab8ad70..117d051 100644 --- a/Source/cmGlobalVisualStudio8Generator.cxx +++ b/Source/cmGlobalVisualStudio8Generator.cxx @@ -11,75 +11,6 @@ #include "cmVisualStudioWCEPlatformParser.h" #include "cmake.h" -static const char vs8generatorName[] = "Visual Studio 8 2005"; - -class cmGlobalVisualStudio8Generator::Factory : public cmGlobalGeneratorFactory -{ -public: - cmGlobalGenerator* CreateGlobalGenerator(const std::string& name, - cmake* cm) const override - { - if (strncmp(name.c_str(), vs8generatorName, - sizeof(vs8generatorName) - 1) != 0) { - return 0; - } - - const char* p = name.c_str() + sizeof(vs8generatorName) - 1; - if (p[0] == '\0') { - return new cmGlobalVisualStudio8Generator(cm, name, ""); - } - - if (p[0] != ' ') { - return 0; - } - - ++p; - - if (!strcmp(p, "Win64")) { - return new cmGlobalVisualStudio8Generator(cm, name, "x64"); - } - - cmVisualStudioWCEPlatformParser parser(p); - parser.ParseVersion("8.0"); - if (!parser.Found()) { - return 0; - } - - cmGlobalVisualStudio8Generator* ret = - new cmGlobalVisualStudio8Generator(cm, name, p); - ret->WindowsCEVersion = parser.GetOSVersion(); - return ret; - } - - void GetDocumentation(cmDocumentationEntry& entry) const override - { - entry.Name = std::string(vs8generatorName) + " [arch]"; - entry.Brief = "Deprecated. Generates Visual Studio 2005 project files. " - "Optional [arch] can be \"Win64\"."; - } - - void GetGenerators(std::vector<std::string>& names) const override - { - names.push_back(vs8generatorName); - names.push_back(vs8generatorName + std::string(" Win64")); - cmVisualStudioWCEPlatformParser parser; - parser.ParseVersion("8.0"); - const std::vector<std::string>& availablePlatforms = - parser.GetAvailablePlatforms(); - for (std::string const& i : availablePlatforms) { - names.push_back("Visual Studio 8 2005 " + i); - } - } - - bool SupportsToolset() const override { return false; } - bool SupportsPlatform() const override { return true; } -}; - -cmGlobalGeneratorFactory* cmGlobalVisualStudio8Generator::NewFactory() -{ - return new Factory; -} - cmGlobalVisualStudio8Generator::cmGlobalVisualStudio8Generator( cmake* cm, const std::string& name, const std::string& platformName) : cmGlobalVisualStudio71Generator(cm, platformName) @@ -87,12 +18,6 @@ cmGlobalVisualStudio8Generator::cmGlobalVisualStudio8Generator( this->ProjectConfigurationSectionName = "ProjectConfigurationPlatforms"; this->Name = name; this->ExtraFlagTable = this->GetExtraFlagTableVS8(); - this->Version = VS8; - std::string vc8Express; - this->ExpressEdition = cmSystemTools::ReadRegistryValue( - "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VCExpress\\8.0\\Setup\\VC;" - "ProductDir", - vc8Express, cmSystemTools::KeyWOW64_32); } std::string cmGlobalVisualStudio8Generator::FindDevEnvCommand() @@ -143,13 +68,6 @@ bool cmGlobalVisualStudio8Generator::SetGeneratorPlatform(std::string const& p, } } -// output standard header for dsw file -void cmGlobalVisualStudio8Generator::WriteSLNHeader(std::ostream& fout) -{ - fout << "Microsoft Visual Studio Solution File, Format Version 9.00\n"; - fout << "# Visual Studio 2005\n"; -} - std::string cmGlobalVisualStudio8Generator::GetGenerateStampList() { return "generate.stamp.list"; @@ -165,62 +83,22 @@ bool cmGlobalVisualStudio8Generator::UseFolderProperty() return IsExpressEdition() ? false : cmGlobalGenerator::UseFolderProperty(); } -std::string cmGlobalVisualStudio8Generator::GetUserMacrosDirectory() -{ - // Some VS8 sp0 versions cannot run macros. - // See http://support.microsoft.com/kb/928209 - const char* vc8sp1Registry = - "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\8.0\\" - "InstalledProducts\\KB926601;"; - const char* vc8exSP1Registry = - "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\8.0\\" - "InstalledProducts\\KB926748;"; - std::string vc8sp1; - if (!cmSystemTools::ReadRegistryValue(vc8sp1Registry, vc8sp1) && - !cmSystemTools::ReadRegistryValue(vc8exSP1Registry, vc8sp1)) { - return ""; - } - - std::string base; - std::string path; - - // base begins with the VisualStudioProjectsLocation reg value... - if (cmSystemTools::ReadRegistryValue( - "HKEY_CURRENT_USER\\Software\\Microsoft\\VisualStudio\\8.0;" - "VisualStudioProjectsLocation", - base)) { - cmSystemTools::ConvertToUnixSlashes(base); - - // 8.0 macros folder: - path = base + "/VSMacros80"; - } - - // path is (correctly) still empty if we did not read the base value from - // the Registry value - return path; -} - -std::string cmGlobalVisualStudio8Generator::GetUserMacrosRegKeyBase() -{ - return "Software\\Microsoft\\VisualStudio\\8.0\\vsmacros"; -} - bool cmGlobalVisualStudio8Generator::AddCheckTarget() { // Add a special target on which all other targets depend that // checks the build system and optionally re-runs CMake. - const char* no_working_directory = 0; + // Skip the target if no regeneration is to be done. + if (this->GlobalSettingIsOn("CMAKE_SUPPRESS_REGENERATION")) { + return false; + } + + const char* no_working_directory = nullptr; std::vector<std::string> no_depends; std::vector<cmLocalGenerator*> const& generators = this->LocalGenerators; cmLocalVisualStudio7Generator* lg = static_cast<cmLocalVisualStudio7Generator*>(generators[0]); cmMakefile* mf = lg->GetMakefile(); - // Skip the target if no regeneration is to be done. - if (mf->IsOn("CMAKE_SUPPRESS_REGENERATION")) { - return false; - } - cmCustomCommandLines noCommandLines; cmTarget* tgt = mf->AddUtilityCommand( CMAKE_CHECK_BUILD_SYSTEM_TARGET, cmMakefile::TargetOrigin::Generator, @@ -266,6 +144,30 @@ bool cmGlobalVisualStudio8Generator::AddCheckTarget() listFiles.insert(listFiles.end(), lmf->GetListFiles().begin(), lmf->GetListFiles().end()); } + + // Add a custom prebuild target to run the VerifyGlobs script. + cmake* cm = this->GetCMakeInstance(); + if (cm->DoWriteGlobVerifyTarget()) { + cmCustomCommandLine verifyCommandLine; + verifyCommandLine.push_back(cmSystemTools::GetCMakeCommand()); + verifyCommandLine.push_back("-P"); + verifyCommandLine.push_back(cm->GetGlobVerifyScript()); + cmCustomCommandLines verifyCommandLines; + verifyCommandLines.push_back(verifyCommandLine); + std::vector<std::string> byproducts; + byproducts.push_back(cm->GetGlobVerifyStamp()); + + mf->AddCustomCommandToTarget(CMAKE_CHECK_BUILD_SYSTEM_TARGET, byproducts, + no_depends, verifyCommandLines, + cmTarget::PRE_BUILD, "Checking File Globs", + no_working_directory, false); + + // Ensure ZERO_CHECK always runs in Visual Studio using MSBuild, + // otherwise the prebuild command will not be run. + tgt->SetProperty("VS_GLOBAL_DisableFastUpToDateCheck", "true"); + listFiles.push_back(cm->GetGlobVerifyStamp()); + } + // Sort the list of input files and remove duplicates. std::sort(listFiles.begin(), listFiles.end(), std::less<std::string>()); std::vector<std::string>::iterator new_end = @@ -273,8 +175,6 @@ bool cmGlobalVisualStudio8Generator::AddCheckTarget() listFiles.erase(new_end, listFiles.end()); // Create a rule to re-run CMake. - std::string stampName = cmake::GetCMakeFilesDirectoryPostSlash(); - stampName += "generate.stamp"; cmCustomCommandLine commandLine; commandLine.push_back(cmSystemTools::GetCMakeCommand()); std::string argH = "-H"; diff --git a/Source/cmGlobalVisualStudio8Generator.h b/Source/cmGlobalVisualStudio8Generator.h index af83e4f..6f64b9c 100644 --- a/Source/cmGlobalVisualStudio8Generator.h +++ b/Source/cmGlobalVisualStudio8Generator.h @@ -15,7 +15,6 @@ class cmGlobalVisualStudio8Generator : public cmGlobalVisualStudio71Generator public: cmGlobalVisualStudio8Generator(cmake* cm, const std::string& name, const std::string& platformName); - static cmGlobalGeneratorFactory* NewFactory(); ///! Get the name for the generator. std::string GetName() const override { return this->Name; } @@ -35,19 +34,6 @@ public: */ void Configure() override; - /** - * Where does this version of Visual Studio look for macros for the - * current user? Returns the empty string if this version of Visual - * Studio does not implement support for VB macros. - */ - std::string GetUserMacrosDirectory() override; - - /** - * What is the reg key path to "vsmacros" for this version of Visual - * Studio? - */ - std::string GetUserMacrosRegKeyBase() override; - /** Return true if the target project file should have the option LinkLibraryDependencies and link to .sln dependencies. */ bool NeedLinkLibraryDependencies(cmGeneratorTarget* target) override; @@ -75,7 +61,6 @@ protected: virtual bool NeedsDeploy(cmStateEnums::TargetType type) const; static cmIDEFlagTable const* GetExtraFlagTableVS8(); - void WriteSLNHeader(std::ostream& fout) override; void WriteSolutionConfigurations( std::ostream& fout, std::vector<std::string> const& configs) override; void WriteProjectConfigurations( @@ -93,9 +78,5 @@ protected: std::string Name; std::string WindowsCEVersion; bool ExpressEdition; - -private: - class Factory; - friend class Factory; }; #endif diff --git a/Source/cmGlobalVisualStudioGenerator.cxx b/Source/cmGlobalVisualStudioGenerator.cxx index a4570e1..fa7dc51 100644 --- a/Source/cmGlobalVisualStudioGenerator.cxx +++ b/Source/cmGlobalVisualStudioGenerator.cxx @@ -737,26 +737,24 @@ bool cmGlobalVisualStudioGenerator::TargetIsFortranOnly( bool cmGlobalVisualStudioGenerator::TargetIsCSharpOnly( cmGeneratorTarget const* gt) { - // check to see if this is a C# build - std::set<std::string> languages; - { - // Issue diagnostic if the source files depend on the config. - std::vector<cmSourceFile*> sources; - if (!gt->GetConfigCommonSourceFiles(sources)) { - return false; - } - // Only "real" targets are allowed to be C# targets. - if (gt->Target->GetType() > cmStateEnums::OBJECT_LIBRARY) { - return false; - } + // C# targets can be defined with add_library() (using SHARED or STATIC) and + // also using add_executable(). We do not treat imported C# targets the same + // (these come in as UTILITY) + if (gt->GetType() != cmStateEnums::SHARED_LIBRARY && + gt->GetType() != cmStateEnums::STATIC_LIBRARY && + gt->GetType() != cmStateEnums::EXECUTABLE) { + return false; } - gt->GetLanguages(languages, ""); - if (languages.size() == 1) { - if (*languages.begin() == "CSharp") { - return true; - } + + // Issue diagnostic if the source files depend on the config. + std::vector<cmSourceFile*> sources; + if (!gt->GetConfigCommonSourceFiles(sources)) { + return false; } - return false; + + std::set<std::string> languages; + gt->GetLanguages(languages, ""); + return languages.size() == 1 && languages.count("CSharp") > 0; } bool cmGlobalVisualStudioGenerator::TargetCanBeReferenced( diff --git a/Source/cmGlobalVisualStudioGenerator.h b/Source/cmGlobalVisualStudioGenerator.h index 75b7f22..f39dcca 100644 --- a/Source/cmGlobalVisualStudioGenerator.h +++ b/Source/cmGlobalVisualStudioGenerator.h @@ -32,7 +32,6 @@ public: /** Known versions of Visual Studio. */ enum VSVersion { - VS8 = 80, VS9 = 90, VS10 = 100, VS11 = 110, diff --git a/Source/cmGlobalXCodeGenerator.cxx b/Source/cmGlobalXCodeGenerator.cxx index 2008a0b..4481bdc 100644 --- a/Source/cmGlobalXCodeGenerator.cxx +++ b/Source/cmGlobalXCodeGenerator.cxx @@ -458,7 +458,7 @@ void cmGlobalXCodeGenerator::AddExtraTargets( makeHelper.push_back(""); // placeholder, see below // Add ZERO_CHECK - bool regenerate = !mf->IsOn("CMAKE_SUPPRESS_REGENERATION"); + bool regenerate = !this->GlobalSettingIsOn("CMAKE_SUPPRESS_REGENERATION"); bool generateTopLevelProjectOnly = mf->IsOn("CMAKE_XCODE_GENERATE_TOP_LEVEL_PROJECT_ONLY"); bool isTopLevel = @@ -466,7 +466,7 @@ void cmGlobalXCodeGenerator::AddExtraTargets( if (regenerate && (isTopLevel || !generateTopLevelProjectOnly)) { this->CreateReRunCMakeFile(root, gens); std::string file = - this->ConvertToRelativeForMake(this->CurrentReRunCMakeMakefile.c_str()); + this->ConvertToRelativeForMake(this->CurrentReRunCMakeMakefile); cmSystemTools::ReplaceString(file, "\\ ", " "); cmTarget* check = mf->AddUtilityCommand( CMAKE_CHECK_BUILD_SYSTEM_TARGET, cmMakefile::TargetOrigin::Generator, @@ -537,6 +537,12 @@ void cmGlobalXCodeGenerator::CreateReRunCMakeFile( std::vector<std::string>::iterator new_end = std::unique(lfiles.begin(), lfiles.end()); lfiles.erase(new_end, lfiles.end()); + + cmake* cm = this->GetCMakeInstance(); + if (cm->DoWriteGlobVerifyTarget()) { + lfiles.emplace_back(cm->GetGlobVerifyStamp()); + } + this->CurrentReRunCMakeMakefile = root->GetCurrentBinaryDirectory(); this->CurrentReRunCMakeMakefile += "/CMakeScripts"; cmSystemTools::MakeDirectory(this->CurrentReRunCMakeMakefile.c_str()); @@ -553,20 +559,34 @@ void cmGlobalXCodeGenerator::CreateReRunCMakeFile( for (const auto& lfile : lfiles) { makefileStream << "TARGETS += $(subst $(space),$(spaceplus),$(wildcard " - << this->ConvertToRelativeForMake(lfile.c_str()) << "))\n"; + << this->ConvertToRelativeForMake(lfile) << "))\n"; } + makefileStream << "\n"; std::string checkCache = root->GetBinaryDirectory(); checkCache += "/"; checkCache += cmake::GetCMakeFilesDirectoryPostSlash(); checkCache += "cmake.check_cache"; - makefileStream << "\n" - << this->ConvertToRelativeForMake(checkCache.c_str()) + if (cm->DoWriteGlobVerifyTarget()) { + makefileStream << ".NOTPARALLEL:\n\n"; + makefileStream << ".PHONY: all VERIFY_GLOBS\n\n"; + makefileStream << "all: VERIFY_GLOBS " + << this->ConvertToRelativeForMake(checkCache) << "\n\n"; + makefileStream << "VERIFY_GLOBS:\n"; + makefileStream << "\t" + << this->ConvertToRelativeForMake( + cmSystemTools::GetCMakeCommand()) + << " -P " + << this->ConvertToRelativeForMake(cm->GetGlobVerifyScript()) + << "\n\n"; + } + + makefileStream << this->ConvertToRelativeForMake(checkCache) << ": $(TARGETS)\n"; makefileStream << "\t" << this->ConvertToRelativeForMake( - cmSystemTools::GetCMakeCommand().c_str()) + cmSystemTools::GetCMakeCommand()) << " -H" << this->ConvertToRelativeForMake(root->GetSourceDirectory()) << " -B" @@ -1581,12 +1601,11 @@ void cmGlobalXCodeGenerator::AddCommandsToBuildPhase( } std::string cdir = this->CurrentLocalGenerator->GetCurrentBinaryDirectory(); - cdir = this->ConvertToRelativeForMake(cdir.c_str()); + cdir = this->ConvertToRelativeForMake(cdir); std::string makecmd = "make -C "; makecmd += cdir; makecmd += " -f "; - makecmd += - this->ConvertToRelativeForMake((makefile + "$CONFIGURATION").c_str()); + makecmd += this->ConvertToRelativeForMake((makefile + "$CONFIGURATION")); makecmd += " all"; buildphase->AddAttribute("shellScript", this->CreateString(makecmd)); buildphase->AddAttribute("showEnvVarsInLog", this->CreateString("0")); @@ -1621,8 +1640,7 @@ void cmGlobalXCodeGenerator::CreateCustomRulesMakefile( const std::vector<std::string>& outputs = ccg.GetOutputs(); if (!outputs.empty()) { for (auto const& output : outputs) { - makefileStream << "\\\n\t" - << this->ConvertToRelativeForMake(output.c_str()); + makefileStream << "\\\n\t" << this->ConvertToRelativeForMake(output); } } else { std::ostringstream str; @@ -1643,8 +1661,7 @@ void cmGlobalXCodeGenerator::CreateCustomRulesMakefile( // There is at least one output, start the rule for it const char* sep = ""; for (auto const& output : outputs) { - makefileStream << sep - << this->ConvertToRelativeForMake(output.c_str()); + makefileStream << sep << this->ConvertToRelativeForMake(output); sep = " "; } makefileStream << ": "; @@ -1656,8 +1673,7 @@ void cmGlobalXCodeGenerator::CreateCustomRulesMakefile( std::string dep; if (this->CurrentLocalGenerator->GetRealDependency(d, configName, dep)) { - makefileStream << "\\\n" - << this->ConvertToRelativeForMake(dep.c_str()); + makefileStream << "\\\n" << this->ConvertToRelativeForMake(dep); } } makefileStream << "\n"; @@ -1674,12 +1690,12 @@ void cmGlobalXCodeGenerator::CreateCustomRulesMakefile( // Build the command line in a single string. std::string cmd2 = ccg.GetCommand(c); cmSystemTools::ReplaceString(cmd2, "/./", "/"); - cmd2 = this->ConvertToRelativeForMake(cmd2.c_str()); + cmd2 = this->ConvertToRelativeForMake(cmd2); std::string cmd; std::string wd = ccg.GetWorkingDirectory(); if (!wd.empty()) { cmd += "cd "; - cmd += this->ConvertToRelativeForMake(wd.c_str()); + cmd += this->ConvertToRelativeForMake(wd); cmd += " && "; } cmd += cmd2; @@ -3200,7 +3216,7 @@ void cmGlobalXCodeGenerator::CreateXCodeDependHackTarget( gt->GetType() == cmStateEnums::SHARED_LIBRARY || gt->GetType() == cmStateEnums::MODULE_LIBRARY) { std::string tfull = gt->GetFullPath(configName); - std::string trel = this->ConvertToRelativeForMake(tfull.c_str()); + std::string trel = this->ConvertToRelativeForMake(tfull); // Add this target to the post-build phases of its dependencies. std::map<std::string, cmXCodeObject::StringVec>::const_iterator y = @@ -3228,7 +3244,7 @@ void cmGlobalXCodeGenerator::CreateXCodeDependHackTarget( target->GetDependLibraries().find(configName); if (x != target->GetDependLibraries().end()) { for (auto const& deplib : x->second) { - std::string file = this->ConvertToRelativeForMake(deplib.c_str()); + std::string file = this->ConvertToRelativeForMake(deplib); makefileStream << "\\\n\t" << file; dummyRules.insert(file); } @@ -3243,7 +3259,7 @@ void cmGlobalXCodeGenerator::CreateXCodeDependHackTarget( d += objLibName; d += ".a"; - std::string dependency = this->ConvertToRelativeForMake(d.c_str()); + std::string dependency = this->ConvertToRelativeForMake(d); makefileStream << "\\\n\t" << dependency; dummyRules.insert(dependency); } @@ -3251,8 +3267,7 @@ void cmGlobalXCodeGenerator::CreateXCodeDependHackTarget( // Write the action to remove the target if it is out of date. makefileStream << "\n"; makefileStream << "\t/bin/rm -f " - << this->ConvertToRelativeForMake(tfull.c_str()) - << "\n"; + << this->ConvertToRelativeForMake(tfull) << "\n"; // if building for more than one architecture // then remove those executables as well if (this->Architectures.size() > 1) { @@ -3264,8 +3279,7 @@ void cmGlobalXCodeGenerator::CreateXCodeDependHackTarget( universalFile += "/"; universalFile += gt->GetFullName(configName); makefileStream << "\t/bin/rm -f " - << this->ConvertToRelativeForMake( - universalFile.c_str()) + << this->ConvertToRelativeForMake(universalFile) << "\n"; } } diff --git a/Source/cmIDEOptions.cxx b/Source/cmIDEOptions.cxx index 354b757..f996788 100644 --- a/Source/cmIDEOptions.cxx +++ b/Source/cmIDEOptions.cxx @@ -25,7 +25,7 @@ cmIDEOptions::~cmIDEOptions() { } -void cmIDEOptions::HandleFlag(const char* flag) +void cmIDEOptions::HandleFlag(std::string const& flag) { // If the last option was -D then this option is the definition. if (this->DoingDefine) { @@ -49,26 +49,27 @@ void cmIDEOptions::HandleFlag(const char* flag) } // Look for known arguments. - if (flag[0] == '-' || (this->AllowSlash && flag[0] == '/')) { + size_t len = flag.length(); + if (len > 0 && (flag[0] == '-' || (this->AllowSlash && flag[0] == '/'))) { // Look for preprocessor definitions. - if (this->AllowDefine && flag[1] == 'D') { - if (flag[2] == '\0') { + if (this->AllowDefine && len > 1 && flag[1] == 'D') { + if (len <= 2) { // The next argument will have the definition. this->DoingDefine = true; } else { // Store this definition. - this->Defines.push_back(flag + 2); + this->Defines.push_back(flag.substr(2)); } return; } // Look for include directory. - if (this->AllowInclude && flag[1] == 'I') { - if (flag[2] == '\0') { + if (this->AllowInclude && len > 1 && flag[1] == 'I') { + if (len <= 2) { // The next argument will have the include directory. this->DoingInclude = true; } else { // Store this include directory. - this->Includes.push_back(flag + 2); + this->Includes.push_back(flag.substr(2)); } return; } @@ -92,8 +93,9 @@ void cmIDEOptions::HandleFlag(const char* flag) } bool cmIDEOptions::CheckFlagTable(cmIDEFlagTable const* table, - const char* flag, bool& flag_handled) + std::string const& flag, bool& flag_handled) { + const char* pf = flag.c_str() + 1; // Look for an entry in the flag table matching this flag. for (cmIDEFlagTable const* entry = table; entry->IDEName; ++entry) { bool entry_found = false; @@ -102,17 +104,17 @@ bool cmIDEOptions::CheckFlagTable(cmIDEFlagTable const* table, // the entry specifies UserRequired we must match only if a // non-empty value is given. int n = static_cast<int>(strlen(entry->commandFlag)); - if ((strncmp(flag + 1, entry->commandFlag, n) == 0 || + if ((strncmp(pf, entry->commandFlag, n) == 0 || (entry->special & cmIDEFlagTable::CaseInsensitive && - cmsysString_strncasecmp(flag + 1, entry->commandFlag, n))) && + cmsysString_strncasecmp(pf, entry->commandFlag, n))) && (!(entry->special & cmIDEFlagTable::UserRequired) || - static_cast<int>(strlen(flag + 1)) > n)) { - this->FlagMapUpdate(entry, flag + n + 1); + static_cast<int>(strlen(pf)) > n)) { + this->FlagMapUpdate(entry, std::string(pf + n)); entry_found = true; } - } else if (strcmp(flag + 1, entry->commandFlag) == 0 || + } else if (strcmp(pf, entry->commandFlag) == 0 || (entry->special & cmIDEFlagTable::CaseInsensitive && - cmsysString_strcasecmp(flag + 1, entry->commandFlag) == 0)) { + cmsysString_strcasecmp(pf, entry->commandFlag) == 0)) { if (entry->special & cmIDEFlagTable::UserFollowing) { // This flag expects a value in the following argument. this->DoingFollowing = entry; @@ -137,7 +139,7 @@ bool cmIDEOptions::CheckFlagTable(cmIDEFlagTable const* table, } void cmIDEOptions::FlagMapUpdate(cmIDEFlagTable const* entry, - const char* new_value) + std::string const& new_value) { if (entry->special & cmIDEFlagTable::UserIgnored) { // Ignore the user-specified value. @@ -157,9 +159,9 @@ void cmIDEOptions::AddDefine(const std::string& def) this->Defines.push_back(def); } -void cmIDEOptions::AddDefines(const char* defines) +void cmIDEOptions::AddDefines(std::string const& defines) { - if (defines) { + if (!defines.empty()) { // Expand the list of definitions. cmSystemTools::ExpandListArgument(defines, this->Defines); } @@ -179,9 +181,9 @@ void cmIDEOptions::AddInclude(const std::string& include) this->Includes.push_back(include); } -void cmIDEOptions::AddIncludes(const char* includes) +void cmIDEOptions::AddIncludes(std::string const& includes) { - if (includes) { + if (!includes.empty()) { // Expand the list of includes. cmSystemTools::ExpandListArgument(includes, this->Includes); } diff --git a/Source/cmIDEOptions.h b/Source/cmIDEOptions.h index 54cb524..a4e5757 100644 --- a/Source/cmIDEOptions.h +++ b/Source/cmIDEOptions.h @@ -22,12 +22,12 @@ public: // Store definitions, includes and flags. void AddDefine(const std::string& define); - void AddDefines(const char* defines); + void AddDefines(std::string const& defines); void AddDefines(const std::vector<std::string>& defines); std::vector<std::string> const& GetDefines() const; void AddInclude(const std::string& includes); - void AddIncludes(const char* includes); + void AddIncludes(std::string const& includes); void AddIncludes(const std::vector<std::string>& includes); std::vector<std::string> const& GetIncludes() const; @@ -95,11 +95,12 @@ protected: FlagTableCount = 16 }; cmIDEFlagTable const* FlagTable[FlagTableCount]; - void HandleFlag(const char* flag); - bool CheckFlagTable(cmIDEFlagTable const* table, const char* flag, + void HandleFlag(std::string const& flag); + bool CheckFlagTable(cmIDEFlagTable const* table, std::string const& flag, bool& flag_handled); - void FlagMapUpdate(cmIDEFlagTable const* entry, const char* new_value); - virtual void StoreUnknownFlag(const char* flag) = 0; + void FlagMapUpdate(cmIDEFlagTable const* entry, + std::string const& new_value); + virtual void StoreUnknownFlag(std::string const& flag) = 0; }; #endif diff --git a/Source/cmInstallCommand.cxx b/Source/cmInstallCommand.cxx index 394f976..b5291a1 100644 --- a/Source/cmInstallCommand.cxx +++ b/Source/cmInstallCommand.cxx @@ -5,6 +5,7 @@ #include "cmsys/Glob.hxx" #include <sstream> #include <stddef.h> +#include <string.h> #include <utility> #include "cmAlgorithms.h" @@ -334,8 +335,8 @@ bool cmInstallCommand::HandleTargetsMode(std::vector<std::string> const& args) // Check whether this is a DLL platform. bool dll_platform = - (this->Makefile->IsOn("WIN32") || this->Makefile->IsOn("CYGWIN") || - this->Makefile->IsOn("MINGW")); + strcmp(this->Makefile->GetSafeDefinition("CMAKE_IMPORT_LIBRARY_SUFFIX"), + "") != 0; for (std::string const& tgt : targetList.GetVector()) { @@ -360,17 +361,6 @@ bool cmInstallCommand::HandleTargetsMode(std::vector<std::string> const& args) this->SetError(e.str()); return false; } - if (target->GetType() == cmStateEnums::OBJECT_LIBRARY) { - std::string reason; - if (!this->Makefile->GetGlobalGenerator()->HasKnownObjectFileLocation( - &reason)) { - std::ostringstream e; - e << "TARGETS given OBJECT library \"" << tgt - << "\" which may not be installed" << reason << "."; - this->SetError(e.str()); - return false; - } - } // Store the target in the list to be installed. targets.push_back(target); } else { @@ -534,15 +524,23 @@ bool cmInstallCommand::HandleTargetsMode(std::vector<std::string> const& args) case cmStateEnums::OBJECT_LIBRARY: { // Objects use OBJECT properties. if (!objectArgs.GetDestination().empty()) { + // Verify that we know where the objects are to install them. + std::string reason; + if (!this->Makefile->GetGlobalGenerator() + ->HasKnownObjectFileLocation(&reason)) { + std::ostringstream e; + e << "TARGETS given OBJECT library \"" << target.GetName() + << "\" whose objects may not be installed" << reason << "."; + this->SetError(e.str()); + return false; + } + objectGenerator = CreateInstallTargetGenerator(target, objectArgs, false); } else { - std::ostringstream e; - e << "TARGETS given no OBJECTS DESTINATION for object library " - "target \"" - << target.GetName() << "\"."; - this->SetError(e.str()); - return false; + // Installing an OBJECT library without a destination transforms + // it to an INTERFACE library. It installs no files but can be + // exported. } } break; case cmStateEnums::EXECUTABLE: { diff --git a/Source/cmInstallFilesCommand.h b/Source/cmInstallFilesCommand.h index 19f2559..a52f45e 100644 --- a/Source/cmInstallFilesCommand.h +++ b/Source/cmInstallFilesCommand.h @@ -48,7 +48,7 @@ protected: private: std::vector<std::string> FinalArgs; - bool IsFilesForm; + bool IsFilesForm = false; std::string Destination; std::vector<std::string> Files; }; diff --git a/Source/cmInstallTargetGenerator.cxx b/Source/cmInstallTargetGenerator.cxx index a9b4908..e0afa2d 100644 --- a/Source/cmInstallTargetGenerator.cxx +++ b/Source/cmInstallTargetGenerator.cxx @@ -135,7 +135,7 @@ void cmInstallTargetGenerator::GenerateScriptForConfig( filesFrom.push_back(std::move(from1)); filesTo.push_back(std::move(to1)); std::string targetNameImportLib; - if (this->Target->GetImplibGNUtoMS(targetNameImport, + if (this->Target->GetImplibGNUtoMS(config, targetNameImport, targetNameImportLib)) { filesFrom.push_back(fromDirConfig + targetNameImportLib); filesTo.push_back(toDir + targetNameImportLib); @@ -201,7 +201,7 @@ void cmInstallTargetGenerator::GenerateScriptForConfig( filesFrom.push_back(std::move(from1)); filesTo.push_back(std::move(to1)); std::string targetNameImportLib; - if (this->Target->GetImplibGNUtoMS(targetNameImport, + if (this->Target->GetImplibGNUtoMS(config, targetNameImport, targetNameImportLib)) { filesFrom.push_back(fromDirConfig + targetNameImportLib); filesTo.push_back(toDir + targetNameImportLib); @@ -398,7 +398,7 @@ std::string cmInstallTargetGenerator::GetInstallFilename( targetNamePDB, config); if (nameType == NameImplib) { // Use the import library name. - if (!target->GetImplibGNUtoMS(targetNameImport, fname, + if (!target->GetImplibGNUtoMS(config, targetNameImport, fname, "${CMAKE_IMPORT_LIBRARY_SUFFIX}")) { fname = targetNameImport; } @@ -419,7 +419,7 @@ std::string cmInstallTargetGenerator::GetInstallFilename( targetNameImport, targetNamePDB, config); if (nameType == NameImplib) { // Use the import library name. - if (!target->GetImplibGNUtoMS(targetNameImport, fname, + if (!target->GetImplibGNUtoMS(config, targetNameImport, fname, "${CMAKE_IMPORT_LIBRARY_SUFFIX}")) { fname = targetNameImport; } diff --git a/Source/cmLinkLineDeviceComputer.cxx b/Source/cmLinkLineDeviceComputer.cxx index 3beeae3..557fa41 100644 --- a/Source/cmLinkLineDeviceComputer.cxx +++ b/Source/cmLinkLineDeviceComputer.cxx @@ -3,9 +3,9 @@ #include "cmLinkLineDeviceComputer.h" -#include <set> #include <sstream> +#include "cmAlgorithms.h" #include "cmComputeLinkInformation.h" #include "cmGeneratorTarget.h" #include "cmGlobalNinjaGenerator.h" @@ -32,38 +32,32 @@ std::string cmLinkLineDeviceComputer::ComputeLinkLibraries( ItemVector const& items = cli.GetItems(); std::string config = cli.GetConfig(); for (auto const& item : items) { - if (!item.Target) { - continue; - } - - bool skippable = false; - switch (item.Target->GetType()) { - case cmStateEnums::SHARED_LIBRARY: - case cmStateEnums::MODULE_LIBRARY: - case cmStateEnums::INTERFACE_LIBRARY: - skippable = true; - break; - case cmStateEnums::STATIC_LIBRARY: - // If a static library is resolving its device linking, it should - // be removed for other device linking - skippable = - item.Target->GetPropertyAsBool("CUDA_RESOLVE_DEVICE_SYMBOLS"); - break; - default: - break; - } - - if (skippable) { - continue; - } - - std::set<std::string> langs; - item.Target->GetLanguages(langs, config); - if (langs.count("CUDA") == 0) { - continue; + if (item.Target) { + bool skip = false; + switch (item.Target->GetType()) { + case cmStateEnums::MODULE_LIBRARY: + case cmStateEnums::INTERFACE_LIBRARY: + skip = true; + break; + case cmStateEnums::STATIC_LIBRARY: + skip = item.Target->GetPropertyAsBool("CUDA_RESOLVE_DEVICE_SYMBOLS"); + break; + default: + break; + } + if (skip) { + continue; + } } if (item.IsPath) { + // nvcc understands absolute paths to libraries ending in '.a' should + // be passed to nvlink. Other extensions like '.so' or '.dylib' are + // rejected by the nvcc front-end even though nvlink knows to ignore + // them. Bypass the front-end via '-Xnvlink'. + if (!cmHasLiteralSuffix(item.Value, ".a")) { + fout << "-Xnvlink "; + } fout << this->ConvertToOutputFormat( this->ConvertToLinkReference(item.Value)); } else { diff --git a/Source/cmListCommand.cxx b/Source/cmListCommand.cxx index ae4f0a8..31bc1c0 100644 --- a/Source/cmListCommand.cxx +++ b/Source/cmListCommand.cxx @@ -5,14 +5,19 @@ #include "cmsys/RegularExpression.hxx" #include <algorithm> #include <assert.h> +#include <functional> #include <iterator> +#include <set> #include <sstream> +#include <stdexcept> #include <stdio.h> #include <stdlib.h> // required for atoi #include "cmAlgorithms.h" +#include "cmGeneratorExpression.h" #include "cmMakefile.h" #include "cmPolicies.h" +#include "cmStringReplaceHelper.h" #include "cmSystemTools.h" #include "cmake.h" @@ -42,6 +47,9 @@ bool cmListCommand::InitialPass(std::vector<std::string> const& args, if (subCommand == "INSERT") { return this->HandleInsertCommand(args); } + if (subCommand == "JOIN") { + return this->HandleJoinCommand(args); + } if (subCommand == "REMOVE_AT") { return this->HandleRemoveAtCommand(args); } @@ -51,9 +59,15 @@ bool cmListCommand::InitialPass(std::vector<std::string> const& args, if (subCommand == "REMOVE_DUPLICATES") { return this->HandleRemoveDuplicatesCommand(args); } + if (subCommand == "TRANSFORM") { + return this->HandleTransformCommand(args); + } if (subCommand == "SORT") { return this->HandleSortCommand(args); } + if (subCommand == "SUBLIST") { + return this->HandleSublistCommand(args); + } if (subCommand == "REVERSE") { return this->HandleReverseCommand(args); } @@ -294,6 +308,34 @@ bool cmListCommand::HandleInsertCommand(std::vector<std::string> const& args) return true; } +bool cmListCommand::HandleJoinCommand(std::vector<std::string> const& args) +{ + if (args.size() != 4) { + std::ostringstream error; + error << "sub-command JOIN requires three arguments (" << args.size() - 1 + << " found)."; + this->SetError(error.str()); + return false; + } + + const std::string& listName = args[1]; + const std::string& glue = args[2]; + const std::string& variableName = args[3]; + + // expand the variable + std::vector<std::string> varArgsExpanded; + if (!this->GetList(varArgsExpanded, listName)) { + this->Makefile->AddDefinition(variableName, ""); + return true; + } + + std::string value = + cmJoin(cmMakeRange(varArgsExpanded.begin(), varArgsExpanded.end()), glue); + + this->Makefile->AddDefinition(variableName, value.c_str()); + return true; +} + bool cmListCommand::HandleRemoveItemCommand( std::vector<std::string> const& args) { @@ -373,6 +415,554 @@ bool cmListCommand::HandleRemoveDuplicatesCommand( return true; } +// Helpers for list(TRANSFORM <list> ...) +namespace { +using transform_type = std::function<std::string(const std::string&)>; + +class transform_error : public std::runtime_error +{ +public: + transform_error(const std::string& error) + : std::runtime_error(error) + { + } +}; + +class TransformSelector +{ +public: + virtual ~TransformSelector() {} + + std::string Tag; + + virtual bool Validate(std::size_t count = 0) = 0; + + virtual bool InSelection(const std::string&) = 0; + + virtual void Transform(std::vector<std::string>& list, + const transform_type& transform) + { + std::transform(list.begin(), list.end(), list.begin(), transform); + } + +protected: + TransformSelector(std::string&& tag) + : Tag(std::move(tag)) + { + } +}; +class TransformNoSelector : public TransformSelector +{ +public: + TransformNoSelector() + : TransformSelector("NO SELECTOR") + { + } + + bool Validate(std::size_t) override { return true; } + + bool InSelection(const std::string&) override { return true; } +}; +class TransformSelectorRegex : public TransformSelector +{ +public: + TransformSelectorRegex(const std::string& regex) + : TransformSelector("REGEX") + , Regex(regex) + { + } + + bool Validate(std::size_t) override { return this->Regex.is_valid(); } + + bool InSelection(const std::string& value) override + { + return this->Regex.find(value); + } + + cmsys::RegularExpression Regex; +}; +class TransformSelectorIndexes : public TransformSelector +{ +public: + std::vector<int> Indexes; + + bool InSelection(const std::string&) override { return true; } + + void Transform(std::vector<std::string>& list, + const transform_type& transform) override + { + this->Validate(list.size()); + + for (auto index : this->Indexes) { + list[index] = transform(list[index]); + } + } + +protected: + TransformSelectorIndexes(std::string&& tag) + : TransformSelector(std::move(tag)) + { + } + TransformSelectorIndexes(std::string&& tag, std::vector<int>&& indexes) + : TransformSelector(std::move(tag)) + , Indexes(indexes) + { + } + + int NormalizeIndex(int index, std::size_t count) + { + if (index < 0) { + index = static_cast<int>(count) + index; + } + if (index < 0 || count <= static_cast<std::size_t>(index)) { + std::ostringstream str; + str << "sub-command TRANSFORM, selector " << this->Tag + << ", index: " << index << " out of range (-" << count << ", " + << count - 1 << ")."; + throw transform_error(str.str()); + } + return index; + } +}; +class TransformSelectorAt : public TransformSelectorIndexes +{ +public: + TransformSelectorAt(std::vector<int>&& indexes) + : TransformSelectorIndexes("AT", std::move(indexes)) + { + } + + bool Validate(std::size_t count) override + { + decltype(Indexes) indexes; + + for (auto index : Indexes) { + indexes.push_back(this->NormalizeIndex(index, count)); + } + this->Indexes = std::move(indexes); + + return true; + } +}; +class TransformSelectorFor : public TransformSelectorIndexes +{ +public: + TransformSelectorFor(int start, int stop, int step) + : TransformSelectorIndexes("FOR") + , Start(start) + , Stop(stop) + , Step(step) + { + } + + bool Validate(std::size_t count) override + { + this->Start = this->NormalizeIndex(this->Start, count); + this->Stop = this->NormalizeIndex(this->Stop, count); + + // compute indexes + auto size = (this->Stop - this->Start + 1) / this->Step; + if ((this->Stop - this->Start + 1) % this->Step != 0) { + size += 1; + } + + this->Indexes.resize(size); + auto start = this->Start, step = this->Step; + std::generate(this->Indexes.begin(), this->Indexes.end(), + [&start, step]() -> int { + auto r = start; + start += step; + return r; + }); + + return true; + } + +private: + int Start, Stop, Step; +}; + +class TransformAction +{ +public: + virtual ~TransformAction() {} + + virtual std::string Transform(const std::string& input) = 0; +}; +class TransformReplace : public TransformAction +{ +public: + TransformReplace(const std::vector<std::string>& arguments, + cmMakefile* makefile) + : ReplaceHelper(arguments[0], arguments[1], makefile) + { + makefile->ClearMatches(); + + if (!this->ReplaceHelper.IsRegularExpressionValid()) { + std::ostringstream error; + error + << "sub-command TRANSFORM, action REPLACE: Failed to compile regex \"" + << arguments[0] << "\"."; + throw transform_error(error.str()); + } + if (!this->ReplaceHelper.IsReplaceExpressionValid()) { + std::ostringstream error; + error << "sub-command TRANSFORM, action REPLACE: " + << this->ReplaceHelper.GetError() << "."; + throw transform_error(error.str()); + } + } + + std::string Transform(const std::string& input) override + { + // Scan through the input for all matches. + std::string output; + + if (!this->ReplaceHelper.Replace(input, output)) { + std::ostringstream error; + error << "sub-command TRANSFORM, action REPLACE: " + << this->ReplaceHelper.GetError() << "."; + throw transform_error(error.str()); + } + + return output; + } + +private: + cmStringReplaceHelper ReplaceHelper; +}; +} + +bool cmListCommand::HandleTransformCommand( + std::vector<std::string> const& args) +{ + if (args.size() < 3) { + this->SetError( + "sub-command TRANSFORM requires an action to be specified."); + return false; + } + + // Structure collecting all elements of the command + struct Command + { + Command(const std::string& listName) + : ListName(listName) + , OutputName(listName) + { + } + + std::string Name; + std::string ListName; + std::vector<std::string> Arguments; + std::unique_ptr<TransformAction> Action; + std::unique_ptr<TransformSelector> Selector; + std::string OutputName; + } command(args[1]); + + // Descriptor of action + // Arity: number of arguments required for the action + // Transform: lambda function implementing the action + struct ActionDescriptor + { + ActionDescriptor(const std::string& name) + : Name(name) + { + } + ActionDescriptor(const std::string& name, int arity, + const transform_type& transform) + : Name(name) + , Arity(arity) + , Transform(transform) + { + } + + operator const std::string&() const { return Name; } + + std::string Name; + int Arity = 0; + transform_type Transform; + }; + + // Build a set of supported actions. + std::set<ActionDescriptor, + std::function<bool(const std::string&, const std::string&)>> + descriptors( + [](const std::string& x, const std::string& y) { return x < y; }); + descriptors = { { "APPEND", 1, + [&command](const std::string& s) -> std::string { + if (command.Selector->InSelection(s)) { + return s + command.Arguments[0]; + } + + return s; + } }, + { "PREPEND", 1, + [&command](const std::string& s) -> std::string { + if (command.Selector->InSelection(s)) { + return command.Arguments[0] + s; + } + + return s; + } }, + { "TOUPPER", 0, + [&command](const std::string& s) -> std::string { + if (command.Selector->InSelection(s)) { + return cmSystemTools::UpperCase(s); + } + + return s; + } }, + { "TOLOWER", 0, + [&command](const std::string& s) -> std::string { + if (command.Selector->InSelection(s)) { + return cmSystemTools::LowerCase(s); + } + + return s; + } }, + { "STRIP", 0, + [&command](const std::string& s) -> std::string { + if (command.Selector->InSelection(s)) { + return cmSystemTools::TrimWhitespace(s); + } + + return s; + } }, + { "GENEX_STRIP", 0, + [&command](const std::string& s) -> std::string { + if (command.Selector->InSelection(s)) { + return cmGeneratorExpression::Preprocess( + s, + cmGeneratorExpression::StripAllGeneratorExpressions); + } + + return s; + } }, + { "REPLACE", 2, + [&command](const std::string& s) -> std::string { + if (command.Selector->InSelection(s)) { + return command.Action->Transform(s); + } + + return s; + } } }; + + using size_type = std::vector<std::string>::size_type; + size_type index = 2; + + // Parse all possible function parameters + auto descriptor = descriptors.find(args[index]); + + if (descriptor == descriptors.end()) { + std::ostringstream error; + error << " sub-command TRANSFORM, " << args[index] << " invalid action."; + this->SetError(error.str()); + return false; + } + + // Action arguments + index += 1; + if (args.size() < index + descriptor->Arity) { + std::ostringstream error; + error << "sub-command TRANSFORM, action " << descriptor->Name + << " expects " << descriptor->Arity << " argument(s)."; + this->SetError(error.str()); + return false; + } + + command.Name = descriptor->Name; + index += descriptor->Arity; + if (descriptor->Arity > 0) { + command.Arguments = + std::vector<std::string>(args.begin() + 3, args.begin() + index); + } + + if (command.Name == "REPLACE") { + try { + command.Action = + cm::make_unique<TransformReplace>(command.Arguments, this->Makefile); + } catch (const transform_error& e) { + this->SetError(e.what()); + return false; + } + } + + const std::string REGEX{ "REGEX" }, AT{ "AT" }, FOR{ "FOR" }, + OUTPUT_VARIABLE{ "OUTPUT_VARIABLE" }; + + // handle optional arguments + while (args.size() > index) { + if ((args[index] == REGEX || args[index] == AT || args[index] == FOR) && + command.Selector) { + std::ostringstream error; + error << "sub-command TRANSFORM, selector already specified (" + << command.Selector->Tag << ")."; + this->SetError(error.str()); + return false; + } + + // REGEX selector + if (args[index] == REGEX) { + if (args.size() == ++index) { + this->SetError("sub-command TRANSFORM, selector REGEX expects " + "'regular expression' argument."); + return false; + } + + command.Selector = cm::make_unique<TransformSelectorRegex>(args[index]); + if (!command.Selector->Validate()) { + std::ostringstream error; + error << "sub-command TRANSFORM, selector REGEX failed to compile " + "regex \""; + error << args[index] << "\"."; + this->SetError(error.str()); + return false; + } + + index += 1; + continue; + } + + // AT selector + if (args[index] == AT) { + // get all specified indexes + std::vector<int> indexes; + while (args.size() > ++index) { + std::size_t pos; + int value; + + try { + value = std::stoi(args[index], &pos); + if (pos != args[index].length()) { + // this is not a number, stop processing + break; + } + indexes.push_back(value); + } catch (const std::invalid_argument&) { + // this is not a number, stop processing + break; + } + } + + if (indexes.empty()) { + this->SetError( + "sub-command TRANSFORM, selector AT expects at least one " + "numeric value."); + return false; + } + + command.Selector = + cm::make_unique<TransformSelectorAt>(std::move(indexes)); + + continue; + } + + // FOR selector + if (args[index] == FOR) { + if (args.size() <= ++index + 1) { + this->SetError("sub-command TRANSFORM, selector FOR expects, at least," + " two arguments."); + return false; + } + + int start = 0, stop = 0, step = 1; + bool valid = true; + try { + std::size_t pos; + + start = std::stoi(args[index], &pos); + if (pos != args[index].length()) { + // this is not a number + valid = false; + } else { + stop = std::stoi(args[++index], &pos); + if (pos != args[index].length()) { + // this is not a number + valid = false; + } + } + } catch (const std::invalid_argument&) { + // this is not numbers + valid = false; + } + if (!valid) { + this->SetError("sub-command TRANSFORM, selector FOR expects, " + "at least, two numeric values."); + return false; + } + // try to read a third numeric value for step + if (args.size() > ++index) { + try { + std::size_t pos; + + step = std::stoi(args[index], &pos); + if (pos != args[index].length()) { + // this is not a number + step = 1; + } else { + index += 1; + } + } catch (const std::invalid_argument&) { + // this is not number, ignore exception + } + } + + if (step < 0) { + this->SetError("sub-command TRANSFORM, selector FOR expects " + "non negative numeric value for <step>."); + } + + command.Selector = + cm::make_unique<TransformSelectorFor>(start, stop, step); + + continue; + } + + // output variable + if (args[index] == OUTPUT_VARIABLE) { + if (args.size() == ++index) { + this->SetError("sub-command TRANSFORM, OUTPUT_VARIABLE " + "expects variable name argument."); + return false; + } + + command.OutputName = args[index++]; + continue; + } + + std::ostringstream error; + error << "sub-command TRANSFORM, '" + << cmJoin(cmMakeRange(args).advance(index), " ") + << "': unexpected argument(s)."; + this->SetError(error.str()); + return false; + } + + // expand the list variable + std::vector<std::string> varArgsExpanded; + if (!this->GetList(varArgsExpanded, command.ListName)) { + this->Makefile->AddDefinition(command.OutputName, ""); + return true; + } + + if (!command.Selector) { + // no selector specified, apply transformation to all elements + command.Selector = cm::make_unique<TransformNoSelector>(); + } + + try { + command.Selector->Transform(varArgsExpanded, descriptor->Transform); + } catch (const transform_error& e) { + this->SetError(e.what()); + return false; + } + + this->Makefile->AddDefinition(command.OutputName, + cmJoin(varArgsExpanded, ";").c_str()); + + return true; +} + bool cmListCommand::HandleSortCommand(std::vector<std::string> const& args) { assert(args.size() >= 2); @@ -396,6 +986,55 @@ bool cmListCommand::HandleSortCommand(std::vector<std::string> const& args) return true; } +bool cmListCommand::HandleSublistCommand(std::vector<std::string> const& args) +{ + if (args.size() != 5) { + std::ostringstream error; + error << "sub-command SUBLIST requires four arguments (" << args.size() - 1 + << " found)."; + this->SetError(error.str()); + return false; + } + + const std::string& listName = args[1]; + const std::string& variableName = args[args.size() - 1]; + + // expand the variable + std::vector<std::string> varArgsExpanded; + if (!this->GetList(varArgsExpanded, listName) || varArgsExpanded.empty()) { + this->Makefile->AddDefinition(variableName, ""); + return true; + } + + const int start = atoi(args[2].c_str()); + const int length = atoi(args[3].c_str()); + + using size_type = decltype(varArgsExpanded)::size_type; + + if (start < 0 || size_type(start) >= varArgsExpanded.size()) { + std::ostringstream error; + error << "begin index: " << start << " is out of range 0 - " + << varArgsExpanded.size() - 1; + this->SetError(error.str()); + return false; + } + if (length < -1) { + std::ostringstream error; + error << "length: " << length << " should be -1 or greater"; + this->SetError(error.str()); + return false; + } + + const size_type end = + (length == -1 || size_type(start + length) > varArgsExpanded.size()) + ? varArgsExpanded.size() + : size_type(start + length); + std::vector<std::string> sublist(varArgsExpanded.begin() + start, + varArgsExpanded.begin() + end); + this->Makefile->AddDefinition(variableName, cmJoin(sublist, ";").c_str()); + return true; +} + bool cmListCommand::HandleRemoveAtCommand(std::vector<std::string> const& args) { if (args.size() < 3) { diff --git a/Source/cmListCommand.h b/Source/cmListCommand.h index 2965399..76a9856 100644 --- a/Source/cmListCommand.h +++ b/Source/cmListCommand.h @@ -37,10 +37,13 @@ protected: bool HandleAppendCommand(std::vector<std::string> const& args); bool HandleFindCommand(std::vector<std::string> const& args); bool HandleInsertCommand(std::vector<std::string> const& args); + bool HandleJoinCommand(std::vector<std::string> const& args); bool HandleRemoveAtCommand(std::vector<std::string> const& args); bool HandleRemoveItemCommand(std::vector<std::string> const& args); bool HandleRemoveDuplicatesCommand(std::vector<std::string> const& args); + bool HandleTransformCommand(std::vector<std::string> const& args); bool HandleSortCommand(std::vector<std::string> const& args); + bool HandleSublistCommand(std::vector<std::string> const& args); bool HandleReverseCommand(std::vector<std::string> const& args); bool HandleFilterCommand(std::vector<std::string> const& args); bool FilterRegex(std::vector<std::string> const& args, bool includeMatches, diff --git a/Source/cmLocalGenerator.cxx b/Source/cmLocalGenerator.cxx index e942ff4..c5370e4 100644 --- a/Source/cmLocalGenerator.cxx +++ b/Source/cmLocalGenerator.cxx @@ -202,6 +202,22 @@ void cmLocalGenerator::ComputeObjectMaxPath() this->ObjectMaxPathViolations.clear(); } +void cmLocalGenerator::MoveSystemIncludesToEnd( + std::vector<std::string>& includeDirs, const std::string& config, + const std::string& lang, const cmGeneratorTarget* target) const +{ + if (!target) { + return; + } + + std::stable_sort( + includeDirs.begin(), includeDirs.end(), + [&target, &config, &lang](std::string const& a, std::string const& b) { + return !target->IsSystemIncludeDirectory(a, config, lang) && + target->IsSystemIncludeDirectory(b, config, lang); + }); +} + void cmLocalGenerator::TraceDependencies() { std::vector<std::string> configs; @@ -651,7 +667,7 @@ std::string cmLocalGenerator::ConvertToIncludeReference( } std::string cmLocalGenerator::GetIncludeFlags( - const std::vector<std::string>& includes, cmGeneratorTarget* target, + const std::vector<std::string>& includeDirs, cmGeneratorTarget* target, const std::string& lang, bool forceFullPaths, bool forResponseFile, const std::string& config) { @@ -659,6 +675,9 @@ std::string cmLocalGenerator::GetIncludeFlags( return ""; } + std::vector<std::string> includes = includeDirs; + this->MoveSystemIncludesToEnd(includes, config, lang, target); + OutputFormat shellFormat = forResponseFile ? RESPONSE : SHELL; std::ostringstream includeFlags; @@ -924,6 +943,8 @@ void cmLocalGenerator::GetIncludeDirectories(std::vector<std::string>& dirs, } } + this->MoveSystemIncludesToEnd(dirs, config, lang, target); + // Add standard include directories for this language. // We do not filter out implicit directories here. std::string const standardIncludesVar = @@ -1561,6 +1582,7 @@ void cmLocalGenerator::AddCompilerRequirementFlag( static std::map<std::string, std::vector<std::string>> langStdMap; if (langStdMap.empty()) { // Maintain sorted order, most recent first. + langStdMap["CXX"].push_back("20"); langStdMap["CXX"].push_back("17"); langStdMap["CXX"].push_back("14"); langStdMap["CXX"].push_back("11"); diff --git a/Source/cmLocalGenerator.h b/Source/cmLocalGenerator.h index 533ac56..9ba62cc 100644 --- a/Source/cmLocalGenerator.h +++ b/Source/cmLocalGenerator.h @@ -411,6 +411,10 @@ private: int targetType); void ComputeObjectMaxPath(); + void MoveSystemIncludesToEnd(std::vector<std::string>& includeDirs, + const std::string& config, + const std::string& lang, + cmGeneratorTarget const* target) const; }; #if defined(CMAKE_BUILD_WITH_CMAKE) diff --git a/Source/cmLocalNinjaGenerator.cxx b/Source/cmLocalNinjaGenerator.cxx index 8c889fc..b5ae939 100644 --- a/Source/cmLocalNinjaGenerator.cxx +++ b/Source/cmLocalNinjaGenerator.cxx @@ -10,6 +10,7 @@ #include <stdio.h> #include <utility> +#include "cmCryptoHash.h" #include "cmCustomCommand.h" #include "cmCustomCommandGenerator.h" #include "cmGeneratedFileStream.h" @@ -24,6 +25,7 @@ #include "cmStateTypes.h" #include "cmSystemTools.h" #include "cmake.h" +#include "cmsys/FStream.hxx" cmLocalNinjaGenerator::cmLocalNinjaGenerator(cmGlobalGenerator* gg, cmMakefile* mf) @@ -195,6 +197,16 @@ void cmLocalNinjaGenerator::WriteNinjaRequiredVersion(std::ostream& os) this->GetGlobalNinjaGenerator()->RequiredNinjaVersionForConsolePool(); } + // The Ninja generator writes rules which require support for restat + // when rebuilding build.ninja manifest (>= 1.8) + if (this->GetGlobalNinjaGenerator()->SupportsManifestRestat() && + this->GetCMakeInstance()->DoWriteGlobVerifyTarget() && + !this->GetGlobalNinjaGenerator()->GlobalSettingIsOn( + "CMAKE_SUPPRESS_REGENERATION")) { + requiredVersion = + this->GetGlobalNinjaGenerator()->RequiredNinjaVersionForManifestRestat(); + } + cmGlobalNinjaGenerator::WriteComment( os, "Minimal version of Ninja required by this file"); os << "ninja_required_version = " << requiredVersion << std::endl @@ -239,8 +251,7 @@ void cmLocalNinjaGenerator::WriteNinjaFilesInclusion(std::ostream& os) cmGlobalNinjaGenerator* ng = this->GetGlobalNinjaGenerator(); std::string const ninjaRulesFile = ng->NinjaOutputPath(cmGlobalNinjaGenerator::NINJA_RULES_FILE); - std::string const rulesFilePath = - ng->EncodeIdent(ng->EncodePath(ninjaRulesFile), os); + std::string const rulesFilePath = ng->EncodePath(ninjaRulesFile); cmGlobalNinjaGenerator::WriteInclude(os, rulesFilePath, "Include rules file."); os << "\n"; @@ -286,8 +297,51 @@ void cmLocalNinjaGenerator::AppendCustomCommandDeps( } } +std::string cmLocalNinjaGenerator::WriteCommandScript( + std::vector<std::string> const& cmdLines, std::string const& customStep, + cmGeneratorTarget const* target) const +{ + std::string scriptPath; + if (target) { + scriptPath = target->GetSupportDirectory(); + } else { + scriptPath = this->GetCurrentBinaryDirectory(); + scriptPath += cmake::GetCMakeFilesDirectory(); + } + cmSystemTools::MakeDirectory(scriptPath); + scriptPath += '/'; + scriptPath += customStep; +#ifdef _WIN32 + scriptPath += ".bat"; +#else + scriptPath += ".sh"; +#endif + + cmsys::ofstream script(scriptPath.c_str()); + +#ifndef _WIN32 + script << "set -e\n\n"; +#endif + + for (auto const& i : cmdLines) { + std::string cmd = i; + // The command line was built assuming it would be written to + // the build.ninja file, so it uses '$$' for '$'. Remove this + // for the raw shell script. + cmSystemTools::ReplaceString(cmd, "$$", "$"); +#ifdef _WIN32 + script << cmd << " || exit /b" << '\n'; +#else + script << cmd << '\n'; +#endif + } + + return scriptPath; +} + std::string cmLocalNinjaGenerator::BuildCommandLine( - const std::vector<std::string>& cmdLines) + std::vector<std::string> const& cmdLines, std::string const& customStep, + cmGeneratorTarget const* target) const { // If we have no commands but we need to build a command anyway, use noop. // This happens when building a POST_BUILD value for link targets that @@ -296,6 +350,35 @@ std::string cmLocalNinjaGenerator::BuildCommandLine( return cmGlobalNinjaGenerator::SHELL_NOOP; } + // If this is a custom step then we will have no '$VAR' ninja placeholders. + // This means we can deal with long command sequences by writing to a script. + // Do this if the command lines are on the scale of the OS limit. + if (!customStep.empty()) { + size_t cmdLinesTotal = 0; + for (std::string const& cmd : cmdLines) { + cmdLinesTotal += cmd.length() + 6; + } + if (cmdLinesTotal > cmSystemTools::CalculateCommandLineLengthLimit() / 2) { + std::string const scriptPath = + this->WriteCommandScript(cmdLines, customStep, target); + std::string cmd +#ifndef _WIN32 + = "/bin/sh " +#endif + ; + cmd += this->ConvertToOutputFormat( + this->GetGlobalNinjaGenerator()->ConvertToNinjaPath(scriptPath), + cmOutputConverter::SHELL); + + // Add an unused argument based on script content so that Ninja + // knows when the command lines change. + cmd += " "; + cmCryptoHash hash(cmCryptoHash::AlgoSHA256); + cmd += hash.HashFile(scriptPath).substr(0, 16); + return cmd; + } + } + std::ostringstream cmd; for (std::vector<std::string>::const_iterator li = cmdLines.begin(); li != cmdLines.end(); ++li) @@ -406,10 +489,16 @@ void cmLocalNinjaGenerator::WriteCustomCommandBuildStatement( "Phony custom command for " + ninjaOutputs[0], ninjaOutputs, ninjaDeps, cmNinjaDeps(), orderOnlyDeps, cmNinjaVars()); } else { + std::string customStep = cmSystemTools::GetFilenameName(ninjaOutputs[0]); + // Hash full path to make unique. + customStep += '-'; + cmCryptoHash hash(cmCryptoHash::AlgoSHA256); + customStep += hash.HashString(ninjaOutputs[0]).substr(0, 7); + this->GetGlobalNinjaGenerator()->WriteCustomCommandBuild( - this->BuildCommandLine(cmdLines), this->ConstructComment(ccg), - "Custom command for " + ninjaOutputs[0], cc->GetDepfile(), - cc->GetUsesTerminal(), + this->BuildCommandLine(cmdLines, customStep), + this->ConstructComment(ccg), "Custom command for " + ninjaOutputs[0], + cc->GetDepfile(), cc->GetUsesTerminal(), /*restat*/ !symbolic || !byproducts.empty(), ninjaOutputs, ninjaDeps, orderOnlyDeps); } diff --git a/Source/cmLocalNinjaGenerator.h b/Source/cmLocalNinjaGenerator.h index 95d8a61..f772fb0 100644 --- a/Source/cmLocalNinjaGenerator.h +++ b/Source/cmLocalNinjaGenerator.h @@ -59,7 +59,10 @@ public: return this->HomeRelativeOutputPath; } - std::string BuildCommandLine(const std::vector<std::string>& cmdLines); + std::string BuildCommandLine( + std::vector<std::string> const& cmdLines, + std::string const& customStep = std::string(), + cmGeneratorTarget const* target = nullptr) const; void AppendTargetOutputs(cmGeneratorTarget* target, cmNinjaDeps& outputs); void AppendTargetDepends( @@ -98,6 +101,10 @@ private: std::string MakeCustomLauncher(cmCustomCommandGenerator const& ccg); + std::string WriteCommandScript(std::vector<std::string> const& cmdLines, + std::string const& customStep, + cmGeneratorTarget const* target) const; + std::string HomeRelativeOutputPath; typedef std::map<cmCustomCommand const*, std::set<cmGeneratorTarget*>> diff --git a/Source/cmLocalUnixMakefileGenerator3.cxx b/Source/cmLocalUnixMakefileGenerator3.cxx index ddd8cc4..cf2a7b9 100644 --- a/Source/cmLocalUnixMakefileGenerator3.cxx +++ b/Source/cmLocalUnixMakefileGenerator3.cxx @@ -760,8 +760,17 @@ void cmLocalUnixMakefileGenerator3::WriteSpecialTargetsBottom( // Write special "cmake_check_build_system" target to run cmake with // the --check-build-system flag. - { + if (!this->GlobalGenerator->GlobalSettingIsOn( + "CMAKE_SUPPRESS_REGENERATION")) { // Build command to run CMake to check if anything needs regenerating. + std::vector<std::string> commands; + cmake* cm = this->GlobalGenerator->GetCMakeInstance(); + if (cm->DoWriteGlobVerifyTarget()) { + std::string rescanRule = "$(CMAKE_COMMAND) -P "; + rescanRule += this->ConvertToOutputFormat(cm->GetGlobVerifyScript(), + cmOutputConverter::SHELL); + commands.push_back(rescanRule); + } std::string cmakefileName = cmake::GetCMakeFilesDirectoryPostSlash(); cmakefileName += "Makefile.cmake"; std::string runRule = @@ -772,7 +781,6 @@ void cmLocalUnixMakefileGenerator3::WriteSpecialTargetsBottom( runRule += " 0"; std::vector<std::string> no_depends; - std::vector<std::string> commands; commands.push_back(std::move(runRule)); if (!this->IsRootMakefile()) { this->CreateCDCommand(commands, this->GetBinaryDirectory(), @@ -1580,7 +1588,11 @@ void cmLocalUnixMakefileGenerator3::WriteLocalAllRules( std::string recursiveTarget = this->GetCurrentBinaryDirectory(); recursiveTarget += "/all"; - depends.push_back("cmake_check_build_system"); + bool regenerate = + !this->GlobalGenerator->GlobalSettingIsOn("CMAKE_SUPPRESS_REGENERATION"); + if (regenerate) { + depends.push_back("cmake_check_build_system"); + } std::string progressDir = this->GetBinaryDirectory(); progressDir += cmake::GetCMakeFilesDirectory(); @@ -1643,7 +1655,7 @@ void cmLocalUnixMakefileGenerator3::WriteLocalAllRules( if (!noall || cmSystemTools::IsOff(noall)) { // Drive the build before installing. depends.push_back("all"); - } else { + } else if (regenerate) { // At least make sure the build system is up to date. depends.push_back("cmake_check_build_system"); } @@ -1657,24 +1669,33 @@ void cmLocalUnixMakefileGenerator3::WriteLocalAllRules( this->WriteMakeRule(ruleFileStream, "Prepare targets for installation.", "preinstall/fast", depends, commands, true); - // write the depend rule, really a recompute depends rule - depends.clear(); - commands.clear(); - std::string cmakefileName = cmake::GetCMakeFilesDirectoryPostSlash(); - cmakefileName += "Makefile.cmake"; - { - std::string runRule = - "$(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR)"; - runRule += " --check-build-system "; - runRule += - this->ConvertToOutputFormat(cmakefileName, cmOutputConverter::SHELL); - runRule += " 1"; - commands.push_back(std::move(runRule)); + if (regenerate) { + // write the depend rule, really a recompute depends rule + depends.clear(); + commands.clear(); + cmake* cm = this->GlobalGenerator->GetCMakeInstance(); + if (cm->DoWriteGlobVerifyTarget()) { + std::string rescanRule = "$(CMAKE_COMMAND) -P "; + rescanRule += this->ConvertToOutputFormat(cm->GetGlobVerifyScript(), + cmOutputConverter::SHELL); + commands.push_back(rescanRule); + } + std::string cmakefileName = cmake::GetCMakeFilesDirectoryPostSlash(); + cmakefileName += "Makefile.cmake"; + { + std::string runRule = + "$(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR)"; + runRule += " --check-build-system "; + runRule += + this->ConvertToOutputFormat(cmakefileName, cmOutputConverter::SHELL); + runRule += " 1"; + commands.push_back(std::move(runRule)); + } + this->CreateCDCommand(commands, this->GetBinaryDirectory(), + this->GetCurrentBinaryDirectory()); + this->WriteMakeRule(ruleFileStream, "clear depends", "depend", depends, + commands, true); } - this->CreateCDCommand(commands, this->GetBinaryDirectory(), - this->GetCurrentBinaryDirectory()); - this->WriteMakeRule(ruleFileStream, "clear depends", "depend", depends, - commands, true); } void cmLocalUnixMakefileGenerator3::ClearDependencies(cmMakefile* mf, diff --git a/Source/cmLocalVisualStudio10Generator.cxx b/Source/cmLocalVisualStudio10Generator.cxx index 2803d4a..5b6e781 100644 --- a/Source/cmLocalVisualStudio10Generator.cxx +++ b/Source/cmLocalVisualStudio10Generator.cxx @@ -62,21 +62,47 @@ cmLocalVisualStudio10Generator::~cmLocalVisualStudio10Generator() { } +void cmLocalVisualStudio10Generator::GenerateTargetsDepthFirst( + cmGeneratorTarget* target, std::vector<cmGeneratorTarget*>& remaining) +{ + if (target->GetType() == cmStateEnums::INTERFACE_LIBRARY) { + return; + } + // Find this target in the list of remaining targets. + auto it = std::find(remaining.begin(), remaining.end(), target); + if (it == remaining.end()) { + // This target was already handled. + return; + } + // Remove this target from the list of remaining targets because + // we are handling it now. + *it = nullptr; + auto& deps = this->GlobalGenerator->GetTargetDirectDepends(target); + for (auto& d : deps) { + // FIXME: Revise CreateSingleVCProj so we do not have to drop `const` here. + auto dependee = const_cast<cmGeneratorTarget*>(&*d); + GenerateTargetsDepthFirst(dependee, remaining); + // Take the union of visited source files of custom commands + auto visited = GetSourcesVisited(dependee); + GetSourcesVisited(target).insert(visited.begin(), visited.end()); + } + if (static_cast<cmGlobalVisualStudioGenerator*>(this->GlobalGenerator) + ->TargetIsFortranOnly(target)) { + this->CreateSingleVCProj(target->GetName(), target); + } else { + cmVisualStudio10TargetGenerator tg( + target, static_cast<cmGlobalVisualStudio10Generator*>( + this->GetGlobalGenerator())); + tg.Generate(); + } +} + void cmLocalVisualStudio10Generator::Generate() { - const std::vector<cmGeneratorTarget*>& tgts = this->GetGeneratorTargets(); - for (cmGeneratorTarget* l : tgts) { - if (l->GetType() == cmStateEnums::INTERFACE_LIBRARY) { - continue; - } - if (static_cast<cmGlobalVisualStudioGenerator*>(this->GlobalGenerator) - ->TargetIsFortranOnly(l)) { - this->CreateSingleVCProj(l->GetName(), l); - } else { - cmVisualStudio10TargetGenerator tg( - l, static_cast<cmGlobalVisualStudio10Generator*>( - this->GetGlobalGenerator())); - tg.Generate(); + std::vector<cmGeneratorTarget*> remaining = this->GetGeneratorTargets(); + for (auto& t : remaining) { + if (t) { + GenerateTargetsDepthFirst(t, remaining); } } this->WriteStampFiles(); diff --git a/Source/cmLocalVisualStudio10Generator.h b/Source/cmLocalVisualStudio10Generator.h index bcdc307..a4150b9 100644 --- a/Source/cmLocalVisualStudio10Generator.h +++ b/Source/cmLocalVisualStudio10Generator.h @@ -33,10 +33,19 @@ public: void ReadAndStoreExternalGUID(const std::string& name, const char* path) override; + std::set<cmSourceFile const*>& GetSourcesVisited(cmGeneratorTarget* target) + { + return SourcesVisited[target]; + }; + protected: const char* ReportErrorLabel() const override; bool CustomCommandUseLocal() const override { return true; } private: + void GenerateTargetsDepthFirst(cmGeneratorTarget* target, + std::vector<cmGeneratorTarget*>& remaining); + + std::map<cmGeneratorTarget*, std::set<cmSourceFile const*>> SourcesVisited; }; #endif diff --git a/Source/cmLocalVisualStudio7Generator.cxx b/Source/cmLocalVisualStudio7Generator.cxx index 13503ad..3460289 100644 --- a/Source/cmLocalVisualStudio7Generator.cxx +++ b/Source/cmLocalVisualStudio7Generator.cxx @@ -160,10 +160,21 @@ void cmLocalVisualStudio7Generator::WriteStampFiles() depName += ".depend"; cmsys::ofstream depFile(depName.c_str()); depFile << "# CMake generation dependency list for this directory.\n"; - std::vector<std::string> const& listFiles = this->Makefile->GetListFiles(); - for (std::vector<std::string>::const_iterator lf = listFiles.begin(); - lf != listFiles.end(); ++lf) { - depFile << *lf << std::endl; + + std::vector<std::string> listFiles(this->Makefile->GetListFiles()); + cmake* cm = this->GlobalGenerator->GetCMakeInstance(); + if (cm->DoWriteGlobVerifyTarget()) { + listFiles.push_back(cm->GetGlobVerifyStamp()); + } + + // Sort the list of input files and remove duplicates. + std::sort(listFiles.begin(), listFiles.end(), std::less<std::string>()); + std::vector<std::string>::iterator new_end = + std::unique(listFiles.begin(), listFiles.end()); + listFiles.erase(new_end, listFiles.end()); + + for (const std::string& lf : listFiles) { + depFile << lf << "\n"; } } @@ -210,7 +221,8 @@ void cmLocalVisualStudio7Generator::CreateSingleVCProj( cmSourceFile* cmLocalVisualStudio7Generator::CreateVCProjBuildRule() { - if (this->Makefile->IsOn("CMAKE_SUPPRESS_REGENERATION")) { + if (this->GlobalGenerator->GlobalSettingIsOn( + "CMAKE_SUPPRESS_REGENERATION")) { return nullptr; } @@ -227,6 +239,18 @@ cmSourceFile* cmLocalVisualStudio7Generator::CreateVCProjBuildRule() return nullptr; } + std::vector<std::string> listFiles = this->Makefile->GetListFiles(); + cmake* cm = this->GlobalGenerator->GetCMakeInstance(); + if (cm->DoWriteGlobVerifyTarget()) { + listFiles.push_back(cm->GetGlobVerifyStamp()); + } + + // Sort the list of input files and remove duplicates. + std::sort(listFiles.begin(), listFiles.end(), std::less<std::string>()); + std::vector<std::string>::iterator new_end = + std::unique(listFiles.begin(), listFiles.end()); + listFiles.erase(new_end, listFiles.end()); + std::string stampName = this->GetCurrentBinaryDirectory(); stampName += "/"; stampName += cmake::GetCMakeFilesDirectoryPostSlash(); @@ -244,17 +268,14 @@ cmSourceFile* cmLocalVisualStudio7Generator::CreateVCProjBuildRule() commandLine.push_back(args); commandLine.push_back("--check-stamp-file"); commandLine.push_back(stampName); - - std::vector<std::string> const& listFiles = this->Makefile->GetListFiles(); - cmCustomCommandLines commandLines; commandLines.push_back(commandLine); const char* no_working_directory = 0; std::string fullpathStampName = cmSystemTools::CollapseFullPath(stampName.c_str()); this->Makefile->AddCustomCommandToOutput( - fullpathStampName.c_str(), listFiles, makefileIn.c_str(), commandLines, - comment.c_str(), no_working_directory, true, false); + fullpathStampName, listFiles, makefileIn, commandLines, comment.c_str(), + no_working_directory, true, false); if (cmSourceFile* file = this->Makefile->GetSource(makefileIn.c_str())) { // Finalize the source file path now since we're adding this after // the generator validated all project-named sources. @@ -791,11 +812,9 @@ void cmLocalVisualStudio7Generator::WriteConfiguration( << "\\$(ConfigurationName)\"\n"; } targetOptions.OutputAdditionalIncludeDirectories( - fout, "\t\t\t\t", "\n", - this->FortranProject ? "Fortran" : langForClCompile); - targetOptions.OutputFlagMap(fout, "\t\t\t\t"); - targetOptions.OutputPreprocessorDefinitions(fout, "\t\t\t\t", "\n", - langForClCompile); + fout, 4, this->FortranProject ? "Fortran" : langForClCompile); + targetOptions.OutputFlagMap(fout, 4); + targetOptions.OutputPreprocessorDefinitions(fout, 4, langForClCompile); fout << "\t\t\t\tObjectFile=\"$(IntDir)\\\"\n"; if (target->GetType() <= cmStateEnums::OBJECT_LIBRARY) { // Specify the compiler program database file if configured. @@ -814,12 +833,10 @@ void cmLocalVisualStudio7Generator::WriteConfiguration( "\t\t\t\tName=\"MASM\"\n" ; /* clang-format on */ - targetOptions.OutputAdditionalIncludeDirectories(fout, "\t\t\t\t", "\n", - "ASM_MASM"); + targetOptions.OutputAdditionalIncludeDirectories(fout, 4, "ASM_MASM"); // Use same preprocessor definitions as VCCLCompilerTool. - targetOptions.OutputPreprocessorDefinitions(fout, "\t\t\t\t", "\n", - "ASM_MASM"); - masmOptions.OutputFlagMap(fout, "\t\t\t\t"); + targetOptions.OutputPreprocessorDefinitions(fout, 4, "ASM_MASM"); + masmOptions.OutputFlagMap(fout, 4); /* clang-format off */ fout << "\t\t\t\tObjectFile=\"$(IntDir)\\\"\n" @@ -836,18 +853,16 @@ void cmLocalVisualStudio7Generator::WriteConfiguration( tool = "VFResourceCompilerTool"; } fout << "\t\t\t<Tool\n\t\t\t\tName=\"" << tool << "\"\n"; - targetOptions.OutputAdditionalIncludeDirectories(fout, "\n\t\t\t\t", "", - "RC"); + targetOptions.OutputAdditionalIncludeDirectories(fout, 4, "RC"); // add the -D flags to the RC tool - targetOptions.OutputPreprocessorDefinitions(fout, "\n\t\t\t\t", "", "RC"); - fout << "/>\n"; + targetOptions.OutputPreprocessorDefinitions(fout, 4, "RC"); + fout << "\t\t\t/>\n"; tool = "VCMIDLTool"; if (this->FortranProject) { tool = "VFMIDLTool"; } fout << "\t\t\t<Tool\n\t\t\t\tName=\"" << tool << "\"\n"; - targetOptions.OutputAdditionalIncludeDirectories(fout, "\n\t\t\t\t", "", - "MIDL"); + targetOptions.OutputAdditionalIncludeDirectories(fout, 4, "MIDL"); fout << "\t\t\t\tMkTypLibCompatible=\"false\"\n"; if (gg->GetPlatformName() == "x64") { fout << "\t\t\t\tTargetEnvironment=\"3\"\n"; @@ -1072,7 +1087,7 @@ void cmLocalVisualStudio7Generator::OutputBuildTool( fout << "\t\t\t\tOutputFile=\"" << this->ConvertToXMLOutputPathSingle(temp.c_str()) << "\"\n"; this->WriteTargetVersionAttribute(fout, target); - linkOptions.OutputFlagMap(fout, "\t\t\t\t"); + linkOptions.OutputFlagMap(fout, 4); fout << "\t\t\t\tAdditionalLibraryDirectories=\""; this->OutputLibraryDirectories(fout, cli.GetDirectories()); fout << "\"\n"; @@ -1157,7 +1172,7 @@ void cmLocalVisualStudio7Generator::OutputBuildTool( fout << "\t\t\t\tOutputFile=\"" << this->ConvertToXMLOutputPathSingle(temp.c_str()) << "\"\n"; this->WriteTargetVersionAttribute(fout, target); - linkOptions.OutputFlagMap(fout, "\t\t\t\t"); + linkOptions.OutputFlagMap(fout, 4); fout << "\t\t\t\tAdditionalLibraryDirectories=\""; this->OutputLibraryDirectories(fout, cli.GetDirectories()); fout << "\"\n"; @@ -1688,18 +1703,17 @@ bool cmLocalVisualStudio7Generator::WriteGroup( } Options fileOptions(this, tool, table, gg->ExtraFlagTable); fileOptions.Parse(fc.CompileFlags.c_str()); - fileOptions.AddDefines(fc.CompileDefs.c_str()); - fileOptions.AddDefines(fc.CompileDefsConfig.c_str()); + fileOptions.AddDefines(fc.CompileDefs); + fileOptions.AddDefines(fc.CompileDefsConfig); // validate source level include directories std::vector<std::string> includes; this->AppendIncludeDirectories(includes, fc.IncludeDirs, **sf); fileOptions.AddIncludes(includes); - fileOptions.OutputFlagMap(fout, "\t\t\t\t\t"); + fileOptions.OutputFlagMap(fout, 5); fileOptions.OutputAdditionalIncludeDirectories( - fout, "\t\t\t\t\t", "\n", + fout, 5, ppLang == "CXX" && this->FortranProject ? "Fortran" : ppLang); - fileOptions.OutputPreprocessorDefinitions(fout, "\t\t\t\t\t", "\n", - ppLang); + fileOptions.OutputPreprocessorDefinitions(fout, 5, ppLang); } if (!fc.AdditionalDeps.empty()) { fout << "\t\t\t\t\tAdditionalDependencies=\"" << fc.AdditionalDeps @@ -2075,6 +2089,19 @@ std::string cmLocalVisualStudio7Generator::ConvertToXMLOutputPathSingle( return ret; } +void cmVS7GeneratorOptions::OutputFlag(std::ostream& fout, int indent, + const char* flag, + const std::string& content) +{ + fout.fill('\t'); + fout.width(indent); + // write an empty string to get the fill level indent to print + fout << ""; + fout << flag << "=\""; + fout << cmLocalVisualStudio7GeneratorEscapeForXML(content); + fout << "\"\n"; +} + // This class is used to parse an existing vs 7 project // and extract the GUID class cmVS7XMLParser : public cmXMLParser diff --git a/Source/cmLocalVisualStudio7Generator.h b/Source/cmLocalVisualStudio7Generator.h index 02e6931..b093e6f 100644 --- a/Source/cmLocalVisualStudio7Generator.h +++ b/Source/cmLocalVisualStudio7Generator.h @@ -21,6 +21,19 @@ class cmMakefile; class cmSourceFile; class cmSourceGroup; +class cmVS7GeneratorOptions : public cmVisualStudioGeneratorOptions +{ +public: + cmVS7GeneratorOptions(cmLocalVisualStudioGenerator* lg, Tool tool, + cmVS7FlagTable const* table = nullptr, + cmVS7FlagTable const* extraTable = nullptr) + : cmVisualStudioGeneratorOptions(lg, tool, table, extraTable) + { + } + void OutputFlag(std::ostream& fout, int indent, const char* tag, + const std::string& content) override; +}; + /** \class cmLocalVisualStudio7Generator * \brief Write Visual Studio .NET project files. * @@ -70,7 +83,7 @@ protected: void CreateSingleVCProj(const std::string& lname, cmGeneratorTarget* tgt); private: - typedef cmVisualStudioGeneratorOptions Options; + typedef cmVS7GeneratorOptions Options; typedef cmLocalVisualStudio7GeneratorFCInfo FCInfo; std::string GetBuildTypeLinkerFlags(std::string rootLinkerFlags, const std::string& configName); diff --git a/Source/cmMacroCommand.cxx b/Source/cmMacroCommand.cxx index 07943e3..6f4b930 100644 --- a/Source/cmMacroCommand.cxx +++ b/Source/cmMacroCommand.cxx @@ -93,7 +93,7 @@ bool cmMacroHelperCommand::InvokeInitialPass( argVs.reserve(expandedArgs.size()); char argvName[60]; for (unsigned int j = 0; j < expandedArgs.size(); ++j) { - sprintf(argvName, "${ARGV%i}", j); + sprintf(argvName, "${ARGV%u}", j); argVs.push_back(argvName); } // Invoke all the functions that were collected in the block. diff --git a/Source/cmMakefile.cxx b/Source/cmMakefile.cxx index 604ca2c..b6bf08b 100644 --- a/Source/cmMakefile.cxx +++ b/Source/cmMakefile.cxx @@ -6,12 +6,12 @@ #include "cmsys/RegularExpression.hxx" #include <algorithm> #include <assert.h> +#include <cstring> #include <ctype.h> #include <iterator> #include <memory> // IWYU pragma: keep #include <sstream> #include <stdlib.h> -#include <string.h> #include <utility> #include "cmAlgorithms.h" @@ -158,6 +158,32 @@ bool cmMakefile::CheckCMP0037(std::string const& targetName, return true; } +void cmMakefile::MaybeWarnCMP0074(std::string const& pkg) +{ + // Warn if a <pkg>_ROOT variable we may use is set. + std::string const varName = pkg + "_ROOT"; + const char* var = this->GetDefinition(varName); + std::string env; + cmSystemTools::GetEnv(varName, env); + + bool const haveVar = var && *var; + bool const haveEnv = !env.empty(); + if ((haveVar || haveEnv) && this->WarnedCMP0074.insert(varName).second) { + std::ostringstream w; + w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0074) << "\n"; + if (haveVar) { + w << "CMake variable " << varName << " is set to:\n" + << " " << var << "\n"; + } + if (haveEnv) { + w << "Environment variable " << varName << " is set to:\n" + << " " << env << "\n"; + } + w << "For compatibility, CMake is ignoring the variable."; + this->IssueMessage(cmake::AUTHOR_WARNING, w.str()); + } +} + cmStringRange cmMakefile::GetIncludeDirectoriesEntries() const { return this->StateSnapshot.GetDirectory().GetIncludeDirectoriesEntries(); @@ -1169,6 +1195,11 @@ void cmMakefile::RemoveDefineFlag(std::string const& flag, } } +void cmMakefile::AddCompileDefinition(std::string const& option) +{ + this->AppendProperty("COMPILE_DEFINITIONS", option.c_str()); +} + void cmMakefile::AddCompileOption(std::string const& option) { this->AppendProperty("COMPILE_OPTIONS", option.c_str()); @@ -1464,7 +1495,7 @@ void cmMakefile::Configure() this->SetCheckCMP0000(true); // Implicitly set the version for the user. - this->SetPolicyVersion("2.4"); + this->SetPolicyVersion("2.4", std::string()); } } bool hasProject = false; @@ -1810,12 +1841,10 @@ void cmMakefile::AddGlobalLinkInformation(cmTarget& target) std::vector<std::string> linkDirs; cmSystemTools::ExpandListArgument(linkDirsProp, linkDirs); - for (std::string const& linkDir : linkDirs) { - std::string newdir = linkDir; - // remove trailing slashes - if (*linkDir.rbegin() == '/') { - newdir = linkDir.substr(0, linkDir.size() - 1); - } + for (std::string& linkDir : linkDirs) { + // Sanitize the path the same way the link_directories command does + // in case projects set the LINK_DIRECTORIES property directly. + cmSystemTools::ConvertToUnixSlashes(linkDir); target.AddLinkDirectory(linkDir); } } @@ -1867,7 +1896,7 @@ cmTarget* cmMakefile::AddLibrary(const std::string& lname, // Clear its dependencies. Otherwise, dependencies might persist // over changes in CMakeLists.txt, making the information stale and // hence useless. - target->ClearDependencyInformation(*this, lname); + target->ClearDependencyInformation(*this); if (excludeFromAll) { target->SetProperty("EXCLUDE_FROM_ALL", "TRUE"); } @@ -3140,6 +3169,14 @@ void cmMakefile::SetArgcArgv(const std::vector<std::string>& args) cmSourceFile* cmMakefile::GetSource(const std::string& sourceName, cmSourceFileLocationKind kind) const { + // First check "Known" paths (avoids the creation of cmSourceFileLocation) + if (kind == cmSourceFileLocationKind::Known) { + auto sfsi = this->KnownFileSearchIndex.find(sourceName); + if (sfsi != this->KnownFileSearchIndex.end()) { + return sfsi->second; + } + } + cmSourceFileLocation sfl(this, sourceName, kind); auto name = this->GetCMakeInstance()->StripExtension(sfl.GetName()); #if defined(_WIN32) || defined(__APPLE__) @@ -3172,6 +3209,10 @@ cmSourceFile* cmMakefile::CreateSource(const std::string& sourceName, name = cmSystemTools::LowerCase(name); #endif this->SourceFileSearchIndex[name].push_back(sf); + // for "Known" paths add direct lookup (used for faster lookup in GetSource) + if (kind == cmSourceFileLocationKind::Known) { + this->KnownFileSearchIndex[sourceName] = sf; + } return sf; } @@ -3240,6 +3281,14 @@ int cmMakefile::TryCompile(const std::string& srcdir, // change to the tests directory and run cmake // use the cmake object instead of calling cmake cmWorkingDirectory workdir(bindir); + if (workdir.Failed()) { + this->IssueMessage(cmake::FATAL_ERROR, + "Failed to set working directory to " + bindir + " : " + + std::strerror(workdir.GetLastResult())); + cmSystemTools::SetFatalErrorOccured(); + this->IsSourceFileTryCompile = false; + return 1; + } // make sure the same generator is used // use this program as the cmake to be run, it should not @@ -3643,6 +3692,20 @@ void cmMakefile::AppendProperty(const std::string& prop, const char* value, const char* cmMakefile::GetProperty(const std::string& prop) const { + // Check for computed properties. + static std::string output; + if (prop == "TESTS") { + std::vector<std::string> keys; + // get list of keys + std::transform(this->Tests.begin(), this->Tests.end(), + std::back_inserter(keys), + [](decltype(this->Tests)::value_type const& pair) { + return pair.first; + }); + output = cmJoin(keys, ";"); + return output.c_str(); + } + return this->StateSnapshot.GetDirectory().GetProperty(prop); } @@ -3782,7 +3845,16 @@ void cmMakefile::RaiseScope(const std::string& var, const char* varDef) std::ostringstream m; m << "Cannot set \"" << var << "\": current scope has no parent."; this->IssueMessage(cmake::AUTHOR_WARNING, m.str()); + return; } + +#ifdef CMAKE_BUILD_WITH_CMAKE + cmVariableWatch* vv = this->GetVariableWatch(); + if (vv) { + vv->VariableAccessed(var, cmVariableWatch::VARIABLE_MODIFIED_ACCESS, + varDef, this); + } +#endif } cmTarget* cmMakefile::AddImportedTarget(const std::string& name, @@ -4023,10 +4095,10 @@ const char* cmMakefile::GetDefineFlagsCMP0059() const return this->DefineFlagsOrig.c_str(); } -cmPolicies::PolicyStatus cmMakefile::GetPolicyStatus( - cmPolicies::PolicyID id) const +cmPolicies::PolicyStatus cmMakefile::GetPolicyStatus(cmPolicies::PolicyID id, + bool parent_scope) const { - return this->StateSnapshot.GetPolicy(id); + return this->StateSnapshot.GetPolicy(id, parent_scope); } bool cmMakefile::PolicyOptionalWarningEnabled(std::string const& var) @@ -4117,9 +4189,10 @@ void cmMakefile::PopSnapshot(bool reportError) assert(this->StateSnapshot.IsValid()); } -bool cmMakefile::SetPolicyVersion(const char* version) +bool cmMakefile::SetPolicyVersion(std::string const& version_min, + std::string const& version_max) { - return cmPolicies::ApplyPolicyVersion(this, version); + return cmPolicies::ApplyPolicyVersion(this, version_min, version_max); } bool cmMakefile::HasCMP0054AlreadyBeenReported( @@ -4164,7 +4237,7 @@ static const char* const CXX_FEATURES[] = { nullptr FOR_EACH_CXX_FEATURE( #undef FEATURE_STRING static const char* const C_STANDARDS[] = { "90", "99", "11" }; -static const char* const CXX_STANDARDS[] = { "98", "11", "14", "17" }; +static const char* const CXX_STANDARDS[] = { "98", "11", "14", "17", "20" }; bool cmMakefile::AddRequiredTargetFeature(cmTarget* target, const std::string& feature, @@ -4414,8 +4487,9 @@ bool cmMakefile::HaveCxxStandardAvailable(cmTarget const* target, bool needCxx11 = false; bool needCxx14 = false; bool needCxx17 = false; + bool needCxx20 = false; this->CheckNeededCxxLanguage(feature, needCxx98, needCxx11, needCxx14, - needCxx17); + needCxx17, needCxx20); const char* existingCxxStandard = target->GetProperty("CXX_STANDARD"); if (!existingCxxStandard) { @@ -4435,7 +4509,8 @@ bool cmMakefile::HaveCxxStandardAvailable(cmTarget const* target, /* clang-format off */ const char* const* needCxxLevel = - needCxx17 ? &CXX_STANDARDS[3] + needCxx20 ? &CXX_STANDARDS[4] + : needCxx17 ? &CXX_STANDARDS[3] : needCxx14 ? &CXX_STANDARDS[2] : needCxx11 ? &CXX_STANDARDS[1] : needCxx98 ? &CXX_STANDARDS[0] @@ -4447,7 +4522,8 @@ bool cmMakefile::HaveCxxStandardAvailable(cmTarget const* target, void cmMakefile::CheckNeededCxxLanguage(const std::string& feature, bool& needCxx98, bool& needCxx11, - bool& needCxx14, bool& needCxx17) const + bool& needCxx14, bool& needCxx17, + bool& needCxx20) const { if (const char* propCxx98 = this->GetDefinition("CMAKE_CXX98_COMPILE_FEATURES")) { @@ -4473,6 +4549,12 @@ void cmMakefile::CheckNeededCxxLanguage(const std::string& feature, cmSystemTools::ExpandListArgument(propCxx17, props); needCxx17 = std::find(props.begin(), props.end(), feature) != props.end(); } + if (const char* propCxx20 = + this->GetDefinition("CMAKE_CXX20_COMPILE_FEATURES")) { + std::vector<std::string> props; + cmSystemTools::ExpandListArgument(propCxx20, props); + needCxx20 = std::find(props.begin(), props.end(), feature) != props.end(); + } } bool cmMakefile::AddRequiredTargetCxxFeature(cmTarget* target, @@ -4483,9 +4565,10 @@ bool cmMakefile::AddRequiredTargetCxxFeature(cmTarget* target, bool needCxx11 = false; bool needCxx14 = false; bool needCxx17 = false; + bool needCxx20 = false; this->CheckNeededCxxLanguage(feature, needCxx98, needCxx11, needCxx14, - needCxx17); + needCxx17, needCxx20); const char* existingCxxStandard = target->GetProperty("CXX_STANDARD"); const char* const* existingCxxLevel = nullptr; @@ -4530,7 +4613,8 @@ bool cmMakefile::AddRequiredTargetCxxFeature(cmTarget* target, /* clang-format off */ const char* const* needCxxLevel = - needCxx17 ? &CXX_STANDARDS[3] + needCxx20 ? &CXX_STANDARDS[4] + : needCxx17 ? &CXX_STANDARDS[3] : needCxx14 ? &CXX_STANDARDS[2] : needCxx11 ? &CXX_STANDARDS[1] : needCxx98 ? &CXX_STANDARDS[0] diff --git a/Source/cmMakefile.h b/Source/cmMakefile.h index 5a30790..16b2047 100644 --- a/Source/cmMakefile.h +++ b/Source/cmMakefile.h @@ -168,6 +168,7 @@ public: */ void AddDefineFlag(std::string const& definition); void RemoveDefineFlag(std::string const& definition); + void AddCompileDefinition(std::string const& definition); void AddCompileOption(std::string const& option); /** Create a new imported target with the name and type given. */ @@ -284,8 +285,10 @@ public: */ bool SetPolicy(cmPolicies::PolicyID id, cmPolicies::PolicyStatus status); bool SetPolicy(const char* id, cmPolicies::PolicyStatus status); - cmPolicies::PolicyStatus GetPolicyStatus(cmPolicies::PolicyID id) const; - bool SetPolicyVersion(const char* version); + cmPolicies::PolicyStatus GetPolicyStatus(cmPolicies::PolicyID id, + bool parent_scope = false) const; + bool SetPolicyVersion(std::string const& version_min, + std::string const& version_max); void RecordPolicies(cmPolicies::PolicyMap& pm); //@} @@ -832,9 +835,11 @@ public: void RemoveExportBuildFileGeneratorCMP0024(cmExportBuildFileGenerator* gen); void AddExportBuildFileGenerator(cmExportBuildFileGenerator* gen); - // Maintain a stack of package names to determine the depth of find modules - // we are currently being called with - std::deque<std::string> FindPackageModuleStack; + // Maintain a stack of package roots to allow nested PACKAGE_ROOT_PATH + // searches + std::deque<std::vector<std::string>> FindPackageRootPathStack; + + void MaybeWarnCMP0074(std::string const& pkg); protected: // add link libraries and directories to the target @@ -861,6 +866,9 @@ protected: typedef std::unordered_map<std::string, SourceFileVec> SourceFileMap; SourceFileMap SourceFileSearchIndex; + // For "Known" paths we can store a direct filename to cmSourceFile map + std::unordered_map<std::string, cmSourceFile*> KnownFileSearchIndex; + // Tests std::map<std::string, cmTest*> Tests; @@ -985,7 +993,7 @@ private: bool& needC99, bool& needC11) const; void CheckNeededCxxLanguage(const std::string& feature, bool& needCxx98, bool& needCxx11, bool& needCxx14, - bool& needCxx17) const; + bool& needCxx17, bool& needCxx20) const; bool HaveCStandardAvailable(cmTarget const* target, const std::string& feature) const; @@ -998,6 +1006,7 @@ private: bool WarnUnused; bool CheckSystemVars; bool CheckCMP0000; + std::set<std::string> WarnedCMP0074; bool IsSourceFileTryCompile; mutable bool SuppressWatches; }; diff --git a/Source/cmMakefileExecutableTargetGenerator.cxx b/Source/cmMakefileExecutableTargetGenerator.cxx index 9bbc043..1e59f44 100644 --- a/Source/cmMakefileExecutableTargetGenerator.cxx +++ b/Source/cmMakefileExecutableTargetGenerator.cxx @@ -477,8 +477,8 @@ void cmMakefileExecutableTargetGenerator::WriteExecutableRule(bool relink) this->LocalGenerator->GetCurrentBinaryDirectory(), targetFullPathImport)); std::string implib; - if (this->GeneratorTarget->GetImplibGNUtoMS(targetFullPathImport, - implib)) { + if (this->GeneratorTarget->GetImplibGNUtoMS( + this->ConfigName, targetFullPathImport, implib)) { exeCleanFiles.push_back(this->LocalGenerator->MaybeConvertToRelativePath( this->LocalGenerator->GetCurrentBinaryDirectory(), implib)); } diff --git a/Source/cmMakefileLibraryTargetGenerator.cxx b/Source/cmMakefileLibraryTargetGenerator.cxx index 9299ffe..27fae04 100644 --- a/Source/cmMakefileLibraryTargetGenerator.cxx +++ b/Source/cmMakefileLibraryTargetGenerator.cxx @@ -641,8 +641,8 @@ void cmMakefileLibraryTargetGenerator::WriteLibraryRules( this->LocalGenerator->GetCurrentBinaryDirectory(), targetFullPathImport)); std::string implib; - if (this->GeneratorTarget->GetImplibGNUtoMS(targetFullPathImport, - implib)) { + if (this->GeneratorTarget->GetImplibGNUtoMS( + this->ConfigName, targetFullPathImport, implib)) { libCleanFiles.push_back(this->LocalGenerator->MaybeConvertToRelativePath( this->LocalGenerator->GetCurrentBinaryDirectory(), implib)); } diff --git a/Source/cmMakefileTargetGenerator.cxx b/Source/cmMakefileTargetGenerator.cxx index 73cf1f0..3998823 100644 --- a/Source/cmMakefileTargetGenerator.cxx +++ b/Source/cmMakefileTargetGenerator.cxx @@ -643,6 +643,18 @@ void cmMakefileTargetGenerator::WriteObjectBuildFile( source.GetFullPath(), workingDirectory, compileCommand); } + // See if we need to use a compiler launcher like ccache or distcc + std::string compilerLauncher; + if (!compileCommands.empty() && (lang == "C" || lang == "CXX" || + lang == "Fortran" || lang == "CUDA")) { + std::string const clauncher_prop = lang + "_COMPILER_LAUNCHER"; + const char* clauncher = + this->GeneratorTarget->GetProperty(clauncher_prop); + if (clauncher && *clauncher) { + compilerLauncher = clauncher; + } + } + // Maybe insert an include-what-you-use runner. if (!compileCommands.empty() && (lang == "C" || lang == "CXX")) { std::string const iwyu_prop = lang + "_INCLUDE_WHAT_YOU_USE"; @@ -656,6 +668,13 @@ void cmMakefileTargetGenerator::WriteObjectBuildFile( if ((iwyu && *iwyu) || (tidy && *tidy) || (cpplint && *cpplint) || (cppcheck && *cppcheck)) { std::string run_iwyu = "$(CMAKE_COMMAND) -E __run_co_compile"; + if (!compilerLauncher.empty()) { + // In __run_co_compile case the launcher command is supplied + // via --launcher=<maybe-list> and consumed + run_iwyu += " --launcher="; + run_iwyu += this->LocalGenerator->EscapeForShell(compilerLauncher); + compilerLauncher.clear(); + } if (iwyu && *iwyu) { run_iwyu += " --iwyu="; run_iwyu += this->LocalGenerator->EscapeForShell(iwyu); @@ -682,21 +701,15 @@ void cmMakefileTargetGenerator::WriteObjectBuildFile( } } - // Maybe insert a compiler launcher like ccache or distcc - if (!compileCommands.empty() && (lang == "C" || lang == "CXX" || - lang == "Fortran" || lang == "CUDA")) { - std::string const clauncher_prop = lang + "_COMPILER_LAUNCHER"; - const char* clauncher = - this->GeneratorTarget->GetProperty(clauncher_prop); - if (clauncher && *clauncher) { - std::vector<std::string> launcher_cmd; - cmSystemTools::ExpandListArgument(clauncher, launcher_cmd, true); - for (std::string& i : launcher_cmd) { - i = this->LocalGenerator->EscapeForShell(i); - } - std::string const& run_launcher = cmJoin(launcher_cmd, " ") + " "; - compileCommands.front().insert(0, run_launcher); + // If compiler launcher was specified and not consumed above, it + // goes to the beginning of the command line. + if (!compileCommands.empty() && !compilerLauncher.empty()) { + std::vector<std::string> args; + cmSystemTools::ExpandListArgument(compilerLauncher, args, true); + for (std::string& i : args) { + i = this->LocalGenerator->EscapeForShell(i); } + compileCommands.front().insert(0, cmJoin(args, " ") + " "); } std::string launcher; @@ -1389,7 +1402,7 @@ std::string cmMakefileTargetGenerator::GetLinkRule( const std::string& linkRuleVar) { std::string linkRule = this->Makefile->GetRequiredDefinition(linkRuleVar); - if (this->GeneratorTarget->HasImplibGNUtoMS()) { + if (this->GeneratorTarget->HasImplibGNUtoMS(this->ConfigName)) { std::string ruleVar = "CMAKE_"; ruleVar += this->GeneratorTarget->GetLinkerLanguage(this->ConfigName); ruleVar += "_GNUtoMS_RULE"; diff --git a/Source/cmNinjaNormalTargetGenerator.cxx b/Source/cmNinjaNormalTargetGenerator.cxx index ddbc772..542bb0a 100644 --- a/Source/cmNinjaNormalTargetGenerator.cxx +++ b/Source/cmNinjaNormalTargetGenerator.cxx @@ -187,7 +187,7 @@ void cmNinjaNormalTargetGenerator::WriteDeviceLinkRule(bool useResponseFile) std::string responseFlag; if (!useResponseFile) { vars.Objects = "$in"; - vars.LinkLibraries = "$LINK_LIBRARIES"; + vars.LinkLibraries = "$LINK_PATH $LINK_LIBRARIES"; } else { std::string cmakeVarLang = "CMAKE_"; cmakeVarLang += this->TargetLinkLanguage; @@ -482,7 +482,7 @@ std::vector<std::string> cmNinjaNormalTargetGenerator::ComputeLinkCmd() const char* linkCmd = mf->GetDefinition(linkCmdVar); if (linkCmd) { std::string linkCmdStr = linkCmd; - if (this->GetGeneratorTarget()->HasImplibGNUtoMS()) { + if (this->GetGeneratorTarget()->HasImplibGNUtoMS(this->ConfigName)) { std::string ruleVar = "CMAKE_"; ruleVar += this->GeneratorTarget->GetLinkerLanguage(this->ConfigName); ruleVar += "_GNUtoMS_RULE"; @@ -881,7 +881,7 @@ void cmNinjaNormalTargetGenerator::WriteLinkStatement() targetOutputImplib, cmOutputConverter::SHELL); vars["TARGET_IMPLIB"] = impLibPath; EnsureParentDirectoryExists(impLibPath); - if (genTarget.HasImportLibrary()) { + if (genTarget.HasImportLibrary(cfgName)) { byproducts.push_back(targetOutputImplib); } } @@ -976,8 +976,10 @@ void cmNinjaNormalTargetGenerator::WriteLinkStatement() preLinkCmdLines.push_back("cd " + homeOutDir); } - vars["PRE_LINK"] = localGen.BuildCommandLine(preLinkCmdLines); - std::string postBuildCmdLine = localGen.BuildCommandLine(postBuildCmdLines); + vars["PRE_LINK"] = localGen.BuildCommandLine(preLinkCmdLines, "pre-link", + this->GeneratorTarget); + std::string postBuildCmdLine = localGen.BuildCommandLine( + postBuildCmdLines, "post-build", this->GeneratorTarget); cmNinjaVars symlinkVars; bool const symlinkNeeded = diff --git a/Source/cmNinjaTargetGenerator.cxx b/Source/cmNinjaTargetGenerator.cxx index a6a3efb..7dfce57 100644 --- a/Source/cmNinjaTargetGenerator.cxx +++ b/Source/cmNinjaTargetGenerator.cxx @@ -445,72 +445,18 @@ void cmNinjaTargetGenerator::WriteCompileRule(const std::string& lang) cmMakefile* mf = this->GetMakefile(); std::string flags = "$FLAGS"; - std::string rspfile; - std::string rspcontent; + std::string responseFlag; bool const lang_supports_response = !(lang == "RC" || lang == "CUDA"); if (lang_supports_response && this->ForceResponseFile()) { std::string const responseFlagVar = "CMAKE_" + lang + "_RESPONSE_FILE_FLAG"; - std::string responseFlag = - this->Makefile->GetSafeDefinition(responseFlagVar); + responseFlag = this->Makefile->GetSafeDefinition(responseFlagVar); if (responseFlag.empty()) { responseFlag = "@"; } - rspfile = "$RSP_FILE"; - responseFlag += rspfile; - rspcontent = " $DEFINES $INCLUDES $FLAGS"; - flags = std::move(responseFlag); - vars.Defines = ""; - vars.Includes = ""; } - // Tell ninja dependency format so all deps can be loaded into a database - std::string deptype; - std::string depfile; - std::string cldeps; - if (explicitPP) { - // The explicit preprocessing step will handle dependency scanning. - } else if (this->NeedDepTypeMSVC(lang)) { - deptype = "msvc"; - depfile.clear(); - flags += " /showIncludes"; - } else if (mf->IsOn("CMAKE_NINJA_CMCLDEPS_" + lang)) { - // For the MS resource compiler we need cmcldeps, but skip dependencies - // for source-file try_compile cases because they are always fresh. - if (!mf->GetIsSourceFileTryCompile()) { - deptype = "gcc"; - depfile = "$DEP_FILE"; - const std::string cl = mf->GetDefinition("CMAKE_C_COMPILER") - ? mf->GetSafeDefinition("CMAKE_C_COMPILER") - : mf->GetSafeDefinition("CMAKE_CXX_COMPILER"); - cldeps = "\""; - cldeps += cmSystemTools::GetCMClDepsCommand(); - cldeps += "\" " + lang + " " + vars.Source + " $DEP_FILE $out \""; - cldeps += mf->GetSafeDefinition("CMAKE_CL_SHOWINCLUDES_PREFIX"); - cldeps += "\" \"" + cl + "\" "; - } - } else { - deptype = "gcc"; - const char* langdeptype = mf->GetDefinition("CMAKE_NINJA_DEPTYPE_" + lang); - if (langdeptype) { - deptype = langdeptype; - } - depfile = "$DEP_FILE"; - const std::string flagsName = "CMAKE_DEPFILE_FLAGS_" + lang; - std::string depfileFlags = mf->GetSafeDefinition(flagsName); - if (!depfileFlags.empty()) { - cmSystemTools::ReplaceString(depfileFlags, "<DEPFILE>", "$DEP_FILE"); - cmSystemTools::ReplaceString(depfileFlags, "<OBJECT>", "$out"); - cmSystemTools::ReplaceString(depfileFlags, "<CMAKE_C_COMPILER>", - mf->GetDefinition("CMAKE_C_COMPILER")); - flags += " " + depfileFlags; - } - } - - vars.Flags = flags.c_str(); - vars.DependencyFile = depfile.c_str(); - std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander( this->GetLocalGenerator()->CreateRulePlaceholderExpander()); @@ -550,7 +496,7 @@ void cmNinjaTargetGenerator::WriteCompileRule(const std::string& lang) vars.Source = "$in"; // Preprocessing and compilation use the same flags. - ppVars.Flags = vars.Flags; + std::string ppFlags = flags; // Move preprocessor definitions to the preprocessor rule. ppVars.Defines = vars.Defines; @@ -560,6 +506,20 @@ void cmNinjaTargetGenerator::WriteCompileRule(const std::string& lang) // compilation rule still needs them for the INCLUDE directive. ppVars.Includes = vars.Includes; + // If using a response file, move defines, includes, and flags into it. + std::string ppRspFile; + std::string ppRspContent; + if (!responseFlag.empty()) { + ppRspFile = "$RSP_FILE"; + ppRspContent = std::string(" ") + ppVars.Defines + " " + + ppVars.Includes + " " + ppFlags; + ppFlags = responseFlag + ppRspFile; + ppVars.Defines = ""; + ppVars.Includes = ""; + } + + ppVars.Flags = ppFlags.c_str(); + // Rule for preprocessing source file. std::vector<std::string> ppCmds; cmSystemTools::ExpandListArgument(ppCmd, ppCmds); @@ -588,13 +548,11 @@ void cmNinjaTargetGenerator::WriteCompileRule(const std::string& lang) ppComment << "Rule for preprocessing " << lang << " files."; std::ostringstream ppDesc; ppDesc << "Building " << lang << " preprocessed $out"; - this->GetGlobalGenerator()->AddRule(this->LanguagePreprocessRule(lang), - ppCmdLine, ppDesc.str(), - ppComment.str(), ppDepfile, ppDeptype, - /*rspfile*/ "", - /*rspcontent*/ "", - /*restat*/ "", - /*generator*/ false); + this->GetGlobalGenerator()->AddRule( + this->LanguagePreprocessRule(lang), ppCmdLine, ppDesc.str(), + ppComment.str(), ppDepfile, ppDeptype, ppRspFile, ppRspContent, + /*restat*/ "", + /*generator*/ false); } if (needDyndep) { @@ -631,6 +589,64 @@ void cmNinjaTargetGenerator::WriteCompileRule(const std::string& lang) /*generator*/ false); } + // If using a response file, move defines, includes, and flags into it. + std::string rspfile; + std::string rspcontent; + if (!responseFlag.empty()) { + rspfile = "$RSP_FILE"; + rspcontent = + std::string(" ") + vars.Defines + " " + vars.Includes + " " + flags; + flags = responseFlag + rspfile; + vars.Defines = ""; + vars.Includes = ""; + } + + // Tell ninja dependency format so all deps can be loaded into a database + std::string deptype; + std::string depfile; + std::string cldeps; + if (explicitPP) { + // The explicit preprocessing step will handle dependency scanning. + } else if (this->NeedDepTypeMSVC(lang)) { + deptype = "msvc"; + depfile.clear(); + flags += " /showIncludes"; + } else if (mf->IsOn("CMAKE_NINJA_CMCLDEPS_" + lang)) { + // For the MS resource compiler we need cmcldeps, but skip dependencies + // for source-file try_compile cases because they are always fresh. + if (!mf->GetIsSourceFileTryCompile()) { + deptype = "gcc"; + depfile = "$DEP_FILE"; + const std::string cl = mf->GetDefinition("CMAKE_C_COMPILER") + ? mf->GetSafeDefinition("CMAKE_C_COMPILER") + : mf->GetSafeDefinition("CMAKE_CXX_COMPILER"); + cldeps = "\""; + cldeps += cmSystemTools::GetCMClDepsCommand(); + cldeps += "\" " + lang + " " + vars.Source + " $DEP_FILE $out \""; + cldeps += mf->GetSafeDefinition("CMAKE_CL_SHOWINCLUDES_PREFIX"); + cldeps += "\" \"" + cl + "\" "; + } + } else { + deptype = "gcc"; + const char* langdeptype = mf->GetDefinition("CMAKE_NINJA_DEPTYPE_" + lang); + if (langdeptype) { + deptype = langdeptype; + } + depfile = "$DEP_FILE"; + const std::string flagsName = "CMAKE_DEPFILE_FLAGS_" + lang; + std::string depfileFlags = mf->GetSafeDefinition(flagsName); + if (!depfileFlags.empty()) { + cmSystemTools::ReplaceString(depfileFlags, "<DEPFILE>", "$DEP_FILE"); + cmSystemTools::ReplaceString(depfileFlags, "<OBJECT>", "$out"); + cmSystemTools::ReplaceString(depfileFlags, "<CMAKE_C_COMPILER>", + mf->GetDefinition("CMAKE_C_COMPILER")); + flags += " " + depfileFlags; + } + } + + vars.Flags = flags.c_str(); + vars.DependencyFile = depfile.c_str(); + // Rule for compiling object file. std::vector<std::string> compileCmds; if (lang == "CUDA") { @@ -653,6 +669,17 @@ void cmNinjaTargetGenerator::WriteCompileRule(const std::string& lang) cmSystemTools::ExpandListArgument(compileCmd, compileCmds); } + // See if we need to use a compiler launcher like ccache or distcc + std::string compilerLauncher; + if (!compileCmds.empty() && + (lang == "C" || lang == "CXX" || lang == "Fortran" || lang == "CUDA")) { + std::string const clauncher_prop = lang + "_COMPILER_LAUNCHER"; + const char* clauncher = this->GeneratorTarget->GetProperty(clauncher_prop); + if (clauncher && *clauncher) { + compilerLauncher = clauncher; + } + } + // Maybe insert an include-what-you-use runner. if (!compileCmds.empty() && (lang == "C" || lang == "CXX")) { std::string const iwyu_prop = lang + "_INCLUDE_WHAT_YOU_USE"; @@ -668,6 +695,13 @@ void cmNinjaTargetGenerator::WriteCompileRule(const std::string& lang) std::string run_iwyu = this->GetLocalGenerator()->ConvertToOutputFormat( cmSystemTools::GetCMakeCommand(), cmOutputConverter::SHELL); run_iwyu += " -E __run_co_compile"; + if (!compilerLauncher.empty()) { + // In __run_co_compile case the launcher command is supplied + // via --launcher=<maybe-list> and consumed + run_iwyu += " --launcher="; + run_iwyu += this->LocalGenerator->EscapeForShell(compilerLauncher); + compilerLauncher.clear(); + } if (iwyu && *iwyu) { run_iwyu += " --iwyu="; run_iwyu += this->GetLocalGenerator()->EscapeForShell(iwyu); @@ -693,20 +727,15 @@ void cmNinjaTargetGenerator::WriteCompileRule(const std::string& lang) } } - // Maybe insert a compiler launcher like ccache or distcc - if (!compileCmds.empty() && - (lang == "C" || lang == "CXX" || lang == "Fortran" || lang == "CUDA")) { - std::string const clauncher_prop = lang + "_COMPILER_LAUNCHER"; - const char* clauncher = this->GeneratorTarget->GetProperty(clauncher_prop); - if (clauncher && *clauncher) { - std::vector<std::string> launcher_cmd; - cmSystemTools::ExpandListArgument(clauncher, launcher_cmd, true); - for (std::string& i : launcher_cmd) { - i = this->LocalGenerator->EscapeForShell(i); - } - std::string const& run_launcher = cmJoin(launcher_cmd, " ") + " "; - compileCmds.front().insert(0, run_launcher); + // If compiler launcher was specified and not consumed above, it + // goes to the beginning of the command line. + if (!compileCmds.empty() && !compilerLauncher.empty()) { + std::vector<std::string> args; + cmSystemTools::ExpandListArgument(compilerLauncher, args, true); + for (std::string& i : args) { + i = this->LocalGenerator->EscapeForShell(i); } + compileCmds.front().insert(0, cmJoin(args, " ") + " "); } if (!compileCmds.empty()) { @@ -792,6 +821,19 @@ void cmNinjaTargetGenerator::WriteObjectBuildStatements() orderOnlyDeps.erase(std::unique(orderOnlyDeps.begin(), orderOnlyDeps.end()), orderOnlyDeps.end()); + // The phony target must depend on at least one input or ninja will explain + // that "output ... of phony edge with no inputs doesn't exist" and consider + // the phony output "dirty". + if (orderOnlyDeps.empty()) { + // Any path that always exists will work here. It would be nice to + // use just "." but that is not supported by Ninja < 1.7. + std::string tgtDir; + tgtDir += this->LocalGenerator->GetCurrentBinaryDirectory(); + tgtDir += "/"; + tgtDir += this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget); + orderOnlyDeps.push_back(this->ConvertToNinjaPath(tgtDir)); + } + { cmNinjaDeps orderOnlyTarget; orderOnlyTarget.push_back(this->OrderDependsTargetForTarget()); @@ -852,13 +894,36 @@ void cmNinjaTargetGenerator::WriteObjectBuildStatement( std::string const objectFileDir = cmSystemTools::GetFilenamePath(objectFileName); + bool const lang_supports_response = + !(language == "RC" || language == "CUDA"); + int const commandLineLengthLimit = + ((lang_supports_response && this->ForceResponseFile())) ? -1 : 0; + cmNinjaVars vars; vars["FLAGS"] = this->ComputeFlagsForObject(source, language); vars["DEFINES"] = this->ComputeDefines(source, language); vars["INCLUDES"] = this->ComputeIncludes(source, language); + if (!this->NeedDepTypeMSVC(language)) { - vars["DEP_FILE"] = this->GetLocalGenerator()->ConvertToOutputFormat( - objectFileName + ".d", cmOutputConverter::SHELL); + bool replaceExt(false); + if (!language.empty()) { + std::string repVar = "CMAKE_"; + repVar += language; + repVar += "_DEPFILE_EXTENSION_REPLACE"; + replaceExt = this->Makefile->IsOn(repVar); + } + if (!replaceExt) { + // use original code + vars["DEP_FILE"] = this->GetLocalGenerator()->ConvertToOutputFormat( + objectFileName + ".d", cmOutputConverter::SHELL); + } else { + // Replace the original source file extension with the + // depend file extension. + std::string dependFileName = + cmSystemTools::GetFilenameWithoutLastExtension(objectFileName) + ".d"; + vars["DEP_FILE"] = this->GetLocalGenerator()->ConvertToOutputFormat( + objectFileDir + "/" + dependFileName, cmOutputConverter::SHELL); + } } this->ExportObjectCompileCommand( @@ -983,9 +1048,12 @@ void cmNinjaTargetGenerator::WriteObjectBuildStatement( this->addPoolNinjaVariable("JOB_POOL_COMPILE", this->GetGeneratorTarget(), ppVars); + std::string const ppRspFile = ppFileName + ".rsp"; + this->GetGlobalGenerator()->WriteBuild( this->GetBuildFileStream(), ppComment, ppRule, ppOutputs, ppImplicitOuts, - ppExplicitDeps, ppImplicitDeps, ppOrderOnlyDeps, ppVars); + ppExplicitDeps, ppImplicitDeps, ppOrderOnlyDeps, ppVars, ppRspFile, + commandLineLengthLimit); } if (needDyndep) { std::string const dyndep = this->GetDyndepFilePath(language); @@ -1005,10 +1073,6 @@ void cmNinjaTargetGenerator::WriteObjectBuildStatement( this->SetMsvcTargetPdbVariable(vars); - bool const lang_supports_response = - !(language == "RC" || language == "CUDA"); - int const commandLineLengthLimit = - ((lang_supports_response && this->ForceResponseFile())) ? -1 : 0; std::string const rspfile = objectFileName + ".rsp"; this->GetGlobalGenerator()->WriteBuild( diff --git a/Source/cmNinjaUtilityTargetGenerator.cxx b/Source/cmNinjaUtilityTargetGenerator.cxx index 7adeb8e..cc6d4b9 100644 --- a/Source/cmNinjaUtilityTargetGenerator.cxx +++ b/Source/cmNinjaUtilityTargetGenerator.cxx @@ -96,8 +96,8 @@ void cmNinjaUtilityTargetGenerator::Generate() this->GetBuildFileStream(), "Utility command for " + this->GetTargetName(), outputs, deps); } else { - std::string command = - this->GetLocalGenerator()->BuildCommandLine(commands); + std::string command = this->GetLocalGenerator()->BuildCommandLine( + commands, "utility", this->GeneratorTarget); const char* echoStr = this->GetGeneratorTarget()->GetProperty("EchoString"); std::string desc; diff --git a/Source/cmOutputConverter.cxx b/Source/cmOutputConverter.cxx index 25db929..fd42c53 100644 --- a/Source/cmOutputConverter.cxx +++ b/Source/cmOutputConverter.cxx @@ -6,7 +6,7 @@ #include <assert.h> #include <ctype.h> #include <set> -#include <sstream> +#include <string.h> #include <vector> #include "cmAlgorithms.h" @@ -341,12 +341,13 @@ redirection character (for example, ^>, ^<, or ^| ). If you need to use the caret character itself (^), use two in a row (^^). */ -int cmOutputConverter::Shell__CharIsWhitespace(char c) +/* Some helpers to identify character classes */ +static int Shell__CharIsWhitespace(char c) { return ((c == ' ') || (c == '\t')); } -int cmOutputConverter::Shell__CharNeedsQuotesOnUnix(char c) +static int Shell__CharNeedsQuotesOnUnix(char c) { return ((c == '\'') || (c == '`') || (c == ';') || (c == '#') || (c == '&') || (c == '$') || (c == '(') || (c == ')') || (c == '~') || @@ -354,12 +355,17 @@ int cmOutputConverter::Shell__CharNeedsQuotesOnUnix(char c) (c == '\\')); } -int cmOutputConverter::Shell__CharNeedsQuotesOnWindows(char c) +static int Shell__CharNeedsQuotesOnWindows(char c) { return ((c == '\'') || (c == '#') || (c == '&') || (c == '<') || (c == '>') || (c == '|') || (c == '^')); } +static int Shell__CharIsMakeVariableName(char c) +{ + return c && (c == '_' || isalpha((static_cast<int>(c)))); +} + int cmOutputConverter::Shell__CharNeedsQuotes(char c, int flags) { /* On Windows the built-in command shell echo never needs quotes. */ @@ -386,11 +392,6 @@ int cmOutputConverter::Shell__CharNeedsQuotes(char c, int flags) return 0; } -int cmOutputConverter::Shell__CharIsMakeVariableName(char c) -{ - return c && (c == '_' || isalpha((static_cast<int>(c)))); -} - const char* cmOutputConverter::Shell__SkipMakeVariables(const char* c) { while (*c == '$' && *(c + 1) == '(') { @@ -481,7 +482,9 @@ int cmOutputConverter::Shell__ArgumentNeedsQuotes(const char* in, int flags) std::string cmOutputConverter::Shell__GetArgument(const char* in, int flags) { - std::ostringstream out; + /* Output will be at least as long as input string. */ + std::string out; + out.reserve(strlen(in)); /* String iterator. */ const char* c; @@ -495,11 +498,11 @@ std::string cmOutputConverter::Shell__GetArgument(const char* in, int flags) /* Add the opening quote for this argument. */ if (flags & Shell_Flag_WatcomQuote) { if (flags & Shell_Flag_IsUnix) { - out << '"'; + out += '"'; } - out << '\''; + out += '\''; } else { - out << '"'; + out += '"'; } } @@ -511,7 +514,7 @@ std::string cmOutputConverter::Shell__GetArgument(const char* in, int flags) if (skip != c) { /* Copy to the end of the make variable references. */ while (c != skip) { - out << *c++; + out += *c++; } /* The make variable reference eliminates any escaping needed @@ -531,7 +534,7 @@ std::string cmOutputConverter::Shell__GetArgument(const char* in, int flags) quoted argument. */ if (*c == '\\' || *c == '"' || *c == '`' || *c == '$') { /* This character needs a backslash to escape it. */ - out << '\\'; + out += '\\'; } } else if (flags & Shell_Flag_EchoWindows) { /* On Windows the built-in command shell echo never needs escaping. */ @@ -545,11 +548,11 @@ std::string cmOutputConverter::Shell__GetArgument(const char* in, int flags) backslashes. */ while (windows_backslashes > 0) { --windows_backslashes; - out << '\\'; + out += '\\'; } /* Add the backslash to escape the double-quote. */ - out << '\\'; + out += '\\'; } else { /* We encountered a normal character. This eliminates any escaping needed for preceding backslashes. */ @@ -562,7 +565,7 @@ std::string cmOutputConverter::Shell__GetArgument(const char* in, int flags) if (flags & Shell_Flag_Make) { /* In Makefiles a dollar is written $$. The make tool will replace it with just $ before passing it to the shell. */ - out << "$$"; + out += "$$"; } else if (flags & Shell_Flag_VSIDE) { /* In a VS IDE a dollar is written "$". If this is written in an un-quoted argument it starts a quoted segment, inserts @@ -570,30 +573,30 @@ std::string cmOutputConverter::Shell__GetArgument(const char* in, int flags) argument it ends quoting, inserts the $ and restarts quoting. Either way the $ is isolated from surrounding text to avoid looking like a variable reference. */ - out << "\"$\""; + out += "\"$\""; } else { /* Otherwise a dollar is written just $. */ - out << '$'; + out += '$'; } } else if (*c == '#') { if ((flags & Shell_Flag_Make) && (flags & Shell_Flag_WatcomWMake)) { /* In Watcom WMake makefiles a pound is written $#. The make tool will replace it with just # before passing it to the shell. */ - out << "$#"; + out += "$#"; } else { /* Otherwise a pound is written just #. */ - out << '#'; + out += '#'; } } else if (*c == '%') { if ((flags & Shell_Flag_VSIDE) || ((flags & Shell_Flag_Make) && ((flags & Shell_Flag_MinGWMake) || (flags & Shell_Flag_NMake)))) { /* In the VS IDE, NMake, or MinGW make a percent is written %%. */ - out << "%%"; + out += "%%"; } else { /* Otherwise a percent is written just %. */ - out << '%'; + out += '%'; } } else if (*c == ';') { if (flags & Shell_Flag_VSIDE) { @@ -602,14 +605,14 @@ std::string cmOutputConverter::Shell__GetArgument(const char* in, int flags) inserts the ; and ends the segment. If it is written in a quoted argument it ends quoting, inserts the ; and restarts quoting. Either way the ; is isolated. */ - out << "\";\""; + out += "\";\""; } else { /* Otherwise a semicolon is written just ;. */ - out << ';'; + out += ';'; } } else { /* Store this character. */ - out << *c; + out += *c; } } @@ -617,19 +620,19 @@ std::string cmOutputConverter::Shell__GetArgument(const char* in, int flags) /* Add enough backslashes to escape any trailing ones. */ while (windows_backslashes > 0) { --windows_backslashes; - out << '\\'; + out += '\\'; } /* Add the closing quote for this argument. */ if (flags & Shell_Flag_WatcomQuote) { - out << '\''; + out += '\''; if (flags & Shell_Flag_IsUnix) { - out << '"'; + out += '"'; } } else { - out << '"'; + out += '"'; } } - return out.str(); + return out; } diff --git a/Source/cmOutputConverter.h b/Source/cmOutputConverter.h index ae15055..ed7143c 100644 --- a/Source/cmOutputConverter.h +++ b/Source/cmOutputConverter.h @@ -117,11 +117,7 @@ public: private: cmState* GetState() const; - static int Shell__CharIsWhitespace(char c); - static int Shell__CharNeedsQuotesOnUnix(char c); - static int Shell__CharNeedsQuotesOnWindows(char c); static int Shell__CharNeedsQuotes(char c, int flags); - static int Shell__CharIsMakeVariableName(char c); static const char* Shell__SkipMakeVariables(const char* c); static int Shell__ArgumentNeedsQuotes(const char* in, int flags); static std::string Shell__GetArgument(const char* in, int flags); diff --git a/Source/cmPolicies.cxx b/Source/cmPolicies.cxx index e7d1b72..dba22b3 100644 --- a/Source/cmPolicies.cxx +++ b/Source/cmPolicies.cxx @@ -153,31 +153,26 @@ static bool GetPolicyDefault(cmMakefile* mf, std::string const& policy, return true; } -bool cmPolicies::ApplyPolicyVersion(cmMakefile* mf, const char* version) +bool cmPolicies::ApplyPolicyVersion(cmMakefile* mf, + std::string const& version_min, + std::string const& version_max) { - std::string ver = "2.4.0"; - - if (version && strlen(version) > 0) { - ver = version; - } - - unsigned int majorVer = 2; - unsigned int minorVer = 0; - unsigned int patchVer = 0; - unsigned int tweakVer = 0; - - // parse the string - if (sscanf(ver.c_str(), "%u.%u.%u.%u", &majorVer, &minorVer, &patchVer, - &tweakVer) < 2) { + // Parse components of the minimum version. + unsigned int minMajor = 2; + unsigned int minMinor = 0; + unsigned int minPatch = 0; + unsigned int minTweak = 0; + if (sscanf(version_min.c_str(), "%u.%u.%u.%u", &minMajor, &minMinor, + &minPatch, &minTweak) < 2) { std::ostringstream e; - e << "Invalid policy version value \"" << ver << "\". " + e << "Invalid policy version value \"" << version_min << "\". " << "A numeric major.minor[.patch[.tweak]] must be given."; mf->IssueMessage(cmake::FATAL_ERROR, e.str()); return false; } // it is an error if the policy version is less than 2.4 - if (majorVer < 2 || (majorVer == 2 && minorVer < 4)) { + if (minMajor < 2 || (minMajor == 2 && minMinor < 4)) { mf->IssueMessage( cmake::FATAL_ERROR, "Compatibility with CMake < 2.4 is not supported by CMake >= 3.0. " @@ -188,19 +183,19 @@ bool cmPolicies::ApplyPolicyVersion(cmMakefile* mf, const char* version) // It is an error if the policy version is greater than the running // CMake. - if (majorVer > cmVersion::GetMajorVersion() || - (majorVer == cmVersion::GetMajorVersion() && - minorVer > cmVersion::GetMinorVersion()) || - (majorVer == cmVersion::GetMajorVersion() && - minorVer == cmVersion::GetMinorVersion() && - patchVer > cmVersion::GetPatchVersion()) || - (majorVer == cmVersion::GetMajorVersion() && - minorVer == cmVersion::GetMinorVersion() && - patchVer == cmVersion::GetPatchVersion() && - tweakVer > cmVersion::GetTweakVersion())) { + if (minMajor > cmVersion::GetMajorVersion() || + (minMajor == cmVersion::GetMajorVersion() && + minMinor > cmVersion::GetMinorVersion()) || + (minMajor == cmVersion::GetMajorVersion() && + minMinor == cmVersion::GetMinorVersion() && + minPatch > cmVersion::GetPatchVersion()) || + (minMajor == cmVersion::GetMajorVersion() && + minMinor == cmVersion::GetMinorVersion() && + minPatch == cmVersion::GetPatchVersion() && + minTweak > cmVersion::GetTweakVersion())) { std::ostringstream e; e << "An attempt was made to set the policy version of CMake to \"" - << version << "\" which is greater than this version of CMake. " + << version_min << "\" which is greater than this version of CMake. " << "This is not allowed because the greater version may have new " << "policies not known to this CMake. " << "You may need a newer CMake version to build this project."; @@ -208,6 +203,52 @@ bool cmPolicies::ApplyPolicyVersion(cmMakefile* mf, const char* version) return false; } + unsigned int polMajor = minMajor; + unsigned int polMinor = minMinor; + unsigned int polPatch = minPatch; + + if (!version_max.empty()) { + // Parse components of the maximum version. + unsigned int maxMajor = 0; + unsigned int maxMinor = 0; + unsigned int maxPatch = 0; + unsigned int maxTweak = 0; + if (sscanf(version_max.c_str(), "%u.%u.%u.%u", &maxMajor, &maxMinor, + &maxPatch, &maxTweak) < 2) { + std::ostringstream e; + e << "Invalid policy max version value \"" << version_max << "\". " + << "A numeric major.minor[.patch[.tweak]] must be given."; + mf->IssueMessage(cmake::FATAL_ERROR, e.str()); + return false; + } + + // It is an error if the min version is greater than the max version. + if (minMajor > maxMajor || (minMajor == maxMajor && minMinor > maxMinor) || + (minMajor == maxMajor && minMinor == maxMinor && + minPatch > maxPatch) || + (minMajor == maxMajor && minMinor == maxMinor && + minPatch == maxPatch && minTweak > maxTweak)) { + std::ostringstream e; + e << "Policy VERSION range \"" << version_min << "..." << version_max + << "\"" + << " specifies a larger minimum than maximum."; + mf->IssueMessage(cmake::FATAL_ERROR, e.str()); + return false; + } + + // Use the max version as the policy version. + polMajor = maxMajor; + polMinor = maxMinor; + polPatch = maxPatch; + } + + return cmPolicies::ApplyPolicyVersion(mf, polMajor, polMinor, polPatch); +} + +bool cmPolicies::ApplyPolicyVersion(cmMakefile* mf, unsigned int majorVer, + unsigned int minorVer, + unsigned int patchVer) +{ // now loop over all the policies and set them as appropriate std::vector<cmPolicies::PolicyID> ancientPolicies; for (PolicyID pid = cmPolicies::CMP0000; pid != cmPolicies::CMPCOUNT; diff --git a/Source/cmPolicies.h b/Source/cmPolicies.h index c39f927..9b9ef60 100644 --- a/Source/cmPolicies.h +++ b/Source/cmPolicies.h @@ -214,7 +214,15 @@ class cmMakefile; 3, 10, 0, cmPolicies::WARN) \ SELECT(POLICY, CMP0072, \ "FindOpenGL prefers GLVND by default when available.", 3, 11, 0, \ - cmPolicies::WARN) + cmPolicies::WARN) \ + SELECT(POLICY, CMP0073, \ + "Do not produce legacy _LIB_DEPENDS cache entries.", 3, 12, 0, \ + cmPolicies::WARN) \ + SELECT(POLICY, CMP0074, "find_package uses PackageName_ROOT variables.", 3, \ + 12, 0, cmPolicies::WARN) \ + SELECT(POLICY, CMP0075, \ + "Include file check macros honor CMAKE_REQUIRED_LIBRARIES.", 3, 12, \ + 0, cmPolicies::WARN) #define CM_SELECT_ID(F, A1, A2, A3, A4, A5, A6) F(A1) #define CM_FOR_EACH_POLICY_ID(POLICY) \ @@ -238,7 +246,8 @@ class cmMakefile; F(CMP0063) \ F(CMP0065) \ F(CMP0068) \ - F(CMP0069) + F(CMP0069) \ + F(CMP0073) /** \class cmPolicies * \brief Handles changes in CMake behavior and policies @@ -284,7 +293,11 @@ public: static cmPolicies::PolicyStatus GetPolicyStatus(cmPolicies::PolicyID id); ///! Set a policy level for this listfile - static bool ApplyPolicyVersion(cmMakefile* mf, const char* version); + static bool ApplyPolicyVersion(cmMakefile* mf, + std::string const& version_min, + std::string const& version_max); + static bool ApplyPolicyVersion(cmMakefile* mf, unsigned int majorVer, + unsigned int minorVer, unsigned int patchVer); ///! return a warning string for a given policy static std::string GetPolicyWarning(cmPolicies::PolicyID id); diff --git a/Source/cmProjectCommand.cxx b/Source/cmProjectCommand.cxx index dfa1858..6ddb0b8 100644 --- a/Source/cmProjectCommand.cxx +++ b/Source/cmProjectCommand.cxx @@ -3,9 +3,11 @@ #include "cmProjectCommand.h" #include "cmsys/RegularExpression.hxx" +#include <functional> #include <sstream> #include <stdio.h> +#include "cmAlgorithms.h" #include "cmMakefile.h" #include "cmPolicies.h" #include "cmStateTypes.h" @@ -66,12 +68,19 @@ bool cmProjectCommand::InitialPass(std::vector<std::string> const& args, bool haveVersion = false; bool haveLanguages = false; bool haveDescription = false; + bool haveHomepage = false; std::string version; std::string description; + std::string homepage; std::vector<std::string> languages; + std::function<void()> missedValueReporter; + auto resetReporter = [&missedValueReporter]() { + missedValueReporter = std::function<void()>(); + }; enum Doing { DoingDescription, + DoingHomepage, DoingLanguages, DoingVersion }; @@ -85,7 +94,18 @@ bool cmProjectCommand::InitialPass(std::vector<std::string> const& args, return true; } haveLanguages = true; + if (missedValueReporter) { + missedValueReporter(); + } doing = DoingLanguages; + if (!languages.empty()) { + std::string msg = + "the following parameters must be specified after LANGUAGES " + "keyword: "; + msg += cmJoin(languages, ", "); + msg += '.'; + this->Makefile->IssueMessage(cmake::WARNING, msg); + } } else if (args[i] == "VERSION") { if (haveVersion) { this->Makefile->IssueMessage(cmake::FATAL_ERROR, @@ -94,7 +114,17 @@ bool cmProjectCommand::InitialPass(std::vector<std::string> const& args, return true; } haveVersion = true; + if (missedValueReporter) { + missedValueReporter(); + } doing = DoingVersion; + missedValueReporter = [this, &resetReporter]() { + this->Makefile->IssueMessage( + cmake::WARNING, + "VERSION keyword not followed by a value or was followed by a " + "value that expanded to nothing."); + resetReporter(); + }; } else if (args[i] == "DESCRIPTION") { if (haveDescription) { this->Makefile->IssueMessage( @@ -103,23 +133,61 @@ bool cmProjectCommand::InitialPass(std::vector<std::string> const& args, return true; } haveDescription = true; + if (missedValueReporter) { + missedValueReporter(); + } doing = DoingDescription; + missedValueReporter = [this, &resetReporter]() { + this->Makefile->IssueMessage( + cmake::WARNING, + "DESCRIPTION keyword not followed by a value or was followed " + "by a value that expanded to nothing."); + resetReporter(); + }; + } else if (args[i] == "HOMEPAGE_URL") { + if (haveHomepage) { + this->Makefile->IssueMessage( + cmake::FATAL_ERROR, "HOMEPAGE_URL may be specified at most once."); + cmSystemTools::SetFatalErrorOccured(); + return true; + } + haveHomepage = true; + doing = DoingHomepage; + missedValueReporter = [this, &resetReporter]() { + this->Makefile->IssueMessage( + cmake::WARNING, + "HOMEPAGE_URL keyword not followed by a value or was followed " + "by a value that expanded to nothing."); + resetReporter(); + }; } else if (doing == DoingVersion) { doing = DoingLanguages; version = args[i]; + resetReporter(); } else if (doing == DoingDescription) { doing = DoingLanguages; description = args[i]; + resetReporter(); + } else if (doing == DoingHomepage) { + doing = DoingLanguages; + homepage = args[i]; + resetReporter(); } else // doing == DoingLanguages { languages.push_back(args[i]); } } - if (haveVersion && !haveLanguages && !languages.empty()) { + if (missedValueReporter) { + missedValueReporter(); + } + + if ((haveVersion || haveDescription || haveHomepage) && !haveLanguages && + !languages.empty()) { this->Makefile->IssueMessage( cmake::FATAL_ERROR, - "project with VERSION must use LANGUAGES before language names."); + "project with VERSION, DESCRIPTION or HOMEPAGE_URL must " + "use LANGUAGES before language names."); cmSystemTools::SetFatalErrorOccured(); return true; } @@ -216,6 +284,8 @@ bool cmProjectCommand::InitialPass(std::vector<std::string> const& args, if (haveDescription) { this->Makefile->AddDefinition("PROJECT_DESCRIPTION", description.c_str()); + this->Makefile->AddDefinition(projectName + "_DESCRIPTION", + description.c_str()); // Set the CMAKE_PROJECT_DESCRIPTION variable to be the highest-level // project name in the tree. If there are two project commands // in the same CMakeLists.txt file, and it is the top level @@ -230,6 +300,24 @@ bool cmProjectCommand::InitialPass(std::vector<std::string> const& args, } } + if (haveHomepage) { + this->Makefile->AddDefinition("PROJECT_HOMEPAGE_URL", homepage.c_str()); + this->Makefile->AddDefinition(projectName + "_HOMEPAGE_URL", + homepage.c_str()); + // Set the CMAKE_PROJECT_HOMEPAGE_URL variable to be the highest-level + // project name in the tree. If there are two project commands + // in the same CMakeLists.txt file, and it is the top level + // CMakeLists.txt file, then go with the last one. + if (!this->Makefile->GetDefinition("CMAKE_PROJECT_HOMEPAGE_URL") || + (this->Makefile->IsRootMakefile())) { + this->Makefile->AddDefinition("CMAKE_PROJECT_HOMEPAGE_URL", + homepage.c_str()); + this->Makefile->AddCacheDefinition( + "CMAKE_PROJECT_HOMEPAGE_URL", homepage.c_str(), + "Value Computed by CMake", cmStateEnums::STATIC); + } + } + if (languages.empty()) { // if no language is specified do c and c++ languages.push_back("C"); diff --git a/Source/cmQtAutoGen.h b/Source/cmQtAutoGen.h index 67f61b1..a3e16ac 100644 --- a/Source/cmQtAutoGen.h +++ b/Source/cmQtAutoGen.h @@ -34,7 +34,7 @@ public: /// @brief Returns the generator name in upper case static std::string GeneratorNameUpper(GeneratorT genType); - /// @brief Returns a the string escaped and enclosed in quotes + /// @brief Returns the string escaped and enclosed in quotes static std::string Quoted(std::string const& text); static std::string QuotedCommand(std::vector<std::string> const& command); diff --git a/Source/cmQtAutoGenerator.cxx b/Source/cmQtAutoGenerator.cxx index 4aa1b1f..bf184d8 100644 --- a/Source/cmQtAutoGenerator.cxx +++ b/Source/cmQtAutoGenerator.cxx @@ -681,7 +681,7 @@ bool cmQtAutoGenerator::Run(std::string const& infoFile, auto makefile = cm::make_unique<cmMakefile>(&gg, snapshot); // The OLD/WARN behavior for policy CMP0053 caused a speed regression. // https://gitlab.kitware.com/cmake/cmake/issues/17570 - makefile->SetPolicyVersion("3.9"); + makefile->SetPolicyVersion("3.9", std::string()); gg.SetCurrentMakefile(makefile.get()); success = this->Init(makefile.get()); } diff --git a/Source/cmQtAutoGeneratorMocUic.cxx b/Source/cmQtAutoGeneratorMocUic.cxx index e2fd158..80db6ac 100644 --- a/Source/cmQtAutoGeneratorMocUic.cxx +++ b/Source/cmQtAutoGeneratorMocUic.cxx @@ -434,7 +434,7 @@ bool cmQtAutoGeneratorMocUic::JobParseT::ParseMocSource(WorkerT& wrk, JobHandleT jobHandle(new JobMocT(std::move(jobPre.SourceFile), FileName, std::move(jobPre.IncludeString))); if (jobPre.self) { - // Read depdendencies from this source + // Read dependencies from this source static_cast<JobMocT&>(*jobHandle).FindDependencies(wrk, meta.Content); } if (!wrk.Gen().ParallelJobPushMoc(jobHandle)) { @@ -452,7 +452,7 @@ bool cmQtAutoGeneratorMocUic::JobParseT::ParseMocHeader(WorkerT& wrk, if (!macroName.empty()) { JobHandleT jobHandle( new JobMocT(std::string(FileName), std::string(), std::string())); - // Read depdendencies from this source + // Read dependencies from this source static_cast<JobMocT&>(*jobHandle).FindDependencies(wrk, meta.Content); success = wrk.Gen().ParallelJobPushMoc(jobHandle); } @@ -1381,7 +1381,7 @@ bool cmQtAutoGeneratorMocUic::Init(cmMakefile* makefile) // Compare list sizes if (sources.size() != options.size()) { std::ostringstream ost; - ost << "files/options lists sizes missmatch (" << sources.size() << "/" + ost << "files/options lists sizes mismatch (" << sources.size() << "/" << options.size() << ")"; Log().ErrorFile(GeneratorT::UIC, InfoFile(), ost.str()); return false; @@ -1884,7 +1884,7 @@ bool cmQtAutoGeneratorMocUic::ParallelJobPushMoc(JobHandleT& jobHandle) error += Quoted(mocJob.IncluderFile); error += " and\n "; error += Quoted(otherJob.IncluderFile); - error += "\ncontain the the same moc include string "; + error += "\ncontain the same moc include string "; error += Quoted(mocJob.IncludeString); error += "\nbut the moc file would be generated from different " "source files\n "; @@ -1933,7 +1933,7 @@ bool cmQtAutoGeneratorMocUic::ParallelJobPushUic(JobHandleT& jobHandle) error += Quoted(uicJob.IncluderFile); error += " and\n "; error += Quoted(otherJob.IncluderFile); - error += "\ncontain the the same uic include string "; + error += "\ncontain the same uic include string "; error += Quoted(uicJob.IncludeString); error += "\nbut the uic file would be generated from different " "source files\n "; diff --git a/Source/cmRulePlaceholderExpander.h b/Source/cmRulePlaceholderExpander.h index 7b19210..a7d8cee 100644 --- a/Source/cmRulePlaceholderExpander.h +++ b/Source/cmRulePlaceholderExpander.h @@ -24,7 +24,7 @@ public: this->TargetImpLib = targetImpLib; } - // Create a struct to hold the varibles passed into + // Create a struct to hold the variables passed into // ExpandRuleVariables struct RuleVariables { diff --git a/Source/cmSearchPath.h b/Source/cmSearchPath.h index fd0c7c5..2a576ed 100644 --- a/Source/cmSearchPath.h +++ b/Source/cmSearchPath.h @@ -39,10 +39,10 @@ public: void AddCMakePrefixPath(const std::string& variable); void AddEnvPrefixPath(const std::string& variable, bool stripBin = false); void AddSuffixes(const std::vector<std::string>& suffixes); - -protected: void AddPrefixPaths(const std::vector<std::string>& paths, const char* base = nullptr); + +protected: void AddPathInternal(const std::string& path, const char* base = nullptr); cmFindCommon* FC; diff --git a/Source/cmState.cxx b/Source/cmState.cxx index bb891b5..a93fb11 100644 --- a/Source/cmState.cxx +++ b/Source/cmState.cxx @@ -13,6 +13,7 @@ #include "cmCommand.h" #include "cmDefinitions.h" #include "cmDisallowedCommand.h" +#include "cmGlobVerificationManager.h" #include "cmListFileCache.h" #include "cmStatePrivate.h" #include "cmStateSnapshot.h" @@ -31,11 +32,13 @@ cmState::cmState() , MSYSShell(false) { this->CacheManager = new cmCacheManager; + this->GlobVerificationManager = new cmGlobVerificationManager; } cmState::~cmState() { delete this->CacheManager; + delete this->GlobVerificationManager; cmDeleteAll(this->BuiltinCommands); cmDeleteAll(this->ScriptedCommands); } @@ -207,6 +210,39 @@ void cmState::AddCacheEntry(const std::string& key, const char* value, this->CacheManager->AddCacheEntry(key, value, helpString, type); } +bool cmState::DoWriteGlobVerifyTarget() const +{ + return this->GlobVerificationManager->DoWriteVerifyTarget(); +} + +std::string const& cmState::GetGlobVerifyScript() const +{ + return this->GlobVerificationManager->GetVerifyScript(); +} + +std::string const& cmState::GetGlobVerifyStamp() const +{ + return this->GlobVerificationManager->GetVerifyStamp(); +} + +bool cmState::SaveVerificationScript(const std::string& path) +{ + return this->GlobVerificationManager->SaveVerificationScript(path); +} + +void cmState::AddGlobCacheEntry(bool recurse, bool listDirectories, + bool followSymlinks, + const std::string& relative, + const std::string& expression, + const std::vector<std::string>& files, + const std::string& variable, + cmListFileBacktrace const& backtrace) +{ + this->GlobVerificationManager->AddCacheEntry( + recurse, listDirectories, followSymlinks, relative, expression, files, + variable, backtrace); +} + void cmState::RemoveCacheEntry(std::string const& key) { this->CacheManager->RemoveCacheEntry(key); diff --git a/Source/cmState.h b/Source/cmState.h index 6cbf82d..4c6fc69 100644 --- a/Source/cmState.h +++ b/Source/cmState.h @@ -12,6 +12,7 @@ #include "cmDefinitions.h" #include "cmLinkedTree.h" +#include "cmListFileCache.h" #include "cmPolicies.h" #include "cmProperty.h" #include "cmPropertyDefinitionMap.h" @@ -21,6 +22,7 @@ class cmCacheManager; class cmCommand; +class cmGlobVerificationManager; class cmPropertyDefinition; class cmStateSnapshot; class cmMessenger; @@ -165,12 +167,24 @@ private: const char* helpString, cmStateEnums::CacheEntryType type); + bool DoWriteGlobVerifyTarget() const; + std::string const& GetGlobVerifyScript() const; + std::string const& GetGlobVerifyStamp() const; + bool SaveVerificationScript(const std::string& path); + void AddGlobCacheEntry(bool recurse, bool listDirectories, + bool followSymlinks, const std::string& relative, + const std::string& expression, + const std::vector<std::string>& files, + const std::string& variable, + cmListFileBacktrace const& bt); + std::map<cmProperty::ScopeType, cmPropertyDefinitionMap> PropertyDefinitions; std::vector<std::string> EnabledLanguages; std::map<std::string, cmCommand*> BuiltinCommands; std::map<std::string, cmCommand*> ScriptedCommands; cmPropertyMap GlobalProperties; cmCacheManager* CacheManager; + cmGlobVerificationManager* GlobVerificationManager; cmLinkedTree<cmStateDetail::BuildsystemDirectoryStateType> BuildsystemDirectory; diff --git a/Source/cmStateSnapshot.cxx b/Source/cmStateSnapshot.cxx index 479ecd2..0229a77 100644 --- a/Source/cmStateSnapshot.cxx +++ b/Source/cmStateSnapshot.cxx @@ -6,7 +6,7 @@ #include <algorithm> #include <assert.h> #include <iterator> -#include <stdio.h> +#include <string> #include "cmAlgorithms.h" #include "cmDefinitions.h" @@ -160,8 +160,8 @@ void cmStateSnapshot::SetPolicy(cmPolicies::PolicyID id, } } -cmPolicies::PolicyStatus cmStateSnapshot::GetPolicy( - cmPolicies::PolicyID id) const +cmPolicies::PolicyStatus cmStateSnapshot::GetPolicy(cmPolicies::PolicyID id, + bool parent_scope) const { cmPolicies::PolicyStatus status = cmPolicies::GetPolicyStatus(id); @@ -180,6 +180,10 @@ cmPolicies::PolicyStatus cmStateSnapshot::GetPolicy( cmLinkedTree<cmStateDetail::PolicyStackEntry>::iterator root = dir->DirectoryEnd->PolicyRoot; for (; leaf != root; ++leaf) { + if (parent_scope) { + parent_scope = false; + continue; + } if (leaf->IsDefined(id)) { status = leaf->Get(id); return status; @@ -328,15 +332,14 @@ void cmStateSnapshot::SetDefaultDefinitions() this->SetDefinition("CMAKE_HOST_SOLARIS", "1"); #endif - char temp[1024]; - sprintf(temp, "%d", cmVersion::GetMinorVersion()); - this->SetDefinition("CMAKE_MINOR_VERSION", temp); - sprintf(temp, "%d", cmVersion::GetMajorVersion()); - this->SetDefinition("CMAKE_MAJOR_VERSION", temp); - sprintf(temp, "%d", cmVersion::GetPatchVersion()); - this->SetDefinition("CMAKE_PATCH_VERSION", temp); - sprintf(temp, "%d", cmVersion::GetTweakVersion()); - this->SetDefinition("CMAKE_TWEAK_VERSION", temp); + this->SetDefinition("CMAKE_MAJOR_VERSION", + std::to_string(cmVersion::GetMajorVersion())); + this->SetDefinition("CMAKE_MINOR_VERSION", + std::to_string(cmVersion::GetMinorVersion())); + this->SetDefinition("CMAKE_PATCH_VERSION", + std::to_string(cmVersion::GetPatchVersion())); + this->SetDefinition("CMAKE_TWEAK_VERSION", + std::to_string(cmVersion::GetTweakVersion())); this->SetDefinition("CMAKE_VERSION", cmVersion::GetCMakeVersion()); this->SetDefinition("CMAKE_FILES_DIRECTORY", diff --git a/Source/cmStateSnapshot.h b/Source/cmStateSnapshot.h index 94d6274..af5653b 100644 --- a/Source/cmStateSnapshot.h +++ b/Source/cmStateSnapshot.h @@ -43,7 +43,8 @@ public: cmStateEnums::SnapshotType GetType() const; void SetPolicy(cmPolicies::PolicyID id, cmPolicies::PolicyStatus status); - cmPolicies::PolicyStatus GetPolicy(cmPolicies::PolicyID id) const; + cmPolicies::PolicyStatus GetPolicy(cmPolicies::PolicyID id, + bool parent_scope = false) const; bool HasDefinedPolicyCMP0011(); void PushPolicy(cmPolicies::PolicyMap const& entry, bool weak); bool PopPolicy(); diff --git a/Source/cmStringCommand.cxx b/Source/cmStringCommand.cxx index 55af078..dabec47 100644 --- a/Source/cmStringCommand.cxx +++ b/Source/cmStringCommand.cxx @@ -13,6 +13,7 @@ #include "cmCryptoHash.h" #include "cmGeneratorExpression.h" #include "cmMakefile.h" +#include "cmStringReplaceHelper.h" #include "cmSystemTools.h" #include "cmTimestamp.h" #include "cmUuid.h" @@ -68,6 +69,9 @@ bool cmStringCommand::InitialPass(std::vector<std::string> const& args, if (subCommand == "CONCAT") { return this->HandleConcatCommand(args); } + if (subCommand == "JOIN") { + return this->HandleJoinCommand(args); + } if (subCommand == "SUBSTRING") { return this->HandleSubstringCommand(args); } @@ -341,46 +345,17 @@ bool cmStringCommand::RegexReplace(std::vector<std::string> const& args) std::string const& regex = args[2]; std::string const& replace = args[3]; std::string const& outvar = args[4]; + cmStringReplaceHelper replaceHelper(regex, replace, this->Makefile); - // Pull apart the replace expression to find the escaped [0-9] values. - std::vector<RegexReplacement> replacement; - std::string::size_type l = 0; - while (l < replace.length()) { - std::string::size_type r = replace.find('\\', l); - if (r == std::string::npos) { - r = replace.length(); - replacement.push_back(replace.substr(l, r - l)); - } else { - if (r - l > 0) { - replacement.push_back(replace.substr(l, r - l)); - } - if (r == (replace.length() - 1)) { - this->SetError("sub-command REGEX, mode REPLACE: " - "replace-expression ends in a backslash."); - return false; - } - if ((replace[r + 1] >= '0') && (replace[r + 1] <= '9')) { - replacement.push_back(replace[r + 1] - '0'); - } else if (replace[r + 1] == 'n') { - replacement.push_back("\n"); - } else if (replace[r + 1] == '\\') { - replacement.push_back("\\"); - } else { - std::string e = "sub-command REGEX, mode REPLACE: Unknown escape \""; - e += replace.substr(r, 2); - e += "\" in replace-expression."; - this->SetError(e); - return false; - } - r += 2; - } - l = r; + if (!replaceHelper.IsReplaceExpressionValid()) { + this->SetError("sub-command REGEX, mode REPLACE: " + + replaceHelper.GetError() + "."); + return false; } this->Makefile->ClearMatches(); - // Compile the regular expression. - cmsys::RegularExpression re; - if (!re.compile(regex.c_str())) { + + if (!replaceHelper.IsRegularExpressionValid()) { std::string e = "sub-command REGEX, mode REPLACE failed to compile regex \"" + regex + "\"."; @@ -389,60 +364,16 @@ bool cmStringCommand::RegexReplace(std::vector<std::string> const& args) } // Concatenate all the last arguments together. - std::string input = cmJoin(cmMakeRange(args).advance(5), std::string()); - - // Scan through the input for all matches. + const std::string input = + cmJoin(cmMakeRange(args).advance(5), std::string()); std::string output; - std::string::size_type base = 0; - while (re.find(input.c_str() + base)) { - this->Makefile->ClearMatches(); - this->Makefile->StoreMatches(re); - std::string::size_type l2 = re.start(); - std::string::size_type r = re.end(); - - // Concatenate the part of the input that was not matched. - output += input.substr(base, l2); - - // Make sure the match had some text. - if (r - l2 == 0) { - std::string e = "sub-command REGEX, mode REPLACE regex \"" + regex + - "\" matched an empty string."; - this->SetError(e); - return false; - } - - // Concatenate the replacement for the match. - for (RegexReplacement const& i : replacement) { - if (i.number < 0) { - // This is just a plain-text part of the replacement. - output += i.value; - } else { - // Replace with part of the match. - int n = i.number; - std::string::size_type start = re.start(n); - std::string::size_type end = re.end(n); - std::string::size_type len = input.length() - base; - if ((start != std::string::npos) && (end != std::string::npos) && - (start <= len) && (end <= len)) { - output += input.substr(base + start, end - start); - } else { - std::string e = - "sub-command REGEX, mode REPLACE: replace expression \"" + - replace + "\" contains an out-of-range escape for regex \"" + - regex + "\"."; - this->SetError(e); - return false; - } - } - } - // Move past the match. - base += r; + if (!replaceHelper.Replace(input, output)) { + this->SetError("sub-command REGEX, mode REPLACE: " + + replaceHelper.GetError() + "."); + return false; } - // Concatenate the text after the last match. - output += input.substr(base, input.length() - base); - // Store the output in the provided variable. this->Makefile->AddDefinition(outvar, output.c_str()); return true; @@ -677,8 +608,26 @@ bool cmStringCommand::HandleConcatCommand(std::vector<std::string> const& args) return false; } - std::string const& variableName = args[1]; - std::string value = cmJoin(cmMakeRange(args).advance(2), std::string()); + return this->joinImpl(args, std::string(), 1); +} + +bool cmStringCommand::HandleJoinCommand(std::vector<std::string> const& args) +{ + if (args.size() < 3) { + this->SetError("sub-command JOIN requires at least two arguments."); + return false; + } + + return this->joinImpl(args, args[1], 2); +} + +bool cmStringCommand::joinImpl(std::vector<std::string> const& args, + std::string const& glue, const size_t varIdx) +{ + std::string const& variableName = args[varIdx]; + // NOTE Items to concat/join placed right after the variable for + // both `CONCAT` and `JOIN` sub-commands. + std::string value = cmJoin(cmMakeRange(args).advance(varIdx + 1), glue); this->Makefile->AddDefinition(variableName, value.c_str()); return true; diff --git a/Source/cmStringCommand.h b/Source/cmStringCommand.h index b287e37..cbff73e 100644 --- a/Source/cmStringCommand.h +++ b/Source/cmStringCommand.h @@ -5,6 +5,7 @@ #include "cmConfigure.h" // IWYU pragma: keep +#include <cstddef> #include <string> #include <vector> @@ -48,6 +49,7 @@ protected: bool HandleAppendCommand(std::vector<std::string> const& args); bool HandlePrependCommand(std::vector<std::string> const& args); bool HandleConcatCommand(std::vector<std::string> const& args); + bool HandleJoinCommand(std::vector<std::string> const& args); bool HandleStripCommand(std::vector<std::string> const& args); bool HandleRandomCommand(std::vector<std::string> const& args); bool HandleFindCommand(std::vector<std::string> const& args); @@ -56,28 +58,8 @@ protected: bool HandleGenexStripCommand(std::vector<std::string> const& args); bool HandleUuidCommand(std::vector<std::string> const& args); - class RegexReplacement - { - public: - RegexReplacement(const char* s) - : number(-1) - , value(s) - { - } - RegexReplacement(const std::string& s) - : number(-1) - , value(s) - { - } - RegexReplacement(int n) - : number(n) - , value() - { - } - RegexReplacement() {} - int number; - std::string value; - }; + bool joinImpl(std::vector<std::string> const& args, std::string const& glue, + size_t varIdx); }; #endif diff --git a/Source/cmStringReplaceHelper.cxx b/Source/cmStringReplaceHelper.cxx new file mode 100644 index 0000000..69b7ced --- /dev/null +++ b/Source/cmStringReplaceHelper.cxx @@ -0,0 +1,117 @@ +/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying + file Copyright.txt or https://cmake.org/licensing for details. */ + +#include "cmStringReplaceHelper.h" + +#include "cmMakefile.h" +#include <sstream> + +cmStringReplaceHelper::cmStringReplaceHelper(const std::string& regex, + const std::string& replace_expr, + cmMakefile* makefile) + : RegExString(regex) + , RegularExpression(regex) + , ReplaceExpression(replace_expr) + , Makefile(makefile) +{ + this->ParseReplaceExpression(); +} + +bool cmStringReplaceHelper::Replace(const std::string& input, + std::string& output) +{ + output.clear(); + + // Scan through the input for all matches. + std::string::size_type base = 0; + while (this->RegularExpression.find(input.c_str() + base)) { + if (this->Makefile != nullptr) { + this->Makefile->ClearMatches(); + this->Makefile->StoreMatches(this->RegularExpression); + } + auto l2 = this->RegularExpression.start(); + auto r = this->RegularExpression.end(); + + // Concatenate the part of the input that was not matched. + output += input.substr(base, l2); + + // Make sure the match had some text. + if (r - l2 == 0) { + std::ostringstream error; + error << "regex \"" << this->RegExString << "\" matched an empty string"; + this->ErrorString = error.str(); + return false; + } + + // Concatenate the replacement for the match. + for (const auto& replacement : this->Replacements) { + if (replacement.Number < 0) { + // This is just a plain-text part of the replacement. + output += replacement.Value; + } else { + // Replace with part of the match. + auto n = replacement.Number; + auto start = this->RegularExpression.start(n); + auto end = this->RegularExpression.end(n); + auto len = input.length() - base; + if ((start != std::string::npos) && (end != std::string::npos) && + (start <= len) && (end <= len)) { + output += input.substr(base + start, end - start); + } else { + std::ostringstream error; + error << "replace expression \"" << this->ReplaceExpression + << "\" contains an out-of-range escape for regex \"" + << this->RegExString << "\""; + this->ErrorString = error.str(); + return false; + } + } + } + + // Move past the match. + base += r; + } + + // Concatenate the text after the last match. + output += input.substr(base, input.length() - base); + + return true; +} + +void cmStringReplaceHelper::ParseReplaceExpression() +{ + std::string::size_type l = 0; + while (l < this->ReplaceExpression.length()) { + auto r = this->ReplaceExpression.find('\\', l); + if (r == std::string::npos) { + r = this->ReplaceExpression.length(); + this->Replacements.push_back(this->ReplaceExpression.substr(l, r - l)); + } else { + if (r - l > 0) { + this->Replacements.push_back(this->ReplaceExpression.substr(l, r - l)); + } + if (r == (this->ReplaceExpression.length() - 1)) { + this->ValidReplaceExpression = false; + this->ErrorString = "replace-expression ends in a backslash"; + return; + } + if ((this->ReplaceExpression[r + 1] >= '0') && + (this->ReplaceExpression[r + 1] <= '9')) { + this->Replacements.push_back(this->ReplaceExpression[r + 1] - '0'); + } else if (this->ReplaceExpression[r + 1] == 'n') { + this->Replacements.push_back("\n"); + } else if (this->ReplaceExpression[r + 1] == '\\') { + this->Replacements.push_back("\\"); + } else { + this->ValidReplaceExpression = false; + std::ostringstream error; + error << "Unknown escape \"" << this->ReplaceExpression.substr(r, 2) + << "\" in replace-expression"; + this->ErrorString = error.str(); + return; + } + r += 2; + } + l = r; + } +} diff --git a/Source/cmStringReplaceHelper.h b/Source/cmStringReplaceHelper.h new file mode 100644 index 0000000..938325a --- /dev/null +++ b/Source/cmStringReplaceHelper.h @@ -0,0 +1,69 @@ +/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying + file Copyright.txt or https://cmake.org/licensing for details. */ +#ifndef cmStringReplaceHelper_h +#define cmStringReplaceHelper_h + +#include "cmsys/RegularExpression.hxx" + +#include <string> +#include <vector> + +class cmMakefile; + +class cmStringReplaceHelper +{ +public: + cmStringReplaceHelper(const std::string& regex, + const std::string& replace_expr, + cmMakefile* makefile = nullptr); + + bool IsRegularExpressionValid() const + { + return this->RegularExpression.is_valid(); + } + bool IsReplaceExpressionValid() const + { + return this->ValidReplaceExpression; + } + + bool Replace(const std::string& input, std::string& output); + + const std::string& GetError() { return this->ErrorString; } + +private: + class RegexReplacement + { + public: + RegexReplacement(const char* s) + : Number(-1) + , Value(s) + { + } + RegexReplacement(const std::string& s) + : Number(-1) + , Value(s) + { + } + RegexReplacement(int n) + : Number(n) + , Value() + { + } + RegexReplacement() {} + + int Number; + std::string Value; + }; + + void ParseReplaceExpression(); + + std::string ErrorString; + std::string RegExString; + cmsys::RegularExpression RegularExpression; + bool ValidReplaceExpression = true; + std::string ReplaceExpression; + std::vector<RegexReplacement> Replacements; + cmMakefile* Makefile = nullptr; +}; + +#endif diff --git a/Source/cmSystemTools.cxx b/Source/cmSystemTools.cxx index eeb73c3..94c5ee8 100644 --- a/Source/cmSystemTools.cxx +++ b/Source/cmSystemTools.cxx @@ -1509,7 +1509,7 @@ cmSystemTools::SaveRestoreEnvironment::~SaveRestoreEnvironment() void cmSystemTools::EnableVSConsoleOutput() { #ifdef _WIN32 - // Visual Studio 8 2005 (devenv.exe or VCExpress.exe) will not + // Visual Studio tools like devenv may not // display output to the console unless this environment variable is // set. We need it to capture the output of these build tools. // Note for future work that one could pass "/out \\.\pipe\NAME" to diff --git a/Source/cmTarget.cxx b/Source/cmTarget.cxx index cd11c4b..d17a85a 100644 --- a/Source/cmTarget.cxx +++ b/Source/cmTarget.cxx @@ -114,15 +114,12 @@ const char* cmTargetPropertyComputer::GetSources<cmTarget>( } if (!noMessage) { e << "Target \"" << tgt->GetName() - << "\" contains " - "$<TARGET_OBJECTS> generator expression in its sources " - "list. " - "This content was not previously part of the SOURCES " - "property " - "when that property was read at configure time. Code " - "reading " - "that property needs to be adapted to ignore the generator " - "expression using the string(GENEX_STRIP) command."; + << "\" contains $<TARGET_OBJECTS> generator expression in its " + "sources list. This content was not previously part of the " + "SOURCES property when that property was read at configure " + "time. Code reading that property needs to be adapted to " + "ignore the generator expression using the string(GENEX_STRIP) " + "command."; messenger->IssueMessage(messageType, e.str(), context); } if (addContent) { @@ -189,18 +186,10 @@ cmTarget::cmTarget(std::string const& name, cmStateEnums::TargetType type, this->ImportedGloballyVisible = vis == VisibilityImportedGlobally; this->BuildInterfaceIncludesAppended = false; - // only add dependency information for library targets - if (this->TargetTypeValue >= cmStateEnums::STATIC_LIBRARY && - this->TargetTypeValue <= cmStateEnums::MODULE_LIBRARY) { - this->RecordDependencies = true; - } else { - this->RecordDependencies = false; - } - // Check whether this is a DLL platform. this->DLLPlatform = - (this->Makefile->IsOn("WIN32") || this->Makefile->IsOn("CYGWIN") || - this->Makefile->IsOn("MINGW")); + strcmp(this->Makefile->GetSafeDefinition("CMAKE_IMPORT_LIBRARY_SUFFIX"), + "") != 0; // Check whether we are targeting an Android platform. this->IsAndroid = @@ -286,6 +275,7 @@ cmTarget::cmTarget(std::string const& name, cmStateEnums::TargetType type, this->SetPropertyDefault("CUDA_SEPARABLE_COMPILATION", nullptr); this->SetPropertyDefault("LINK_SEARCH_START_STATIC", nullptr); this->SetPropertyDefault("LINK_SEARCH_END_STATIC", nullptr); + this->SetPropertyDefault("FOLDER", nullptr); } // Collect the set of configuration types. @@ -509,7 +499,7 @@ std::string cmTarget::ProcessSourceItemCMP0049(const std::string& s) { std::string src = s; - // For backwards compatibility replace varibles in source names. + // For backwards compatibility replace variables in source names. // This should eventually be removed. this->Makefile->ExpandVariablesInString(src); if (src != s) { @@ -638,27 +628,11 @@ const std::vector<std::string>& cmTarget::GetLinkDirectories() const return this->LinkDirectories; } -void cmTarget::ClearDependencyInformation(cmMakefile& mf, - const std::string& target) +void cmTarget::ClearDependencyInformation(cmMakefile& mf) { - // Clear the dependencies. The cache variable must exist iff we are - // recording dependency information for this target. - std::string depname = target; + std::string depname = this->GetName(); depname += "_LIB_DEPENDS"; - if (this->RecordDependencies) { - mf.AddCacheDefinition(depname, "", "Dependencies for target", - cmStateEnums::STATIC); - } else { - if (mf.GetDefinition(depname)) { - std::string message = "Target "; - message += target; - message += " has dependency information when it shouldn't.\n"; - message += "Your cache is probably stale. Please remove the entry\n "; - message += depname; - message += "\nfrom the cache."; - cmSystemTools::Error(message.c_str()); - } - } + mf.RemoveCacheDefinition(depname); } std::string cmTarget::GetDebugGeneratorExpressions( @@ -742,19 +716,15 @@ void cmTarget::AddLinkLibrary(cmMakefile& mf, const std::string& lib, } if (cmGeneratorExpression::Find(lib) != std::string::npos || - (tgt && tgt->GetType() == cmStateEnums::INTERFACE_LIBRARY) || + (tgt && (tgt->GetType() == cmStateEnums::INTERFACE_LIBRARY || + tgt->GetType() == cmStateEnums::OBJECT_LIBRARY)) || (this->Name == lib)) { return; } - { - cmTarget::LibraryID tmp; - tmp.first = lib; - tmp.second = llt; - this->OriginalLinkLibraries.emplace_back(lib, llt); - } + this->OriginalLinkLibraries.emplace_back(lib, llt); - // Add the explicit dependency information for this target. This is + // Add the explicit dependency information for libraries. This is // simply a set of libraries separated by ";". There should always // be a trailing ";". These library names are not canonical, in that // they may be "-framework x", "-ly", "/path/libz.a", etc. @@ -762,7 +732,10 @@ void cmTarget::AddLinkLibrary(cmMakefile& mf, const std::string& lib, // may be purposefully duplicated to handle recursive dependencies, // and we removing one instance will break the link line. Duplicates // will be appropriately eliminated at emit time. - if (this->RecordDependencies) { + if (this->TargetTypeValue >= cmStateEnums::STATIC_LIBRARY && + this->TargetTypeValue <= cmStateEnums::MODULE_LIBRARY && + (this->GetPolicyStatusCMP0073() == cmPolicies::OLD || + this->GetPolicyStatusCMP0073() == cmPolicies::WARN)) { std::string targetEntry = this->Name; targetEntry += "_LIB_DEPENDS"; std::string dependencies; diff --git a/Source/cmTarget.h b/Source/cmTarget.h index 56f3e3a..62c4e22 100644 --- a/Source/cmTarget.h +++ b/Source/cmTarget.h @@ -137,7 +137,7 @@ public: /** * Clear the dependency information recorded for this target, if any. */ - void ClearDependencyInformation(cmMakefile& mf, const std::string& target); + void ClearDependencyInformation(cmMakefile& mf); void AddLinkLibrary(cmMakefile& mf, const std::string& lib, cmTargetLinkLibraryType llt); @@ -310,7 +310,6 @@ private: cmTargetInternalPointer Internal; cmStateEnums::TargetType TargetTypeValue; bool HaveInstallRule; - bool RecordDependencies; bool DLLPlatform; bool IsAndroid; bool IsImportedTarget; diff --git a/Source/cmTargetLinkLibrariesCommand.cxx b/Source/cmTargetLinkLibrariesCommand.cxx index 9e4575a..699fff8 100644 --- a/Source/cmTargetLinkLibrariesCommand.cxx +++ b/Source/cmTargetLinkLibrariesCommand.cxx @@ -94,16 +94,6 @@ bool cmTargetLinkLibrariesCommand::InitialPass( return true; } - // OBJECT libraries are not allowed on the LHS of the command. - if (this->Target->GetType() == cmStateEnums::OBJECT_LIBRARY) { - std::ostringstream e; - e << "Object library target \"" << args[0] << "\" " - << "may not link to anything."; - this->Makefile->IssueMessage(cmake::FATAL_ERROR, e.str()); - cmSystemTools::SetFatalErrorOccured(); - return true; - } - // Having a UTILITY library on the LHS is a bug. if (this->Target->GetType() == cmStateEnums::UTILITY) { std::ostringstream e; @@ -401,14 +391,15 @@ bool cmTargetLinkLibrariesCommand::HandleLibrary(const std::string& lib, if (tgt && (tgt->GetType() != cmStateEnums::STATIC_LIBRARY) && (tgt->GetType() != cmStateEnums::SHARED_LIBRARY) && (tgt->GetType() != cmStateEnums::UNKNOWN_LIBRARY) && + (tgt->GetType() != cmStateEnums::OBJECT_LIBRARY) && (tgt->GetType() != cmStateEnums::INTERFACE_LIBRARY) && !tgt->IsExecutableWithExports()) { std::ostringstream e; e << "Target \"" << lib << "\" of type " << cmState::GetTargetTypeName(tgt->GetType()) << " may not be linked into another target. One may link only to " - "INTERFACE, STATIC or SHARED libraries, or to executables with the " - "ENABLE_EXPORTS property set."; + "INTERFACE, OBJECT, STATIC or SHARED libraries, or to executables " + "with the ENABLE_EXPORTS property set."; this->Makefile->IssueMessage(cmake::FATAL_ERROR, e.str()); } diff --git a/Source/cmTargetLinkLibrariesCommand.h b/Source/cmTargetLinkLibrariesCommand.h index a2f3ecd..54f8cf4 100644 --- a/Source/cmTargetLinkLibrariesCommand.h +++ b/Source/cmTargetLinkLibrariesCommand.h @@ -43,7 +43,7 @@ private: void LinkLibraryTypeSpecifierWarning(int left, int right); static const char* LinkLibraryTypeNames[3]; - cmTarget* Target; + cmTarget* Target = nullptr; enum ProcessingState { ProcessingLinkLibraries, @@ -55,7 +55,7 @@ private: ProcessingKeywordPrivateInterface }; - ProcessingState CurrentProcessingState; + ProcessingState CurrentProcessingState = ProcessingLinkLibraries; bool HandleLibrary(const std::string& lib, cmTargetLinkLibraryType llt); }; diff --git a/Source/cmTargetPropCommandBase.h b/Source/cmTargetPropCommandBase.h index 3c736fc..943285d 100644 --- a/Source/cmTargetPropCommandBase.h +++ b/Source/cmTargetPropCommandBase.h @@ -28,7 +28,7 @@ public: protected: std::string Property; - cmTarget* Target; + cmTarget* Target = nullptr; virtual void HandleInterfaceContent(cmTarget* tgt, const std::vector<std::string>& content, diff --git a/Source/cmVisualStudio10TargetGenerator.cxx b/Source/cmVisualStudio10TargetGenerator.cxx index 8a9df8f..71fe300 100644 --- a/Source/cmVisualStudio10TargetGenerator.cxx +++ b/Source/cmVisualStudio10TargetGenerator.cxx @@ -8,7 +8,7 @@ #include "cmGeneratedFileStream.h" #include "cmGeneratorTarget.h" #include "cmGlobalVisualStudio10Generator.h" -#include "cmLocalVisualStudio7Generator.h" +#include "cmLocalVisualStudio10Generator.h" #include "cmMakefile.h" #include "cmSourceFile.h" #include "cmSystemTools.h" @@ -28,12 +28,146 @@ static std::string cmVS10EscapeXML(std::string arg) return arg; } -static std::string cmVS10EscapeQuotes(std::string arg) +static std::string cmVS10EscapeAttr(std::string arg) { + cmSystemTools::ReplaceString(arg, "&", "&"); + cmSystemTools::ReplaceString(arg, "<", "<"); + cmSystemTools::ReplaceString(arg, ">", ">"); cmSystemTools::ReplaceString(arg, "\"", """); return arg; } +struct cmVisualStudio10TargetGenerator::Elem +{ + std::ostream& S; + int Indent; + bool HasElements = false; + const char* Tag = nullptr; + + Elem(std::ostream& s, int i) + : S(s) + , Indent(i) + { + } + Elem(const Elem&) = delete; + Elem(Elem& par) + : S(par.S) + , Indent(par.Indent + 1) + { + par.SetHasElements(); + } + Elem(Elem& par, const char* tag) + : S(par.S) + , Indent(par.Indent + 1) + { + par.SetHasElements(); + this->StartElement(tag); + } + void SetHasElements() + { + if (!HasElements) { + this->S << ">\n"; + HasElements = true; + } + } + std::ostream& WriteString(const char* line); + Elem& StartElement(const char* tag) + { + this->Tag = tag; + this->WriteString("<") << tag; + return *this; + } + template <typename T> + void WriteElem(const char* tag, const T& val) + { + this->WriteString("<") << tag << ">" << val << "</" << tag << ">\n"; + } + void Element(const char* tag, const std::string& val) + { + Elem(*this).WriteElem(tag, cmVS10EscapeXML(val)); + } + template <typename T> + void Attr(const char* an, const T& av) + { + this->S << " " << an << "=\"" << av << "\""; + } + Elem& Attribute(const char* an, const std::string& av) + { + Attr(an, cmVS10EscapeAttr(av)); + return *this; + } + // This method for now assumes that this->Tag has been set, e.g. by calling + // StartElement(). Also, it finishes the element so it should be the last + // one called + void Content(const std::string& val) + { + S << ">" << cmVS10EscapeXML(val) << "</" << this->Tag << ">\n"; + } + void WriteEndTag(const char* tag) + { + if (HasElements) { + this->WriteString("</") << tag << ">\n"; + } else { + this->S << " />\n"; + } + } + void EndElement() { this->WriteEndTag(this->Tag); } +}; + +class cmVS10GeneratorOptions : public cmVisualStudioGeneratorOptions +{ +public: + cmVS10GeneratorOptions(cmLocalVisualStudioGenerator* lg, Tool tool, + cmVS7FlagTable const* table, + cmVisualStudio10TargetGenerator* g = nullptr) + : cmVisualStudioGeneratorOptions(lg, tool, table) + , TargetGenerator(g) + { + } + + void OutputFlag(std::ostream& fout, int indent, const char* tag, + const std::string& content) override + { + if (!this->GetConfiguration().empty()) { + // if there are configuration specific flags, then + // use the configuration specific tag for PreprocessorDefinitions + this->TargetGenerator->WritePlatformConfigTag( + tag, this->GetConfiguration(), indent); + } else { + fout.fill(' '); + fout.width(indent * 2); + // write an empty string to get the fill level indent to print + fout << ""; + fout << "<" << tag << ">"; + } + fout << cmVS10EscapeXML(content); + fout << "</" << tag << ">\n"; + } + +private: + cmVisualStudio10TargetGenerator* TargetGenerator; +}; + +inline void cmVisualStudio10TargetGenerator::WriteElem(const char* tag, + const char* val, + int indentLevel) +{ + Elem(*this->BuildFileStream, indentLevel).WriteElem(tag, val); +} + +inline void cmVisualStudio10TargetGenerator::WriteElem(const char* tag, + std::string const& val, + int indentLevel) +{ + Elem(*this->BuildFileStream, indentLevel).WriteElem(tag, val); +} + +inline void cmVisualStudio10TargetGenerator::WriteElemEscapeXML( + const char* tag, std::string const& val, int indentLevel) +{ + this->WriteElem(tag, cmVS10EscapeXML(val), indentLevel); +} + static std::string cmVS10EscapeComment(std::string comment) { // MSBuild takes the CDATA of a <Message></Message> element and just @@ -84,16 +218,16 @@ static std::string computeProjectFileExtension(cmGeneratorTarget const* t, cmVisualStudio10TargetGenerator::cmVisualStudio10TargetGenerator( cmGeneratorTarget* target, cmGlobalVisualStudio10Generator* gg) + : GeneratorTarget(target) + , Makefile(target->Target->GetMakefile()) + , Platform(gg->GetPlatformName()) + , Name(target->GetName()) + , GUID(gg->GetGUID(this->Name)) + , GlobalGenerator(gg) + , LocalGenerator( + (cmLocalVisualStudio10Generator*)target->GetLocalGenerator()) { - this->GlobalGenerator = gg; - this->GeneratorTarget = target; - this->Makefile = target->Target->GetMakefile(); this->Makefile->GetConfigurations(this->Configurations); - this->LocalGenerator = - (cmLocalVisualStudio7Generator*)this->GeneratorTarget->GetLocalGenerator(); - this->Name = this->GeneratorTarget->GetName(); - this->GUID = this->GlobalGenerator->GetGUID(this->Name); - this->Platform = gg->GetPlatformName(); this->NsightTegra = gg->IsNsightTegra(); for (int i = 0; i < 4; ++i) { this->NsightTegraVersion[i] = 0; @@ -125,47 +259,60 @@ cmVisualStudio10TargetGenerator::~cmVisualStudio10TargetGenerator() delete this->BuildFileStream; } -void cmVisualStudio10TargetGenerator::WritePlatformConfigTag( - const char* tag, const std::string& config, int indentLevel, - const char* attribute, const char* end, std::ostream* stream) - +std::string cmVisualStudio10TargetGenerator::CalcCondition( + const std::string& config) const { - if (!stream) { - stream = this->BuildFileStream; - } - stream->fill(' '); - stream->width(indentLevel * 2); - (*stream) << ""; // applies indentation - (*stream) << "<" << tag << " Condition=\""; - (*stream) << "'$(Configuration)|$(Platform)'=='"; - (*stream) << config << "|" << this->Platform; - (*stream) << "'"; + std::ostringstream oss; + oss << "'$(Configuration)|$(Platform)'=='"; + oss << config << "|" << this->Platform; + oss << "'"; // handle special case for 32 bit C# targets if (this->ProjectType == csproj && this->Platform == "Win32") { - (*stream) << " Or "; - (*stream) << "'$(Configuration)|$(Platform)'=='"; - (*stream) << config << "|x86"; - (*stream) << "'"; + oss << " Or "; + oss << "'$(Configuration)|$(Platform)'=='"; + oss << config << "|x86"; + oss << "'"; } - (*stream) << "\""; + return oss.str(); +} + +void cmVisualStudio10TargetGenerator::WritePlatformConfigTag( + const char* tag, const std::string& config, int indentLevel, + const char* attribute) + +{ + std::ostream& stream = *this->BuildFileStream; + stream.fill(' '); + stream.width(indentLevel * 2); + stream << ""; // applies indentation + stream << "<" << tag << " Condition=\""; + stream << this->CalcCondition(config); + stream << "\""; if (attribute) { - (*stream) << attribute; + stream << attribute; } // close the tag - (*stream) << ">"; - if (end) { - (*stream) << end; + stream << ">"; + if (attribute) { + stream << "\n"; } } +std::ostream& cmVisualStudio10TargetGenerator::Elem::WriteString( + const char* line) +{ + this->S.fill(' '); + this->S.width(this->Indent * 2); + // write an empty string to get the fill level indent to print + this->S << ""; + this->S << line; + return this->S; +} + void cmVisualStudio10TargetGenerator::WriteString(const char* line, int indentLevel) { - this->BuildFileStream->fill(' '); - this->BuildFileStream->width(indentLevel * 2); - // write an empty string to get the fill level indent to print - (*this->BuildFileStream) << ""; - (*this->BuildFileStream) << line; + Elem(*this->BuildFileStream, indentLevel).WriteString(line); } #define VS10_CXX_DEFAULT_PROPS "$(VCTargetsPath)\\Microsoft.Cpp.Default.props" @@ -253,8 +400,8 @@ void cmVisualStudio10TargetGenerator::Generate() if (this->NsightTegra) { this->WriteString("<PropertyGroup Label=\"NsightTegraProject\">\n", 1); - const int nsightTegraMajorVersion = this->NsightTegraVersion[0]; - const int nsightTegraMinorVersion = this->NsightTegraVersion[1]; + const unsigned int nsightTegraMajorVersion = this->NsightTegraVersion[0]; + const unsigned int nsightTegraMinorVersion = this->NsightTegraVersion[1]; if (nsightTegraMajorVersion >= 2) { this->WriteString("<NsightTegraProjectRevisionNumber>", 2); if (nsightTegraMajorVersion > 3 || @@ -266,16 +413,10 @@ void cmVisualStudio10TargetGenerator::Generate() } (*this->BuildFileStream) << "</NsightTegraProjectRevisionNumber>\n"; // Tell newer versions to upgrade silently when loading. - this->WriteString("<NsightTegraUpgradeOnceWithoutPrompt>" - "true" - "</NsightTegraUpgradeOnceWithoutPrompt>\n", - 2); + this->WriteElem("NsightTegraUpgradeOnceWithoutPrompt", "true", 2); } else { // Require Nsight Tegra 1.6 for JCompile support. - this->WriteString("<NsightTegraProjectRevisionNumber>" - "7" - "</NsightTegraProjectRevisionNumber>\n", - 2); + this->WriteElem("NsightTegraProjectRevisionNumber", "7", 2); } this->WriteString("</PropertyGroup>\n", 1); } @@ -283,9 +424,7 @@ void cmVisualStudio10TargetGenerator::Generate() if (const char* hostArch = this->GlobalGenerator->GetPlatformToolsetHostArchitecture()) { this->WriteString("<PropertyGroup>\n", 1); - this->WriteString("<PreferredToolArchitecture>", 2); - (*this->BuildFileStream) << cmVS10EscapeXML(hostArch) - << "</PreferredToolArchitecture>\n"; + this->WriteElemEscapeXML("PreferredToolArchitecture", hostArch, 2); this->WriteString("</PropertyGroup>\n", 1); } @@ -293,8 +432,7 @@ void cmVisualStudio10TargetGenerator::Generate() this->WriteProjectConfigurations(); } this->WriteString("<PropertyGroup Label=\"Globals\">\n", 1); - this->WriteString("<ProjectGuid>", 2); - (*this->BuildFileStream) << "{" << this->GUID << "}</ProjectGuid>\n"; + this->WriteElem("ProjectGuid", "{" + this->GUID + "}", 2); if (this->MSTools && this->GeneratorTarget->GetType() <= cmStateEnums::GLOBAL_TARGET) { @@ -323,61 +461,45 @@ void cmVisualStudio10TargetGenerator::Generate() this->GeneratorTarget->GetProperty("VS_SCC_PROVIDER"); if (vsProjectName && vsLocalPath && vsProvider) { - this->WriteString("<SccProjectName>", 2); - (*this->BuildFileStream) << cmVS10EscapeXML(vsProjectName) - << "</SccProjectName>\n"; - this->WriteString("<SccLocalPath>", 2); - (*this->BuildFileStream) << cmVS10EscapeXML(vsLocalPath) - << "</SccLocalPath>\n"; - this->WriteString("<SccProvider>", 2); - (*this->BuildFileStream) << cmVS10EscapeXML(vsProvider) - << "</SccProvider>\n"; + this->WriteElemEscapeXML("SccProjectName", vsProjectName, 2); + this->WriteElemEscapeXML("SccLocalPath", vsLocalPath, 2); + this->WriteElemEscapeXML("SccProvider", vsProvider, 2); const char* vsAuxPath = this->GeneratorTarget->GetProperty("VS_SCC_AUXPATH"); if (vsAuxPath) { - this->WriteString("<SccAuxPath>", 2); - (*this->BuildFileStream) << cmVS10EscapeXML(vsAuxPath) - << "</SccAuxPath>\n"; + this->WriteElemEscapeXML("SccAuxPath", vsAuxPath, 2); } } if (this->GeneratorTarget->GetPropertyAsBool("VS_WINRT_COMPONENT")) { - this->WriteString("<WinMDAssembly>true</WinMDAssembly>\n", 2); + this->WriteElem("WinMDAssembly", "true", 2); } const char* vsGlobalKeyword = this->GeneratorTarget->GetProperty("VS_GLOBAL_KEYWORD"); if (!vsGlobalKeyword) { - this->WriteString("<Keyword>Win32Proj</Keyword>\n", 2); + this->WriteElem("Keyword", "Win32Proj", 2); } else { - this->WriteString("<Keyword>", 2); - (*this->BuildFileStream) << cmVS10EscapeXML(vsGlobalKeyword) - << "</Keyword>\n"; + this->WriteElemEscapeXML("Keyword", vsGlobalKeyword, 2); } const char* vsGlobalRootNamespace = this->GeneratorTarget->GetProperty("VS_GLOBAL_ROOTNAMESPACE"); if (vsGlobalRootNamespace) { - this->WriteString("<RootNamespace>", 2); - (*this->BuildFileStream) << cmVS10EscapeXML(vsGlobalRootNamespace) - << "</RootNamespace>\n"; + this->WriteElemEscapeXML("RootNamespace", vsGlobalRootNamespace, 2); } - this->WriteString("<Platform>", 2); - (*this->BuildFileStream) << cmVS10EscapeXML(this->Platform) - << "</Platform>\n"; + this->WriteElemEscapeXML("Platform", this->Platform, 2); const char* projLabel = this->GeneratorTarget->GetProperty("PROJECT_LABEL"); if (!projLabel) { projLabel = this->Name.c_str(); } - this->WriteString("<ProjectName>", 2); - (*this->BuildFileStream) << cmVS10EscapeXML(projLabel) << "</ProjectName>\n"; + this->WriteElemEscapeXML("ProjectName", projLabel, 2); if (const char* targetFrameworkVersion = this->GeneratorTarget->GetProperty( "VS_DOTNET_TARGET_FRAMEWORK_VERSION")) { - this->WriteString("<TargetFrameworkVersion>", 2); - (*this->BuildFileStream) << cmVS10EscapeXML(targetFrameworkVersion) - << "</TargetFrameworkVersion>\n"; + this->WriteElemEscapeXML("TargetFrameworkVersion", targetFrameworkVersion, + 2); } // Disable the project upgrade prompt that is displayed the first time a @@ -385,9 +507,7 @@ void cmVisualStudio10TargetGenerator::Generate() // the IDE (respected by VS 2013 and above). if (this->GlobalGenerator->GetVersion() >= cmGlobalVisualStudioGenerator::VS12) { - this->WriteString("<VCProjectUpgraderObjectName>NoUpgrade" - "</VCProjectUpgraderObjectName>\n", - 2); + this->WriteElem("VCProjectUpgraderObjectName", "NoUpgrade", 2); } std::vector<std::string> keys = this->GeneratorTarget->GetPropertyKeys(); @@ -438,8 +558,7 @@ void cmVisualStudio10TargetGenerator::Generate() } outputType += "</OutputType>\n"; this->WriteString(outputType.c_str(), 2); - this->WriteString("<AppDesignerFolder>Properties</AppDesignerFolder>\n", - 2); + this->WriteElem("AppDesignerFolder", "Properties", 2); } this->WriteString("</PropertyGroup>\n", 1); @@ -468,7 +587,8 @@ void cmVisualStudio10TargetGenerator::Generate() "BuildCustomizations\\CUDA ", 2); (*this->BuildFileStream) - << cmVS10EscapeXML(this->GlobalGenerator->GetPlatformToolsetCudaString()) + << cmVS10EscapeAttr( + this->GlobalGenerator->GetPlatformToolsetCudaString()) << ".props\" />\n"; } if (this->GlobalGenerator->IsMasmEnabled()) { @@ -488,7 +608,7 @@ void cmVisualStudio10TargetGenerator::Generate() this->Makefile->ConfigureFile(propsTemplate.c_str(), propsLocal.c_str(), false, true, true); std::string import = std::string("<Import Project=\"") + - cmVS10EscapeXML(propsLocal) + "\" />\n"; + cmVS10EscapeAttr(propsLocal) + "\" />\n"; this->WriteString(import.c_str(), 2); } this->WriteString("</ImportGroup>\n", 1); @@ -510,8 +630,8 @@ void cmVisualStudio10TargetGenerator::Generate() ConvertToWindowsSlash(props); this->WriteString("", 2); (*this->BuildFileStream) - << "<Import Project=\"" << cmVS10EscapeXML(props) << "\"" - << " Condition=\"exists('" << cmVS10EscapeXML(props) << "')\"" + << "<Import Project=\"" << cmVS10EscapeAttr(props) << "\"" + << " Condition=\"exists('" << cmVS10EscapeAttr(props) << "')\"" << " Label=\"LocalAppDataPlatform\" />\n"; } } @@ -546,7 +666,8 @@ void cmVisualStudio10TargetGenerator::Generate() "BuildCustomizations\\CUDA ", 2); (*this->BuildFileStream) - << cmVS10EscapeXML(this->GlobalGenerator->GetPlatformToolsetCudaString()) + << cmVS10EscapeAttr( + this->GlobalGenerator->GetPlatformToolsetCudaString()) << ".targets\" />\n"; } if (this->GlobalGenerator->IsMasmEnabled()) { @@ -558,7 +679,7 @@ void cmVisualStudio10TargetGenerator::Generate() std::string nasmTargets = GetCMakeFilePath("Templates/MSBuild/nasm.targets"); std::string import = "<Import Project=\""; - import += cmVS10EscapeXML(nasmTargets) + "\" />\n"; + import += cmVS10EscapeAttr(nasmTargets) + "\" />\n"; this->WriteString(import.c_str(), 2); } this->WriteString("</ImportGroup>\n", 1); @@ -602,8 +723,7 @@ void cmVisualStudio10TargetGenerator::WriteDotNetReferences() if (!name.empty()) { std::string path = i.second.GetValue(); if (!cmsys::SystemTools::FileIsFullPath(path)) { - path = std::string(this->GeneratorTarget->Target->GetMakefile() - ->GetCurrentSourceDirectory()) + + path = std::string(this->Makefile->GetCurrentSourceDirectory()) + "/" + path; } ConvertToWindowsSlash(path); @@ -636,13 +756,9 @@ void cmVisualStudio10TargetGenerator::WriteDotNetReference( std::string const& ref, std::string const& hint) { this->WriteString("<Reference Include=\"", 2); - (*this->BuildFileStream) << cmVS10EscapeXML(ref) << "\">\n"; - this->WriteString("<CopyLocalSatelliteAssemblies>true" - "</CopyLocalSatelliteAssemblies>\n", - 3); - this->WriteString("<ReferenceOutputAssembly>true" - "</ReferenceOutputAssembly>\n", - 3); + (*this->BuildFileStream) << cmVS10EscapeAttr(ref) << "\">\n"; + this->WriteElem("CopyLocalSatelliteAssemblies", "true", 3); + this->WriteElem("ReferenceOutputAssembly", "true", 3); if (!hint.empty()) { const char* privateReference = "True"; if (const char* value = this->GeneratorTarget->GetProperty( @@ -651,10 +767,8 @@ void cmVisualStudio10TargetGenerator::WriteDotNetReference( privateReference = "False"; } } - this->WriteString("<Private>", 3); - (*this->BuildFileStream) << privateReference << "</Private>\n"; - this->WriteString("<HintPath>", 3); - (*this->BuildFileStream) << hint << "</HintPath>\n"; + this->WriteElem("Private", privateReference, 3); + this->WriteElem("HintPath", hint, 3); } this->WriteDotNetReferenceCustomTags(ref); this->WriteString("</Reference>\n", 2); @@ -713,9 +827,8 @@ void cmVisualStudio10TargetGenerator::WriteEmbeddedResourceGroup() (*this->BuildFileStream) << obj << "\">\n"; if (this->ProjectType != csproj) { - this->WriteString("<DependentUpon>", 3); std::string hFileName = obj.substr(0, obj.find_last_of(".")) + ".h"; - (*this->BuildFileStream) << hFileName << "</DependentUpon>\n"; + this->WriteElem("DependentUpon", hFileName, 3); for (std::string const& i : this->Configurations) { this->WritePlatformConfigTag("LogicalName", i, 3); @@ -743,8 +856,7 @@ void cmVisualStudio10TargetGenerator::WriteEmbeddedResourceGroup() link = cmsys::SystemTools::GetFilenameName(obj); } if (!link.empty()) { - this->WriteString("<Link>", 3); - (*this->BuildFileStream) << link << "</Link>\n"; + this->WriteElem("Link", link, 3); } } // Determine if this is a generated resource from a .Designer.cs file @@ -758,9 +870,7 @@ void cmVisualStudio10TargetGenerator::WriteEmbeddedResourceGroup() generator = g; } if (!generator.empty()) { - this->WriteString("<Generator>", 3); - (*this->BuildFileStream) << cmVS10EscapeXML(generator) - << "</Generator>\n"; + this->WriteElemEscapeXML("Generator", generator, 3); if (designerResource.find(srcDir) == 0) { designerResource = designerResource.substr(srcDir.length() + 1); } else if (designerResource.find(binDir) == 0) { @@ -770,9 +880,7 @@ void cmVisualStudio10TargetGenerator::WriteEmbeddedResourceGroup() cmsys::SystemTools::GetFilenameName(designerResource); } ConvertToWindowsSlash(designerResource); - this->WriteString("<LastGenOutput>", 3); - (*this->BuildFileStream) << designerResource - << "</LastGenOutput>\n"; + this->WriteElem("LastGenOutput", designerResource, 3); } } const cmPropertyMap& props = oi->GetProperties(); @@ -807,7 +915,7 @@ void cmVisualStudio10TargetGenerator::WriteXamlFilesGroup() this->WriteString("<ItemGroup>\n", 1); for (cmSourceFile const* oi : xamlObjs) { std::string obj = oi->GetFullPath(); - std::string xamlType; + const char* xamlType; const char* xamlTypeProperty = oi->GetProperty("VS_XAML_TYPE"); if (xamlTypeProperty) { xamlType = xamlTypeProperty; @@ -815,7 +923,9 @@ void cmVisualStudio10TargetGenerator::WriteXamlFilesGroup() xamlType = "Page"; } - this->WriteSource(xamlType, oi, ">\n"); + Elem e2(*this->BuildFileStream, 2); + this->WriteSource(xamlType, oi); + e2.SetHasElements(); if (this->ProjectType == csproj && !this->InSourceBuild) { // add <Link> tag to written XAML source if necessary const std::string srcDir = this->Makefile->GetCurrentSourceDirectory(); @@ -830,13 +940,11 @@ void cmVisualStudio10TargetGenerator::WriteXamlFilesGroup() } if (!link.empty()) { ConvertToWindowsSlash(link); - this->WriteString("<Link>", 3); - (*this->BuildFileStream) << link << "</Link>\n"; + this->WriteElem("Link", link, 3); } } - this->WriteString("<SubType>Designer</SubType>\n", 3); - this->WriteString("</", 2); - (*this->BuildFileStream) << xamlType << ">\n"; + this->WriteElem("SubType", "Designer", 3); + e2.WriteEndTag(xamlType); } this->WriteString("</ItemGroup>\n", 1); } @@ -858,10 +966,7 @@ void cmVisualStudio10TargetGenerator::WriteTargetSpecificReferences() void cmVisualStudio10TargetGenerator::WriteTargetsFileReferences() { - for (std::vector<TargetsFileAndConfigs>::iterator i = - this->TargetsFileAndConfigsVec.begin(); - i != this->TargetsFileAndConfigsVec.end(); ++i) { - TargetsFileAndConfigs const& tac = *i; + for (TargetsFileAndConfigs const& tac : this->TargetsFileAndConfigsVec) { this->WriteString("<Import Project=\"", 3); (*this->BuildFileStream) << tac.File << "\" "; (*this->BuildFileStream) << "Condition=\""; @@ -896,11 +1001,10 @@ void cmVisualStudio10TargetGenerator::WriteWinRTReferences() } if (!references.empty()) { this->WriteString("<ItemGroup>\n", 1); - for (std::vector<std::string>::iterator ri = references.begin(); - ri != references.end(); ++ri) { + for (std::string const& ri : references) { this->WriteString("<Reference Include=\"", 2); - (*this->BuildFileStream) << cmVS10EscapeXML(*ri) << "\">\n"; - this->WriteString("<IsWinMDFile>true</IsWinMDFile>\n", 3); + (*this->BuildFileStream) << cmVS10EscapeAttr(ri) << "\">\n"; + this->WriteElem("IsWinMDFile", "true", 3); this->WriteString("</Reference>\n", 2); } this->WriteString("</ItemGroup>\n", 1); @@ -912,16 +1016,11 @@ void cmVisualStudio10TargetGenerator::WriteWinRTReferences() void cmVisualStudio10TargetGenerator::WriteProjectConfigurations() { this->WriteString("<ItemGroup Label=\"ProjectConfigurations\">\n", 1); - for (std::vector<std::string>::const_iterator i = - this->Configurations.begin(); - i != this->Configurations.end(); ++i) { + for (std::string const& c : this->Configurations) { this->WriteString("<ProjectConfiguration Include=\"", 2); - (*this->BuildFileStream) << *i << "|" << this->Platform << "\">\n"; - this->WriteString("<Configuration>", 3); - (*this->BuildFileStream) << *i << "</Configuration>\n"; - this->WriteString("<Platform>", 3); - (*this->BuildFileStream) << cmVS10EscapeXML(this->Platform) - << "</Platform>\n"; + (*this->BuildFileStream) << c << "|" << this->Platform << "\">\n"; + this->WriteElem("Configuration", c, 3); + this->WriteElemEscapeXML("Platform", this->Platform, 3); this->WriteString("</ProjectConfiguration>\n", 2); } this->WriteString("</ItemGroup>\n", 1); @@ -929,11 +1028,9 @@ void cmVisualStudio10TargetGenerator::WriteProjectConfigurations() void cmVisualStudio10TargetGenerator::WriteProjectConfigurationValues() { - for (std::vector<std::string>::const_iterator i = - this->Configurations.begin(); - i != this->Configurations.end(); ++i) { - this->WritePlatformConfigTag("PropertyGroup", *i, 1, - " Label=\"Configuration\"", "\n"); + for (std::string const& c : this->Configurations) { + this->WritePlatformConfigTag("PropertyGroup", c, 1, + " Label=\"Configuration\""); if (this->ProjectType != csproj) { std::string configType = "<ConfigurationType>"; @@ -979,12 +1076,12 @@ void cmVisualStudio10TargetGenerator::WriteProjectConfigurationValues() if (this->MSTools) { if (!this->Managed) { - this->WriteMSToolConfigurationValues(*i); + this->WriteMSToolConfigurationValues(c); } else { - this->WriteMSToolConfigurationValuesManaged(*i); + this->WriteMSToolConfigurationValuesManaged(c); } } else if (this->NsightTegra) { - this->WriteNsightTegraConfigurationValues(*i); + this->WriteNsightTegraConfigurationValues(c); } this->WriteString("</PropertyGroup>\n", 1); @@ -994,11 +1091,8 @@ void cmVisualStudio10TargetGenerator::WriteProjectConfigurationValues() void cmVisualStudio10TargetGenerator::WriteMSToolConfigurationValues( std::string const& config) { - cmGlobalVisualStudio10Generator* gg = - static_cast<cmGlobalVisualStudio10Generator*>(this->GlobalGenerator); - const char* mfcFlag = - this->GeneratorTarget->Target->GetMakefile()->GetDefinition( - "CMAKE_MFC_FLAG"); + cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator; + const char* mfcFlag = this->Makefile->GetDefinition("CMAKE_MFC_FLAG"); if (mfcFlag) { std::string const mfcFlagValue = mfcFlag; @@ -1010,9 +1104,7 @@ void cmVisualStudio10TargetGenerator::WriteMSToolConfigurationValues( useOfMfcValue = "Dynamic"; } } - std::string mfcLine = "<UseOfMfc>"; - mfcLine += useOfMfcValue + "</UseOfMfc>\n"; - this->WriteString(mfcLine.c_str(), 2); + this->WriteElem("UseOfMfc", useOfMfcValue, 2); } if ((this->GeneratorTarget->GetType() <= cmStateEnums::OBJECT_LIBRARY && @@ -1021,57 +1113,46 @@ void cmVisualStudio10TargetGenerator::WriteMSToolConfigurationValues( this->GlobalGenerator->TargetsWindowsPhone() || this->GlobalGenerator->TargetsWindowsStore() || this->GeneratorTarget->GetPropertyAsBool("VS_WINRT_EXTENSIONS")) { - this->WriteString("<CharacterSet>Unicode</CharacterSet>\n", 2); + this->WriteElem("CharacterSet", "Unicode", 2); } else if (this->GeneratorTarget->GetType() <= cmStateEnums::MODULE_LIBRARY && this->ClOptions[config]->UsingSBCS()) { - this->WriteString("<CharacterSet>NotSet</CharacterSet>\n", 2); + this->WriteElem("CharacterSet", "NotSet", 2); } else { - this->WriteString("<CharacterSet>MultiByte</CharacterSet>\n", 2); + this->WriteElem("CharacterSet", "MultiByte", 2); } if (const char* toolset = gg->GetPlatformToolset()) { - std::string pts = "<PlatformToolset>"; - pts += toolset; - pts += "</PlatformToolset>\n"; - this->WriteString(pts.c_str(), 2); + this->WriteElem("PlatformToolset", toolset, 2); } if (this->GeneratorTarget->GetPropertyAsBool("VS_WINRT_COMPONENT") || this->GeneratorTarget->GetPropertyAsBool("VS_WINRT_EXTENSIONS")) { - this->WriteString("<WindowsAppContainer>true" - "</WindowsAppContainer>\n", - 2); + this->WriteElem("WindowsAppContainer", "true", 2); } } void cmVisualStudio10TargetGenerator::WriteMSToolConfigurationValuesManaged( std::string const& config) { - cmGlobalVisualStudio10Generator* gg = - static_cast<cmGlobalVisualStudio10Generator*>(this->GlobalGenerator); + cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator; Options& o = *(this->ClOptions[config]); if (o.IsDebug()) { - this->WriteString("<DebugSymbols>true</DebugSymbols>\n", 2); - this->WriteString("<DefineDebug>true</DefineDebug>\n", 2); + this->WriteElem("DebugSymbols", "true", 2); + this->WriteElem("DefineDebug", "true", 2); } std::string outDir = this->GeneratorTarget->GetDirectory(config) + "/"; ConvertToWindowsSlash(outDir); - this->WriteString("<OutputPath>", 2); - (*this->BuildFileStream) << cmVS10EscapeXML(outDir) << "</OutputPath>\n"; + this->WriteElemEscapeXML("OutputPath", outDir, 2); if (o.HasFlag("Platform")) { - this->WriteString("<PlatformTarget>", 2); - (*this->BuildFileStream) << cmVS10EscapeXML(o.GetFlag("Platform")) - << "</PlatformTarget>\n"; + this->WriteElemEscapeXML("PlatformTarget", o.GetFlag("Platform"), 2); o.RemoveFlag("Platform"); } if (const char* toolset = gg->GetPlatformToolset()) { - this->WriteString("<PlatformToolset>", 2); - (*this->BuildFileStream) << cmVS10EscapeXML(toolset) - << "</PlatformToolset>\n"; + this->WriteElemEscapeXML("PlatformToolset", toolset, 2); } std::string postfixName = cmSystemTools::UpperCase(config); @@ -1081,27 +1162,24 @@ void cmVisualStudio10TargetGenerator::WriteMSToolConfigurationValuesManaged( if (const char* postfix = this->GeneratorTarget->GetProperty(postfixName)) { assemblyName += postfix; } - this->WriteString("<AssemblyName>", 2); - (*this->BuildFileStream) << cmVS10EscapeXML(assemblyName) - << "</AssemblyName>\n"; + this->WriteElemEscapeXML("AssemblyName", assemblyName, 2); if (cmStateEnums::EXECUTABLE == this->GeneratorTarget->GetType()) { - this->WriteString("<StartAction>Program</StartAction>\n", 2); + this->WriteElem("StartAction", "Program", 2); this->WriteString("<StartProgram>", 2); (*this->BuildFileStream) << cmVS10EscapeXML(outDir) << cmVS10EscapeXML(assemblyName) << ".exe</StartProgram>\n"; } - o.OutputFlagMap(*this->BuildFileStream, " "); + o.OutputFlagMap(*this->BuildFileStream, 2); } //---------------------------------------------------------------------------- void cmVisualStudio10TargetGenerator::WriteNsightTegraConfigurationValues( std::string const&) { - cmGlobalVisualStudio10Generator* gg = - static_cast<cmGlobalVisualStudio10Generator*>(this->GlobalGenerator); + cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator; const char* toolset = gg->GetPlatformToolset(); std::string ntv = "<NdkToolchainVersion>"; ntv += toolset ? toolset : "Default"; @@ -1109,40 +1187,30 @@ void cmVisualStudio10TargetGenerator::WriteNsightTegraConfigurationValues( this->WriteString(ntv.c_str(), 2); if (const char* minApi = this->GeneratorTarget->GetProperty("ANDROID_API_MIN")) { - this->WriteString("<AndroidMinAPI>", 2); - (*this->BuildFileStream) << "android-" << cmVS10EscapeXML(minApi) - << "</AndroidMinAPI>\n"; + this->WriteElem("AndroidMinAPI", "android-" + cmVS10EscapeXML(minApi), 2); } if (const char* api = this->GeneratorTarget->GetProperty("ANDROID_API")) { - this->WriteString("<AndroidTargetAPI>", 2); - (*this->BuildFileStream) << "android-" << cmVS10EscapeXML(api) - << "</AndroidTargetAPI>\n"; + this->WriteElem("AndroidTargetAPI", "android-" + cmVS10EscapeXML(api), 2); } if (const char* cpuArch = this->GeneratorTarget->GetProperty("ANDROID_ARCH")) { - this->WriteString("<AndroidArch>", 2); - (*this->BuildFileStream) << cmVS10EscapeXML(cpuArch) << "</AndroidArch>\n"; + this->WriteElemEscapeXML("AndroidArch", cpuArch, 2); } if (const char* stlType = this->GeneratorTarget->GetProperty("ANDROID_STL_TYPE")) { - this->WriteString("<AndroidStlType>", 2); - (*this->BuildFileStream) << cmVS10EscapeXML(stlType) - << "</AndroidStlType>\n"; + this->WriteElemEscapeXML("AndroidStlType", stlType, 2); } } void cmVisualStudio10TargetGenerator::WriteCustomCommands() { - this->SourcesVisited.clear(); this->CSharpCustomCommandNames.clear(); std::vector<cmSourceFile const*> customCommands; this->GeneratorTarget->GetCustomCommands(customCommands, ""); - for (std::vector<cmSourceFile const*>::const_iterator si = - customCommands.begin(); - si != customCommands.end(); ++si) { - this->WriteCustomCommand(*si); + for (cmSourceFile const* si : customCommands) { + this->WriteCustomCommand(si); } // Add CMakeLists.txt file with rule to re-run CMake for user convenience. @@ -1158,12 +1226,13 @@ void cmVisualStudio10TargetGenerator::WriteCustomCommands() void cmVisualStudio10TargetGenerator::WriteCustomCommand( cmSourceFile const* sf) { - if (this->SourcesVisited.insert(sf).second) { + if (this->LocalGenerator->GetSourcesVisited(this->GeneratorTarget) + .insert(sf) + .second) { if (std::vector<cmSourceFile*> const* depends = this->GeneratorTarget->GetSourceDepends(sf)) { - for (std::vector<cmSourceFile*>::const_iterator di = depends->begin(); - di != depends->end(); ++di) { - this->WriteCustomCommand(*di); + for (cmSourceFile const* di : *depends) { + this->WriteCustomCommand(di); } } if (cmCustomCommand const* command = sf->GetCustomCommand()) { @@ -1186,10 +1255,10 @@ void cmVisualStudio10TargetGenerator::WriteCustomRule( // VS 10 will always rebuild a custom command attached to a .rule // file that doesn't exist so create the file explicitly. if (source->GetPropertyAsBool("__CMAKE_RULE")) { - if (!cmSystemTools::FileExists(sourcePath.c_str())) { + if (!cmSystemTools::FileExists(sourcePath)) { // Make sure the path exists for the file std::string path = cmSystemTools::GetFilenamePath(sourcePath); - cmSystemTools::MakeDirectory(path.c_str()); + cmSystemTools::MakeDirectory(path); cmsys::ofstream fout(sourcePath.c_str()); if (fout) { fout << "# generated from CMake\n"; @@ -1209,88 +1278,77 @@ void cmVisualStudio10TargetGenerator::WriteCustomRule( } cmLocalVisualStudio7Generator* lg = this->LocalGenerator; + Elem e2(*this->BuildFileStream, 2); if (this->ProjectType != csproj) { - this->WriteSource("CustomBuild", source, ">\n"); + this->WriteSource("CustomBuild", source); + e2.SetHasElements(); } else { this->WriteString("<ItemGroup>\n", 1); std::string link; this->GetCSharpSourceLink(source, link); - this->WriteSource("None", source, ">\n"); + this->WriteSource("None", source); + e2.SetHasElements(); if (!link.empty()) { - this->WriteString("<Link>", 3); - (*this->BuildFileStream) << link << "</Link>\n"; + this->WriteElem("Link", link, 3); } - this->WriteString("</None>\n", 2); + e2.WriteEndTag("None"); this->WriteString("</ItemGroup>\n", 1); } - for (std::vector<std::string>::const_iterator i = - this->Configurations.begin(); - i != this->Configurations.end(); ++i) { - cmCustomCommandGenerator ccg(command, *i, this->LocalGenerator); + for (std::string const& c : this->Configurations) { + cmCustomCommandGenerator ccg(command, c, lg); std::string comment = lg->ConstructComment(ccg); comment = cmVS10EscapeComment(comment); - std::string script = cmVS10EscapeXML(lg->ConstructScript(ccg)); + std::string script = lg->ConstructScript(ccg); // input files for custom command std::stringstream inputs; - inputs << cmVS10EscapeXML(source->GetFullPath()); - for (std::vector<std::string>::const_iterator d = ccg.GetDepends().begin(); - d != ccg.GetDepends().end(); ++d) { + inputs << source->GetFullPath(); + for (std::string const& d : ccg.GetDepends()) { std::string dep; - if (this->LocalGenerator->GetRealDependency(*d, *i, dep)) { + if (lg->GetRealDependency(d, c, dep)) { ConvertToWindowsSlash(dep); - inputs << ";" << cmVS10EscapeXML(dep); + inputs << ";" << dep; } } // output files for custom command std::stringstream outputs; const char* sep = ""; - for (std::vector<std::string>::const_iterator o = ccg.GetOutputs().begin(); - o != ccg.GetOutputs().end(); ++o) { - std::string out = *o; + for (std::string const& o : ccg.GetOutputs()) { + std::string out = o; ConvertToWindowsSlash(out); - outputs << sep << cmVS10EscapeXML(out); + outputs << sep << out; sep = ";"; } if (this->ProjectType == csproj) { - std::string name = "CustomCommand_" + *i + "_" + + std::string name = "CustomCommand_" + c + "_" + cmSystemTools::ComputeStringMD5(sourcePath); - std::string inputs_s = inputs.str(); - std::string outputs_s = outputs.str(); - comment = cmVS10EscapeQuotes(comment); - script = cmVS10EscapeQuotes(script); - inputs_s = cmVS10EscapeQuotes(inputs_s); - outputs_s = cmVS10EscapeQuotes(outputs_s); - this->WriteCustomRuleCSharp(*i, name, script, inputs_s, outputs_s, + this->WriteCustomRuleCSharp(c, name, script, inputs.str(), outputs.str(), comment); } else { - this->WriteCustomRuleCpp(*i, script, inputs.str(), outputs.str(), + this->WriteCustomRuleCpp(e2, c, script, inputs.str(), outputs.str(), comment); } } if (this->ProjectType != csproj) { - this->WriteString("</CustomBuild>\n", 2); + e2.WriteEndTag("CustomBuild"); } } void cmVisualStudio10TargetGenerator::WriteCustomRuleCpp( - std::string const& config, std::string const& script, + Elem& e2, std::string const& config, std::string const& script, std::string const& inputs, std::string const& outputs, std::string const& comment) { - this->WritePlatformConfigTag("Message", config, 3); - (*this->BuildFileStream) << cmVS10EscapeXML(comment) << "</Message>\n"; - this->WritePlatformConfigTag("Command", config, 3); - (*this->BuildFileStream) << script << "</Command>\n"; - this->WritePlatformConfigTag("AdditionalInputs", config, 3); - (*this->BuildFileStream) << inputs; - (*this->BuildFileStream) << ";%(AdditionalInputs)</AdditionalInputs>\n"; - this->WritePlatformConfigTag("Outputs", config, 3); - (*this->BuildFileStream) << outputs << "</Outputs>\n"; + const std::string cond = this->CalcCondition(config); + Elem(e2, "Message").Attribute("Condition", cond).Content(comment); + Elem(e2, "Command").Attribute("Condition", cond).Content(script); + Elem(e2, "AdditionalInputs") + .Attribute("Condition", cond) + .Content(inputs + ";%(AdditionalInputs)"); + Elem(e2, "Outputs").Attribute("Condition", cond).Content(outputs); if (this->LocalGenerator->GetVersion() > cmGlobalVisualStudioGenerator::VS10) { // VS >= 11 let us turn off linking of custom command outputs. - this->WritePlatformConfigTag("LinkObjects", config, 3); - (*this->BuildFileStream) << "false</LinkObjects>\n"; + Elem(e2, "LinkObjects").Attribute("Condition", cond).Content("false"); } } @@ -1302,17 +1360,16 @@ void cmVisualStudio10TargetGenerator::WriteCustomRuleCSharp( this->CSharpCustomCommandNames.insert(name); std::stringstream attributes; attributes << "\n Name=\"" << name << "\""; - attributes << "\n Inputs=\"" << inputs << "\""; - attributes << "\n Outputs=\"" << outputs << "\""; - this->WritePlatformConfigTag("Target", config, 1, attributes.str().c_str(), - "\n"); + attributes << "\n Inputs=\"" << cmVS10EscapeAttr(inputs) << "\""; + attributes << "\n Outputs=\"" << cmVS10EscapeAttr(outputs) << "\""; + this->WritePlatformConfigTag("Target", config, 1, attributes.str().c_str()); if (!comment.empty()) { this->WriteString("<Exec Command=\"", 2); - (*this->BuildFileStream) << "echo " << cmVS10EscapeXML(comment) + (*this->BuildFileStream) << "echo " << cmVS10EscapeAttr(comment) << "\" />\n"; } this->WriteString("<Exec Command=\"", 2); - (*this->BuildFileStream) << script << "\" />\n"; + (*this->BuildFileStream) << cmVS10EscapeAttr(script) << "\" />\n"; this->WriteString("</Target>\n", 1); } @@ -1321,8 +1378,8 @@ std::string cmVisualStudio10TargetGenerator::ConvertPath( { return forceRelative ? cmSystemTools::RelativePath( - this->LocalGenerator->GetCurrentBinaryDirectory(), path.c_str()) - : path.c_str(); + this->LocalGenerator->GetCurrentBinaryDirectory(), path) + : path; } static void ConvertToWindowsSlash(std::string& s) @@ -1334,6 +1391,7 @@ static void ConvertToWindowsSlash(std::string& s) pos++; } } + void cmVisualStudio10TargetGenerator::WriteGroups() { if (this->ProjectType == csproj) { @@ -1347,10 +1405,8 @@ void cmVisualStudio10TargetGenerator::WriteGroups() this->GeneratorTarget->GetAllConfigSources(); std::set<cmSourceGroup*> groupsUsed; - for (std::vector<cmGeneratorTarget::AllConfigSource>::const_iterator si = - sources.begin(); - si != sources.end(); ++si) { - std::string const& source = si->Source->GetFullPath(); + for (cmGeneratorTarget::AllConfigSource const& si : sources) { + std::string const& source = si.Source->GetFullPath(); cmSourceGroup* sourceGroup = this->Makefile->FindSourceGroup(source, sourceGroups); groupsUsed.insert(sourceGroup); @@ -1369,72 +1425,72 @@ void cmVisualStudio10TargetGenerator::WriteGroups() fout.SetCopyIfDifferent(true); char magic[] = { char(0xEF), char(0xBB), char(0xBF) }; fout.write(magic, 3); - cmGeneratedFileStream* save = this->BuildFileStream; - this->BuildFileStream = &fout; // get the tools version to use const std::string toolsVer(this->GlobalGenerator->GetToolsVersion()); - std::string project_defaults = "<?xml version=\"1.0\" encoding=\"" + - this->GlobalGenerator->Encoding() + "\"?>\n"; - project_defaults.append("<Project ToolsVersion=\""); - project_defaults.append(toolsVer + "\" "); - project_defaults.append( - "xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n"); - this->WriteString(project_defaults.c_str(), 0); + fout << "<?xml version=\"1.0\" encoding=\"" + << this->GlobalGenerator->Encoding() << "\"?>\n"; - for (ToolSourceMap::const_iterator ti = this->Tools.begin(); - ti != this->Tools.end(); ++ti) { - this->WriteGroupSources(ti->first.c_str(), ti->second, sourceGroups); + Elem e0(fout, 0); + e0.StartElement("Project"); + e0.Attr("ToolsVersion", toolsVer); + e0.Attr("xmlns", "http://schemas.microsoft.com/developer/msbuild/2003"); + e0.SetHasElements(); + + for (auto const& ti : this->Tools) { + this->WriteGroupSources(e0, ti.first, ti.second, sourceGroups); } // Added files are images and the manifest. if (!this->AddedFiles.empty()) { - this->WriteString("<ItemGroup>\n", 1); + Elem e1(e0, "ItemGroup"); + e1.SetHasElements(); for (std::string const& oi : this->AddedFiles) { std::string fileName = cmSystemTools::LowerCase(cmSystemTools::GetFilenameName(oi)); if (fileName == "wmappmanifest.xml") { - this->WriteString("<XML Include=\"", 2); - (*this->BuildFileStream) << oi << "\">\n"; - this->WriteString("<Filter>Resource Files</Filter>\n", 3); - this->WriteString("</XML>\n", 2); + Elem e2(e1, "XML"); + e2.Attr("Include", oi); + Elem(e2).WriteElem("Filter", "Resource Files"); + e2.EndElement(); } else if (cmSystemTools::GetFilenameExtension(fileName) == ".appxmanifest") { - this->WriteString("<AppxManifest Include=\"", 2); - (*this->BuildFileStream) << oi << "\">\n"; - this->WriteString("<Filter>Resource Files</Filter>\n", 3); - this->WriteString("</AppxManifest>\n", 2); + Elem e2(e1, "AppxManifest"); + e2.Attr("Include", oi); + Elem(e2).WriteElem("Filter", "Resource Files"); + e2.EndElement(); } else if (cmSystemTools::GetFilenameExtension(fileName) == ".pfx") { - this->WriteString("<None Include=\"", 2); - (*this->BuildFileStream) << oi << "\">\n"; - this->WriteString("<Filter>Resource Files</Filter>\n", 3); - this->WriteString("</None>\n", 2); + Elem e2(e1, "None"); + e2.Attr("Include", oi); + Elem(e2).WriteElem("Filter", "Resource Files"); + e2.EndElement(); } else { - this->WriteString("<Image Include=\"", 2); - (*this->BuildFileStream) << oi << "\">\n"; - this->WriteString("<Filter>Resource Files</Filter>\n", 3); - this->WriteString("</Image>\n", 2); + Elem e2(e1, "Image"); + e2.Attr("Include", oi); + Elem(e2).WriteElem("Filter", "Resource Files"); + e2.EndElement(); } } - this->WriteString("</ItemGroup>\n", 1); + e1.EndElement(); } std::vector<cmSourceFile const*> resxObjs; this->GeneratorTarget->GetResxSources(resxObjs, ""); if (!resxObjs.empty()) { - this->WriteString("<ItemGroup>\n", 1); + Elem e1(e0, "ItemGroup"); for (cmSourceFile const* oi : resxObjs) { std::string obj = oi->GetFullPath(); - this->WriteString("<EmbeddedResource Include=\"", 2); ConvertToWindowsSlash(obj); - (*this->BuildFileStream) << cmVS10EscapeXML(obj) << "\">\n"; - this->WriteString("<Filter>Resource Files</Filter>\n", 3); - this->WriteString("</EmbeddedResource>\n", 2); + Elem e2(e1, "EmbeddedResource"); + e2.Attr("Include", cmVS10EscapeAttr(obj)); + Elem(e2).WriteElem("Filter", "Resource Files"); + e2.EndElement(); } - this->WriteString("</ItemGroup>\n", 1); + e1.EndElement(); } - this->WriteString("<ItemGroup>\n", 1); + Elem e1(e0, "ItemGroup"); + e1.SetHasElements(); std::vector<cmSourceGroup*> groupsVec(groupsUsed.begin(), groupsUsed.end()); std::sort(groupsVec.begin(), groupsVec.end(), [](cmSourceGroup* l, cmSourceGroup* r) { @@ -1443,35 +1499,29 @@ void cmVisualStudio10TargetGenerator::WriteGroups() for (cmSourceGroup* sg : groupsVec) { std::string const& name = sg->GetFullName(); if (!name.empty()) { - this->WriteString("<Filter Include=\"", 2); - (*this->BuildFileStream) << name << "\">\n"; - std::string guidName = "SG_Filter_"; - guidName += name; - this->WriteString("<UniqueIdentifier>", 3); + std::string guidName = "SG_Filter_" + name; std::string guid = this->GlobalGenerator->GetGUID(guidName); - (*this->BuildFileStream) << "{" << guid << "}" - << "</UniqueIdentifier>\n"; - this->WriteString("</Filter>\n", 2); + Elem e2(e1, "Filter"); + e2.Attr("Include", name); + Elem(e2).WriteElem("UniqueIdentifier", "{" + guid + "}"); + e2.EndElement(); } } if (!resxObjs.empty() || !this->AddedFiles.empty()) { - this->WriteString("<Filter Include=\"Resource Files\">\n", 2); std::string guidName = "SG_Filter_Resource Files"; - this->WriteString("<UniqueIdentifier>", 3); std::string guid = this->GlobalGenerator->GetGUID(guidName); - (*this->BuildFileStream) << "{" << guid << "}" - << "</UniqueIdentifier>\n"; - this->WriteString("<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;", 3); - (*this->BuildFileStream) << "gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;"; - (*this->BuildFileStream) << "mfcribbon-ms</Extensions>\n"; - this->WriteString("</Filter>\n", 2); + Elem e2(e1, "Filter"); + e2.Attr("Include", "Resource Files"); + Elem(e2).WriteElem("UniqueIdentifier", "{" + guid + "}"); + Elem(e2).WriteElem("Extensions", + "rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;" + "gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms"); + e2.EndElement(); } - this->WriteString("</ItemGroup>\n", 1); - this->WriteString("</Project>\n", 0); - // restore stream pointer - this->BuildFileStream = save; + e1.EndElement(); + e0.EndElement(); if (fout.Close()) { this->GlobalGenerator->FileReplacedDuringGenerate(path); @@ -1516,61 +1566,56 @@ void cmVisualStudio10TargetGenerator::AddMissingSourceGroups( } void cmVisualStudio10TargetGenerator::WriteGroupSources( - const char* name, ToolSources const& sources, + Elem& e0, std::string const& name, ToolSources const& sources, std::vector<cmSourceGroup>& sourceGroups) { - this->WriteString("<ItemGroup>\n", 1); + Elem e1(e0, "ItemGroup"); + e1.SetHasElements(); for (ToolSource const& s : sources) { cmSourceFile const* sf = s.SourceFile; std::string const& source = sf->GetFullPath(); cmSourceGroup* sourceGroup = this->Makefile->FindSourceGroup(source, sourceGroups); std::string const& filter = sourceGroup->GetFullName(); - this->WriteString("<", 2); std::string path = this->ConvertPath(source, s.RelativePath); ConvertToWindowsSlash(path); - (*this->BuildFileStream) << name << " Include=\"" << cmVS10EscapeXML(path); + Elem e2(e1, name.c_str()); + e2.Attr("Include", cmVS10EscapeAttr(path)); if (!filter.empty()) { - (*this->BuildFileStream) << "\">\n"; - this->WriteString("<Filter>", 3); - (*this->BuildFileStream) << filter << "</Filter>\n"; - this->WriteString("</", 2); - (*this->BuildFileStream) << name << ">\n"; - } else { - (*this->BuildFileStream) << "\" />\n"; + Elem(e2).WriteElem("Filter", filter); } + e2.EndElement(); } - this->WriteString("</ItemGroup>\n", 1); + e1.EndElement(); } void cmVisualStudio10TargetGenerator::WriteHeaderSource(cmSourceFile const* sf) { std::string const& fileName = sf->GetFullPath(); + Elem e2(*this->BuildFileStream, 2); + this->WriteSource("ClInclude", sf); if (this->IsResxHeader(fileName)) { - this->WriteSource("ClInclude", sf, ">\n"); - this->WriteString("<FileType>CppForm</FileType>\n", 3); - this->WriteString("</ClInclude>\n", 2); + e2.SetHasElements(); + this->WriteElem("FileType", "CppForm", 3); } else if (this->IsXamlHeader(fileName)) { - this->WriteSource("ClInclude", sf, ">\n"); - this->WriteString("<DependentUpon>", 3); std::string xamlFileName = fileName.substr(0, fileName.find_last_of(".")); - (*this->BuildFileStream) << xamlFileName << "</DependentUpon>\n"; - this->WriteString("</ClInclude>\n", 2); - } else { - this->WriteSource("ClInclude", sf); + e2.SetHasElements(); + this->WriteElem("DependentUpon", xamlFileName, 3); } + e2.WriteEndTag("ClInclude"); } void cmVisualStudio10TargetGenerator::WriteExtraSource(cmSourceFile const* sf) { bool toolHasSettings = false; - std::string tool = "None"; + const char* tool = "None"; std::string shaderType; std::string shaderEntryPoint; std::string shaderModel; std::string shaderAdditionalFlags; std::string shaderDisableOptimizations; std::string shaderEnableDebug; + std::string shaderObjectFileName; std::string outputHeaderFile; std::string variableName; std::string settingsGenerator; @@ -1647,6 +1692,10 @@ void cmVisualStudio10TargetGenerator::WriteExtraSource(cmSourceFile const* sf) shaderDisableOptimizations = cmSystemTools::IsOn(sdo) ? "true" : "false"; toolHasSettings = true; } + if (const char* sofn = sf->GetProperty("VS_SHADER_OBJECT_FILE_NAME")) { + shaderObjectFileName = sofn; + toolHasSettings = true; + } } else if (ext == "jpg" || ext == "png") { tool = "Image"; } else if (ext == "resw") { @@ -1714,8 +1763,10 @@ void cmVisualStudio10TargetGenerator::WriteExtraSource(cmSourceFile const* sf) } } + Elem e2(*this->BuildFileStream, 2); + this->WriteSource(tool, sf); if (toolHasSettings) { - this->WriteSource(tool, sf, ">\n"); + e2.SetHasElements(); if (!deployContent.empty()) { cmGeneratorExpression ge; @@ -1749,19 +1800,13 @@ void cmVisualStudio10TargetGenerator::WriteExtraSource(cmSourceFile const* sf) } } if (!shaderType.empty()) { - this->WriteString("<ShaderType>", 3); - (*this->BuildFileStream) << cmVS10EscapeXML(shaderType) - << "</ShaderType>\n"; + this->WriteElemEscapeXML("ShaderType", shaderType, 3); } if (!shaderEntryPoint.empty()) { - this->WriteString("<EntryPointName>", 3); - (*this->BuildFileStream) << cmVS10EscapeXML(shaderEntryPoint) - << "</EntryPointName>\n"; + this->WriteElemEscapeXML("EntryPointName", shaderEntryPoint, 3); } if (!shaderModel.empty()) { - this->WriteString("<ShaderModel>", 3); - (*this->BuildFileStream) << cmVS10EscapeXML(shaderModel) - << "</ShaderModel>\n"; + this->WriteElemEscapeXML("ShaderModel", shaderModel, 3); } if (!outputHeaderFile.empty()) { for (size_t i = 0; i != this->Configurations.size(); ++i) { @@ -1786,60 +1831,45 @@ void cmVisualStudio10TargetGenerator::WriteExtraSource(cmSourceFile const* sf) } } if (!shaderEnableDebug.empty()) { - this->WriteString("<EnableDebuggingInformation>", 3); - (*this->BuildFileStream) << cmVS10EscapeXML(shaderEnableDebug) - << "</EnableDebuggingInformation>\n"; + this->WriteElemEscapeXML("EnableDebuggingInformation", shaderEnableDebug, + 3); } if (!shaderDisableOptimizations.empty()) { - this->WriteString("<DisableOptimizations>", 3); - (*this->BuildFileStream) << cmVS10EscapeXML(shaderDisableOptimizations) - << "</DisableOptimizations>\n"; + this->WriteElemEscapeXML("DisableOptimizations", + shaderDisableOptimizations, 3); + } + if (!shaderObjectFileName.empty()) { + this->WriteElemEscapeXML("ObjectFileOutput", shaderObjectFileName, 3); } if (!shaderAdditionalFlags.empty()) { - this->WriteString("<AdditionalOptions>", 3); - (*this->BuildFileStream) << cmVS10EscapeXML(shaderAdditionalFlags) - << "</AdditionalOptions>\n"; + this->WriteElemEscapeXML("AdditionalOptions", shaderAdditionalFlags, 3); } if (!settingsGenerator.empty()) { - this->WriteString("<Generator>", 3); - (*this->BuildFileStream) << cmVS10EscapeXML(settingsGenerator) - << "</Generator>\n"; + this->WriteElemEscapeXML("Generator", settingsGenerator, 3); } if (!settingsLastGenOutput.empty()) { - this->WriteString("<LastGenOutput>", 3); - (*this->BuildFileStream) << cmVS10EscapeXML(settingsLastGenOutput) - << "</LastGenOutput>\n"; + this->WriteElemEscapeXML("LastGenOutput", settingsLastGenOutput, 3); } if (!sourceLink.empty()) { - this->WriteString("<Link>", 3); - (*this->BuildFileStream) << cmVS10EscapeXML(sourceLink) << "</Link>\n"; + this->WriteElemEscapeXML("Link", sourceLink, 3); } if (!subType.empty()) { - this->WriteString("<SubType>", 3); - (*this->BuildFileStream) << cmVS10EscapeXML(subType) << "</SubType>\n"; + this->WriteElemEscapeXML("SubType", subType, 3); } if (!copyToOutDir.empty()) { - this->WriteString("<CopyToOutputDirectory>", 3); - (*this->BuildFileStream) << cmVS10EscapeXML(copyToOutDir) - << "</CopyToOutputDirectory>\n"; + this->WriteElemEscapeXML("CopyToOutputDirectory", copyToOutDir, 3); } if (!includeInVsix.empty()) { - this->WriteString("<IncludeInVSIX>", 3); - (*this->BuildFileStream) << cmVS10EscapeXML(includeInVsix) - << "</IncludeInVSIX>\n"; + this->WriteElemEscapeXML("IncludeInVSIX", includeInVsix, 3); } // write source file specific tags this->WriteCSharpSourceProperties(sourceFileTags); - this->WriteString("</", 2); - (*this->BuildFileStream) << tool << ">\n"; - } else { - this->WriteSource(tool, sf); } + e2.WriteEndTag(tool); } void cmVisualStudio10TargetGenerator::WriteSource(std::string const& tool, - cmSourceFile const* sf, - const char* end) + cmSourceFile const* sf) { // Visual Studio tools append relative paths to the current dir, as in: // @@ -1853,7 +1883,7 @@ void cmVisualStudio10TargetGenerator::WriteSource(std::string const& tool, std::string sourceFile = this->ConvertPath(sf->GetFullPath(), forceRelative); if (this->LocalGenerator->GetVersion() == cmGlobalVisualStudioGenerator::VS10 && - cmSystemTools::FileIsFullPath(sourceFile.c_str())) { + cmSystemTools::FileIsFullPath(sourceFile)) { // Normal path conversion resulted in a full path. VS 10 (but not 11) // refuses to show the property page in the IDE for a source file with a // full path (not starting in a '.' or '/' AFAICT). CMake <= 2.8.4 used a @@ -1876,8 +1906,7 @@ void cmVisualStudio10TargetGenerator::WriteSource(std::string const& tool, ConvertToWindowsSlash(sourceFile); this->WriteString("<", 2); (*this->BuildFileStream) << tool << " Include=\"" - << cmVS10EscapeXML(sourceFile) << "\"" - << (end ? end : " />\n"); + << cmVS10EscapeAttr(sourceFile) << "\""; ToolSource toolSource = { sf, forceRelative }; this->Tools[tool].push_back(toolSource); @@ -1906,7 +1935,7 @@ void cmVisualStudio10TargetGenerator::WriteAllSources() // Skip explicit reference to CMakeLists.txt source. continue; } - std::string tool; + const char* tool = nullptr; switch (si.Kind) { case cmGeneratorTarget::SourceKindAppManifest: tool = "AppxManifest"; @@ -1975,7 +2004,7 @@ void cmVisualStudio10TargetGenerator::WriteAllSources() break; } - if (!tool.empty()) { + if (tool) { // Compute set of configurations to exclude, if any. std::vector<size_t> const& include_configs = si.Configs; std::vector<size_t> exclude_configs; @@ -1983,31 +2012,15 @@ void cmVisualStudio10TargetGenerator::WriteAllSources() include_configs.begin(), include_configs.end(), std::back_inserter(exclude_configs)); + Elem e2(*this->BuildFileStream, 2); + this->WriteSource(tool, si.Source); if (si.Kind == cmGeneratorTarget::SourceKindObjectSource) { - // FIXME: refactor generation to avoid tracking XML syntax state. - this->WriteSource(tool, si.Source, ""); - bool have_nested = this->OutputSourceSpecificFlags(si.Source); - if (!exclude_configs.empty()) { - if (!have_nested) { - (*this->BuildFileStream) << ">\n"; - } - this->WriteExcludeFromBuild(exclude_configs); - have_nested = true; - } - if (have_nested) { - this->WriteString("</", 2); - (*this->BuildFileStream) << tool << ">\n"; - } else { - (*this->BuildFileStream) << " />\n"; - } - } else if (!exclude_configs.empty()) { - this->WriteSource(tool, si.Source, ">\n"); - this->WriteExcludeFromBuild(exclude_configs); - this->WriteString("</", 2); - (*this->BuildFileStream) << tool << ">\n"; - } else { - this->WriteSource(tool, si.Source); + this->OutputSourceSpecificFlags(e2, si.Source); + } + if (!exclude_configs.empty()) { + this->WriteExcludeFromBuild(e2, exclude_configs); } + e2.WriteEndTag(tool); } } @@ -2018,8 +2031,8 @@ void cmVisualStudio10TargetGenerator::WriteAllSources() this->WriteString("</ItemGroup>\n", 1); } -bool cmVisualStudio10TargetGenerator::OutputSourceSpecificFlags( - cmSourceFile const* source) +void cmVisualStudio10TargetGenerator::OutputSourceSpecificFlags( + Elem& e2, cmSourceFile const* source) { cmSourceFile const& sf = *source; @@ -2079,22 +2092,14 @@ bool cmVisualStudio10TargetGenerator::OutputSourceSpecificFlags( } } bool noWinRT = this->TargetCompileAsWinRT && lang == "C"; - bool hasFlags = false; // for the first time we need a new line if there is something // produced here. - const char* firstString = ">\n"; if (!objectName.empty()) { - (*this->BuildFileStream) << firstString; - firstString = ""; - hasFlags = true; + e2.SetHasElements(); if (lang == "CUDA") { - this->WriteString("<CompileOut>", 3); - (*this->BuildFileStream) << "$(IntDir)/" << objectName - << "</CompileOut>\n"; + this->WriteElem("CompileOut", "$(IntDir)/" + objectName, 3); } else { - this->WriteString("<ObjectFileName>", 3); - (*this->BuildFileStream) << "$(IntDir)/" << objectName - << "</ObjectFileName>\n"; + this->WriteElem("ObjectFileName", "$(IntDir)/" + objectName, 3); } } for (std::string const& config : this->Configurations) { @@ -2114,11 +2119,8 @@ bool cmVisualStudio10TargetGenerator::OutputSourceSpecificFlags( // use them if (!flags.empty() || !options.empty() || !configDefines.empty() || !includes.empty() || compileAs || noWinRT) { - (*this->BuildFileStream) << firstString; - firstString = ""; // only do firstString once - hasFlags = true; - cmGlobalVisualStudio10Generator* gg = - static_cast<cmGlobalVisualStudio10Generator*>(this->GlobalGenerator); + e2.SetHasElements(); + cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator; cmIDEFlagTable const* flagtable = nullptr; const std::string& srclang = source->GetLanguage(); if (srclang == "C" || srclang == "CXX") { @@ -2137,9 +2139,9 @@ bool cmVisualStudio10TargetGenerator::OutputSourceSpecificFlags( cmGeneratorExpressionInterpreter genexInterpreter( this->LocalGenerator, this->GeneratorTarget, config, this->GeneratorTarget->GetName(), lang); - cmVisualStudioGeneratorOptions clOptions( + cmVS10GeneratorOptions clOptions( this->LocalGenerator, cmVisualStudioGeneratorOptions::Compiler, - flagtable, 0, this); + flagtable, this); if (compileAs) { clOptions.AddFlag("CompileAs", compileAs); } @@ -2170,7 +2172,7 @@ bool cmVisualStudio10TargetGenerator::OutputSourceSpecificFlags( clOptions.AddDefines( genexInterpreter.Evaluate(configDefines, "COMPILE_DEFINITIONS")); } else { - clOptions.AddDefines(configDefines.c_str()); + clOptions.AddDefines(configDefines); } std::vector<std::string> includeList; if (configDependentIncludes) { @@ -2182,23 +2184,19 @@ bool cmVisualStudio10TargetGenerator::OutputSourceSpecificFlags( *source); } clOptions.AddIncludes(includeList); - clOptions.SetConfiguration(config.c_str()); + clOptions.SetConfiguration(config); clOptions.PrependInheritedString("AdditionalOptions"); - clOptions.OutputAdditionalIncludeDirectories(*this->BuildFileStream, - " ", "\n", lang); - clOptions.OutputFlagMap(*this->BuildFileStream, " "); - clOptions.OutputPreprocessorDefinitions(*this->BuildFileStream, " ", - "\n", lang); + clOptions.OutputAdditionalIncludeDirectories(*this->BuildFileStream, 3, + lang); + clOptions.OutputFlagMap(*this->BuildFileStream, 3); + clOptions.OutputPreprocessorDefinitions(*this->BuildFileStream, 3, lang); } } if (this->IsXamlSource(source->GetFullPath())) { - (*this->BuildFileStream) << firstString; - firstString = ""; // only do firstString once - hasFlags = true; - this->WriteString("<DependentUpon>", 3); + e2.SetHasElements(); const std::string& fileName = source->GetFullPath(); std::string xamlFileName = fileName.substr(0, fileName.find_last_of(".")); - (*this->BuildFileStream) << xamlFileName << "</DependentUpon>\n"; + this->WriteElem("DependentUpon", xamlFileName, 3); } if (this->ProjectType == csproj) { std::string f = source->GetFullPath(); @@ -2213,25 +2211,22 @@ bool cmVisualStudio10TargetGenerator::OutputSourceSpecificFlags( this->GetCSharpSourceProperties(&sf, sourceFileTags); // write source file specific tags if (!sourceFileTags.empty()) { - hasFlags = true; - (*this->BuildFileStream) << firstString; - firstString = ""; + e2.SetHasElements(); this->WriteCSharpSourceProperties(sourceFileTags); } } - - return hasFlags; } void cmVisualStudio10TargetGenerator::WriteExcludeFromBuild( - std::vector<size_t> const& exclude_configs) + Elem& e2, std::vector<size_t> const& exclude_configs) { + e2.SetHasElements(); for (size_t ci : exclude_configs) { this->WriteString("", 3); (*this->BuildFileStream) << "<ExcludedFromBuild Condition=\"'$(Configuration)|$(Platform)'=='" - << cmVS10EscapeXML(this->Configurations[ci]) << "|" - << cmVS10EscapeXML(this->Platform) << "'\">true</ExcludedFromBuild>\n"; + << cmVS10EscapeAttr(this->Configurations[ci]) << "|" + << cmVS10EscapeAttr(this->Platform) << "'\">true</ExcludedFromBuild>\n"; } } @@ -2246,9 +2241,7 @@ void cmVisualStudio10TargetGenerator::WritePathAndIncrementalLinkOptions() } this->WriteString("<PropertyGroup>\n", 1); - this->WriteString("<_ProjectFileVersion>10.0.20506.1" - "</_ProjectFileVersion>\n", - 2); + this->WriteElem("_ProjectFileVersion", "10.0.20506.1", 2); for (std::string const& config : this->Configurations) { if (ttype >= cmStateEnums::UTILITY) { this->WritePlatformConfigTag("IntDir", config, 2); @@ -2281,6 +2274,55 @@ void cmVisualStudio10TargetGenerator::WritePathAndIncrementalLinkOptions() *this->BuildFileStream << cmVS10EscapeXML(intermediateDir) << "</IntDir>\n"; + if (const char* sdkExecutableDirectories = this->Makefile->GetDefinition( + "CMAKE_VS_SDK_EXECUTABLE_DIRECTORIES")) { + this->WritePlatformConfigTag("ExecutablePath", config, 2); + *this->BuildFileStream << cmVS10EscapeXML(sdkExecutableDirectories) + << "</ExecutablePath>\n"; + } + + if (const char* sdkIncludeDirectories = this->Makefile->GetDefinition( + "CMAKE_VS_SDK_INCLUDE_DIRECTORIES")) { + this->WritePlatformConfigTag("IncludePath", config, 2); + *this->BuildFileStream << cmVS10EscapeXML(sdkIncludeDirectories) + << "</IncludePath>\n"; + } + + if (const char* sdkReferenceDirectories = this->Makefile->GetDefinition( + "CMAKE_VS_SDK_REFERENCE_DIRECTORIES")) { + this->WritePlatformConfigTag("ReferencePath", config, 2); + *this->BuildFileStream << cmVS10EscapeXML(sdkReferenceDirectories) + << "</ReferencePath>\n"; + } + + if (const char* sdkLibraryDirectories = this->Makefile->GetDefinition( + "CMAKE_VS_SDK_LIBRARY_DIRECTORIES")) { + this->WritePlatformConfigTag("LibraryPath", config, 2); + *this->BuildFileStream << cmVS10EscapeXML(sdkLibraryDirectories) + << "</LibraryPath>\n"; + } + + if (const char* sdkLibraryWDirectories = this->Makefile->GetDefinition( + "CMAKE_VS_SDK_LIBRARY_WINRT_DIRECTORIES")) { + this->WritePlatformConfigTag("LibraryWPath", config, 2); + *this->BuildFileStream << cmVS10EscapeXML(sdkLibraryWDirectories) + << "</LibraryWPath>\n"; + } + + if (const char* sdkSourceDirectories = + this->Makefile->GetDefinition("CMAKE_VS_SDK_SOURCE_DIRECTORIES")) { + this->WritePlatformConfigTag("SourcePath", config, 2); + *this->BuildFileStream << cmVS10EscapeXML(sdkSourceDirectories) + << "</SourcePath>\n"; + } + + if (const char* sdkExcludeDirectories = this->Makefile->GetDefinition( + "CMAKE_VS_SDK_EXCLUDE_DIRECTORIES")) { + this->WritePlatformConfigTag("ExcludePath", config, 2); + *this->BuildFileStream << cmVS10EscapeXML(sdkExcludeDirectories) + << "</ExcludePath>\n"; + } + if (const char* workingDir = this->GeneratorTarget->GetProperty( "VS_DEBUGGER_WORKING_DIRECTORY")) { this->WritePlatformConfigTag("LocalDebuggerWorkingDirectory", config, @@ -2289,6 +2331,13 @@ void cmVisualStudio10TargetGenerator::WritePathAndIncrementalLinkOptions() << "</LocalDebuggerWorkingDirectory>\n"; } + if (const char* debuggerCommand = + this->GeneratorTarget->GetProperty("VS_DEBUGGER_COMMAND")) { + this->WritePlatformConfigTag("LocalDebuggerCommand", config, 2); + *this->BuildFileStream << cmVS10EscapeXML(debuggerCommand) + << "</LocalDebuggerCommand>\n"; + } + std::string name = cmSystemTools::GetFilenameWithoutLastExtension(targetNameFull); this->WritePlatformConfigTag("TargetName", config, 2); @@ -2381,8 +2430,7 @@ bool cmVisualStudio10TargetGenerator::ComputeClOptions( // copied from cmLocalVisualStudio7Generator.cxx 805 // TODO: Integrate code below with cmLocalVisualStudio7Generator. - cmGlobalVisualStudio10Generator* gg = - static_cast<cmGlobalVisualStudio10Generator*>(this->GlobalGenerator); + cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator; std::unique_ptr<Options> pOptions; switch (this->ProjectType) { case vcxproj: @@ -2429,15 +2477,11 @@ bool cmVisualStudio10TargetGenerator::ComputeClOptions( std::string baseFlagVar = "CMAKE_"; baseFlagVar += langForClCompile; baseFlagVar += "_FLAGS"; - flags = - this->GeneratorTarget->Target->GetMakefile()->GetRequiredDefinition( - baseFlagVar); + flags = this->Makefile->GetRequiredDefinition(baseFlagVar); std::string flagVar = baseFlagVar + std::string("_") + cmSystemTools::UpperCase(configName); flags += " "; - flags += - this->GeneratorTarget->Target->GetMakefile()->GetRequiredDefinition( - flagVar); + flags += this->Makefile->GetRequiredDefinition(flagVar); this->LocalGenerator->AddCompileOptions(flags, this->GeneratorTarget, langForClCompile, configName); } @@ -2453,8 +2497,7 @@ bool cmVisualStudio10TargetGenerator::ComputeClOptions( this->GeneratorTarget->IsIPOEnabled(linkLanguage, configName); // Get preprocessor definitions for this directory. - std::string defineFlags = - this->GeneratorTarget->Target->GetMakefile()->GetDefineFlags(); + std::string defineFlags = this->Makefile->GetDefineFlags(); if (this->MSTools) { if (this->ProjectType == vcxproj) { clOptions.FixExceptionHandlingDefault(); @@ -2463,6 +2506,22 @@ bool cmVisualStudio10TargetGenerator::ComputeClOptions( clOptions.AddFlag("AssemblerListingLocation", asmLocation); } } + + // check for managed C++ assembly compiler flag. This overrides any + // /clr* compiler flags which may be defined in the flags variable(s). + if (this->ProjectType != csproj) { + // TODO: add check here, if /clr was defined manually and issue + // warning that this is discouraged. + if (auto* clr = + this->GeneratorTarget->GetProperty("COMMON_LANGUAGE_RUNTIME")) { + std::string clrString = clr; + if (!clrString.empty()) { + clrString = ":" + clrString; + } + flags += " /clr" + clrString; + } + } + clOptions.Parse(flags.c_str()); clOptions.Parse(defineFlags.c_str()); std::vector<std::string> targetDefines; @@ -2550,18 +2609,16 @@ void cmVisualStudio10TargetGenerator::WriteClOptions( } this->WriteString("<ClCompile>\n", 2); clOptions.PrependInheritedString("AdditionalOptions"); - clOptions.OutputAdditionalIncludeDirectories( - *this->BuildFileStream, " ", "\n", this->LangForClCompile); - clOptions.OutputFlagMap(*this->BuildFileStream, " "); - clOptions.OutputPreprocessorDefinitions(*this->BuildFileStream, " ", - "\n", this->LangForClCompile); + clOptions.OutputAdditionalIncludeDirectories(*this->BuildFileStream, 3, + this->LangForClCompile); + clOptions.OutputFlagMap(*this->BuildFileStream, 3); + clOptions.OutputPreprocessorDefinitions(*this->BuildFileStream, 3, + this->LangForClCompile); if (this->NsightTegra) { if (const char* processMax = this->GeneratorTarget->GetProperty("ANDROID_PROCESS_MAX")) { - this->WriteString("<ProcessMax>", 3); - *this->BuildFileStream << cmVS10EscapeXML(processMax) - << "</ProcessMax>\n"; + this->WriteElemEscapeXML("ProcessMax", processMax, 3); } } @@ -2569,12 +2626,9 @@ void cmVisualStudio10TargetGenerator::WriteClOptions( cmsys::RegularExpression clangToolset("v[0-9]+_clang_.*"); const char* toolset = this->GlobalGenerator->GetPlatformToolset(); if (toolset && clangToolset.find(toolset)) { - this->WriteString("<ObjectFileName>" - "$(IntDir)%(filename).obj" - "</ObjectFileName>\n", - 3); + this->WriteElem("ObjectFileName", "$(IntDir)%(filename).obj", 3); } else { - this->WriteString("<ObjectFileName>$(IntDir)</ObjectFileName>\n", 3); + this->WriteElem("ObjectFileName", "$(IntDir)", 3); } // If not in debug mode, write the DebugInformationFormat field @@ -2590,9 +2644,7 @@ void cmVisualStudio10TargetGenerator::WriteClOptions( std::string pdb = this->GeneratorTarget->GetCompilePDBPath(configName); if (!pdb.empty()) { ConvertToWindowsSlash(pdb); - this->WriteString("<ProgramDataBaseFileName>", 3); - *this->BuildFileStream << cmVS10EscapeXML(pdb) - << "</ProgramDataBaseFileName>\n"; + this->WriteElemEscapeXML("ProgramDataBaseFileName", pdb, 3); } } @@ -2612,8 +2664,7 @@ bool cmVisualStudio10TargetGenerator::ComputeRcOptions() bool cmVisualStudio10TargetGenerator::ComputeRcOptions( std::string const& configName) { - cmGlobalVisualStudio10Generator* gg = - static_cast<cmGlobalVisualStudio10Generator*>(this->GlobalGenerator); + cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator; auto pOptions = cm::make_unique<Options>( this->LocalGenerator, Options::ResourceCompiler, gg->GetRcFlagTable()); Options& rcOptions = *pOptions; @@ -2647,12 +2698,11 @@ void cmVisualStudio10TargetGenerator::WriteRCOptions( this->WriteString("<ResourceCompile>\n", 2); Options& rcOptions = *(this->RcOptions[configName]); - rcOptions.OutputPreprocessorDefinitions(*this->BuildFileStream, " ", - "\n", "RC"); - rcOptions.OutputAdditionalIncludeDirectories(*this->BuildFileStream, - " ", "\n", "RC"); + rcOptions.OutputPreprocessorDefinitions(*this->BuildFileStream, 3, "RC"); + rcOptions.OutputAdditionalIncludeDirectories(*this->BuildFileStream, 3, + "RC"); rcOptions.PrependInheritedString("AdditionalOptions"); - rcOptions.OutputFlagMap(*this->BuildFileStream, " "); + rcOptions.OutputFlagMap(*this->BuildFileStream, 3); this->WriteString("</ResourceCompile>\n", 2); } @@ -2673,8 +2723,7 @@ bool cmVisualStudio10TargetGenerator::ComputeCudaOptions() bool cmVisualStudio10TargetGenerator::ComputeCudaOptions( std::string const& configName) { - cmGlobalVisualStudio10Generator* gg = - static_cast<cmGlobalVisualStudio10Generator*>(this->GlobalGenerator); + cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator; auto pOptions = cm::make_unique<Options>( this->LocalGenerator, Options::CudaCompiler, gg->GetCudaFlagTable()); Options& cudaOptions = *pOptions; @@ -2690,8 +2739,7 @@ bool cmVisualStudio10TargetGenerator::ComputeCudaOptions( configName); // Get preprocessor definitions for this directory. - std::string defineFlags = - this->GeneratorTarget->Target->GetMakefile()->GetDefineFlags(); + std::string defineFlags = this->Makefile->GetDefineFlags(); cudaOptions.Parse(flags.c_str()); cudaOptions.Parse(defineFlags.c_str()); @@ -2729,6 +2777,20 @@ bool cmVisualStudio10TargetGenerator::ComputeCudaOptions( cudaOptions.AppendFlagString("AdditionalOptions", "-x cu"); } + // Specify the compiler program database file if configured. + std::string pdb = this->GeneratorTarget->GetCompilePDBPath(configName); + if (!pdb.empty()) { + // CUDA does not have a field for this and does not honor the + // ProgramDataBaseFileName field in ClCompile. Work around this + // limitation by creating the directory and passing the flag ourselves. + std::string const pdbDir = cmSystemTools::GetFilenamePath(pdb); + cmSystemTools::MakeDirectory(pdbDir); + pdb = this->ConvertPath(pdb, true); + ConvertToWindowsSlash(pdb); + std::string const clFd = "-Xcompiler=\"-Fd\\\"" + pdb + "\\\"\""; + cudaOptions.AppendFlagString("AdditionalOptions", clFd); + } + // CUDA automatically passes the proper '--machine' flag to nvcc // for the current architecture, but does not reflect this default // in the user-visible IDE settings. Set it explicitly. @@ -2785,12 +2847,11 @@ void cmVisualStudio10TargetGenerator::WriteCudaOptions( this->WriteString("<CudaCompile>\n", 2); Options& cudaOptions = *(this->CudaOptions[configName]); - cudaOptions.OutputAdditionalIncludeDirectories(*this->BuildFileStream, - " ", "\n", "CUDA"); - cudaOptions.OutputPreprocessorDefinitions(*this->BuildFileStream, " ", - "\n", "CUDA"); + cudaOptions.OutputAdditionalIncludeDirectories(*this->BuildFileStream, 3, + "CUDA"); + cudaOptions.OutputPreprocessorDefinitions(*this->BuildFileStream, 3, "CUDA"); cudaOptions.PrependInheritedString("AdditionalOptions"); - cudaOptions.OutputFlagMap(*this->BuildFileStream, " "); + cudaOptions.OutputFlagMap(*this->BuildFileStream, 3); this->WriteString("</CudaCompile>\n", 2); } @@ -2811,8 +2872,7 @@ bool cmVisualStudio10TargetGenerator::ComputeCudaLinkOptions() bool cmVisualStudio10TargetGenerator::ComputeCudaLinkOptions( std::string const& configName) { - cmGlobalVisualStudio10Generator* gg = - static_cast<cmGlobalVisualStudio10Generator*>(this->GlobalGenerator); + cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator; auto pOptions = cm::make_unique<Options>( this->LocalGenerator, Options::CudaCompiler, gg->GetCudaFlagTable()); Options& cudaLinkOptions = *pOptions; @@ -2860,7 +2920,7 @@ void cmVisualStudio10TargetGenerator::WriteCudaLinkOptions( this->WriteString("<CudaLink>\n", 2); Options& cudaLinkOptions = *(this->CudaLinkOptions[configName]); - cudaLinkOptions.OutputFlagMap(*this->BuildFileStream, " "); + cudaLinkOptions.OutputFlagMap(*this->BuildFileStream, 3); this->WriteString("</CudaLink>\n", 2); } @@ -2880,8 +2940,7 @@ bool cmVisualStudio10TargetGenerator::ComputeMasmOptions() bool cmVisualStudio10TargetGenerator::ComputeMasmOptions( std::string const& configName) { - cmGlobalVisualStudio10Generator* gg = - static_cast<cmGlobalVisualStudio10Generator*>(this->GlobalGenerator); + cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator; auto pOptions = cm::make_unique<Options>( this->LocalGenerator, Options::MasmCompiler, gg->GetMasmFlagTable()); Options& masmOptions = *pOptions; @@ -2912,14 +2971,14 @@ void cmVisualStudio10TargetGenerator::WriteMasmOptions( // Preprocessor definitions and includes are shared with clOptions. Options& clOptions = *(this->ClOptions[configName]); - clOptions.OutputPreprocessorDefinitions(*this->BuildFileStream, " ", - "\n", "ASM_MASM"); + clOptions.OutputPreprocessorDefinitions(*this->BuildFileStream, 3, + "ASM_MASM"); Options& masmOptions = *(this->MasmOptions[configName]); - masmOptions.OutputAdditionalIncludeDirectories(*this->BuildFileStream, - " ", "\n", "ASM_MASM"); + masmOptions.OutputAdditionalIncludeDirectories(*this->BuildFileStream, 3, + "ASM_MASM"); masmOptions.PrependInheritedString("AdditionalOptions"); - masmOptions.OutputFlagMap(*this->BuildFileStream, " "); + masmOptions.OutputFlagMap(*this->BuildFileStream, 3); this->WriteString("</MASM>\n", 2); } @@ -2940,8 +2999,7 @@ bool cmVisualStudio10TargetGenerator::ComputeNasmOptions() bool cmVisualStudio10TargetGenerator::ComputeNasmOptions( std::string const& configName) { - cmGlobalVisualStudio10Generator* gg = - static_cast<cmGlobalVisualStudio10Generator*>(this->GlobalGenerator); + cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator; auto pOptions = cm::make_unique<Options>( this->LocalGenerator, Options::NasmCompiler, gg->GetNasmFlagTable()); Options& nasmOptions = *pOptions; @@ -2974,17 +3032,17 @@ void cmVisualStudio10TargetGenerator::WriteNasmOptions( std::vector<std::string> includes = this->GetIncludes(configName, "ASM_NASM"); Options& nasmOptions = *(this->NasmOptions[configName]); - nasmOptions.OutputAdditionalIncludeDirectories(*this->BuildFileStream, - " ", "\n", "ASM_NASM"); - nasmOptions.OutputFlagMap(*this->BuildFileStream, " "); + nasmOptions.OutputAdditionalIncludeDirectories(*this->BuildFileStream, 3, + "ASM_NASM"); + nasmOptions.OutputFlagMap(*this->BuildFileStream, 3); nasmOptions.PrependInheritedString("AdditionalOptions"); - nasmOptions.OutputPreprocessorDefinitions(*this->BuildFileStream, " ", - "\n", "ASM_NASM"); + nasmOptions.OutputPreprocessorDefinitions(*this->BuildFileStream, 3, + "ASM_NASM"); // Preprocessor definitions and includes are shared with clOptions. Options& clOptions = *(this->ClOptions[configName]); - clOptions.OutputPreprocessorDefinitions(*this->BuildFileStream, " ", - "\n", "ASM_NASM"); + clOptions.OutputPreprocessorDefinitions(*this->BuildFileStream, 3, + "ASM_NASM"); this->WriteString("</NASM>\n", 2); } @@ -3001,14 +3059,13 @@ void cmVisualStudio10TargetGenerator::WriteLibOptions( libflags, cmSystemTools::UpperCase(config), this->GeneratorTarget); if (!libflags.empty()) { this->WriteString("<Lib>\n", 2); - cmGlobalVisualStudio10Generator* gg = - static_cast<cmGlobalVisualStudio10Generator*>(this->GlobalGenerator); - cmVisualStudioGeneratorOptions libOptions( - this->LocalGenerator, cmVisualStudioGeneratorOptions::Linker, - gg->GetLibFlagTable(), 0, this); + cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator; + cmVS10GeneratorOptions libOptions(this->LocalGenerator, + cmVisualStudioGeneratorOptions::Linker, + gg->GetLibFlagTable(), this); libOptions.Parse(libflags.c_str()); libOptions.PrependInheritedString("AdditionalOptions"); - libOptions.OutputFlagMap(*this->BuildFileStream, " "); + libOptions.OutputFlagMap(*this->BuildFileStream, 3); this->WriteString("</Lib>\n", 2); } @@ -3018,9 +3075,7 @@ void cmVisualStudio10TargetGenerator::WriteLibOptions( if (this->GlobalGenerator->TargetsWindowsPhone() || this->GlobalGenerator->TargetsWindowsStore()) { this->WriteString("<Link>\n", 2); - this->WriteString("<GenerateWindowsMetadata>false" - "</GenerateWindowsMetadata>\n", - 3); + this->WriteElem("GenerateWindowsMetadata", "false", 3); this->WriteString("</Link>\n", 2); } } @@ -3071,32 +3126,28 @@ void cmVisualStudio10TargetGenerator::WriteAntBuildOptions( { std::string antBuildPath = rootDir; this->WriteString("<AntBuild>\n", 2); - this->WriteString("<AntBuildPath>", 3); ConvertToWindowsSlash(antBuildPath); - (*this->BuildFileStream) << cmVS10EscapeXML(antBuildPath) - << "</AntBuildPath>\n"; + this->WriteElemEscapeXML("AntBuildPath", antBuildPath, 3); } if (this->GeneratorTarget->GetPropertyAsBool("ANDROID_SKIP_ANT_STEP")) { - this->WriteString("<SkipAntStep>true</SkipAntStep>\n", 3); + this->WriteElem("SkipAntStep", "true", 3); } if (this->GeneratorTarget->GetPropertyAsBool("ANDROID_PROGUARD")) { - this->WriteString("<EnableProGuard>true</EnableProGuard>\n", 3); + this->WriteElem("EnableProGuard", "true", 3); } if (const char* proGuardConfigLocation = this->GeneratorTarget->GetProperty("ANDROID_PROGUARD_CONFIG_PATH")) { - this->WriteString("<ProGuardConfigLocation>", 3); - (*this->BuildFileStream) << cmVS10EscapeXML(proGuardConfigLocation) - << "</ProGuardConfigLocation>\n"; + this->WriteElemEscapeXML("ProGuardConfigLocation", proGuardConfigLocation, + 3); } if (const char* securePropertiesLocation = this->GeneratorTarget->GetProperty("ANDROID_SECURE_PROPS_PATH")) { - this->WriteString("<SecurePropertiesLocation>", 3); - (*this->BuildFileStream) << cmVS10EscapeXML(securePropertiesLocation) - << "</SecurePropertiesLocation>\n"; + this->WriteElemEscapeXML("SecurePropertiesLocation", + securePropertiesLocation, 3); } if (const char* nativeLibDirectoriesExpression = @@ -3106,9 +3157,7 @@ void cmVisualStudio10TargetGenerator::WriteAntBuildOptions( ge.Parse(nativeLibDirectoriesExpression); std::string nativeLibDirs = cge->Evaluate(this->LocalGenerator, configName); - this->WriteString("<NativeLibDirectories>", 3); - (*this->BuildFileStream) << cmVS10EscapeXML(nativeLibDirs) - << "</NativeLibDirectories>\n"; + this->WriteElemEscapeXML("NativeLibDirectories", nativeLibDirs, 3); } if (const char* nativeLibDependenciesExpression = @@ -3119,16 +3168,12 @@ void cmVisualStudio10TargetGenerator::WriteAntBuildOptions( ge.Parse(nativeLibDependenciesExpression); std::string nativeLibDeps = cge->Evaluate(this->LocalGenerator, configName); - this->WriteString("<NativeLibDependencies>", 3); - (*this->BuildFileStream) << cmVS10EscapeXML(nativeLibDeps) - << "</NativeLibDependencies>\n"; + this->WriteElemEscapeXML("NativeLibDependencies", nativeLibDeps, 3); } if (const char* javaSourceDir = this->GeneratorTarget->GetProperty("ANDROID_JAVA_SOURCE_DIR")) { - this->WriteString("<JavaSourceDir>", 3); - (*this->BuildFileStream) << cmVS10EscapeXML(javaSourceDir) - << "</JavaSourceDir>\n"; + this->WriteElemEscapeXML("JavaSourceDir", javaSourceDir, 3); } if (const char* jarDirectoriesExpression = @@ -3138,31 +3183,23 @@ void cmVisualStudio10TargetGenerator::WriteAntBuildOptions( ge.Parse(jarDirectoriesExpression); std::string jarDirectories = cge->Evaluate(this->LocalGenerator, configName); - this->WriteString("<JarDirectories>", 3); - (*this->BuildFileStream) << cmVS10EscapeXML(jarDirectories) - << "</JarDirectories>\n"; + this->WriteElemEscapeXML("JarDirectories", jarDirectories, 3); } if (const char* jarDeps = this->GeneratorTarget->GetProperty("ANDROID_JAR_DEPENDENCIES")) { - this->WriteString("<JarDependencies>", 3); - (*this->BuildFileStream) << cmVS10EscapeXML(jarDeps) - << "</JarDependencies>\n"; + this->WriteElemEscapeXML("JarDependencies", jarDeps, 3); } if (const char* assetsDirectories = this->GeneratorTarget->GetProperty("ANDROID_ASSETS_DIRECTORIES")) { - this->WriteString("<AssetsDirectories>", 3); - (*this->BuildFileStream) << cmVS10EscapeXML(assetsDirectories) - << "</AssetsDirectories>\n"; + this->WriteElemEscapeXML("AssetsDirectories", assetsDirectories, 3); } { std::string manifest_xml = rootDir + "/AndroidManifest.xml"; ConvertToWindowsSlash(manifest_xml); - this->WriteString("<AndroidManifestLocation>", 3); - (*this->BuildFileStream) << cmVS10EscapeXML(manifest_xml) - << "</AndroidManifestLocation>\n"; + this->WriteElemEscapeXML("AndroidManifestLocation", manifest_xml, 3); } if (const char* antAdditionalOptions = @@ -3192,11 +3229,9 @@ bool cmVisualStudio10TargetGenerator::ComputeLinkOptions() bool cmVisualStudio10TargetGenerator::ComputeLinkOptions( std::string const& config) { - cmGlobalVisualStudio10Generator* gg = - static_cast<cmGlobalVisualStudio10Generator*>(this->GlobalGenerator); - auto pOptions = - cm::make_unique<Options>(this->LocalGenerator, Options::Linker, - gg->GetLinkFlagTable(), nullptr, this); + cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator; + auto pOptions = cm::make_unique<Options>( + this->LocalGenerator, Options::Linker, gg->GetLinkFlagTable(), this); Options& linkOptions = *pOptions; cmGeneratorTarget::LinkClosure const* linkClosure = @@ -3224,12 +3259,10 @@ bool cmVisualStudio10TargetGenerator::ComputeLinkOptions( linkFlagVarBase += linkType; linkFlagVarBase += "_LINKER_FLAGS"; flags += " "; - flags += this->GeneratorTarget->Target->GetMakefile()->GetRequiredDefinition( - linkFlagVarBase); + flags += this->Makefile->GetRequiredDefinition(linkFlagVarBase); std::string linkFlagVar = linkFlagVarBase + "_" + CONFIG; flags += " "; - flags += this->GeneratorTarget->Target->GetMakefile()->GetRequiredDefinition( - linkFlagVar); + flags += this->Makefile->GetRequiredDefinition(linkFlagVar); const char* targetLinkFlags = this->GeneratorTarget->GetProperty("LINK_FLAGS"); if (targetLinkFlags) { @@ -3383,7 +3416,7 @@ bool cmVisualStudio10TargetGenerator::ComputeLinkOptions( cmGeneratorTarget::ModuleDefinitionInfo const* mdi = this->GeneratorTarget->GetModuleDefinitionInfo(config); if (mdi && !mdi->DefFile.empty()) { - linkOptions.AddFlag("ModuleDefinitionFile", mdi->DefFile.c_str()); + linkOptions.AddFlag("ModuleDefinitionFile", mdi->DefFile); } linkOptions.AppendFlag("IgnoreSpecificDefaultLibraries", "%(IgnoreSpecificDefaultLibraries)"); @@ -3460,14 +3493,13 @@ void cmVisualStudio10TargetGenerator::WriteLinkOptions( this->WriteString("<Link>\n", 2); linkOptions.PrependInheritedString("AdditionalOptions"); - linkOptions.OutputFlagMap(*this->BuildFileStream, " "); + linkOptions.OutputFlagMap(*this->BuildFileStream, 3); this->WriteString("</Link>\n", 2); if (!this->GlobalGenerator->NeedLinkLibraryDependencies( this->GeneratorTarget)) { this->WriteString("<ProjectReference>\n", 2); - this->WriteString( - "<LinkLibraryDependencies>false</LinkLibraryDependencies>\n", 3); + this->WriteElem("LinkLibraryDependencies", "false", 3); this->WriteString("</ProjectReference>\n", 2); } } @@ -3481,6 +3513,17 @@ void cmVisualStudio10TargetGenerator::AddLibraries( std::string currentBinDir = this->LocalGenerator->GetCurrentBinaryDirectory(); for (cmComputeLinkInformation::Item const& l : libs) { + // Do not allow C# targets to be added to the LIB listing. LIB files are + // used for linking C++ dependencies. C# libraries do not have lib files. + // Instead, they compile down to C# reference libraries (DLL files). The + // `<ProjectReference>` elements added to the vcxproj are enough for the + // IDE to deduce the DLL file required by other C# projects that need its + // reference library. + if (l.Target && + cmGlobalVisualStudioGenerator::TargetIsCSharpOnly(l.Target)) { + continue; + } + if (l.IsPath) { std::string path = this->LocalGenerator->ConvertToRelativePath(currentBinDir, l.Value); @@ -3550,15 +3593,11 @@ void cmVisualStudio10TargetGenerator::WriteMidlOptions( this->WriteString("%(AdditionalIncludeDirectories)" "</AdditionalIncludeDirectories>\n", 0); - this->WriteString("<OutputDirectory>$(ProjectDir)/$(IntDir)" - "</OutputDirectory>\n", - 3); - this->WriteString("<HeaderFileName>%(Filename).h</HeaderFileName>\n", 3); - this->WriteString("<TypeLibraryName>%(Filename).tlb</TypeLibraryName>\n", 3); - this->WriteString("<InterfaceIdentifierFileName>" - "%(Filename)_i.c</InterfaceIdentifierFileName>\n", - 3); - this->WriteString("<ProxyFileName>%(Filename)_p.c</ProxyFileName>\n", 3); + this->WriteElem("OutputDirectory", "$(ProjectDir)/$(IntDir)", 3); + this->WriteElem("HeaderFileName", "%(Filename).h", 3); + this->WriteElem("TypeLibraryName", "%(Filename).tlb", 3); + this->WriteElem("InterfaceIdentifierFileName", "%(Filename)_i.c", 3); + this->WriteElem("ProxyFileName", "%(Filename)_p.c", 3); this->WriteString("</Midl>\n", 2); } @@ -3650,8 +3689,7 @@ void cmVisualStudio10TargetGenerator::WriteEvent( } comment = cmVS10EscapeComment(comment); if (this->ProjectType != csproj) { - this->WriteString("<Message>", 3); - (*this->BuildFileStream) << cmVS10EscapeXML(comment) << "</Message>\n"; + this->WriteElemEscapeXML("Message", comment, 3); this->WriteString("<Command>", 3); } else { std::string strippedComment = comment; @@ -3686,8 +3724,7 @@ void cmVisualStudio10TargetGenerator::WriteProjectReferences() } // skip fortran targets as they can not be processed by MSBuild // the only reference will be in the .sln file - if (static_cast<cmGlobalVisualStudioGenerator*>(this->GlobalGenerator) - ->TargetIsFortranOnly(dt)) { + if (this->GlobalGenerator->TargetIsFortranOnly(dt)) { continue; } this->WriteString("<ProjectReference Include=\"", 2); @@ -3704,20 +3741,13 @@ void cmVisualStudio10TargetGenerator::WriteProjectReferences() path += computeProjectFileExtension(dt, *this->Configurations.begin()); } ConvertToWindowsSlash(path); - (*this->BuildFileStream) << cmVS10EscapeXML(path) << "\">\n"; - this->WriteString("<Project>", 3); - (*this->BuildFileStream) << "{" << this->GlobalGenerator->GetGUID(name) - << "}"; - (*this->BuildFileStream) << "</Project>\n"; - this->WriteString("<Name>", 3); - (*this->BuildFileStream) << name << "</Name>\n"; + (*this->BuildFileStream) << cmVS10EscapeAttr(path) << "\">\n"; + this->WriteElem("Project", + "{" + this->GlobalGenerator->GetGUID(name) + "}", 3); + this->WriteElem("Name", name, 3); this->WriteDotNetReferenceCustomTags(name); - if (csproj == this->ProjectType) { - if (!static_cast<cmGlobalVisualStudioGenerator*>(this->GlobalGenerator) - ->TargetCanBeReferenced(dt)) { - this->WriteString( - "<ReferenceOutputAssembly>false</ReferenceOutputAssembly>\n", 3); - } + if (!this->GlobalGenerator->TargetCanBeReferenced(dt)) { + this->WriteElem("ReferenceOutputAssembly", "false", 3); } this->WriteString("</ProjectReference>\n", 2); } @@ -3777,7 +3807,7 @@ void cmVisualStudio10TargetGenerator::WriteSDKReferences() hasWrittenItemGroup = true; for (std::string const& ri : sdkReferences) { this->WriteString("<SDKReference Include=\"", 2); - (*this->BuildFileStream) << cmVS10EscapeXML(ri) << "\"/>\n"; + (*this->BuildFileStream) << cmVS10EscapeAttr(ri) << "\"/>\n"; } } @@ -3846,14 +3876,12 @@ void cmVisualStudio10TargetGenerator::WriteWinRTPackageCertificateKeyFile() this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget); ConvertToWindowsSlash(artifactDir); this->WriteString("<PropertyGroup>\n", 1); - this->WriteString("<AppxPackageArtifactsDir>", 2); - (*this->BuildFileStream) << cmVS10EscapeXML(artifactDir) - << "\\</AppxPackageArtifactsDir>\n"; - this->WriteString("<ProjectPriFullPath>", 2); + this->WriteElemEscapeXML("AppxPackageArtifactsDir", artifactDir + "\\", + 2); std::string resourcePriFile = this->DefaultArtifactDir + "/resources.pri"; ConvertToWindowsSlash(resourcePriFile); - (*this->BuildFileStream) << resourcePriFile << "</ProjectPriFullPath>\n"; + this->WriteElem("ProjectPriFullPath", resourcePriFile, 2); // If we are missing files and we don't have a certificate and // aren't targeting WP8.0, add a default certificate @@ -3867,26 +3895,18 @@ void cmVisualStudio10TargetGenerator::WriteWinRTPackageCertificateKeyFile() this->AddedFiles.push_back(pfxFile); } - this->WriteString("<", 2); - (*this->BuildFileStream) << "PackageCertificateKeyFile>" << pfxFile - << "</PackageCertificateKeyFile>\n"; + this->WriteElem("PackageCertificateKeyFile", pfxFile, 2); std::string thumb = cmSystemTools::ComputeCertificateThumbprint(pfxFile); if (!thumb.empty()) { - this->WriteString("<PackageCertificateThumbprint>", 2); - (*this->BuildFileStream) << thumb - << "</PackageCertificateThumbprint>\n"; + this->WriteElem("PackageCertificateThumbprint", thumb, 2); } this->WriteString("</PropertyGroup>\n", 1); } else if (!pfxFile.empty()) { this->WriteString("<PropertyGroup>\n", 1); - this->WriteString("<", 2); - (*this->BuildFileStream) << "PackageCertificateKeyFile>" << pfxFile - << "</PackageCertificateKeyFile>\n"; + this->WriteElem("PackageCertificateKeyFile", pfxFile, 2); std::string thumb = cmSystemTools::ComputeCertificateThumbprint(pfxFile); if (!thumb.empty()) { - this->WriteString("<PackageCertificateThumbprint>", 2); - (*this->BuildFileStream) << thumb - << "</PackageCertificateThumbprint>\n"; + this->WriteElem("PackageCertificateThumbprint", thumb, 2); } this->WriteString("</PropertyGroup>\n", 1); } @@ -3928,52 +3948,35 @@ bool cmVisualStudio10TargetGenerator::IsXamlSource( void cmVisualStudio10TargetGenerator::WriteApplicationTypeSettings() { - cmGlobalVisualStudio10Generator* gg = - static_cast<cmGlobalVisualStudio10Generator*>(this->GlobalGenerator); + cmGlobalVisualStudio10Generator* gg = this->GlobalGenerator; bool isAppContainer = false; bool const isWindowsPhone = this->GlobalGenerator->TargetsWindowsPhone(); bool const isWindowsStore = this->GlobalGenerator->TargetsWindowsStore(); std::string const& v = this->GlobalGenerator->GetSystemVersion(); if (isWindowsPhone || isWindowsStore) { - this->WriteString("<ApplicationType>", 2); - (*this->BuildFileStream) - << (isWindowsPhone ? "Windows Phone" : "Windows Store") - << "</ApplicationType>\n"; - this->WriteString("<DefaultLanguage>en-US" - "</DefaultLanguage>\n", - 2); + this->WriteElem("ApplicationType", + (isWindowsPhone ? "Windows Phone" : "Windows Store"), 2); + this->WriteElem("DefaultLanguage", "en-US", 2); if (cmHasLiteralPrefix(v, "10.0")) { - this->WriteString("<ApplicationTypeRevision>", 2); - (*this->BuildFileStream) << cmVS10EscapeXML("10.0") - << "</ApplicationTypeRevision>\n"; + this->WriteElemEscapeXML("ApplicationTypeRevision", "10.0", 2); // Visual Studio 14.0 is necessary for building 10.0 apps - this->WriteString("<MinimumVisualStudioVersion>14.0" - "</MinimumVisualStudioVersion>\n", - 2); + this->WriteElem("MinimumVisualStudioVersion", "14.0", 2); if (this->GeneratorTarget->GetType() < cmStateEnums::UTILITY) { isAppContainer = true; } } else if (v == "8.1") { - this->WriteString("<ApplicationTypeRevision>", 2); - (*this->BuildFileStream) << cmVS10EscapeXML(v) - << "</ApplicationTypeRevision>\n"; + this->WriteElemEscapeXML("ApplicationTypeRevision", v, 2); // Visual Studio 12.0 is necessary for building 8.1 apps - this->WriteString("<MinimumVisualStudioVersion>12.0" - "</MinimumVisualStudioVersion>\n", - 2); + this->WriteElem("MinimumVisualStudioVersion", "12.0", 2); if (this->GeneratorTarget->GetType() < cmStateEnums::UTILITY) { isAppContainer = true; } } else if (v == "8.0") { - this->WriteString("<ApplicationTypeRevision>", 2); - (*this->BuildFileStream) << cmVS10EscapeXML(v) - << "</ApplicationTypeRevision>\n"; + this->WriteElemEscapeXML("ApplicationTypeRevision", v, 2); // Visual Studio 11.0 is necessary for building 8.0 apps - this->WriteString("<MinimumVisualStudioVersion>11.0" - "</MinimumVisualStudioVersion>\n", - 2); + this->WriteElem("MinimumVisualStudioVersion", "11.0", 2); if (isWindowsStore && this->GeneratorTarget->GetType() < cmStateEnums::UTILITY) { @@ -3981,52 +3984,42 @@ void cmVisualStudio10TargetGenerator::WriteApplicationTypeSettings() } else if (isWindowsPhone && this->GeneratorTarget->GetType() == cmStateEnums::EXECUTABLE) { - this->WriteString("<XapOutputs>true</XapOutputs>\n", 2); - this->WriteString("<XapFilename>", 2); - (*this->BuildFileStream) - << cmVS10EscapeXML(this->Name) - << "_$(Configuration)_$(Platform).xap</XapFilename>\n"; + this->WriteElem("XapOutputs", "true", 2); + this->WriteElem("XapFilename", cmVS10EscapeXML(this->Name) + + "_$(Configuration)_$(Platform).xap", + 2); } } } if (isAppContainer) { - this->WriteString("<AppContainerApplication>true" - "</AppContainerApplication>\n", - 2); + this->WriteElem("AppContainerApplication", "true", 2); } else if (this->Platform == "ARM64") { - this->WriteString("<WindowsSDKDesktopARM64Support>true" - "</WindowsSDKDesktopARM64Support>\n", - 2); + this->WriteElem("WindowsSDKDesktopARM64Support", "true", 2); } else if (this->Platform == "ARM") { - this->WriteString("<WindowsSDKDesktopARMSupport>true" - "</WindowsSDKDesktopARMSupport>\n", - 2); + this->WriteElem("WindowsSDKDesktopARMSupport", "true", 2); } std::string const& targetPlatformVersion = gg->GetWindowsTargetPlatformVersion(); if (!targetPlatformVersion.empty()) { - this->WriteString("<WindowsTargetPlatformVersion>", 2); - (*this->BuildFileStream) << cmVS10EscapeXML(targetPlatformVersion) - << "</WindowsTargetPlatformVersion>\n"; + this->WriteElemEscapeXML("WindowsTargetPlatformVersion", + targetPlatformVersion, 2); } const char* targetPlatformMinVersion = this->GeneratorTarget->GetProperty( "VS_WINDOWS_TARGET_PLATFORM_MIN_VERSION"); if (targetPlatformMinVersion) { - this->WriteString("<WindowsTargetPlatformMinVersion>", 2); - (*this->BuildFileStream) << cmVS10EscapeXML(targetPlatformMinVersion) - << "</WindowsTargetPlatformMinVersion>\n"; + this->WriteElemEscapeXML("WindowsTargetPlatformMinVersion", + targetPlatformMinVersion, 2); } else if (isWindowsStore && cmHasLiteralPrefix(v, "10.0")) { // If the min version is not set, then use the TargetPlatformVersion if (!targetPlatformVersion.empty()) { - this->WriteString("<WindowsTargetPlatformMinVersion>", 2); - (*this->BuildFileStream) << cmVS10EscapeXML(targetPlatformVersion) - << "</WindowsTargetPlatformMinVersion>\n"; + this->WriteElemEscapeXML("WindowsTargetPlatformMinVersion", + targetPlatformVersion, 2); } } // Added IoT Startup Task support if (this->GeneratorTarget->GetPropertyAsBool("VS_IOT_STARTUP_TASK")) { - this->WriteString("<ContainsStartupTask>true</ContainsStartupTask>\n", 2); + this->WriteElem("ContainsStartupTask", "true", 2); } } @@ -4156,8 +4149,8 @@ void cmVisualStudio10TargetGenerator::WriteMissingFilesWP80() std::string sourceFile = this->ConvertPath(manifestFile, false); ConvertToWindowsSlash(sourceFile); this->WriteString("<Xml Include=\"", 2); - (*this->BuildFileStream) << cmVS10EscapeXML(sourceFile) << "\">\n"; - this->WriteString("<SubType>Designer</SubType>\n", 3); + (*this->BuildFileStream) << cmVS10EscapeAttr(sourceFile) << "\">\n"; + this->WriteElem("SubType", "Designer", 3); this->WriteString("</Xml>\n", 2); this->AddedFiles.push_back(sourceFile); @@ -4166,14 +4159,14 @@ void cmVisualStudio10TargetGenerator::WriteMissingFilesWP80() false); ConvertToWindowsSlash(smallLogo); this->WriteString("<Image Include=\"", 2); - (*this->BuildFileStream) << cmVS10EscapeXML(smallLogo) << "\" />\n"; + (*this->BuildFileStream) << cmVS10EscapeAttr(smallLogo) << "\" />\n"; this->AddedFiles.push_back(smallLogo); std::string logo = this->DefaultArtifactDir + "/Logo.png"; cmSystemTools::CopyAFile(templateFolder + "/Logo.png", logo, false); ConvertToWindowsSlash(logo); this->WriteString("<Image Include=\"", 2); - (*this->BuildFileStream) << cmVS10EscapeXML(logo) << "\" />\n"; + (*this->BuildFileStream) << cmVS10EscapeAttr(logo) << "\" />\n"; this->AddedFiles.push_back(logo); std::string applicationIcon = @@ -4182,7 +4175,7 @@ void cmVisualStudio10TargetGenerator::WriteMissingFilesWP80() applicationIcon, false); ConvertToWindowsSlash(applicationIcon); this->WriteString("<Image Include=\"", 2); - (*this->BuildFileStream) << cmVS10EscapeXML(applicationIcon) << "\" />\n"; + (*this->BuildFileStream) << cmVS10EscapeAttr(applicationIcon) << "\" />\n"; this->AddedFiles.push_back(applicationIcon); } @@ -4434,8 +4427,8 @@ void cmVisualStudio10TargetGenerator::WriteCommonMissingFiles( std::string sourceFile = this->ConvertPath(manifestFile, false); ConvertToWindowsSlash(sourceFile); this->WriteString("<AppxManifest Include=\"", 2); - (*this->BuildFileStream) << cmVS10EscapeXML(sourceFile) << "\">\n"; - this->WriteString("<SubType>Designer</SubType>\n", 3); + (*this->BuildFileStream) << cmVS10EscapeAttr(sourceFile) << "\">\n"; + this->WriteElem("SubType", "Designer", 3); this->WriteString("</AppxManifest>\n", 2); this->AddedFiles.push_back(sourceFile); @@ -4444,7 +4437,7 @@ void cmVisualStudio10TargetGenerator::WriteCommonMissingFiles( false); ConvertToWindowsSlash(smallLogo); this->WriteString("<Image Include=\"", 2); - (*this->BuildFileStream) << cmVS10EscapeXML(smallLogo) << "\" />\n"; + (*this->BuildFileStream) << cmVS10EscapeAttr(smallLogo) << "\" />\n"; this->AddedFiles.push_back(smallLogo); std::string smallLogo44 = this->DefaultArtifactDir + "/SmallLogo44x44.png"; @@ -4452,14 +4445,14 @@ void cmVisualStudio10TargetGenerator::WriteCommonMissingFiles( false); ConvertToWindowsSlash(smallLogo44); this->WriteString("<Image Include=\"", 2); - (*this->BuildFileStream) << cmVS10EscapeXML(smallLogo44) << "\" />\n"; + (*this->BuildFileStream) << cmVS10EscapeAttr(smallLogo44) << "\" />\n"; this->AddedFiles.push_back(smallLogo44); std::string logo = this->DefaultArtifactDir + "/Logo.png"; cmSystemTools::CopyAFile(templateFolder + "/Logo.png", logo, false); ConvertToWindowsSlash(logo); this->WriteString("<Image Include=\"", 2); - (*this->BuildFileStream) << cmVS10EscapeXML(logo) << "\" />\n"; + (*this->BuildFileStream) << cmVS10EscapeAttr(logo) << "\" />\n"; this->AddedFiles.push_back(logo); std::string storeLogo = this->DefaultArtifactDir + "/StoreLogo.png"; @@ -4467,7 +4460,7 @@ void cmVisualStudio10TargetGenerator::WriteCommonMissingFiles( false); ConvertToWindowsSlash(storeLogo); this->WriteString("<Image Include=\"", 2); - (*this->BuildFileStream) << cmVS10EscapeXML(storeLogo) << "\" />\n"; + (*this->BuildFileStream) << cmVS10EscapeAttr(storeLogo) << "\" />\n"; this->AddedFiles.push_back(storeLogo); std::string splashScreen = this->DefaultArtifactDir + "/SplashScreen.png"; @@ -4475,14 +4468,14 @@ void cmVisualStudio10TargetGenerator::WriteCommonMissingFiles( false); ConvertToWindowsSlash(splashScreen); this->WriteString("<Image Include=\"", 2); - (*this->BuildFileStream) << cmVS10EscapeXML(splashScreen) << "\" />\n"; + (*this->BuildFileStream) << cmVS10EscapeAttr(splashScreen) << "\" />\n"; this->AddedFiles.push_back(splashScreen); // This file has already been added to the build so don't copy it std::string keyFile = this->DefaultArtifactDir + "/Windows_TemporaryKey.pfx"; ConvertToWindowsSlash(keyFile); this->WriteString("<None Include=\"", 2); - (*this->BuildFileStream) << cmVS10EscapeXML(keyFile) << "\" />\n"; + (*this->BuildFileStream) << cmVS10EscapeAttr(keyFile) << "\" />\n"; } bool cmVisualStudio10TargetGenerator::ForceOld(const std::string& source) const diff --git a/Source/cmVisualStudio10TargetGenerator.h b/Source/cmVisualStudio10TargetGenerator.h index 33d4fb7..4d74afd 100644 --- a/Source/cmVisualStudio10TargetGenerator.h +++ b/Source/cmVisualStudio10TargetGenerator.h @@ -17,11 +17,11 @@ class cmCustomCommand; class cmGeneratedFileStream; class cmGeneratorTarget; class cmGlobalVisualStudio10Generator; -class cmLocalVisualStudio7Generator; +class cmLocalVisualStudio10Generator; class cmMakefile; class cmSourceFile; class cmSourceGroup; -class cmVisualStudioGeneratorOptions; +class cmVS10GeneratorOptions; class cmVisualStudio10TargetGenerator { @@ -33,9 +33,9 @@ public: ~cmVisualStudio10TargetGenerator(); void Generate(); // used by cmVisualStudioGeneratorOptions + std::string CalcCondition(const std::string& config) const; void WritePlatformConfigTag(const char* tag, const std::string& config, - int indentLevel, const char* attribute = 0, - const char* end = 0, std::ostream* strm = 0); + int indentLevel, const char* attribute = 0); private: struct ToolSource @@ -53,8 +53,14 @@ private: std::vector<std::string> Configs; }; + struct Elem; + std::string ConvertPath(std::string const& path, bool forceRelative); void WriteString(const char* line, int indentLevel); + void WriteElem(const char* tag, const char* val, int indentLevel); + void WriteElem(const char* tag, std::string const& val, int indentLevel); + void WriteElemEscapeXML(const char* tag, std::string const& val, + int indentLevel); void WriteProjectConfigurations(); void WriteProjectConfigurationValues(); void WriteMSToolConfigurationValues(std::string const& config); @@ -62,9 +68,9 @@ private: void WriteHeaderSource(cmSourceFile const* sf); void WriteExtraSource(cmSourceFile const* sf); void WriteNsightTegraConfigurationValues(std::string const& config); - void WriteSource(std::string const& tool, cmSourceFile const* sf, - const char* end = 0); - void WriteExcludeFromBuild(std::vector<size_t> const& exclude_configs); + void WriteSource(std::string const& tool, cmSourceFile const* sf); + void WriteExcludeFromBuild(Elem&, + std::vector<size_t> const& exclude_configs); void WriteAllSources(); void WriteDotNetReferences(); void WriteDotNetReference(std::string const& ref, std::string const& hint); @@ -126,8 +132,8 @@ private: void OutputLinkIncremental(std::string const& configName); void WriteCustomRule(cmSourceFile const* source, cmCustomCommand const& command); - void WriteCustomRuleCpp(std::string const& config, std::string const& script, - std::string const& inputs, + void WriteCustomRuleCpp(Elem& e2, std::string const& config, + std::string const& script, std::string const& inputs, std::string const& outputs, std::string const& comment); void WriteCustomRuleCSharp(std::string const& config, @@ -141,7 +147,7 @@ private: void WriteGroups(); void WriteProjectReferences(); void WriteApplicationTypeSettings(); - bool OutputSourceSpecificFlags(cmSourceFile const* source); + void OutputSourceSpecificFlags(Elem&, cmSourceFile const* source); void AddLibraries(cmComputeLinkInformation& cli, std::vector<std::string>& libVec, std::vector<std::string>& vsTargetVec); @@ -153,7 +159,8 @@ private: void WriteEvent(const char* name, std::vector<cmCustomCommand> const& commands, std::string const& configName); - void WriteGroupSources(const char* name, ToolSources const& sources, + void WriteGroupSources(Elem& e0, std::string const& name, + ToolSources const& sources, std::vector<cmSourceGroup>&); void AddMissingSourceGroups(std::set<cmSourceGroup*>& groupsUsed, const std::vector<cmSourceGroup>& allGroups); @@ -170,7 +177,7 @@ private: void GetCSharpSourceLink(cmSourceFile const* sf, std::string& link); private: - typedef cmVisualStudioGeneratorOptions Options; + typedef cmVS10GeneratorOptions Options; typedef std::map<std::string, std::unique_ptr<Options>> OptionsMap; OptionsMap ClOptions; OptionsMap RcOptions; @@ -190,20 +197,19 @@ private: bool InSourceBuild; std::vector<std::string> Configurations; std::vector<TargetsFileAndConfigs> TargetsFileAndConfigsVec; - cmGeneratorTarget* GeneratorTarget; - cmMakefile* Makefile; - std::string Platform; - std::string GUID; - std::string Name; + cmGeneratorTarget* const GeneratorTarget; + cmMakefile* const Makefile; + std::string const Platform; + std::string const Name; + std::string const GUID; bool MSTools; bool Managed; bool NsightTegra; - int NsightTegraVersion[4]; + unsigned int NsightTegraVersion[4]; bool TargetCompileAsWinRT; - cmGlobalVisualStudio10Generator* GlobalGenerator; + cmGlobalVisualStudio10Generator* const GlobalGenerator; cmGeneratedFileStream* BuildFileStream; - cmLocalVisualStudio7Generator* LocalGenerator; - std::set<cmSourceFile const*> SourcesVisited; + cmLocalVisualStudio10Generator* const LocalGenerator; std::set<std::string> CSharpCustomCommandNames; bool IsMissingFiles; std::vector<std::string> AddedFiles; diff --git a/Source/cmVisualStudioGeneratorOptions.cxx b/Source/cmVisualStudioGeneratorOptions.cxx index ccbff83..3ec3355 100644 --- a/Source/cmVisualStudioGeneratorOptions.cxx +++ b/Source/cmVisualStudioGeneratorOptions.cxx @@ -4,43 +4,19 @@ #include "cmLocalVisualStudioGenerator.h" #include "cmOutputConverter.h" #include "cmSystemTools.h" -#include "cmVisualStudio10TargetGenerator.h" -static std::string cmVisualStudio10GeneratorOptionsEscapeForXML( - std::string ret) +static void cmVS10EscapeForMSBuild(std::string& ret) { cmSystemTools::ReplaceString(ret, ";", "%3B"); - cmSystemTools::ReplaceString(ret, "&", "&"); - cmSystemTools::ReplaceString(ret, "<", "<"); - cmSystemTools::ReplaceString(ret, ">", ">"); - return ret; -} - -static std::string cmVisualStudioGeneratorOptionsEscapeForXML(std::string ret) -{ - cmSystemTools::ReplaceString(ret, "&", "&"); - cmSystemTools::ReplaceString(ret, "\"", """); - cmSystemTools::ReplaceString(ret, "<", "<"); - cmSystemTools::ReplaceString(ret, ">", ">"); - cmSystemTools::ReplaceString(ret, "\n", "
"); - return ret; -} - -cmVisualStudioGeneratorOptions::cmVisualStudioGeneratorOptions( - cmLocalVisualStudioGenerator* lg, Tool tool, - cmVisualStudio10TargetGenerator* g) - : cmVisualStudioGeneratorOptions(lg, tool, nullptr, nullptr, g) -{ } cmVisualStudioGeneratorOptions::cmVisualStudioGeneratorOptions( cmLocalVisualStudioGenerator* lg, Tool tool, cmVS7FlagTable const* table, - cmVS7FlagTable const* extraTable, cmVisualStudio10TargetGenerator* g) + cmVS7FlagTable const* extraTable) : cmIDEOptions() , LocalGenerator(lg) , Version(lg->GetVersion()) , CurrentTool(tool) - , TargetGenerator(g) { // Store the given flag tables. this->AddTable(table); @@ -151,10 +127,9 @@ bool cmVisualStudioGeneratorOptions::IsManaged() const bool cmVisualStudioGeneratorOptions::UsingUnicode() const { - // Look for the a _UNICODE definition. - for (std::vector<std::string>::const_iterator di = this->Defines.begin(); - di != this->Defines.end(); ++di) { - if (*di == "_UNICODE") { + // Look for a _UNICODE definition. + for (std::string const& di : this->Defines) { + if (di == "_UNICODE") { return true; } } @@ -162,10 +137,9 @@ bool cmVisualStudioGeneratorOptions::UsingUnicode() const } bool cmVisualStudioGeneratorOptions::UsingSBCS() const { - // Look for the a _SBCS definition. - for (std::vector<std::string>::const_iterator di = this->Defines.begin(); - di != this->Defines.end(); ++di) { - if (*di == "_SBCS") { + // Look for a _SBCS definition. + for (std::string const& di : this->Defines) { + if (di == "_SBCS") { return true; } } @@ -227,7 +201,7 @@ void cmVisualStudioGeneratorOptions::FixCudaCodeGeneration() // It translates to -arch=<virtual> -code=<real>. cmSystemTools::ReplaceString(arch_name, "sm_", "compute_"); } - for (auto const& c : codes) { + for (std::string const& c : codes) { std::string entry = arch_name + "," + c; result.push_back(entry); } @@ -237,7 +211,7 @@ void cmVisualStudioGeneratorOptions::FixCudaCodeGeneration() // -gencode=<arch>,<code> // -gencode=<arch>,[<code1>,<code2>] // -gencode=<arch>,"<code1>,<code2>" - for (auto const& e : gencode) { + for (std::string const& e : gencode) { std::string entry = e; cmSystemTools::ReplaceString(entry, "arch=", ""); cmSystemTools::ReplaceString(entry, "code=", ""); @@ -285,7 +259,7 @@ void cmVisualStudioGeneratorOptions::FixManifestUACFlags() uacExecuteLevelMap["highestAvailable"] = "HighestAvailable"; uacExecuteLevelMap["requireAdministrator"] = "RequireAdministrator"; - for (auto const& subopt : subOptions) { + for (std::string const& subopt : subOptions) { std::vector<std::string> keyValue; cmsys::SystemTools::Split(subopt, keyValue, '='); if (keyValue.size() != 2 || (uacMap.find(keyValue[0]) == uacMap.end())) { @@ -332,9 +306,8 @@ void cmVisualStudioGeneratorOptions::Parse(const char* flags) // Process flags that need to be represented specially in the IDE // project file. - for (std::vector<std::string>::iterator ai = args.begin(); ai != args.end(); - ++ai) { - this->HandleFlag(ai->c_str()); + for (std::string const& ai : args) { + this->HandleFlag(ai); } } @@ -396,23 +369,23 @@ void cmVisualStudioGeneratorOptions::Reparse(std::string const& key) this->Parse(original.c_str()); } -void cmVisualStudioGeneratorOptions::StoreUnknownFlag(const char* flag) +void cmVisualStudioGeneratorOptions::StoreUnknownFlag(std::string const& flag) { // Look for Intel Fortran flags that do not map well in the flag table. if (this->CurrentTool == FortranCompiler) { - if (strcmp(flag, "/dbglibs") == 0) { + if (flag == "/dbglibs") { this->FortranRuntimeDebug = true; return; } - if (strcmp(flag, "/threads") == 0) { + if (flag == "/threads") { this->FortranRuntimeMT = true; return; } - if (strcmp(flag, "/libs:dll") == 0) { + if (flag == "/libs:dll") { this->FortranRuntimeDLL = true; return; } - if (strcmp(flag, "/libs:static") == 0) { + if (flag == "/libs:static") { this->FortranRuntimeDLL = false; return; } @@ -420,7 +393,7 @@ void cmVisualStudioGeneratorOptions::StoreUnknownFlag(const char* flag) // This option is not known. Store it in the output flags. std::string const opts = cmOutputConverter::EscapeWindowsShellArgument( - flag, cmOutputConverter::Shell_Flag_AllowMakeVariables | + flag.c_str(), cmOutputConverter::Shell_Flag_AllowMakeVariables | cmOutputConverter::Shell_Flag_VSIDE); this->AppendFlagString(this->UnknownFlagField, opts); } @@ -437,14 +410,19 @@ cmIDEOptions::FlagValue cmVisualStudioGeneratorOptions::TakeFlag( return value; } -void cmVisualStudioGeneratorOptions::SetConfiguration(const char* config) +void cmVisualStudioGeneratorOptions::SetConfiguration( + const std::string& config) { this->Configuration = config; } +const std::string& cmVisualStudioGeneratorOptions::GetConfiguration() const +{ + return this->Configuration; +} + void cmVisualStudioGeneratorOptions::OutputPreprocessorDefinitions( - std::ostream& fout, const char* prefix, const char* suffix, - const std::string& lang) + std::ostream& fout, int indent, const std::string& lang) { if (this->Defines.empty()) { return; @@ -453,19 +431,8 @@ void cmVisualStudioGeneratorOptions::OutputPreprocessorDefinitions( if (lang == "CUDA") { tag = "Defines"; } - if (this->Version >= cmGlobalVisualStudioGenerator::VS10) { - // if there are configuration specific flags, then - // use the configuration specific tag for PreprocessorDefinitions - if (!this->Configuration.empty()) { - fout << prefix; - this->TargetGenerator->WritePlatformConfigTag( - tag, this->Configuration.c_str(), 0, 0, 0, &fout); - } else { - fout << prefix << "<" << tag << ">"; - } - } else { - fout << prefix << tag << "=\""; - } + + std::ostringstream oss; const char* sep = ""; std::vector<std::string>::const_iterator de = cmRemoveDuplicates(this->Defines); @@ -474,34 +441,30 @@ void cmVisualStudioGeneratorOptions::OutputPreprocessorDefinitions( // Escape the definition for the compiler. std::string define; if (this->Version < cmGlobalVisualStudioGenerator::VS10) { - define = this->LocalGenerator->EscapeForShell(di->c_str(), true); + define = this->LocalGenerator->EscapeForShell(*di, true); } else { define = *di; } - // Escape this flag for the IDE. + // Escape this flag for the MSBuild. if (this->Version >= cmGlobalVisualStudioGenerator::VS10) { - define = cmVisualStudio10GeneratorOptionsEscapeForXML(define); - + cmVS10EscapeForMSBuild(define); if (lang == "RC") { cmSystemTools::ReplaceString(define, "\"", "\\\""); } - } else { - define = cmVisualStudioGeneratorOptionsEscapeForXML(define); } // Store the flag in the project file. - fout << sep << define; + oss << sep << define; sep = ";"; } if (this->Version >= cmGlobalVisualStudioGenerator::VS10) { - fout << ";%(" << tag << ")</" << tag << ">" << suffix; - } else { - fout << "\"" << suffix; + oss << ";%(" << tag << ")"; } + + this->OutputFlag(fout, indent, tag, oss.str()); } void cmVisualStudioGeneratorOptions::OutputAdditionalIncludeDirectories( - std::ostream& fout, const char* prefix, const char* suffix, - const std::string& lang) + std::ostream& fout, int indent, const std::string& lang) { if (this->Includes.empty()) { return; @@ -514,20 +477,7 @@ void cmVisualStudioGeneratorOptions::OutputAdditionalIncludeDirectories( tag = "IncludePaths"; } - if (this->Version >= cmGlobalVisualStudioGenerator::VS10) { - // if there are configuration specific flags, then - // use the configuration specific tag for PreprocessorDefinitions - if (!this->Configuration.empty()) { - fout << prefix; - this->TargetGenerator->WritePlatformConfigTag( - tag, this->Configuration.c_str(), 0, 0, 0, &fout); - } else { - fout << prefix << "<" << tag << ">"; - } - } else { - fout << prefix << tag << "=\""; - } - + std::ostringstream oss; const char* sep = ""; for (std::string include : this->Includes) { // first convert all of the slashes @@ -541,59 +491,40 @@ void cmVisualStudioGeneratorOptions::OutputAdditionalIncludeDirectories( include += "\\"; } - // Escape this include for the IDE. - fout << sep << (this->Version >= cmGlobalVisualStudioGenerator::VS10 - ? cmVisualStudio10GeneratorOptionsEscapeForXML(include) - : cmVisualStudioGeneratorOptionsEscapeForXML(include)); + // Escape this include for the MSBuild. + if (this->Version >= cmGlobalVisualStudioGenerator::VS10) { + cmVS10EscapeForMSBuild(include); + } + oss << sep << include; sep = ";"; if (lang == "Fortran") { include += "/$(ConfigurationName)"; - fout << sep << (this->Version >= cmGlobalVisualStudioGenerator::VS10 - ? cmVisualStudio10GeneratorOptionsEscapeForXML(include) - : cmVisualStudioGeneratorOptionsEscapeForXML(include)); + oss << sep << include; } } if (this->Version >= cmGlobalVisualStudioGenerator::VS10) { - fout << sep << "%(" << tag << ")</" << tag << ">" << suffix; - } else { - fout << "\"" << suffix; + oss << sep << "%(" << tag << ")"; } + + this->OutputFlag(fout, indent, tag, oss.str()); } void cmVisualStudioGeneratorOptions::OutputFlagMap(std::ostream& fout, - const char* indent) + int indent) { - if (this->Version >= cmGlobalVisualStudioGenerator::VS10) { - for (std::map<std::string, FlagValue>::iterator m = this->FlagMap.begin(); - m != this->FlagMap.end(); ++m) { - fout << indent; - if (!this->Configuration.empty()) { - this->TargetGenerator->WritePlatformConfigTag( - m->first.c_str(), this->Configuration.c_str(), 0, 0, 0, &fout); - } else { - fout << "<" << m->first << ">"; + for (auto const& m : this->FlagMap) { + std::ostringstream oss; + const char* sep = ""; + for (std::string i : m.second) { + if (this->Version >= cmGlobalVisualStudioGenerator::VS10) { + cmVS10EscapeForMSBuild(i); } - const char* sep = ""; - for (std::vector<std::string>::iterator i = m->second.begin(); - i != m->second.end(); ++i) { - fout << sep << cmVisualStudio10GeneratorOptionsEscapeForXML(*i); - sep = ";"; - } - fout << "</" << m->first << ">\n"; - } - } else { - for (std::map<std::string, FlagValue>::iterator m = this->FlagMap.begin(); - m != this->FlagMap.end(); ++m) { - fout << indent << m->first << "=\""; - const char* sep = ""; - for (std::vector<std::string>::iterator i = m->second.begin(); - i != m->second.end(); ++i) { - fout << sep << cmVisualStudioGeneratorOptionsEscapeForXML(*i); - sep = ";"; - } - fout << "\"\n"; + oss << sep << i; + sep = ";"; } + + this->OutputFlag(fout, indent, m.first.c_str(), oss.str()); } } diff --git a/Source/cmVisualStudioGeneratorOptions.h b/Source/cmVisualStudioGeneratorOptions.h index 2dffe9b..c6b594d 100644 --- a/Source/cmVisualStudioGeneratorOptions.h +++ b/Source/cmVisualStudioGeneratorOptions.h @@ -16,8 +16,6 @@ class cmLocalVisualStudioGenerator; typedef cmIDEFlagTable cmVS7FlagTable; -class cmVisualStudio10TargetGenerator; - class cmVisualStudioGeneratorOptions : public cmIDEOptions { public: @@ -34,12 +32,8 @@ public: CSharpCompiler }; cmVisualStudioGeneratorOptions(cmLocalVisualStudioGenerator* lg, Tool tool, - cmVS7FlagTable const* table, - cmVS7FlagTable const* extraTable = 0, - cmVisualStudio10TargetGenerator* g = 0); - - cmVisualStudioGeneratorOptions(cmLocalVisualStudioGenerator* lg, Tool tool, - cmVisualStudio10TargetGenerator* g = 0); + cmVS7FlagTable const* table = nullptr, + cmVS7FlagTable const* extraTable = nullptr); // Add a table of flags. void AddTable(cmVS7FlagTable const* table); @@ -83,15 +77,17 @@ public: bool IsWinRt() const; bool IsManaged() const; // Write options to output. - void OutputPreprocessorDefinitions(std::ostream& fout, const char* prefix, - const char* suffix, + void OutputPreprocessorDefinitions(std::ostream& fout, int indent, const std::string& lang); - void OutputAdditionalIncludeDirectories(std::ostream& fout, - const char* prefix, - const char* suffix, + void OutputAdditionalIncludeDirectories(std::ostream& fout, int indent, const std::string& lang); - void OutputFlagMap(std::ostream& fout, const char* indent); - void SetConfiguration(const char* config); + void OutputFlagMap(std::ostream& fout, int indent); + void SetConfiguration(const std::string& config); + const std::string& GetConfiguration() const; + +protected: + virtual void OutputFlag(std::ostream& fout, int indent, const char* tag, + const std::string& content) = 0; private: cmLocalVisualStudioGenerator* LocalGenerator; @@ -99,7 +95,6 @@ private: std::string Configuration; Tool CurrentTool; - cmVisualStudio10TargetGenerator* TargetGenerator; bool FortranRuntimeDebug; bool FortranRuntimeDLL; @@ -107,7 +102,7 @@ private: std::string UnknownFlagField; - virtual void StoreUnknownFlag(const char* flag); + void StoreUnknownFlag(std::string const& flag) override; FlagValue TakeFlag(std::string const& key); }; diff --git a/Source/cmWorkingDirectory.cxx b/Source/cmWorkingDirectory.cxx index 99c9ba8..816f104 100644 --- a/Source/cmWorkingDirectory.cxx +++ b/Source/cmWorkingDirectory.cxx @@ -4,10 +4,12 @@ #include "cmSystemTools.h" +#include <cerrno> + cmWorkingDirectory::cmWorkingDirectory(std::string const& newdir) { this->OldDir = cmSystemTools::GetCurrentWorkingDirectory(); - cmSystemTools::ChangeDirectory(newdir); + this->SetDirectory(newdir); } cmWorkingDirectory::~cmWorkingDirectory() @@ -15,10 +17,20 @@ cmWorkingDirectory::~cmWorkingDirectory() this->Pop(); } +bool cmWorkingDirectory::SetDirectory(std::string const& newdir) +{ + if (cmSystemTools::ChangeDirectory(newdir) == 0) { + this->ResultCode = 0; + return true; + } + this->ResultCode = errno; + return false; +} + void cmWorkingDirectory::Pop() { if (!this->OldDir.empty()) { - cmSystemTools::ChangeDirectory(this->OldDir); + this->SetDirectory(this->OldDir); this->OldDir.clear(); } } diff --git a/Source/cmWorkingDirectory.h b/Source/cmWorkingDirectory.h index aff9267..1f18ce7 100644 --- a/Source/cmWorkingDirectory.h +++ b/Source/cmWorkingDirectory.h @@ -9,6 +9,12 @@ /** \class cmWorkingDirectory * \brief An RAII class to manipulate the working directory. + * + * The current working directory is set to the location given to the + * constructor. The working directory can be changed again as needed + * by calling SetDirectory(). When the object is destroyed, the destructor + * will restore the working directory to what it was when the object was + * created, regardless of any calls to SetDirectory() in the meantime. */ class cmWorkingDirectory { @@ -16,10 +22,21 @@ public: cmWorkingDirectory(std::string const& newdir); ~cmWorkingDirectory(); + bool SetDirectory(std::string const& newdir); void Pop(); + bool Failed() const { return ResultCode != 0; } + + /** \return 0 if the last attempt to set the working directory was + * successful. If it failed, the value returned will be the + * \c errno value associated with the failure. A description + * of the error code can be obtained by passing the result + * to \c std::strerror(). + */ + int GetLastResult() const { return ResultCode; } private: std::string OldDir; + int ResultCode; }; #endif diff --git a/Source/cmXMLWriter.cxx b/Source/cmXMLWriter.cxx index 3cbc70d..9d2a3c4 100644 --- a/Source/cmXMLWriter.cxx +++ b/Source/cmXMLWriter.cxx @@ -9,6 +9,7 @@ cmXMLWriter::cmXMLWriter(std::ostream& output, std::size_t level) : Output(output) , IndentationElement(1, '\t') , Level(level) + , Indent(0) , ElementOpen(false) , BreakAttrib(false) , IsContent(false) @@ -17,7 +18,7 @@ cmXMLWriter::cmXMLWriter(std::ostream& output, std::size_t level) cmXMLWriter::~cmXMLWriter() { - assert(this->Elements.empty()); + assert(this->Indent == 0); } void cmXMLWriter::StartDocument(const char* encoding) @@ -27,27 +28,29 @@ void cmXMLWriter::StartDocument(const char* encoding) void cmXMLWriter::EndDocument() { - assert(this->Elements.empty()); + assert(this->Indent == 0); this->Output << '\n'; } void cmXMLWriter::StartElement(std::string const& name) { this->CloseStartElement(); - this->ConditionalLineBreak(!this->IsContent, this->Elements.size()); + this->ConditionalLineBreak(!this->IsContent); this->Output << '<' << name; this->Elements.push(name); + ++this->Indent; this->ElementOpen = true; this->BreakAttrib = false; } void cmXMLWriter::EndElement() { - assert(!this->Elements.empty()); + assert(this->Indent > 0); + --this->Indent; if (this->ElementOpen) { this->Output << "/>"; } else { - this->ConditionalLineBreak(!this->IsContent, this->Elements.size() - 1); + this->ConditionalLineBreak(!this->IsContent); this->IsContent = false; this->Output << "</" << this->Elements.top() << '>'; } @@ -58,7 +61,7 @@ void cmXMLWriter::EndElement() void cmXMLWriter::Element(const char* name) { this->CloseStartElement(); - this->ConditionalLineBreak(!this->IsContent, this->Elements.size()); + this->ConditionalLineBreak(!this->IsContent); this->Output << '<' << name << "/>"; } @@ -70,7 +73,7 @@ void cmXMLWriter::BreakAttributes() void cmXMLWriter::Comment(const char* comment) { this->CloseStartElement(); - this->ConditionalLineBreak(!this->IsContent, this->Elements.size()); + this->ConditionalLineBreak(!this->IsContent); this->Output << "<!-- " << comment << " -->"; } @@ -83,14 +86,14 @@ void cmXMLWriter::CData(std::string const& data) void cmXMLWriter::Doctype(const char* doctype) { this->CloseStartElement(); - this->ConditionalLineBreak(!this->IsContent, this->Elements.size()); + this->ConditionalLineBreak(!this->IsContent); this->Output << "<!DOCTYPE " << doctype << ">"; } void cmXMLWriter::ProcessingInstruction(const char* target, const char* data) { this->CloseStartElement(); - this->ConditionalLineBreak(!this->IsContent, this->Elements.size()); + this->ConditionalLineBreak(!this->IsContent); this->Output << "<?" << target << ' ' << data << "?>"; } @@ -106,11 +109,11 @@ void cmXMLWriter::SetIndentationElement(std::string const& element) this->IndentationElement = element; } -void cmXMLWriter::ConditionalLineBreak(bool condition, std::size_t indent) +void cmXMLWriter::ConditionalLineBreak(bool condition) { if (condition) { this->Output << '\n'; - for (std::size_t i = 0; i < indent + this->Level; ++i) { + for (std::size_t i = 0; i < this->Indent + this->Level; ++i) { this->Output << this->IndentationElement; } } @@ -119,7 +122,7 @@ void cmXMLWriter::ConditionalLineBreak(bool condition, std::size_t indent) void cmXMLWriter::PreAttribute() { assert(this->ElementOpen); - this->ConditionalLineBreak(this->BreakAttrib, this->Elements.size()); + this->ConditionalLineBreak(this->BreakAttrib); if (!this->BreakAttrib) { this->Output << ' '; } @@ -134,7 +137,7 @@ void cmXMLWriter::PreContent() void cmXMLWriter::CloseStartElement() { if (this->ElementOpen) { - this->ConditionalLineBreak(this->BreakAttrib, this->Elements.size()); + this->ConditionalLineBreak(this->BreakAttrib); this->Output << '>'; this->ElementOpen = false; } diff --git a/Source/cmXMLWriter.h b/Source/cmXMLWriter.h index 7bae21e..ff0df18 100644 --- a/Source/cmXMLWriter.h +++ b/Source/cmXMLWriter.h @@ -67,7 +67,7 @@ public: void SetIndentationElement(std::string const& element); private: - void ConditionalLineBreak(bool condition, std::size_t indent); + void ConditionalLineBreak(bool condition); void PreAttribute(); void PreContent(); @@ -128,9 +128,62 @@ private: std::stack<std::string, std::vector<std::string>> Elements; std::string IndentationElement; std::size_t Level; + std::size_t Indent; bool ElementOpen; bool BreakAttrib; bool IsContent; }; +class cmXMLElement; // IWYU pragma: keep + +class cmXMLDocument +{ +public: + cmXMLDocument(cmXMLWriter& xml) + : xmlwr(xml) + { + xmlwr.StartDocument(); + } + ~cmXMLDocument() { xmlwr.EndDocument(); } +private: + friend class cmXMLElement; + cmXMLWriter& xmlwr; +}; + +class cmXMLElement +{ +public: + cmXMLElement(cmXMLWriter& xml, const char* tag) + : xmlwr(xml) + { + xmlwr.StartElement(tag); + } + cmXMLElement(cmXMLElement& par, const char* tag) + : xmlwr(par.xmlwr) + { + xmlwr.StartElement(tag); + } + cmXMLElement(cmXMLDocument& doc, const char* tag) + : xmlwr(doc.xmlwr) + { + xmlwr.StartElement(tag); + } + ~cmXMLElement() { xmlwr.EndElement(); } + + template <typename T> + cmXMLElement& Attribute(const char* name, T const& value) + { + xmlwr.Attribute(name, value); + return *this; + } + template <typename T> + void Content(T const& content) + { + xmlwr.Content(content); + } + +private: + cmXMLWriter& xmlwr; +}; + #endif diff --git a/Source/cmake.cxx b/Source/cmake.cxx index 5620723..5bae4e7 100644 --- a/Source/cmake.cxx +++ b/Source/cmake.cxx @@ -55,7 +55,6 @@ #include "cmGlobalVisualStudio12Generator.h" #include "cmGlobalVisualStudio14Generator.h" #include "cmGlobalVisualStudio15Generator.h" -#include "cmGlobalVisualStudio8Generator.h" #include "cmGlobalVisualStudio9Generator.h" #include "cmVSSetupHelper.h" @@ -98,13 +97,13 @@ #include "cmsys/Glob.hxx" #include "cmsys/RegularExpression.hxx" #include <algorithm> +#include <cstring> #include <iostream> #include <iterator> #include <memory> // IWYU pragma: keep #include <sstream> #include <stdio.h> #include <stdlib.h> -#include <string.h> #include <utility> namespace { @@ -1434,6 +1433,7 @@ int cmake::ActualConfigure() // only save the cache if there were no fatal errors if (this->GetWorkingMode() == NORMAL_MODE) { + this->State->SaveVerificationScript(this->GetHomeOutputDirectory()); this->SaveCache(this->GetHomeOutputDirectory()); } if (cmSystemTools::GetErrorOccuredFlag()) { @@ -1464,8 +1464,7 @@ void cmake::CreateDefaultGlobalGenerator() { "12.0", "Visual Studio 12 2013" }, // { "11.0", "Visual Studio 11 2012" }, // { "10.0", "Visual Studio 10 2010" }, // - { "9.0", "Visual Studio 9 2008" }, // - { "8.0", "Visual Studio 8 2005" } + { "9.0", "Visual Studio 9 2008" } }; static const char* const vsEntries[] = { "\\Setup\\VC;ProductDir", // @@ -1649,6 +1648,33 @@ void cmake::AddCacheEntry(const std::string& key, const char* value, this->UnwatchUnusedCli(key); } +bool cmake::DoWriteGlobVerifyTarget() const +{ + return this->State->DoWriteGlobVerifyTarget(); +} + +std::string const& cmake::GetGlobVerifyScript() const +{ + return this->State->GetGlobVerifyScript(); +} + +std::string const& cmake::GetGlobVerifyStamp() const +{ + return this->State->GetGlobVerifyStamp(); +} + +void cmake::AddGlobCacheEntry(bool recurse, bool listDirectories, + bool followSymlinks, const std::string& relative, + const std::string& expression, + const std::vector<std::string>& files, + const std::string& variable, + cmListFileBacktrace const& backtrace) +{ + this->State->AddGlobCacheEntry(recurse, listDirectories, followSymlinks, + relative, expression, files, variable, + backtrace); +} + std::string cmake::StripExtension(const std::string& file) const { auto dotpos = file.rfind('.'); @@ -1689,7 +1715,6 @@ void cmake::AddDefaultGenerators() this->Generators.push_back(cmGlobalVisualStudio11Generator::NewFactory()); this->Generators.push_back(cmGlobalVisualStudio10Generator::NewFactory()); this->Generators.push_back(cmGlobalVisualStudio9Generator::NewFactory()); - this->Generators.push_back(cmGlobalVisualStudio8Generator::NewFactory()); this->Generators.push_back(cmGlobalBorlandMakefileGenerator::NewFactory()); this->Generators.push_back(cmGlobalNMakeMakefileGenerator::NewFactory()); this->Generators.push_back(cmGlobalJOMMakefileGenerator::NewFactory()); @@ -2209,6 +2234,15 @@ int cmake::GetSystemInformation(std::vector<std::string>& args) { // now run cmake on the CMakeLists file cmWorkingDirectory workdir(destPath); + if (workdir.Failed()) { + // We created the directory and we were able to copy the CMakeLists.txt + // file to it, so we wouldn't expect to get here unless the default + // permissions are questionable or some other process has deleted the + // directory + std::cerr << "Failed to change to directory " << destPath << " : " + << std::strerror(workdir.GetLastResult()) << std::endl; + return 1; + } std::vector<std::string> args2; args2.push_back(args[0]); args2.push_back(destPath); @@ -2387,17 +2421,17 @@ int cmake::Build(const std::string& dir, const std::string& target, std::cerr << "Error: could not find CMAKE_GENERATOR in Cache\n"; return 1; } - std::unique_ptr<cmGlobalGenerator> gen( - this->CreateGlobalGenerator(cachedGenerator)); - if (!gen.get()) { + cmGlobalGenerator* gen = this->CreateGlobalGenerator(cachedGenerator); + if (!gen) { std::cerr << "Error: could create CMAKE_GENERATOR \"" << cachedGenerator << "\"\n"; return 1; } + this->SetGlobalGenerator(gen); const char* cachedGeneratorInstance = this->State->GetCacheEntryValue("CMAKE_GENERATOR_INSTANCE"); if (cachedGeneratorInstance) { - cmMakefile mf(gen.get(), this->GetCurrentSnapshot()); + cmMakefile mf(gen, this->GetCurrentSnapshot()); if (!gen->SetGeneratorInstance(cachedGeneratorInstance, &mf)) { return 1; } @@ -2425,40 +2459,52 @@ int cmake::Build(const std::string& dir, const std::string& target, // to limitations of the underlying build system. std::string const stampList = cachePath + "/" + GetCMakeFilesDirectoryPostSlash() + - cmGlobalVisualStudio8Generator::GetGenerateStampList(); + cmGlobalVisualStudio9Generator::GetGenerateStampList(); // Note that the stampList file only exists for VS generators. - if (cmSystemTools::FileExists(stampList) && - !cmakeCheckStampList(stampList.c_str(), false)) { - - // Correctly initialize the home (=source) and home output (=binary) - // directories, which is required for running the generation step. - std::string homeOrig = this->GetHomeDirectory(); - std::string homeOutputOrig = this->GetHomeOutputDirectory(); - this->SetDirectoriesFromFile(cachePath.c_str()); + if (cmSystemTools::FileExists(stampList)) { + // Check if running for Visual Studio 9 - we need to explicitly run + // the glob verification script before starting the build this->AddScriptingCommands(); - this->AddProjectCommands(); + if (this->GlobalGenerator->MatchesGeneratorName("Visual Studio 9 2008")) { + std::string const globVerifyScript = cachePath + "/" + + GetCMakeFilesDirectoryPostSlash() + "VerifyGlobs.cmake"; + if (cmSystemTools::FileExists(globVerifyScript)) { + std::vector<std::string> args; + this->ReadListFile(args, globVerifyScript.c_str()); + } + } - int ret = this->Configure(); - if (ret) { - cmSystemTools::Message("CMake Configure step failed. " - "Build files cannot be regenerated correctly."); - return ret; - } - ret = this->Generate(); - if (ret) { - cmSystemTools::Message("CMake Generate step failed. " - "Build files cannot be regenerated correctly."); - return ret; - } - std::string message = "Build files have been written to: "; - message += this->GetHomeOutputDirectory(); - this->UpdateProgress(message.c_str(), -1); - - // Restore the previously set directories to their original value. - this->SetHomeDirectory(homeOrig); - this->SetHomeOutputDirectory(homeOutputOrig); + if (!cmakeCheckStampList(stampList.c_str(), false)) { + // Correctly initialize the home (=source) and home output (=binary) + // directories, which is required for running the generation step. + std::string homeOrig = this->GetHomeDirectory(); + std::string homeOutputOrig = this->GetHomeOutputDirectory(); + this->SetDirectoriesFromFile(cachePath.c_str()); + + this->AddProjectCommands(); + + int ret = this->Configure(); + if (ret) { + cmSystemTools::Message("CMake Configure step failed. " + "Build files cannot be regenerated correctly."); + return ret; + } + ret = this->Generate(); + if (ret) { + cmSystemTools::Message("CMake Generate step failed. " + "Build files cannot be regenerated correctly."); + return ret; + } + std::string message = "Build files have been written to: "; + message += this->GetHomeOutputDirectory(); + this->UpdateProgress(message.c_str(), -1); + + // Restore the previously set directories to their original value. + this->SetHomeDirectory(homeOrig); + this->SetHomeOutputDirectory(homeOutputOrig); + } } #endif diff --git a/Source/cmake.h b/Source/cmake.h index 1ac549b..63dbe9f 100644 --- a/Source/cmake.h +++ b/Source/cmake.h @@ -255,6 +255,16 @@ public: void AddCacheEntry(const std::string& key, const char* value, const char* helpString, int type); + bool DoWriteGlobVerifyTarget() const; + std::string const& GetGlobVerifyScript() const; + std::string const& GetGlobVerifyStamp() const; + void AddGlobCacheEntry(bool recurse, bool listDirectories, + bool followSymlinks, const std::string& relative, + const std::string& expression, + const std::vector<std::string>& files, + const std::string& variable, + cmListFileBacktrace const& bt); + /** * Get the system information and write it to the file specified */ @@ -574,6 +584,7 @@ private: F(cxx_std_11) \ F(cxx_std_14) \ F(cxx_std_17) \ + F(cxx_std_20) \ F(cxx_aggregate_default_initializers) \ F(cxx_alias_templates) \ F(cxx_alignas) \ diff --git a/Source/cmcmd.cxx b/Source/cmcmd.cxx index 0988c3c..6f3a90f 100644 --- a/Source/cmcmd.cxx +++ b/Source/cmcmd.cxx @@ -359,7 +359,8 @@ struct CoCompileJob int cmcmd::HandleCoCompileCommands(std::vector<std::string>& args) { std::vector<CoCompileJob> jobs; - std::string sourceFile; // store --source= + std::string sourceFile; // store --source= + std::vector<std::string> launchers; // store --launcher= // Default is to run the original command found after -- if the option // does not need to do that, it should be specified here, currently only @@ -390,15 +391,17 @@ int cmcmd::HandleCoCompileCommands(std::vector<std::string>& args) } } } - if (cmHasLiteralPrefix(arg, "--source=")) { - sourceFile = arg.substr(9); - optionFound = true; - } - // if it was not a co-compiler or --source then error if (!optionFound) { - std::cerr << "__run_co_compile given unknown argument: " << arg - << "\n"; - return 1; + if (cmHasLiteralPrefix(arg, "--source=")) { + sourceFile = arg.substr(9); + } else if (cmHasLiteralPrefix(arg, "--launcher=")) { + cmSystemTools::ExpandListArgument(arg.substr(11), launchers, true); + } else { + // if it was not a co-compiler or --source/--launcher then error + std::cerr << "__run_co_compile given unknown argument: " << arg + << "\n"; + return 1; + } } } else { // if not doing_options then push to orig_cmd orig_cmd.push_back(arg); @@ -436,6 +439,11 @@ int cmcmd::HandleCoCompileCommands(std::vector<std::string>& args) return 0; } + // Prepend launcher argument(s), if any + if (!launchers.empty()) { + orig_cmd.insert(orig_cmd.begin(), launchers.begin(), launchers.end()); + } + // Now run the real compiler command and return its result value int ret; if (!cmSystemTools::RunSingleCommand(orig_cmd, nullptr, nullptr, &ret, @@ -689,8 +697,6 @@ int cmcmd::ExecuteCMakeCommand(std::vector<std::string>& args) // Touch file if (args[1] == "touch_nocreate" && args.size() > 2) { for (std::string::size_type cc = 2; cc < args.size(); cc++) { - // Complain if the file could not be removed, still exists, - // and the -f option was not given. if (!cmSystemTools::Touch(args[cc], false)) { return 1; } diff --git a/Source/kwsys/SystemInformation.cxx b/Source/kwsys/SystemInformation.cxx index 2b9d7b1..7426816 100644 --- a/Source/kwsys/SystemInformation.cxx +++ b/Source/kwsys/SystemInformation.cxx @@ -94,7 +94,6 @@ typedef int siginfo_t; #endif #ifdef __APPLE__ -#include <fenv.h> #include <mach/host_info.h> #include <mach/mach.h> #include <mach/mach_types.h> @@ -114,7 +113,6 @@ typedef int siginfo_t; #endif #if defined(__linux) || defined(__sun) || defined(_SCO_DS) -#include <fenv.h> #include <netdb.h> #include <netinet/in.h> #include <sys/socket.h> diff --git a/Source/kwsys/SystemTools.cxx b/Source/kwsys/SystemTools.cxx index 106afe5..52f509a 100644 --- a/Source/kwsys/SystemTools.cxx +++ b/Source/kwsys/SystemTools.cxx @@ -3344,15 +3344,20 @@ std::string SystemTools::RelativePath(const std::string& local, static std::string GetCasePathName(std::string const& pathIn) { std::string casePath; - std::vector<std::string> path_components; - SystemTools::SplitPath(pathIn, path_components); - if (path_components[0].empty()) // First component always exists. - { - // Relative paths cannot be converted. + + // First check if the file is relative. We don't fix relative paths since the + // real case depends on the root directory and the given path fragment may + // have meaning elsewhere in the project. + if (!SystemTools::FileIsFullPath(pathIn)) { + // This looks unnecessary, but it allows for the return value optimization + // since all return paths return the same local variable. casePath = pathIn; return casePath; } + std::vector<std::string> path_components; + SystemTools::SplitPath(pathIn, path_components); + // Start with root component. std::vector<std::string>::size_type idx = 0; casePath = path_components[idx++]; diff --git a/Source/kwsys/Terminal.c b/Source/kwsys/Terminal.c index eaa5c7d..c9f9dc5 100644 --- a/Source/kwsys/Terminal.c +++ b/Source/kwsys/Terminal.c @@ -153,6 +153,7 @@ static const char* kwsysTerminalVT100Names[] = { "Eterm", "xterm-88color", "xterm-color", "xterm-debian", + "xterm-kitty", "xterm-termite", 0 }; diff --git a/Source/kwsys/testSystemTools.cxx b/Source/kwsys/testSystemTools.cxx index e436a2b..a6d934b 100644 --- a/Source/kwsys/testSystemTools.cxx +++ b/Source/kwsys/testSystemTools.cxx @@ -738,29 +738,29 @@ static bool CheckGetPath() #endif const char* registryPath = "[HKEY_LOCAL_MACHINE\\SOFTWARE\\MyApp; MyKey]"; - std::vector<std::string> originalPathes; - originalPathes.push_back(registryPath); + std::vector<std::string> originalPaths; + originalPaths.push_back(registryPath); - std::vector<std::string> expectedPathes; - expectedPathes.push_back(registryPath); + std::vector<std::string> expectedPaths; + expectedPaths.push_back(registryPath); #ifdef _WIN32 - expectedPathes.push_back("C:/Somewhere/something"); - expectedPathes.push_back("D:/Temp"); + expectedPaths.push_back("C:/Somewhere/something"); + expectedPaths.push_back("D:/Temp"); #else - expectedPathes.push_back("/Somewhere/something"); - expectedPathes.push_back("/tmp"); + expectedPaths.push_back("/Somewhere/something"); + expectedPaths.push_back("/tmp"); #endif bool res = true; res &= CheckPutEnv(std::string(envName) + "=" + envValue, envName, envValue); - std::vector<std::string> pathes = originalPathes; - kwsys::SystemTools::GetPath(pathes, envName); + std::vector<std::string> paths = originalPaths; + kwsys::SystemTools::GetPath(paths, envName); - if (pathes != expectedPathes) { - std::cerr << "GetPath(" << StringVectorToString(originalPathes) << ", " - << envName << ") yielded " << StringVectorToString(pathes) - << " instead of " << StringVectorToString(expectedPathes) + if (paths != expectedPaths) { + std::cerr << "GetPath(" << StringVectorToString(originalPaths) << ", " + << envName << ") yielded " << StringVectorToString(paths) + << " instead of " << StringVectorToString(expectedPaths) << std::endl; res = false; } diff --git a/Tests/BuildDepends/CMakeLists.txt b/Tests/BuildDepends/CMakeLists.txt index 11978db..3b4ff60 100644 --- a/Tests/BuildDepends/CMakeLists.txt +++ b/Tests/BuildDepends/CMakeLists.txt @@ -42,7 +42,7 @@ list(APPEND _cmake_options "-DTEST_LINK_DEPENDS=${TEST_LINK_DEPENDS}") list(APPEND _cmake_options "-DCMAKE_FORCE_DEPFILES=1") -if(NOT CMAKE_GENERATOR MATCHES "Visual Studio ([^89]|[89][0-9])") +if(NOT CMAKE_GENERATOR MATCHES "Visual Studio ([^9]|9[0-9])") set(TEST_MULTI3 1) list(APPEND _cmake_options "-DTEST_MULTI3=1") endif() diff --git a/Tests/CMakeCommands/add_compile_definitions/CMakeLists.txt b/Tests/CMakeCommands/add_compile_definitions/CMakeLists.txt new file mode 100644 index 0000000..2eb887e --- /dev/null +++ b/Tests/CMakeCommands/add_compile_definitions/CMakeLists.txt @@ -0,0 +1,15 @@ +cmake_minimum_required(VERSION 3.1) + +project(add_compile_definitions LANGUAGES CXX) + +add_compile_definitions(TEST_DEFINITION + $<$<COMPILE_LANGUAGE:CXX>:LANG_$<COMPILE_LANGUAGE>> + $<$<EQUAL:0,1>:UNEXPECTED_DEFINITION>) + +add_executable(add_compile_definitions main.cpp) + +add_library(imp UNKNOWN IMPORTED) +get_target_property(_res imp COMPILE_DEFINITIONS) +if (_res) + message(SEND_ERROR "add_compile_definitions populated the COMPILE_DEFINITIONS target property") +endif() diff --git a/Tests/CMakeCommands/add_compile_definitions/main.cpp b/Tests/CMakeCommands/add_compile_definitions/main.cpp new file mode 100644 index 0000000..b382922 --- /dev/null +++ b/Tests/CMakeCommands/add_compile_definitions/main.cpp @@ -0,0 +1,17 @@ + +#ifndef TEST_DEFINITION +#error Expected TEST_DEFINITION +#endif + +#ifndef LANG_CXX +#error Expected LANG_CXX +#endif + +#ifdef UNPEXTED_DEFINITION +#error Unexpected UNPEXTED_DEFINITION +#endif + +int main(void) +{ + return 0; +} diff --git a/Tests/CMakeCommands/target_compile_features/CMakeLists.txt b/Tests/CMakeCommands/target_compile_features/CMakeLists.txt index 5096a58..9664025 100644 --- a/Tests/CMakeCommands/target_compile_features/CMakeLists.txt +++ b/Tests/CMakeCommands/target_compile_features/CMakeLists.txt @@ -1,5 +1,4 @@ -cmake_minimum_required(VERSION 3.0) -cmake_policy(SET CMP0057 NEW) +cmake_minimum_required(VERSION 3.3) project(target_compile_features) set(CMAKE_VERBOSE_MAKEFILE ON) @@ -19,7 +18,8 @@ if (c_restrict IN_LIST CMAKE_C_COMPILE_FEATURES) target_link_libraries(c_restrict_user_specific c_lib_restrict_specific) endif() -if (c_std_99 IN_LIST CMAKE_C_COMPILE_FEATURES) +if (c_std_99 IN_LIST CMAKE_C_COMPILE_FEATURES AND + NOT "${CMAKE_C_COMPILER_ID}" STREQUAL "MSVC") add_executable(c_target_compile_features_meta main.c) target_compile_features(c_target_compile_features_meta PRIVATE c_std_99 diff --git a/Tests/CMakeLib/CMakeLists.txt b/Tests/CMakeLib/CMakeLists.txt index 06df53f..126076d 100644 --- a/Tests/CMakeLib/CMakeLists.txt +++ b/Tests/CMakeLib/CMakeLists.txt @@ -49,3 +49,6 @@ if(TEST_CompileCommandOutput) endif() add_subdirectory(PseudoMemcheck) + +add_executable(testAffinity testAffinity.cxx) +target_link_libraries(testAffinity CMakeLib) diff --git a/Tests/CMakeLib/testAffinity.cxx b/Tests/CMakeLib/testAffinity.cxx new file mode 100644 index 0000000..4b82280 --- /dev/null +++ b/Tests/CMakeLib/testAffinity.cxx @@ -0,0 +1,18 @@ +/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying + file Copyright.txt or https://cmake.org/licensing for details. */ +#include "cmAffinity.h" + +#include <cstddef> +#include <iostream> +#include <set> + +int main() +{ + std::set<size_t> cpus = cmAffinity::GetProcessorsAvailable(); + if (!cpus.empty()) { + std::cout << "CPU affinity mask count is '" << cpus.size() << "'.\n"; + } else { + std::cout << "CPU affinity not supported on this platform.\n"; + } + return 0; +} diff --git a/Tests/CMakeLists.txt b/Tests/CMakeLists.txt index 08bfebe..b11cf03 100644 --- a/Tests/CMakeLists.txt +++ b/Tests/CMakeLists.txt @@ -64,7 +64,7 @@ if(BUILD_TESTING) set(CMake_TEST_DEVENV "") if(CMAKE_VS_DEVENV_COMMAND) set(CMake_TEST_DEVENV "${CMAKE_VS_DEVENV_COMMAND}") - elseif(CMAKE_GENERATOR MATCHES "Visual Studio [89] " AND + elseif(CMAKE_GENERATOR MATCHES "Visual Studio 9 " AND NOT CMAKE_MAKE_PROGRAM MATCHES "[mM][sS][bB][uU][iI][lL][dD]\\.[eE][xX][eE]") set(CMake_TEST_DEVENV "${CMAKE_MAKE_PROGRAM}") endif() @@ -345,9 +345,10 @@ if(BUILD_TESTING) endif() endif() - if(${CMAKE_GENERATOR} MATCHES "Visual Studio ([^89]|[89][0-9])") + if(${CMAKE_GENERATOR} MATCHES "Visual Studio ([^9]|[9][0-9])") ADD_TEST_MACRO(CSharpOnly CSharpOnly) ADD_TEST_MACRO(CSharpLinkToCxx CSharpLinkToCxx) + ADD_TEST_MACRO(CSharpLinkFromCxx CSharpLinkFromCxx) endif() ADD_TEST_MACRO(COnly COnly) @@ -816,6 +817,8 @@ ${CMake_BINARY_DIR}/bin/cmake -DDIR=dev -P ${CMake_SOURCE_DIR}/Utilities/Release ADD_TEST_MACRO(CustomCommandByproducts CustomCommandByproducts) + ADD_TEST_MACRO(CommandLength CommandLength) + ADD_TEST_MACRO(EmptyDepends ${CMAKE_CTEST_COMMAND}) add_test(CustomCommandWorkingDirectory ${CMAKE_CTEST_COMMAND} @@ -1323,6 +1326,10 @@ ${CMake_BINARY_DIR}/bin/cmake -DDIR=dev -P ${CMake_SOURCE_DIR}/Utilities/Release add_subdirectory(FindBZip2) endif() + if(CMake_TEST_FindCURL) + add_subdirectory(FindCURL) + endif() + if(CMake_TEST_FindDoxygen) add_subdirectory(FindDoxygen) endif() @@ -1352,6 +1359,10 @@ ${CMake_BINARY_DIR}/bin/cmake -DDIR=dev -P ${CMake_SOURCE_DIR}/Utilities/Release add_subdirectory(FindICU) endif() + if(CMake_TEST_FindJPEG) + add_subdirectory(FindJPEG) + endif() + if(CMake_TEST_FindJsonCpp) add_subdirectory(FindJsonCpp) endif() @@ -1364,6 +1375,10 @@ ${CMake_BINARY_DIR}/bin/cmake -DDIR=dev -P ${CMake_SOURCE_DIR}/Utilities/Release add_subdirectory(FindLibUV) endif() + if(CMake_TEST_FindLibXml2) + add_subdirectory(FindLibXml2) + endif() + if(CMake_TEST_FindLTTngUST) add_subdirectory(FindLTTngUST) endif() @@ -1416,13 +1431,36 @@ ${CMake_BINARY_DIR}/bin/cmake -DDIR=dev -P ${CMake_SOURCE_DIR}/Utilities/Release add_subdirectory(FindXercesC) endif() + if(CMake_TEST_FindPython) + add_subdirectory(FindPython) + endif() + + if(CMake_TEST_UseSWIG) + add_subdirectory(UseSWIG) + endif() + add_subdirectory(FindThreads) # Matlab module - if(CMake_TEST_FindMatlab) + # CMake_TEST_FindMatlab: indicates to look for Matlab (from PATH for Linux) + # CMake_TEST_FindMatlab_MCR: indicates the MCR is installed + # CMake_TEST_FindMatlab_MCR_ROOT_DIR: indicates an optional root directory for the MCR, required on Linux + if(CMake_TEST_FindMatlab OR CMake_TEST_FindMatlab_MCR OR (NOT "${CMake_TEST_FindMatlab_MCR_ROOT_DIR}" STREQUAL "")) + set(FindMatlab_additional_test_options ) + if(CMake_TEST_FindMatlab_MCR OR NOT "${CMake_TEST_FindMatlab_MCR_ROOT_DIR}" STREQUAL "") + set(FindMatlab_additional_test_options -DIS_MCR=TRUE) + endif() + if(NOT "${CMake_TEST_FindMatlab_MCR_ROOT_DIR}" STREQUAL "") + set(FindMatlab_additional_test_options ${FindMatlab_additional_test_options} "-DMCR_ROOT:FILEPATH=${CMake_TEST_FindMatlab_MCR_ROOT_DIR}") + endif() + set(FindMatlab.basic_checks_BUILD_OPTIONS ${FindMatlab_additional_test_options}) ADD_TEST_MACRO(FindMatlab.basic_checks ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION>) + set(FindMatlab.versions_checks_BUILD_OPTIONS ${FindMatlab_additional_test_options}) ADD_TEST_MACRO(FindMatlab.versions_checks ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION>) + set(FindMatlab.components_checks_BUILD_OPTIONS ${FindMatlab_additional_test_options}) ADD_TEST_MACRO(FindMatlab.components_checks ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION>) + set(FindMatlab.failure_reports_BUILD_OPTIONS ${FindMatlab_additional_test_options}) + ADD_TEST_MACRO(FindMatlab.failure_reports ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION>) endif() find_package(GTK2 QUIET) @@ -1443,6 +1481,7 @@ ${CMake_BINARY_DIR}/bin/cmake -DDIR=dev -P ${CMake_SOURCE_DIR}/Utilities/Release ) list(APPEND TEST_BUILD_DIRS "${CMake_BINARY_DIR}/Tests/ExternalProject") set_tests_properties(ExternalProject PROPERTIES + RUN_SERIAL 1 TIMEOUT ${CMAKE_LONG_TEST_TIMEOUT}) add_test(NAME ExternalProjectSubdir @@ -1482,6 +1521,7 @@ ${CMake_BINARY_DIR}/bin/cmake -DDIR=dev -P ${CMake_SOURCE_DIR}/Utilities/Release ) list(APPEND TEST_BUILD_DIRS "${CMake_BINARY_DIR}/Tests/ExternalProjectLocal") set_tests_properties(ExternalProjectLocal PROPERTIES + RUN_SERIAL 1 TIMEOUT ${CMAKE_LONG_TEST_TIMEOUT}) add_test(ExternalProjectUpdateSetup ${CMAKE_CTEST_COMMAND} @@ -1497,6 +1537,7 @@ ${CMake_BINARY_DIR}/bin/cmake -DDIR=dev -P ${CMake_SOURCE_DIR}/Utilities/Release ) list(APPEND TEST_BUILD_DIRS "${CMake_BINARY_DIR}/Tests/ExternalProjectUpdate") set_tests_properties(ExternalProjectUpdateSetup PROPERTIES + RUN_SERIAL 1 TIMEOUT ${CMAKE_LONG_TEST_TIMEOUT}) add_test(NAME ExternalProjectUpdate @@ -1511,6 +1552,7 @@ ${CMake_BINARY_DIR}/bin/cmake -DDIR=dev -P ${CMake_SOURCE_DIR}/Utilities/Release ) list(APPEND TEST_BUILD_DIRS "${CMake_BINARY_DIR}/Tests/ExternalProjectUpdate") set_tests_properties(ExternalProjectUpdate PROPERTIES + RUN_SERIAL 1 TIMEOUT ${CMAKE_LONG_TEST_TIMEOUT} WORKING_DIRECTORY ${CMake_SOURCE_DIR}/Tests/ExternalProjectUpdate DEPENDS ExternalProjectUpdateSetup ) @@ -1910,7 +1952,7 @@ ${CMake_BINARY_DIR}/bin/cmake -DDIR=dev -P ${CMake_SOURCE_DIR}/Utilities/Release endif() if(MSVC AND NOT MSVC_VERSION LESS 1310 - AND (NOT CMAKE_GENERATOR MATCHES "Visual Studio [89]( |$)" + AND (NOT CMAKE_GENERATOR MATCHES "Visual Studio 9 " OR CMAKE_SIZEOF_VOID_P EQUAL 4) ) ADD_TEST_MACRO(VSMASM VSMASM) @@ -1921,7 +1963,7 @@ ${CMake_BINARY_DIR}/bin/cmake -DDIR=dev -P ${CMake_SOURCE_DIR}/Utilities/Release ADD_TEST_MACRO(SBCS SBCS) endif() - if(NOT "${CMAKE_GENERATOR}" MATCHES "Visual Studio [89]( |$)" + if(NOT "${CMAKE_GENERATOR}" MATCHES "Visual Studio 9 " AND NOT CMAKE_GENERATOR_TOOLSET) ADD_TEST_MACRO(VSWindowsFormsResx VSWindowsFormsResx) endif() @@ -2120,7 +2162,7 @@ ${CMake_BINARY_DIR}/bin/cmake -DDIR=dev -P ${CMake_SOURCE_DIR}/Utilities/Release endif() endif() - if(CMAKE_GENERATOR MATCHES "Visual Studio ([^89]|[89][0-9])" AND nasm) + if(CMAKE_GENERATOR MATCHES "Visual Studio ([^9]|9[0-9])" AND nasm) ADD_TEST_MACRO(VSNASM VSNASM) endif() @@ -2728,6 +2770,7 @@ ${CMake_BINARY_DIR}/bin/cmake -DDIR=dev -P ${CMake_SOURCE_DIR}/Utilities/Release --output-log "${CMake_BINARY_DIR}/Tests/CTestConfig/ScriptWithArgs.log" ) + ADD_TEST_MACRO(CMakeCommands.add_compile_definitions add_compile_definitions) ADD_TEST_MACRO(CMakeCommands.add_compile_options add_compile_options) ADD_TEST_MACRO(CMakeCommands.target_link_libraries target_link_libraries) ADD_TEST_MACRO(CMakeCommands.target_include_directories target_include_directories) diff --git a/Tests/CMakeOnly/AllFindModules/CMakeLists.txt b/Tests/CMakeOnly/AllFindModules/CMakeLists.txt index 443d366..a53e441 100644 --- a/Tests/CMakeOnly/AllFindModules/CMakeLists.txt +++ b/Tests/CMakeOnly/AllFindModules/CMakeLists.txt @@ -86,7 +86,7 @@ foreach(VTEST ALSA ARMADILLO BZIP2 CUPS CURL EXPAT FREETYPE GETTEXT GIT HG endforeach() foreach(VTEST BISON Boost CUDA DOXYGEN FLEX GIF GTK2 - HDF5 LibArchive OPENSCENEGRAPH RUBY SWIG Protobuf) + HDF5 JPEG LibArchive OPENSCENEGRAPH RUBY SWIG Protobuf) check_version_string(${VTEST} ${VTEST}_VERSION) endforeach() diff --git a/Tests/CMakeOnly/CMakeLists.txt b/Tests/CMakeOnly/CMakeLists.txt index c84fa74..204d54c 100644 --- a/Tests/CMakeOnly/CMakeLists.txt +++ b/Tests/CMakeOnly/CMakeLists.txt @@ -33,7 +33,7 @@ add_CMakeOnly_test(CompilerIdCXX) if(CMAKE_Fortran_COMPILER) add_CMakeOnly_test(CompilerIdFortran) endif() -if(CMAKE_GENERATOR MATCHES "Visual Studio ([^89]|[89][0-9])") +if(CMAKE_GENERATOR MATCHES "Visual Studio ([^9]|9[0-9])") add_CMakeOnly_test(CompilerIdCSharp) endif() diff --git a/Tests/CSharpLinkFromCxx/.gitattributes b/Tests/CSharpLinkFromCxx/.gitattributes new file mode 100644 index 0000000..57a39049 --- /dev/null +++ b/Tests/CSharpLinkFromCxx/.gitattributes @@ -0,0 +1 @@ +UsefulManagedCppClass.* -format.clang-format diff --git a/Tests/CSharpLinkFromCxx/CMakeLists.txt b/Tests/CSharpLinkFromCxx/CMakeLists.txt new file mode 100644 index 0000000..9a1a993 --- /dev/null +++ b/Tests/CSharpLinkFromCxx/CMakeLists.txt @@ -0,0 +1,19 @@ +# Take a C# shared library and link it to a managed C++ shared library +cmake_minimum_required(VERSION 3.10) +project (CSharpLinkFromCxx CXX CSharp) + +add_library(CSharpLibrary SHARED UsefulCSharpClass.cs) + +# we have to change the default flags for the +# managed C++ project to build +string(REPLACE "/EHsc" "" CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS}) +string(REPLACE "/RTC1" "" CMAKE_CXX_FLAGS_DEBUG ${CMAKE_CXX_FLAGS_DEBUG}) + +# The C# project is a dependency of the C++/CLI project +add_library(ManagedCppLibrary SHARED UsefulManagedCppClass.cpp UsefulManagedCppClass.hpp) +target_compile_options(ManagedCppLibrary PRIVATE "/clr") +target_link_libraries(ManagedCppLibrary PUBLIC CSharpLibrary) + +# Main executable for the test framework +add_executable(CSharpLinkFromCxx CSharpLinkFromCxx.cs) +target_link_libraries(CSharpLinkFromCxx PRIVATE ManagedCppLibrary) diff --git a/Tests/CSharpLinkFromCxx/CSharpLinkFromCxx.cs b/Tests/CSharpLinkFromCxx/CSharpLinkFromCxx.cs new file mode 100644 index 0000000..31a74eb --- /dev/null +++ b/Tests/CSharpLinkFromCxx/CSharpLinkFromCxx.cs @@ -0,0 +1,16 @@ +using System; +using CSharpLibrary; + +namespace CSharpLinkFromCxx +{ + internal class CSharpLinkFromCxx + { + public static void Main(string[] args) + { + Console.WriteLine("Starting test for CSharpLinkFromCxx"); + + var useful = new UsefulManagedCppClass(); + useful.RunTest(); + } + } +} diff --git a/Tests/CSharpLinkFromCxx/UsefulCSharpClass.cs b/Tests/CSharpLinkFromCxx/UsefulCSharpClass.cs new file mode 100644 index 0000000..749e57d --- /dev/null +++ b/Tests/CSharpLinkFromCxx/UsefulCSharpClass.cs @@ -0,0 +1,12 @@ +using System; + +namespace CSharpLibrary +{ + public class UsefulCSharpClass + { + public string GetSomethingUseful() + { + return "Something Useful"; + } + } +} diff --git a/Tests/CSharpLinkFromCxx/UsefulManagedCppClass.cpp b/Tests/CSharpLinkFromCxx/UsefulManagedCppClass.cpp new file mode 100644 index 0000000..9468812 --- /dev/null +++ b/Tests/CSharpLinkFromCxx/UsefulManagedCppClass.cpp @@ -0,0 +1,15 @@ +#include "UsefulManagedCppClass.hpp" + +namespace CSharpLibrary +{ + UsefulManagedCppClass::UsefulManagedCppClass() + { + auto useful = gcnew UsefulCSharpClass(); + m_usefulString = useful->GetSomethingUseful(); + } + + void UsefulManagedCppClass::RunTest() + { + Console::WriteLine("Printing from Managed CPP Class: " + m_usefulString); + } +} diff --git a/Tests/CSharpLinkFromCxx/UsefulManagedCppClass.hpp b/Tests/CSharpLinkFromCxx/UsefulManagedCppClass.hpp new file mode 100644 index 0000000..def7cea --- /dev/null +++ b/Tests/CSharpLinkFromCxx/UsefulManagedCppClass.hpp @@ -0,0 +1,16 @@ +using namespace System; + +namespace CSharpLibrary +{ + public ref class UsefulManagedCppClass + { + public: + + UsefulManagedCppClass(); + void RunTest(); + + private: + + String^ m_usefulString; + }; +} diff --git a/Tests/CTestTest/test.cmake.in b/Tests/CTestTest/test.cmake.in index 589bd44..23166a7 100644 --- a/Tests/CTestTest/test.cmake.in +++ b/Tests/CTestTest/test.cmake.in @@ -62,7 +62,7 @@ COVERAGE_COMMAND:FILEPATH=@COVERAGE_COMMAND@ set (CTEST_DASHBOARD_ROOT "@CMAKE_CURRENT_BINARY_DIR@/Tests/CTestTest") -# set any extra environment varibles here +# set any extra environment variables here set (CTEST_ENVIRONMENT ) diff --git a/Tests/CommandLength/CMakeLists.txt b/Tests/CommandLength/CMakeLists.txt new file mode 100644 index 0000000..6836051 --- /dev/null +++ b/Tests/CommandLength/CMakeLists.txt @@ -0,0 +1,17 @@ +cmake_minimum_required(VERSION 3.10) +project(CommandLength C) + +add_executable(CommandLength test.c) +add_custom_command(TARGET CommandLength POST_BUILD VERBATIM + COMMAND ${CMAKE_COMMAND} -E make_directory log) + +set(msg "xxxx $$$$ yyyy") +set(msg "${msg} ${msg}") +set(msg "${msg} ${msg}") +set(msg "${msg} ${msg}") +set(msg "${msg} ${msg}") +foreach(i RANGE 1 1000) + add_custom_command(TARGET CommandLength POST_BUILD VERBATIM + COMMAND ${CMAKE_COMMAND} -E echo "${i} ${msg}" > log/${i} + ) +endforeach() diff --git a/Tests/CommandLength/test.c b/Tests/CommandLength/test.c new file mode 100644 index 0000000..f8b643a --- /dev/null +++ b/Tests/CommandLength/test.c @@ -0,0 +1,4 @@ +int main() +{ + return 0; +} diff --git a/Tests/CompileFeatures/CMakeLists.txt b/Tests/CompileFeatures/CMakeLists.txt index b560acd..b0bc656 100644 --- a/Tests/CompileFeatures/CMakeLists.txt +++ b/Tests/CompileFeatures/CMakeLists.txt @@ -224,54 +224,22 @@ if (C_expected_features) add_executable(CompileFeaturesGenex_C genex_test.c) set_property(TARGET CompileFeaturesGenex_C PROPERTY C_STANDARD 11) - if (CMAKE_C_COMPILER_ID STREQUAL "GNU") - if (NOT CMAKE_C_COMPILER_VERSION VERSION_LESS 4.6) - list(APPEND expected_defs - EXPECT_C_STATIC_ASSERT=1 - ) - else() - list(APPEND expected_defs - EXPECT_C_STATIC_ASSERT=0 + foreach(f + c_restrict + c_static_assert + c_function_prototypes ) - endif() - elseif(CMAKE_C_COMPILER_ID STREQUAL "Clang" - OR CMAKE_C_COMPILER_ID STREQUAL "AppleClang") - list(APPEND expected_defs - EXPECT_C_STATIC_ASSERT=1 - ) - elseif (CMAKE_C_COMPILER_ID STREQUAL "Intel") - if (NOT CMAKE_C_COMPILER_VERSION VERSION_LESS 15) - list(APPEND expected_defs - EXPECT_C_STATIC_ASSERT=1 - ) + if(${f} IN_LIST C_expected_features) + set(expect_${f} 1) else() - list(APPEND expected_defs - EXPECT_C_STATIC_ASSERT=0 - ) + set(expect_${f} 0) endif() - elseif (CMAKE_C_COMPILER_ID STREQUAL "SunPro") - if (NOT CMAKE_C_COMPILER_VERSION VERSION_LESS 5.13) - list(APPEND expected_defs - EXPECT_C_STATIC_ASSERT=1 - ) - else() - list(APPEND expected_defs - EXPECT_C_STATIC_ASSERT=0 - ) - endif() - endif() - - list(APPEND expected_defs - EXPECT_C_FUNCTION_PROTOTYPES=1 - EXPECT_C_RESTRICT=1 - ) - - target_compile_definitions(CompileFeaturesGenex_C PRIVATE - HAVE_C_FUNCTION_PROTOTYPES=$<COMPILE_FEATURES:c_function_prototypes> - HAVE_C_RESTRICT=$<COMPILE_FEATURES:c_restrict> - HAVE_C_STATIC_ASSERT=$<COMPILE_FEATURES:c_static_assert> - ${expected_defs} - ) + string(TOUPPER "${f}" F) + target_compile_definitions(CompileFeaturesGenex_C PRIVATE + EXPECT_${F}=${expect_${f}} + HAVE_${F}=$<COMPILE_FEATURES:${f}> + ) + endforeach() endif() if (CMAKE_CXX_COMPILE_FEATURES) @@ -280,6 +248,7 @@ if (CMAKE_CXX_COMPILE_FEATURES) if (std_flag_idx EQUAL -1) add_executable(default_dialect default_dialect.cpp) target_compile_definitions(default_dialect PRIVATE + DEFAULT_CXX20=$<EQUAL:${CMAKE_CXX_STANDARD_DEFAULT},20> DEFAULT_CXX17=$<EQUAL:${CMAKE_CXX_STANDARD_DEFAULT},17> DEFAULT_CXX14=$<EQUAL:${CMAKE_CXX_STANDARD_DEFAULT},14> DEFAULT_CXX11=$<EQUAL:${CMAKE_CXX_STANDARD_DEFAULT},11> @@ -318,144 +287,62 @@ else() add_executable(IfaceCompileFeatures main.cpp) target_link_libraries(IfaceCompileFeatures iface) - if (CMAKE_CXX_COMPILER_ID STREQUAL "GNU") - if (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 4.8) - add_definitions( - -DEXPECT_OVERRIDE_CONTROL=1 - -DEXPECT_INHERITING_CONSTRUCTORS=1 - -DEXPECT_FINAL=1 - -DEXPECT_INHERITING_CONSTRUCTORS_AND_FINAL=1 - ) - elseif (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 4.7) - add_definitions( - -DEXPECT_OVERRIDE_CONTROL=1 - -DEXPECT_INHERITING_CONSTRUCTORS=0 - -DEXPECT_FINAL=1 - -DEXPECT_INHERITING_CONSTRUCTORS_AND_FINAL=0 - ) - else() - add_definitions( - -DEXPECT_OVERRIDE_CONTROL=0 - -DEXPECT_INHERITING_CONSTRUCTORS=0 - -DEXPECT_FINAL=0 - -DEXPECT_INHERITING_CONSTRUCTORS_AND_FINAL=0 - ) - endif() - elseif(CMAKE_CXX_COMPILER_ID STREQUAL "Clang") - add_definitions( - -DEXPECT_OVERRIDE_CONTROL=1 - -DEXPECT_INHERITING_CONSTRUCTORS=1 - -DEXPECT_FINAL=1 - -DEXPECT_INHERITING_CONSTRUCTORS_AND_FINAL=1 - ) - elseif(CMAKE_CXX_COMPILER_ID STREQUAL "AppleClang") - if (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 5.0) - add_definitions( - -DEXPECT_OVERRIDE_CONTROL=1 - -DEXPECT_INHERITING_CONSTRUCTORS=1 - -DEXPECT_FINAL=1 - -DEXPECT_INHERITING_CONSTRUCTORS_AND_FINAL=1 - ) - else() - add_definitions( - -DEXPECT_OVERRIDE_CONTROL=1 - -DEXPECT_INHERITING_CONSTRUCTORS=0 - -DEXPECT_FINAL=1 - -DEXPECT_INHERITING_CONSTRUCTORS_AND_FINAL=0 - ) - endif() - elseif(CMAKE_CXX_COMPILER_ID STREQUAL "MSVC") - if (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 19.0) - add_definitions( - -DEXPECT_OVERRIDE_CONTROL=1 - -DEXPECT_INHERITING_CONSTRUCTORS=1 - -DEXPECT_FINAL=1 - -DEXPECT_INHERITING_CONSTRUCTORS_AND_FINAL=1 - ) - elseif(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 17.0) - add_definitions( - -DEXPECT_OVERRIDE_CONTROL=1 - -DEXPECT_INHERITING_CONSTRUCTORS=0 - -DEXPECT_FINAL=1 - -DEXPECT_INHERITING_CONSTRUCTORS_AND_FINAL=0 - ) - else() - add_definitions( - -DEXPECT_OVERRIDE_CONTROL=0 - -DEXPECT_INHERITING_CONSTRUCTORS=0 - -DEXPECT_FINAL=0 - -DEXPECT_INHERITING_CONSTRUCTORS_AND_FINAL=0 - ) - endif() - elseif (CMAKE_CXX_COMPILER_ID STREQUAL "SunPro") - add_definitions( - -DEXPECT_OVERRIDE_CONTROL=1 - -DEXPECT_INHERITING_CONSTRUCTORS=1 - -DEXPECT_FINAL=1 - -DEXPECT_INHERITING_CONSTRUCTORS_AND_FINAL=1 - ) - elseif (CMAKE_CXX_COMPILER_ID STREQUAL "Intel") - if (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 15) - add_definitions( - -DEXPECT_OVERRIDE_CONTROL=1 - -DEXPECT_INHERITING_CONSTRUCTORS=1 - -DEXPECT_FINAL=1 - -DEXPECT_INHERITING_CONSTRUCTORS_AND_FINAL=1 - ) - elseif (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 14) - add_definitions( - -DEXPECT_OVERRIDE_CONTROL=1 - -DEXPECT_INHERITING_CONSTRUCTORS=0 - -DEXPECT_FINAL=1 - -DEXPECT_INHERITING_CONSTRUCTORS_AND_FINAL=0 + foreach(f + cxx_final + cxx_override + cxx_auto_type + cxx_inheriting_constructors ) + if(${f} IN_LIST CXX_expected_features) + set(expect_${f} 1) else() - add_definitions( - -DEXPECT_OVERRIDE_CONTROL=0 - -DEXPECT_INHERITING_CONSTRUCTORS=0 - -DEXPECT_FINAL=0 - -DEXPECT_INHERITING_CONSTRUCTORS_AND_FINAL=0 - ) + set(expect_${f} 0) endif() + endforeach() + + if(expect_cxx_final AND expect_cxx_override) + set(expect_override_control 1) + else() + set(expect_override_control 0) + endif() + if(expect_cxx_inheriting_constructors AND expect_cxx_final) + set(expect_inheriting_constructors_and_final 1) + else() + set(expect_inheriting_constructors_and_final 0) endif() - add_executable(CompileFeaturesGenex genex_test.cpp) - set_property(TARGET CompileFeaturesGenex PROPERTY CXX_STANDARD 11) - target_compile_definitions(CompileFeaturesGenex PRIVATE + set(genex_test_defs HAVE_OVERRIDE_CONTROL=$<COMPILE_FEATURES:cxx_final,cxx_override> HAVE_AUTO_TYPE=$<COMPILE_FEATURES:cxx_auto_type> HAVE_INHERITING_CONSTRUCTORS=$<COMPILE_FEATURES:cxx_inheriting_constructors> HAVE_FINAL=$<COMPILE_FEATURES:cxx_final> HAVE_INHERITING_CONSTRUCTORS_AND_FINAL=$<COMPILE_FEATURES:cxx_inheriting_constructors,cxx_final> - ) + EXPECT_OVERRIDE_CONTROL=${expect_override_control} + EXPECT_INHERITING_CONSTRUCTORS=${expect_cxx_inheriting_constructors} + EXPECT_FINAL=${expect_cxx_final} + EXPECT_INHERITING_CONSTRUCTORS_AND_FINAL=${expect_inheriting_constructors_and_final} + ) if (CMAKE_CXX_STANDARD_DEFAULT) - target_compile_definitions(CompileFeaturesGenex PRIVATE + list(APPEND genex_test_defs TEST_CXX_STD HAVE_CXX_STD_11=$<COMPILE_FEATURES:cxx_std_11> HAVE_CXX_STD_14=$<COMPILE_FEATURES:cxx_std_14> HAVE_CXX_STD_17=$<COMPILE_FEATURES:cxx_std_17> + HAVE_CXX_STD_20=$<COMPILE_FEATURES:cxx_std_20> ) endif() + add_executable(CompileFeaturesGenex genex_test.cpp) + set_property(TARGET CompileFeaturesGenex PROPERTY CXX_STANDARD 11) + target_compile_definitions(CompileFeaturesGenex PRIVATE ${genex_test_defs}) + add_executable(CompileFeaturesGenex2 genex_test.cpp) target_compile_features(CompileFeaturesGenex2 PRIVATE cxx_std_11) - target_compile_definitions(CompileFeaturesGenex2 PRIVATE - HAVE_OVERRIDE_CONTROL=$<COMPILE_FEATURES:cxx_final,cxx_override> - HAVE_AUTO_TYPE=$<COMPILE_FEATURES:cxx_auto_type> - HAVE_INHERITING_CONSTRUCTORS=$<COMPILE_FEATURES:cxx_inheriting_constructors> - HAVE_FINAL=$<COMPILE_FEATURES:cxx_final> - HAVE_INHERITING_CONSTRUCTORS_AND_FINAL=$<COMPILE_FEATURES:cxx_inheriting_constructors,cxx_final> - ) + target_compile_definitions(CompileFeaturesGenex2 PRIVATE ${genex_test_defs}) add_library(std_11_iface INTERFACE) target_compile_features(std_11_iface INTERFACE cxx_std_11) add_executable(CompileFeaturesGenex3 genex_test.cpp) target_link_libraries(CompileFeaturesGenex3 PRIVATE std_11_iface) - target_compile_definitions(CompileFeaturesGenex3 PRIVATE - HAVE_OVERRIDE_CONTROL=$<COMPILE_FEATURES:cxx_final,cxx_override> - HAVE_AUTO_TYPE=$<COMPILE_FEATURES:cxx_auto_type> - HAVE_INHERITING_CONSTRUCTORS=$<COMPILE_FEATURES:cxx_inheriting_constructors> - HAVE_FINAL=$<COMPILE_FEATURES:cxx_final> - HAVE_INHERITING_CONSTRUCTORS_AND_FINAL=$<COMPILE_FEATURES:cxx_inheriting_constructors,cxx_final> - ) + target_compile_definitions(CompileFeaturesGenex3 PRIVATE ${genex_test_defs}) endif() diff --git a/Tests/CompileFeatures/default_dialect.cpp b/Tests/CompileFeatures/default_dialect.cpp index 0de1125..7ddcfe7 100644 --- a/Tests/CompileFeatures/default_dialect.cpp +++ b/Tests/CompileFeatures/default_dialect.cpp @@ -8,7 +8,11 @@ struct Outputter; #define CXX_STD __cplusplus #endif -#if DEFAULT_CXX17 +#if DEFAULT_CXX20 +#if CXX_STD <= 201703L +Outputter<CXX_STD> o; +#endif +#elif DEFAULT_CXX17 #if CXX_STD <= 201402L Outputter<CXX_STD> o; #endif diff --git a/Tests/CompileFeatures/genex_test.c b/Tests/CompileFeatures/genex_test.c index 1d54840..e58d793 100644 --- a/Tests/CompileFeatures/genex_test.c +++ b/Tests/CompileFeatures/genex_test.c @@ -8,7 +8,7 @@ #error EXPECT_C_RESTRICT not defined #endif -#if !EXPECT_C_STATIC_ASSERT +#if !HAVE_C_STATIC_ASSERT #if EXPECT_C_STATIC_ASSERT #error "Expect c_static_assert feature" #endif @@ -18,11 +18,17 @@ #endif #endif -#if !EXPECT_C_FUNCTION_PROTOTYPES +#if !HAVE_C_FUNCTION_PROTOTYPES +#if EXPECT_C_FUNCTION_PROTOTYPES #error Expect c_function_prototypes support #endif +#else +#if !EXPECT_C_FUNCTION_PROTOTYPES +#error Expect no c_function_prototypes support +#endif +#endif -#if !EXPECT_C_RESTRICT +#if !HAVE_C_RESTRICT #if EXPECT_C_RESTRICT #error Expect c_restrict support #endif diff --git a/Tests/CompileOptions/CMakeLists.txt b/Tests/CompileOptions/CMakeLists.txt index 692e0de..c9f1710 100644 --- a/Tests/CompileOptions/CMakeLists.txt +++ b/Tests/CompileOptions/CMakeLists.txt @@ -18,9 +18,21 @@ set_property(TARGET CompileOptions PROPERTY COMPILE_OPTIONS "-DTEST_DEFINE" "-DNEEDS_ESCAPE=\"E$CAPE\"" "$<$<CXX_COMPILER_ID:GNU>:-DTEST_DEFINE_GNU>" + "SHELL:" # produces no options ${c_tests} ${cxx_tests} ) +if(BORLAND OR WATCOM) + # these compilers do not support separate -D flags + target_compile_definitions(CompileOptions PRIVATE NO_DEF_TESTS) +else() + set_property(TARGET CompileOptions APPEND PROPERTY COMPILE_OPTIONS + "SHELL:-D DEF_A" + "$<1:SHELL:-D DEF_B>" + "SHELL:-D 'DEF_C' -D \"DEF_D\"" + [[SHELL:-D "DEF_STR=\"string with spaces\""]] + ) +endif() if(CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang|Borland|Embarcadero") set_property(TARGET CompileOptions APPEND PROPERTY COMPILE_OPTIONS diff --git a/Tests/CompileOptions/main.cpp b/Tests/CompileOptions/main.cpp index 63a0480..4779b88 100644 --- a/Tests/CompileOptions/main.cpp +++ b/Tests/CompileOptions/main.cpp @@ -12,6 +12,28 @@ #endif #endif +#ifndef NO_DEF_TESTS +#ifndef DEF_A +#error Expected definition DEF_A +#endif + +#ifndef DEF_B +#error Expected definition DEF_B +#endif + +#ifndef DEF_C +#error Expected definition DEF_C +#endif + +#ifndef DEF_D +#error Expected definition DEF_D +#endif + +#ifndef DEF_STR +#error Expected definition DEF_STR +#endif +#endif + #include <string.h> int main() @@ -20,6 +42,9 @@ int main() #ifdef TEST_OCTOTHORPE && strcmp(TEST_OCTOTHORPE, "#") == 0 #endif +#ifndef NO_DEF_TESTS + && strcmp(DEF_STR, "string with spaces") == 0 +#endif && strcmp(EXPECTED_C_COMPILER_VERSION, TEST_C_COMPILER_VERSION) == 0 && strcmp(EXPECTED_CXX_COMPILER_VERSION, TEST_CXX_COMPILER_VERSION) == diff --git a/Tests/Complex/Cache/CMakeCache.txt b/Tests/Complex/Cache/CMakeCache.txt index 17c55aa..727faa2 100644 --- a/Tests/Complex/Cache/CMakeCache.txt +++ b/Tests/Complex/Cache/CMakeCache.txt @@ -5,7 +5,7 @@ # If you do want to change a value, simply edit, save, and exit the editor. # The syntax for the file is as follows: # KEY:TYPE=VALUE -# KEY is the name of a varible in the cache. +# KEY is the name of a variable in the cache. # TYPE is a hint to GUI's for the type of VALUE, DO NOT EDIT TYPE!. # VALUE is the current value for the KEY. diff --git a/Tests/ComplexOneConfig/Cache/CMakeCache.txt b/Tests/ComplexOneConfig/Cache/CMakeCache.txt index 17c55aa..727faa2 100644 --- a/Tests/ComplexOneConfig/Cache/CMakeCache.txt +++ b/Tests/ComplexOneConfig/Cache/CMakeCache.txt @@ -5,7 +5,7 @@ # If you do want to change a value, simply edit, save, and exit the editor. # The syntax for the file is as follows: # KEY:TYPE=VALUE -# KEY is the name of a varible in the cache. +# KEY is the name of a variable in the cache. # TYPE is a hint to GUI's for the type of VALUE, DO NOT EDIT TYPE!. # VALUE is the current value for the KEY. diff --git a/Tests/Contracts/PLplot/CMakeLists.txt b/Tests/Contracts/PLplot/CMakeLists.txt index b87b4c3..8e95ba3 100644 --- a/Tests/Contracts/PLplot/CMakeLists.txt +++ b/Tests/Contracts/PLplot/CMakeLists.txt @@ -9,7 +9,7 @@ if(NOT PLplot_GIT_TAG) set(PLplot_GIT_TAG "plplot-5.13.0") endif() ExternalProject_Add(PLplot - GIT_REPOSITORY "https://git.code.sf.net/p/plplot/plplot.git" + GIT_REPOSITORY "https://git.code.sf.net/p/plplot/plplot" GIT_TAG "${PLplot_GIT_TAG}" PREFIX "${PLplot_PREFIX}" CMAKE_ARGS diff --git a/Tests/CudaOnly/CMakeLists.txt b/Tests/CudaOnly/CMakeLists.txt index 5ad6e6b..59f3e84 100644 --- a/Tests/CudaOnly/CMakeLists.txt +++ b/Tests/CudaOnly/CMakeLists.txt @@ -2,6 +2,11 @@ ADD_TEST_MACRO(CudaOnly.EnableStandard CudaOnlyEnableStandard) ADD_TEST_MACRO(CudaOnly.ExportPTX CudaOnlyExportPTX) ADD_TEST_MACRO(CudaOnly.GPUDebugFlag CudaOnlyGPUDebugFlag) +ADD_TEST_MACRO(CudaOnly.LinkSystemDeviceLibraries CudaOnlyLinkSystemDeviceLibraries) ADD_TEST_MACRO(CudaOnly.ResolveDeviceSymbols CudaOnlyResolveDeviceSymbols) ADD_TEST_MACRO(CudaOnly.SeparateCompilation CudaOnlySeparateCompilation) ADD_TEST_MACRO(CudaOnly.WithDefs CudaOnlyWithDefs) + +if(MSVC) + ADD_TEST_MACRO(CudaOnly.PDB CudaOnlyPDB) +endif() diff --git a/Tests/CudaOnly/LinkSystemDeviceLibraries/CMakeLists.txt b/Tests/CudaOnly/LinkSystemDeviceLibraries/CMakeLists.txt new file mode 100644 index 0000000..62be1e6 --- /dev/null +++ b/Tests/CudaOnly/LinkSystemDeviceLibraries/CMakeLists.txt @@ -0,0 +1,15 @@ +cmake_minimum_required(VERSION 3.8) +project(CudaOnlyLinkSystemDeviceLibraries CUDA) + +string(APPEND CMAKE_CUDA_FLAGS " -gencode arch=compute_35,code=compute_35 -gencode arch=compute_35,code=sm_35") +set(CMAKE_CUDA_STANDARD 11) + +add_executable(CudaOnlyLinkSystemDeviceLibraries main.cu) +set_target_properties( CudaOnlyLinkSystemDeviceLibraries + PROPERTIES CUDA_SEPARABLE_COMPILATION ON) +target_link_libraries( CudaOnlyLinkSystemDeviceLibraries PRIVATE cublas_device) + +if(APPLE) + # Help the static cuda runtime find the driver (libcuda.dyllib) at runtime. + set_property(TARGET CudaOnlyLinkSystemDeviceLibraries PROPERTY BUILD_RPATH ${CMAKE_CUDA_IMPLICIT_LINK_DIRECTORIES}) +endif() diff --git a/Tests/CudaOnly/LinkSystemDeviceLibraries/main.cu b/Tests/CudaOnly/LinkSystemDeviceLibraries/main.cu new file mode 100644 index 0000000..7eecec1 --- /dev/null +++ b/Tests/CudaOnly/LinkSystemDeviceLibraries/main.cu @@ -0,0 +1,77 @@ + +#include <cublas_v2.h> +#include <cuda_runtime.h> +#include <iostream> + +__global__ void deviceCublasSgemm(int n, float alpha, float beta, + const float* d_A, const float* d_B, + float* d_C) +{ + cublasHandle_t cnpHandle; + cublasStatus_t status = cublasCreate(&cnpHandle); + + if (status != CUBLAS_STATUS_SUCCESS) { + return; + } + + // Call function defined in the cublas_device system static library. + // This way we can verify that we properly pass system libraries to the + // device link line + status = cublasSgemm(cnpHandle, CUBLAS_OP_N, CUBLAS_OP_N, n, n, n, &alpha, + d_A, n, d_B, n, &beta, d_C, n); + + cublasDestroy(cnpHandle); +} + +int choose_cuda_device() +{ + int nDevices = 0; + cudaError_t err = cudaGetDeviceCount(&nDevices); + if (err != cudaSuccess) { + std::cerr << "Failed to retrieve the number of CUDA enabled devices" + << std::endl; + return 1; + } + for (int i = 0; i < nDevices; ++i) { + cudaDeviceProp prop; + cudaError_t err = cudaGetDeviceProperties(&prop, i); + if (err != cudaSuccess) { + std::cerr << "Could not retrieve properties from CUDA device " << i + << std::endl; + return 1; + } + + if (prop.major > 3 || (prop.major == 3 && prop.minor >= 5)) { + err = cudaSetDevice(i); + if (err != cudaSuccess) { + std::cout << "Could not select CUDA device " << i << std::endl; + } else { + return 0; + } + } + } + + std::cout << "Could not find a CUDA enabled card supporting compute >=3.5" + << std::endl; + return 1; +} + +int main(int argc, char** argv) +{ + int ret = choose_cuda_device(); + if (ret) { + return 0; + } + + // initial values that will make sure that the cublasSgemm won't actually + // do any work + int n = 0; + float alpha = 1; + float beta = 1; + float* d_A = nullptr; + float* d_B = nullptr; + float* d_C = nullptr; + deviceCublasSgemm<<<1, 1>>>(n, alpha, beta, d_A, d_B, d_C); + + return 0; +} diff --git a/Tests/CudaOnly/PDB/CMakeLists.txt b/Tests/CudaOnly/PDB/CMakeLists.txt new file mode 100644 index 0000000..34e1e5c --- /dev/null +++ b/Tests/CudaOnly/PDB/CMakeLists.txt @@ -0,0 +1,19 @@ +cmake_minimum_required(VERSION 3.11) +project (CudaOnlyPDB CUDA) + +add_executable(CudaOnlyPDB main.cu) +set_target_properties(CudaOnlyPDB PROPERTIES + PDB_NAME LinkPDBName + PDB_OUTPUT_DIRECTORY LinkPDBDir + COMPILE_PDB_NAME CompPDBName + COMPILE_PDB_OUTPUT_DIRECTORY CompPDBDir + ) + +set(pdbs + ${CMAKE_CURRENT_BINARY_DIR}/CompPDBDir/${CMAKE_CFG_INTDIR}/CompPDBName.pdb + ${CMAKE_CURRENT_BINARY_DIR}/LinkPDBDir/${CMAKE_CFG_INTDIR}/LinkPDBName.pdb + ) +add_custom_command(TARGET CudaOnlyPDB POST_BUILD + COMMAND ${CMAKE_COMMAND} -Dconfig=$<CONFIG> "-Dpdbs=${pdbs}" + -P ${CMAKE_CURRENT_SOURCE_DIR}/check_pdbs.cmake + ) diff --git a/Tests/CudaOnly/PDB/check_pdbs.cmake b/Tests/CudaOnly/PDB/check_pdbs.cmake new file mode 100644 index 0000000..5e01ca7 --- /dev/null +++ b/Tests/CudaOnly/PDB/check_pdbs.cmake @@ -0,0 +1,10 @@ +if(NOT "${config}" MATCHES "[Dd][Ee][Bb]") + return() +endif() +foreach(pdb ${pdbs}) + if(EXISTS "${pdb}") + message(STATUS "PDB Exists: ${pdb}") + else() + message(SEND_ERROR "PDB MISSING:\n ${pdb}") + endif() +endforeach() diff --git a/Tests/CudaOnly/PDB/main.cu b/Tests/CudaOnly/PDB/main.cu new file mode 100644 index 0000000..f8b643a --- /dev/null +++ b/Tests/CudaOnly/PDB/main.cu @@ -0,0 +1,4 @@ +int main() +{ + return 0; +} diff --git a/Tests/ExportImport/Export/CMakeLists.txt b/Tests/ExportImport/Export/CMakeLists.txt index eeae3f0..0f1a556 100644 --- a/Tests/ExportImport/Export/CMakeLists.txt +++ b/Tests/ExportImport/Export/CMakeLists.txt @@ -83,11 +83,23 @@ set_property(TARGET testLib7 PROPERTY OUTPUT_NAME testLib7-$<CONFIG>) add_library(testLib8 OBJECT testLib8A.c testLib8B.c sub/testLib8C.c) if(NOT CMAKE_GENERATOR STREQUAL "Xcode" OR NOT CMAKE_OSX_ARCHITECTURES MATCHES "[;$]") - set(maybe_testLib8 testLib8) + set(maybe_OBJECTS_DESTINATION OBJECTS DESTINATION $<1:lib>) else() - set(maybe_testLib8 "") + set(maybe_OBJECTS_DESTINATION "") endif() +cmake_policy(PUSH) +cmake_policy(SET CMP0022 NEW) +add_library(testLib9ObjPub OBJECT testLib9ObjPub.c) +target_compile_definitions(testLib9ObjPub INTERFACE testLib9ObjPub_USED) +add_library(testLib9ObjPriv OBJECT testLib9ObjPriv.c) +target_compile_definitions(testLib9ObjPriv INTERFACE testLib9ObjPriv_USED) +add_library(testLib9ObjIface OBJECT testLib9ObjIface.c) +target_compile_definitions(testLib9ObjIface INTERFACE testLib9ObjIface_USED) +add_library(testLib9 STATIC testLib9.c) +target_link_libraries(testLib9 INTERFACE testLib9ObjIface PUBLIC testLib9ObjPub PRIVATE testLib9ObjPriv) +cmake_policy(POP) + # Test using the target_link_libraries command to set the # LINK_INTERFACE_LIBRARIES* properties. We construct two libraries # providing the same two symbols. In each library one of the symbols @@ -344,6 +356,14 @@ install(FILES set_property(TARGET testLib2 APPEND PROPERTY INTERFACE_COMPILE_DEFINITIONS USING_TESTLIB2) set_property(TARGET testLib3 APPEND PROPERTY INTERFACE_COMPILE_DEFINITIONS USING_TESTLIB3) +set_target_properties(testLib3 PROPERTIES + EXPORT_PROPERTIES "EXPORTED_PROPERTY1" + EXPORTED_PROPERTY1 "EXPORTING_TESTLIB3") +set_target_properties(testLib4 PROPERTIES + EXPORTED_PROPERTY2 "EXPORTING_TESTLIB4_1" + EXPORTED_PROPERTY3 "EXPORTING_TESTLIB4_2") +set_property(TARGET testLib4 PROPERTY + EXPORT_PROPERTIES EXPORTED_PROPERTY2 EXPORTED_PROPERTY3) set_property(TARGET cmp0022NEW APPEND PROPERTY INTERFACE_LINK_LIBRARIES testLib2) # set_property(TARGET cmp0022NEW APPEND PROPERTY LINK_INTERFACE_LIBRARIES testLibIncludeRequired2) # TODO: Test for error @@ -483,7 +503,8 @@ install( TARGETS testExe1 testLib1 testLib2 testExe2 testLib3 testLib4 testExe3 testExe4 testExe2lib testLib4lib testLib4libdbg testLib4libopt - testLib6 testLib7 ${maybe_testLib8} + testLib6 testLib7 testLib8 + testLib9 testLibCycleA testLibCycleB testLibNoSONAME cmp0022NEW cmp0022OLD @@ -492,10 +513,15 @@ install( RUNTIME DESTINATION $<1:bin> LIBRARY DESTINATION $<1:lib> NAMELINK_SKIP ARCHIVE DESTINATION $<1:lib> - OBJECTS DESTINATION $<1:lib> + ${maybe_OBJECTS_DESTINATION} FRAMEWORK DESTINATION Frameworks BUNDLE DESTINATION Applications ) +install( + TARGETS + testLib9ObjPub testLib9ObjPriv testLib9ObjIface + EXPORT exp + ) if (APPLE) file(COPY testLib4.h DESTINATION ${CMAKE_CURRENT_BINARY_DIR}/testLib4.framework/Headers) file(COPY testLib4.h DESTINATION ${CMAKE_CURRENT_BINARY_DIR}/Debug/testLib4.framework/Headers) @@ -545,7 +571,8 @@ export(TARGETS testExe1 testLib1 testLib2 testLib3 FILE ExportBuildTree.cmake ) export(TARGETS testExe2 testLib4 testLib5 testLib6 testLib7 testExe3 testExe4 testExe2lib - ${maybe_testLib8} + testLib8 + testLib9 testLib9ObjPub testLib9ObjPriv testLib9ObjIface testLib4lib testLib4libdbg testLib4libopt testLibCycleA testLibCycleB testLibNoSONAME diff --git a/Tests/ExportImport/Export/testLib9.c b/Tests/ExportImport/Export/testLib9.c new file mode 100644 index 0000000..fe8610b --- /dev/null +++ b/Tests/ExportImport/Export/testLib9.c @@ -0,0 +1,15 @@ +#ifndef testLib9ObjPub_USED +#error "testLib9ObjPub_USED not defined!" +#endif +#ifndef testLib9ObjPriv_USED +#error "testLib9ObjPriv_USED not defined!" +#endif +#ifdef testLib9ObjIface_USED +#error "testLib9ObjIface_USED defined but should not be!" +#endif +int testLib9ObjPub(void); +int testLib9ObjPriv(void); +int testLib9(void) +{ + return (testLib9ObjPub() + testLib9ObjPriv()); +} diff --git a/Tests/ExportImport/Export/testLib9ObjIface.c b/Tests/ExportImport/Export/testLib9ObjIface.c new file mode 100644 index 0000000..e75440a --- /dev/null +++ b/Tests/ExportImport/Export/testLib9ObjIface.c @@ -0,0 +1,11 @@ +/* Duplicate symbols from other sources to verify that this source + is not included when the object library is used. */ +int testLib9ObjMissing(void); +int testLib9ObjPub(void) +{ + return testLib9ObjMissing(); +} +int testLib9ObjPriv(void) +{ + return testLib9ObjMissing(); +} diff --git a/Tests/ExportImport/Export/testLib9ObjPriv.c b/Tests/ExportImport/Export/testLib9ObjPriv.c new file mode 100644 index 0000000..6fa63cc --- /dev/null +++ b/Tests/ExportImport/Export/testLib9ObjPriv.c @@ -0,0 +1,4 @@ +int testLib9ObjPriv(void) +{ + return 0; +} diff --git a/Tests/ExportImport/Export/testLib9ObjPub.c b/Tests/ExportImport/Export/testLib9ObjPub.c new file mode 100644 index 0000000..66e2624 --- /dev/null +++ b/Tests/ExportImport/Export/testLib9ObjPub.c @@ -0,0 +1,4 @@ +int testLib9ObjPub(void) +{ + return 0; +} diff --git a/Tests/ExportImport/Import/A/CMakeLists.txt b/Tests/ExportImport/Import/A/CMakeLists.txt index 01960ea..39a89dc 100644 --- a/Tests/ExportImport/Import/A/CMakeLists.txt +++ b/Tests/ExportImport/Import/A/CMakeLists.txt @@ -32,6 +32,20 @@ add_executable(imp_testExe1 ${Import_BINARY_DIR}/exp_generated4.c ) +function(checkForProperty _TARGET _PROP _EXPECTED) + get_target_property(EXPORTED_PROPERTY ${_TARGET} "${_PROP}") + if (NOT EXPORTED_PROPERTY STREQUAL "${_EXPECTED}") + message(SEND_ERROR "${_TARGET} was expected to export \"${_PROP}\" with value \"${_EXPECTED}\" but got \"${EXPORTED_PROPERTY}\"") + endif() +endfunction() + +checkForProperty(bld_testLib3 "EXPORTED_PROPERTY1" "EXPORTING_TESTLIB3") +checkForProperty(exp_testLib3 "EXPORTED_PROPERTY1" "EXPORTING_TESTLIB3") +checkForProperty(bld_testLib4 "EXPORTED_PROPERTY2" "EXPORTING_TESTLIB4_1") +checkForProperty(exp_testLib4 "EXPORTED_PROPERTY2" "EXPORTING_TESTLIB4_1") +checkForProperty(bld_testLib4 "EXPORTED_PROPERTY3" "EXPORTING_TESTLIB4_2") +checkForProperty(exp_testLib4 "EXPORTED_PROPERTY3" "EXPORTING_TESTLIB4_2") + # Try linking to a library imported from the install tree. target_link_libraries(imp_testExe1 exp_testLib2 @@ -229,15 +243,44 @@ add_library(imp_lib1b STATIC imp_lib1.c) target_link_libraries(imp_lib1b bld_testLib2) if(NOT CMAKE_GENERATOR STREQUAL "Xcode" OR NOT CMAKE_OSX_ARCHITECTURES MATCHES "[;$]") - # Create a executable that is using objects imported from the install tree - add_executable(imp_testLib8 imp_testLib8.c $<TARGET_OBJECTS:exp_testLib8>) + set(bld_objlib_type OBJECT_LIBRARY) + + # Create executables using objects imported from the install tree + add_executable(imp_testLib8_src imp_testLib8.c $<TARGET_OBJECTS:exp_testLib8>) + add_executable(imp_testLib8_link imp_testLib8.c) + target_link_libraries(imp_testLib8_link exp_testLib8) if(NOT CMAKE_GENERATOR STREQUAL "Xcode" OR NOT XCODE_VERSION VERSION_LESS 5) - # Create a executable that is using objects imported from the build tree - add_executable(imp_testLib8b imp_testLib8.c $<TARGET_OBJECTS:bld_testLib8>) + # Create executables using objects imported from the build tree + add_executable(imp_testLib8b_src imp_testLib8.c $<TARGET_OBJECTS:bld_testLib8>) + add_executable(imp_testLib8b_link imp_testLib8.c) + target_link_libraries(imp_testLib8b_link bld_testLib8) endif() +else() + set(bld_objlib_type INTERFACE_LIBRARY) endif() +# Create an executable that uses a library imported from the install tree +# that itself was built using an object library. Verify we get the usage +# requirements. +add_executable(imp_testLib9 imp_testLib9.c) +target_link_libraries(imp_testLib9 exp_testLib9) +# Similarly for importing from the build tree. +add_executable(imp_testLib9b imp_testLib9.c) +target_link_libraries(imp_testLib9b bld_testLib9) + +# Check that object libraries were transformed on export as expected. +foreach(vis Pub Priv Iface) + get_property(type TARGET exp_testLib9Obj${vis} PROPERTY TYPE) + if(NOT type STREQUAL INTERFACE_LIBRARY) + message(FATAL_ERROR "exp_testLib9Obj${vis} type is '${type}', not 'INTERFACE_LIBRARY'") + endif() + get_property(type TARGET bld_testLib9Obj${vis} PROPERTY TYPE) + if(NOT type STREQUAL "${bld_objlib_type}") + message(FATAL_ERROR "bld_testLib9Obj${vis} type is '${type}', not '${bld_objlib_type}'") + endif() +endforeach() + #----------------------------------------------------------------------------- # Test that handling imported targets, including transitive dependencies, # works in CheckFunctionExists (...and hopefully all other try_compile() checks diff --git a/Tests/ExportImport/Import/A/imp_testLib9.c b/Tests/ExportImport/Import/A/imp_testLib9.c new file mode 100644 index 0000000..f9c05fd --- /dev/null +++ b/Tests/ExportImport/Import/A/imp_testLib9.c @@ -0,0 +1,16 @@ +#ifndef testLib9ObjPub_USED +#error "testLib9ObjPub_USED not defined!" +#endif +#ifdef testLib9ObjPriv_USED +#error "testLib9ObjPriv_USED defined but should not be!" +#endif +#ifndef testLib9ObjIface_USED +#error "testLib9ObjIface_USED not defined!" +#endif + +int testLib9(void); + +int main() +{ + return testLib9(); +} diff --git a/Tests/FindCURL/CMakeLists.txt b/Tests/FindCURL/CMakeLists.txt new file mode 100644 index 0000000..0cfd629 --- /dev/null +++ b/Tests/FindCURL/CMakeLists.txt @@ -0,0 +1,10 @@ +add_test(NAME FindCURL.Test COMMAND + ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION> + --build-and-test + "${CMake_SOURCE_DIR}/Tests/FindCURL/Test" + "${CMake_BINARY_DIR}/Tests/FindCURL/Test" + ${build_generator_args} + --build-project TestFindCURL + --build-options ${build_options} + --test-command ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION> + ) diff --git a/Tests/FindCURL/Test/CMakeLists.txt b/Tests/FindCURL/Test/CMakeLists.txt new file mode 100644 index 0000000..f0e5568 --- /dev/null +++ b/Tests/FindCURL/Test/CMakeLists.txt @@ -0,0 +1,16 @@ +cmake_minimum_required(VERSION 3.10) +project(TestFindCURL C) +include(CTest) + +find_package(CURL REQUIRED) + +add_definitions(-DCMAKE_EXPECTED_CURL_VERSION="${CURL_VERSION_STRING}") + +add_executable(test_tgt main.c) +target_link_libraries(test_tgt CURL::CURL) +add_test(NAME test_tgt COMMAND test_tgt) + +add_executable(test_var main.c) +target_include_directories(test_var PRIVATE ${CURL_INCLUDE_DIRS}) +target_link_libraries(test_var PRIVATE ${CURL_LIBRARIES}) +add_test(NAME test_var COMMAND test_var) diff --git a/Tests/FindCURL/Test/main.c b/Tests/FindCURL/Test/main.c new file mode 100644 index 0000000..263775f --- /dev/null +++ b/Tests/FindCURL/Test/main.c @@ -0,0 +1,17 @@ +#include <curl/curl.h> +#include <stdio.h> +#include <stdlib.h> + +int main() +{ + struct curl_slist* slist; + + curl_global_init(0); + + slist = curl_slist_append(NULL, "CMake"); + curl_slist_free_all(slist); + + curl_global_cleanup(); + + return 0; +} diff --git a/Tests/FindJPEG/CMakeLists.txt b/Tests/FindJPEG/CMakeLists.txt new file mode 100644 index 0000000..c8663c5 --- /dev/null +++ b/Tests/FindJPEG/CMakeLists.txt @@ -0,0 +1,10 @@ +add_test(NAME FindJPEG.Test COMMAND + ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION> + --build-and-test + "${CMake_SOURCE_DIR}/Tests/FindJPEG/Test" + "${CMake_BINARY_DIR}/Tests/FindJPEG/Test" + ${build_generator_args} + --build-project TestFindJPEG + --build-options ${build_options} + --test-command ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION> + ) diff --git a/Tests/FindJPEG/Test/CMakeLists.txt b/Tests/FindJPEG/Test/CMakeLists.txt new file mode 100644 index 0000000..a744f85 --- /dev/null +++ b/Tests/FindJPEG/Test/CMakeLists.txt @@ -0,0 +1,14 @@ +cmake_minimum_required(VERSION 3.1) +project(TestFindJPEG C) +include(CTest) + +find_package(JPEG) + +add_executable(test_jpeg_tgt main.c) +target_link_libraries(test_jpeg_tgt JPEG::JPEG) +add_test(NAME test_jpeg_tgt COMMAND test_jpeg_tgt) + +add_executable(test_jpeg_var main.c) +target_include_directories(test_jpeg_var PRIVATE ${JPEG_INCLUDE_DIRS}) +target_link_libraries(test_jpeg_var PRIVATE ${JPEG_LIBRARIES}) +add_test(NAME test_jpeg_var COMMAND test_jpeg_var) diff --git a/Tests/FindJPEG/Test/main.c b/Tests/FindJPEG/Test/main.c new file mode 100644 index 0000000..c6e48f0 --- /dev/null +++ b/Tests/FindJPEG/Test/main.c @@ -0,0 +1,16 @@ +#include <assert.h> +#include <stdio.h> + +#include <jpeglib.h> + +int main() +{ + /* Without any JPEG file to open, test that the call fails as + expected. This tests that linking worked. */ + struct jpeg_decompress_struct cinfo; + struct jpeg_error_mgr jerr; + cinfo.err = jpeg_std_error(&jerr); + jpeg_create_decompress(&cinfo); + + return 0; +} diff --git a/Tests/FindLibXml2/CMakeLists.txt b/Tests/FindLibXml2/CMakeLists.txt new file mode 100644 index 0000000..6c2464f --- /dev/null +++ b/Tests/FindLibXml2/CMakeLists.txt @@ -0,0 +1,10 @@ +add_test(NAME FindLibXml2.Test COMMAND + ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION> + --build-and-test + "${CMake_SOURCE_DIR}/Tests/FindLibXml2/Test" + "${CMake_BINARY_DIR}/Tests/FindLibXml2/Test" + ${build_generator_args} + --build-project TestFindLibXml2 + --build-options ${build_options} + --test-command ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION> + ) diff --git a/Tests/FindLibXml2/Test/CMakeLists.txt b/Tests/FindLibXml2/Test/CMakeLists.txt new file mode 100644 index 0000000..df5d8c3 --- /dev/null +++ b/Tests/FindLibXml2/Test/CMakeLists.txt @@ -0,0 +1,16 @@ +cmake_minimum_required(VERSION 3.4) +project(TestFindLibXml2 C) +include(CTest) + +find_package(LibXml2 REQUIRED) + +add_definitions(-DCMAKE_EXPECTED_LibXml2_VERSION="${LIBXML2_VERSION_STRING}") + +add_executable(test_tgt main.c) +target_link_libraries(test_tgt LibXml2::LibXml2) +add_test(NAME test_tgt COMMAND test_tgt) + +add_executable(test_var main.c) +target_include_directories(test_var PRIVATE ${LIBXML2_INCLUDE_DIRS}) +target_link_libraries(test_var PRIVATE ${LIBXML2_LIBRARIES}) +add_test(NAME test_var COMMAND test_var) diff --git a/Tests/FindLibXml2/Test/main.c b/Tests/FindLibXml2/Test/main.c new file mode 100644 index 0000000..264f07d --- /dev/null +++ b/Tests/FindLibXml2/Test/main.c @@ -0,0 +1,19 @@ +#include <assert.h> +#include <libxml/tree.h> +#include <string.h> + +int main() +{ + xmlDoc* doc; + + xmlInitParser(); + + doc = xmlNewDoc(BAD_CAST "1.0"); + xmlFreeDoc(doc); + + assert(strstr(CMAKE_EXPECTED_LibXml2_VERSION, LIBXML_DOTTED_VERSION)); + + xmlCleanupParser(); + + return 0; +} diff --git a/Tests/FindMatlab/basic_checks/CMakeLists.txt b/Tests/FindMatlab/basic_checks/CMakeLists.txt index bf54427..4a74d93 100644 --- a/Tests/FindMatlab/basic_checks/CMakeLists.txt +++ b/Tests/FindMatlab/basic_checks/CMakeLists.txt @@ -8,8 +8,23 @@ set(MATLAB_FIND_DEBUG TRUE) # the success of the following command is dependent on the current configuration: # - on 32bits builds (cmake is building with 32 bits), it looks for 32 bits Matlab # - on 64bits builds (cmake is building with 64 bits), it looks for 64 bits Matlab -find_package(Matlab REQUIRED COMPONENTS MX_LIBRARY MAIN_PROGRAM) +if(IS_MCR) + set(components MX_LIBRARY) + set(RUN_UNIT_TESTS FALSE) +else() + set(RUN_UNIT_TESTS TRUE) + set(components MX_LIBRARY MAIN_PROGRAM) +endif() + +if(NOT "${MCR_ROOT}" STREQUAL "") + set(Matlab_ROOT_DIR "${MCR_ROOT}") + if(NOT EXISTS "${MCR_ROOT}") + message(FATAL_ERROR "MCR does not exist ${MCR_ROOT}") + endif() +endif() + +find_package(Matlab REQUIRED COMPONENTS ${components}) matlab_add_mex( @@ -21,37 +36,39 @@ matlab_add_mex( DOCUMENTATION ${CMAKE_CURRENT_SOURCE_DIR}/../help_text1.m.txt ) +if(RUN_UNIT_TESTS) + matlab_add_unit_test( + NAME ${PROJECT_NAME}_matlabtest-1 + TIMEOUT 300 + UNITTEST_FILE ${CMAKE_CURRENT_SOURCE_DIR}/../cmake_matlab_unit_tests1.m + ADDITIONAL_PATH $<TARGET_FILE_DIR:cmake_matlab_test_wrapper1> + ) + + # timeout tests, TIMEOUT set to very short on purpose + matlab_add_unit_test( + NAME ${PROJECT_NAME}_matlabtest-2 + TIMEOUT 15 + UNITTEST_FILE ${CMAKE_CURRENT_SOURCE_DIR}/../cmake_matlab_unit_tests_timeout.m + ADDITIONAL_PATH $<TARGET_FILE_DIR:cmake_matlab_test_wrapper1> + ) + set_tests_properties(${PROJECT_NAME}_matlabtest-2 PROPERTIES WILL_FAIL TRUE) + + + # testing the test without the unittest framework of Matlab + matlab_add_unit_test( + NAME ${PROJECT_NAME}_matlabtest-3 + TIMEOUT 300 + NO_UNITTEST_FRAMEWORK + UNITTEST_FILE ${CMAKE_CURRENT_SOURCE_DIR}/../cmake_matlab_unit_tests2.m + ADDITIONAL_PATH $<TARGET_FILE_DIR:cmake_matlab_test_wrapper1> + ) -matlab_add_unit_test( - NAME ${PROJECT_NAME}_matlabtest-1 - TIMEOUT 90 - UNITTEST_FILE ${CMAKE_CURRENT_SOURCE_DIR}/../cmake_matlab_unit_tests1.m - ADDITIONAL_PATH $<TARGET_FILE_DIR:cmake_matlab_test_wrapper1> - ) - -matlab_add_unit_test( - NAME ${PROJECT_NAME}_matlabtest-2 - TIMEOUT 15 - UNITTEST_FILE ${CMAKE_CURRENT_SOURCE_DIR}/../cmake_matlab_unit_tests_timeout.m - ADDITIONAL_PATH $<TARGET_FILE_DIR:cmake_matlab_test_wrapper1> - ) -set_tests_properties(${PROJECT_NAME}_matlabtest-2 PROPERTIES WILL_FAIL TRUE) - - -# testing the test without the unittest framework of Matlab -matlab_add_unit_test( - NAME ${PROJECT_NAME}_matlabtest-3 - TIMEOUT 30 - NO_UNITTEST_FRAMEWORK - UNITTEST_FILE ${CMAKE_CURRENT_SOURCE_DIR}/../cmake_matlab_unit_tests2.m - ADDITIONAL_PATH $<TARGET_FILE_DIR:cmake_matlab_test_wrapper1> - ) - -matlab_add_unit_test( - NAME ${PROJECT_NAME}_matlabtest-4 - TIMEOUT 30 - NO_UNITTEST_FRAMEWORK - UNITTEST_FILE ${CMAKE_CURRENT_SOURCE_DIR}/../cmake_matlab_unit_tests3.m - ADDITIONAL_PATH $<TARGET_FILE_DIR:cmake_matlab_test_wrapper1> - ) -set_tests_properties(${PROJECT_NAME}_matlabtest-4 PROPERTIES WILL_FAIL TRUE) + matlab_add_unit_test( + NAME ${PROJECT_NAME}_matlabtest-4 + TIMEOUT 300 + NO_UNITTEST_FRAMEWORK + UNITTEST_FILE ${CMAKE_CURRENT_SOURCE_DIR}/../cmake_matlab_unit_tests3.m + ADDITIONAL_PATH $<TARGET_FILE_DIR:cmake_matlab_test_wrapper1> + ) + set_tests_properties(${PROJECT_NAME}_matlabtest-4 PROPERTIES WILL_FAIL TRUE) +endif() diff --git a/Tests/FindMatlab/components_checks/CMakeLists.txt b/Tests/FindMatlab/components_checks/CMakeLists.txt index 3dec093..da6a2b0 100644 --- a/Tests/FindMatlab/components_checks/CMakeLists.txt +++ b/Tests/FindMatlab/components_checks/CMakeLists.txt @@ -5,10 +5,18 @@ project(component_checks) set(MATLAB_FIND_DEBUG TRUE) +if(NOT "${MCR_ROOT}" STREQUAL "") + set(Matlab_ROOT_DIR "${MCR_ROOT}") + if(NOT EXISTS "${MCR_ROOT}") + message(FATAL_ERROR "MCR does not exist ${MCR_ROOT}") + endif() +endif() + # the success of the following command is dependent on the current configuration: # - on 32bits builds (cmake is building with 32 bits), it looks for 32 bits Matlab # - on 64bits builds (cmake is building with 64 bits), it looks for 64 bits Matlab -find_package(Matlab REQUIRED COMPONENTS MX_LIBRARY ENG_LIBRARY MAT_LIBRARY MAIN_PROGRAM) +find_package(Matlab REQUIRED COMPONENTS MX_LIBRARY ENG_LIBRARY MAT_LIBRARY + OPTIONAL_COMPONENTS MAIN_PROGRAM) message(STATUS "FindMatlab libraries: ${Matlab_LIBRARIES}") diff --git a/Tests/FindMatlab/failure_reports/CMakeLists.txt b/Tests/FindMatlab/failure_reports/CMakeLists.txt new file mode 100644 index 0000000..e597a4a --- /dev/null +++ b/Tests/FindMatlab/failure_reports/CMakeLists.txt @@ -0,0 +1,56 @@ + +cmake_minimum_required (VERSION 2.8.12) +enable_testing() +project(failure_reports) + +# gather tests about proper failure reports + +set(MATLAB_FIND_DEBUG TRUE) + +if(IS_MCR) + set(components MX_LIBRARY) + set(RUN_UNIT_TESTS FALSE) +else() + set(RUN_UNIT_TESTS TRUE) + set(components MX_LIBRARY MAIN_PROGRAM) +endif() + +if(NOT "${MCR_ROOT}" STREQUAL "") + set(Matlab_ROOT_DIR "${MCR_ROOT}") + if(NOT EXISTS "${MCR_ROOT}") + message(FATAL_ERROR "MCR does not exist ${MCR_ROOT}") + endif() +endif() + +find_package(Matlab REQUIRED COMPONENTS ${components}) + +# main extensions for testing, same as other tests +matlab_add_mex( + # target name + NAME cmake_matlab_test_wrapper1 + # output name + OUTPUT_NAME cmake_matlab_mex1 + SRC ${CMAKE_CURRENT_SOURCE_DIR}/../matlab_wrapper1.cpp + DOCUMENTATION ${CMAKE_CURRENT_SOURCE_DIR}/../help_text1.m.txt + ) + +if(RUN_UNIT_TESTS) + # the unit test file does not exist: the failure should be properly reported + matlab_add_unit_test( + NAME ${PROJECT_NAME}_matlabtest-1 + TIMEOUT 300 + UNITTEST_FILE ${CMAKE_CURRENT_SOURCE_DIR}/../nonexistantfile.m + ADDITIONAL_PATH $<TARGET_FILE_DIR:cmake_matlab_test_wrapper1> + ) + set_tests_properties(${PROJECT_NAME}_matlabtest-1 PROPERTIES WILL_FAIL TRUE) + + # without the unit test framework + matlab_add_unit_test( + NAME ${PROJECT_NAME}_matlabtest-2 + TIMEOUT 300 + NO_UNITTEST_FRAMEWORK + UNITTEST_FILE ${CMAKE_CURRENT_SOURCE_DIR}/../nonexistantfile2.m + ADDITIONAL_PATH $<TARGET_FILE_DIR:cmake_matlab_test_wrapper1> + ) + set_tests_properties(${PROJECT_NAME}_matlabtest-2 PROPERTIES WILL_FAIL TRUE) +endif() diff --git a/Tests/FindMatlab/versions_checks/CMakeLists.txt b/Tests/FindMatlab/versions_checks/CMakeLists.txt index 5d20685..d015730 100644 --- a/Tests/FindMatlab/versions_checks/CMakeLists.txt +++ b/Tests/FindMatlab/versions_checks/CMakeLists.txt @@ -7,6 +7,13 @@ set(MATLAB_FIND_DEBUG TRUE) set(MATLAB_ADDITIONAL_VERSIONS "dummy=14.9") +if(NOT "${MCR_ROOT}" STREQUAL "") + set(Matlab_ROOT_DIR "${MCR_ROOT}") + if(NOT EXISTS "${MCR_ROOT}") + message(FATAL_ERROR "MCR does not exist ${MCR_ROOT}") + endif() +endif() + # the success of the following command is dependent on the current configuration # in this case, we are only interested in the version macros find_package(Matlab) diff --git a/Tests/FindPython/CMakeLists.txt b/Tests/FindPython/CMakeLists.txt new file mode 100644 index 0000000..639d29c --- /dev/null +++ b/Tests/FindPython/CMakeLists.txt @@ -0,0 +1,69 @@ +add_test(NAME FindPython.Python2 COMMAND + ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION> + --build-and-test + "${CMake_SOURCE_DIR}/Tests/FindPython/Python2" + "${CMake_BINARY_DIR}/Tests/FindPython/Python2" + ${build_generator_args} + --build-project TestPython2 + --build-options ${build_options} + --test-command ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION> + ) + +add_test(NAME FindPython.Python2Fail COMMAND + ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION> + --build-and-test + "${CMake_SOURCE_DIR}/Tests/FindPython/Python2Fail" + "${CMake_BINARY_DIR}/Tests/FindPython/Python2Fail" + ${build_generator_args} + --build-project TestPython2Fail + --build-options ${build_options} + --test-command ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION> + ) +set_tests_properties(FindPython.Python2Fail PROPERTIES + PASS_REGULAR_EXPRESSION "Could NOT find Python2 \\(missing: foobar\\)") + +add_test(NAME FindPython.Python3 COMMAND + ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION> + --build-and-test + "${CMake_SOURCE_DIR}/Tests/FindPython/Python3" + "${CMake_BINARY_DIR}/Tests/FindPython/Python3" + ${build_generator_args} + --build-project TestPython3 + --build-options ${build_options} + --test-command ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION> + ) + +add_test(NAME FindPython.Python3Fail COMMAND + ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION> + --build-and-test + "${CMake_SOURCE_DIR}/Tests/FindPython/Python3Fail" + "${CMake_BINARY_DIR}/Tests/FindPython/Python3Fail" + ${build_generator_args} + --build-project TestPython3Fail + --build-options ${build_options} + --test-command ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION> + ) +set_tests_properties(FindPython.Python3Fail PROPERTIES + PASS_REGULAR_EXPRESSION "Could NOT find Python3 \\(missing: foobar\\)") + +add_test(NAME FindPython.Python COMMAND + ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION> + --build-and-test + "${CMake_SOURCE_DIR}/Tests/FindPython/Python" + "${CMake_BINARY_DIR}/Tests/FindPython/Python" + ${build_generator_args} + --build-project TestPython + --build-options ${build_options} + --test-command ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION> + ) + +add_test(NAME FindPython.MultiplePackages COMMAND + ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION> + --build-and-test + "${CMake_SOURCE_DIR}/Tests/FindPython/MultiplePackages" + "${CMake_BINARY_DIR}/Tests/FindPython/MultiplePackages" + ${build_generator_args} + --build-project TestMultiplePackages + --build-options ${build_options} + --test-command ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION> + ) diff --git a/Tests/FindPython/MultiplePackages/CMakeLists.txt b/Tests/FindPython/MultiplePackages/CMakeLists.txt new file mode 100644 index 0000000..5c85155 --- /dev/null +++ b/Tests/FindPython/MultiplePackages/CMakeLists.txt @@ -0,0 +1,33 @@ +cmake_minimum_required(VERSION 3.1) + +project(TestMultiplePackages C) + +find_package (Python2 REQUIRED COMPONENTS Interpreter Development) +find_package (Python3 REQUIRED COMPONENTS Interpreter Development) + +# Must find Python 3 +find_package (Python REQUIRED) + +if (NOT Python3_EXECUTABLE STREQUAL Python_EXECUTABLE) + message (FATAL_ERROR + "Python interpreters do not match:\n" + " Python_EXECUTABLE='${Python_EXECUTABLE}'\n" + " Python3_EXECUTABLE='${Python3_EXECUTABLE}'\n" + ) +endif() + + +Python2_add_library (spam2 MODULE ../spam.c) +target_compile_definitions (spam2 PRIVATE PYTHON2) + +Python3_add_library (spam3 MODULE ../spam.c) +target_compile_definitions (spam3 PRIVATE PYTHON3) + + +add_test (NAME python2_spam2 + COMMAND "${CMAKE_COMMAND}" -E env "PYTHONPATH=$<TARGET_FILE_DIR:spam3>" + "${Python2_EXECUTABLE}" -c "import spam2; spam2.system(\"cd\")") + +add_test (NAME python3_spam3 + COMMAND "${CMAKE_COMMAND}" -E env "PYTHONPATH=$<TARGET_FILE_DIR:spam3>" + "${Python3_EXECUTABLE}" -c "import spam3; spam3.system(\"cd\")") diff --git a/Tests/FindPython/Python/CMakeLists.txt b/Tests/FindPython/Python/CMakeLists.txt new file mode 100644 index 0000000..bebd23f --- /dev/null +++ b/Tests/FindPython/Python/CMakeLists.txt @@ -0,0 +1,17 @@ +cmake_minimum_required(VERSION 3.1) + +project(TestPython C) + +include(CTest) + +find_package(Python 3 REQUIRED COMPONENTS Interpreter Development) +if (NOT Python_FOUND) + message (FATAL_ERROR "Fail to found Python 3") +endif() + +Python_add_library (spam3 MODULE ../spam.c) +target_compile_definitions (spam3 PRIVATE PYTHON3) + +add_test (NAME python_spam3 + COMMAND "${CMAKE_COMMAND}" -E env "PYTHONPATH=$<TARGET_FILE_DIR:spam3>" + "${Python_EXECUTABLE}" -c "import spam3; spam3.system(\"cd\")") diff --git a/Tests/FindPython/Python2/CMakeLists.txt b/Tests/FindPython/Python2/CMakeLists.txt new file mode 100644 index 0000000..9622b6f --- /dev/null +++ b/Tests/FindPython/Python2/CMakeLists.txt @@ -0,0 +1,22 @@ +cmake_minimum_required(VERSION 3.1) + +project(TestPython2 C) + +include(CTest) + +find_package(Python2 3 QUIET) +if (Python2_FOUND) + message (FATAL_ERROR "Wrong python version found: ${Python2_VERSION}") +endif() + +find_package(Python2 REQUIRED COMPONENTS Interpreter Development) +if (NOT Python2_FOUND) + message (FATAL_ERROR "Fail to found Python 2") +endif() + +Python2_add_library (spam2 MODULE ../spam.c) +target_compile_definitions (spam2 PRIVATE PYTHON2) + +add_test (NAME python2_spam2 + COMMAND "${CMAKE_COMMAND}" -E env "PYTHONPATH=$<TARGET_FILE_DIR:spam2>" + "${Python2_EXECUTABLE}" -c "import spam2; spam2.system(\"cd\")") diff --git a/Tests/FindPython/Python2Fail/CMakeLists.txt b/Tests/FindPython/Python2Fail/CMakeLists.txt new file mode 100644 index 0000000..989688f --- /dev/null +++ b/Tests/FindPython/Python2Fail/CMakeLists.txt @@ -0,0 +1,14 @@ +cmake_minimum_required(VERSION 3.1) + +project(TestPython2Fail C) + +include(CTest) + +find_package(Python2 REQUIRED COMPONENTS Interpreter Development foobar) + +Python2_add_library (spam2 MODULE ../spam.c) +target_compile_definitions (spam2 PRIVATE PYTHON2) + +add_test (NAME python2_spam2 + COMMAND "${CMAKE_COMMAND}" -E env "PYTHONPATH=$<TARGET_FILE_DIR:spam2>" + "${Python2_EXECUTABLE}" -c "import spam2; spam2.system(\"cd\")") diff --git a/Tests/FindPython/Python3/CMakeLists.txt b/Tests/FindPython/Python3/CMakeLists.txt new file mode 100644 index 0000000..cb86eae --- /dev/null +++ b/Tests/FindPython/Python3/CMakeLists.txt @@ -0,0 +1,22 @@ +cmake_minimum_required(VERSION 3.1) + +project(TestPython3 C) + +include(CTest) + +find_package(Python3 2 QUIET) +if (Python3_FOUND) + message (FATAL_ERROR "Wrong python version found: ${Python3_VERSION}") +endif() + +find_package(Python3 REQUIRED COMPONENTS Interpreter Development) +if (NOT Python3_FOUND) + message (FATAL_ERROR "Fail to found Python 3") +endif() + +Python3_add_library (spam3 MODULE ../spam.c) +target_compile_definitions (spam3 PRIVATE PYTHON3) + +add_test (NAME python3_spam3 + COMMAND "${CMAKE_COMMAND}" -E env "PYTHONPATH=$<TARGET_FILE_DIR:spam3>" + "${Python3_EXECUTABLE}" -c "import spam3; spam3.system(\"cd\")") diff --git a/Tests/FindPython/Python3Fail/CMakeLists.txt b/Tests/FindPython/Python3Fail/CMakeLists.txt new file mode 100644 index 0000000..cd46c88 --- /dev/null +++ b/Tests/FindPython/Python3Fail/CMakeLists.txt @@ -0,0 +1,14 @@ +cmake_minimum_required(VERSION 3.1) + +project(TestPython3Fail C) + +include(CTest) + +find_package(Python3 REQUIRED COMPONENTS Interpreter Development foobar) + +Python3_add_library (spam3 MODULE ../spam.c) +target_compile_definitions (spam3 PRIVATE PYTHON3) + +add_test (NAME python3_spam3 + COMMAND "${CMAKE_COMMAND}" -E env "PYTHONPATH=$<TARGET_FILE_DIR:spam3>" + "${Python3_EXECUTABLE}" -c "import spam3; spam3.system(\"cd\")") diff --git a/Tests/FindPython/spam.c b/Tests/FindPython/spam.c new file mode 100644 index 0000000..1c65d54 --- /dev/null +++ b/Tests/FindPython/spam.c @@ -0,0 +1,41 @@ + +#include <Python.h> + +static PyObject* spam_system(PyObject* self, PyObject* args) +{ + const char* command; + int sts; + + if (!PyArg_ParseTuple(args, "s", &command)) + return NULL; + sts = system(command); + /* return PyLong_FromLong(sts); */ + return Py_BuildValue("i", sts); +} + +static PyMethodDef SpamMethods[] = { + { "system", spam_system, METH_VARARGS, "Execute a shell command." }, + { NULL, NULL, 0, NULL } /* Sentinel */ +}; + +#if defined(PYTHON2) +PyMODINIT_FUNC initspam2(void) +{ + (void)Py_InitModule("spam2", SpamMethods); +} +#endif + +#if defined(PYTHON3) +static struct PyModuleDef spammodule = { + PyModuleDef_HEAD_INIT, "spam3", /* name of module */ + NULL, /* module documentation, may be NULL */ + -1, /* size of per-interpreter state of the module, + or -1 if the module keeps state in global variables. */ + SpamMethods +}; + +PyMODINIT_FUNC PyInit_spam3(void) +{ + return PyModule_Create(&spammodule); +} +#endif diff --git a/Tests/FortranModules/Submodules/CMakeLists.txt b/Tests/FortranModules/Submodules/CMakeLists.txt index bf0152f..ab8e0f9 100644 --- a/Tests/FortranModules/Submodules/CMakeLists.txt +++ b/Tests/FortranModules/Submodules/CMakeLists.txt @@ -1 +1,23 @@ -add_executable(submod main.f90 provide.f90) +# The program units in this file consist of a module/submodule +# tree represented by the following graph: +# +# parent +# | +# / \ +# / \ +# child sibling +# | +# grandchild +# | +# GreatGrandChild +# +# where the parent node is a module and all other nodes are submodules. + +add_executable(submod + main.f90 + parent.f90 + child.f90 + grandchild.f90 + greatgrandchild.f90 + sibling.f90 + ) diff --git a/Tests/FortranModules/Submodules/child.f90 b/Tests/FortranModules/Submodules/child.f90 new file mode 100644 index 0000000..838ab61 --- /dev/null +++ b/Tests/FortranModules/Submodules/child.f90 @@ -0,0 +1,10 @@ +! Test the notation for a 1st-generation direct +! descendant of a parent module +submodule ( parent ) child + implicit none +contains + module function child_function() result(child_stuff) + logical :: child_stuff + child_stuff=.true. + end function +end submodule child diff --git a/Tests/FortranModules/Submodules/grandchild.f90 b/Tests/FortranModules/Submodules/grandchild.f90 new file mode 100644 index 0000000..1aef63e --- /dev/null +++ b/Tests/FortranModules/Submodules/grandchild.f90 @@ -0,0 +1,8 @@ +! Test the notation for an Nth-generation descendant +! for N>1, which necessitates the colon. +submodule ( parent : child ) grandchild +contains + module subroutine grandchild_subroutine() + print *,"Test passed." + end subroutine +end submodule grandchild diff --git a/Tests/FortranModules/Submodules/greatgrandchild.f90 b/Tests/FortranModules/Submodules/greatgrandchild.f90 new file mode 100644 index 0000000..85404ea --- /dev/null +++ b/Tests/FortranModules/Submodules/greatgrandchild.f90 @@ -0,0 +1,8 @@ +! Test the notation for an Nth-generation descendant +! for N>1, which necessitates the colon. +submodule ( parent : grandchild ) GreatGrandChild +contains + module subroutine GreatGrandChild_subroutine() + print *,"Test passed." + end subroutine +end submodule GreatGrandChild diff --git a/Tests/FortranModules/Submodules/main.f90 b/Tests/FortranModules/Submodules/main.f90 index 3c750ce..3cd2989 100644 --- a/Tests/FortranModules/Submodules/main.f90 +++ b/Tests/FortranModules/Submodules/main.f90 @@ -1,5 +1,7 @@ program main use parent, only : child_function,grandchild_subroutine + use parent, only : sibling_function,GreatGrandChild_subroutine implicit none if (child_function()) call grandchild_subroutine + if (sibling_function()) call GreatGrandChild_subroutine end program diff --git a/Tests/FortranModules/Submodules/parent.f90 b/Tests/FortranModules/Submodules/parent.f90 new file mode 100644 index 0000000..3180b70 --- /dev/null +++ b/Tests/FortranModules/Submodules/parent.f90 @@ -0,0 +1,22 @@ +module parent + implicit none + + interface + + ! Test Fortran 2008 "module function" syntax + module function child_function() result(child_stuff) + logical :: child_stuff + end function + module function sibling_function() result(sibling_stuff) + logical :: sibling_stuff + end function + + ! Test Fortran 2008 "module subroutine" syntax + module subroutine grandchild_subroutine() + end subroutine + module subroutine GreatGrandChild_subroutine() + end subroutine + + end interface + +end module parent diff --git a/Tests/FortranModules/Submodules/provide.f90 b/Tests/FortranModules/Submodules/provide.f90 deleted file mode 100644 index 0ad216a..0000000 --- a/Tests/FortranModules/Submodules/provide.f90 +++ /dev/null @@ -1,57 +0,0 @@ -! The program units in this file consist of a -! module/submodule tree represented by the following -! graph: -! -! parent -! | -! / \ -! / \ -! child sibling -! | -! grandchild -! -! where the parent node is a module and all other -! nodes are submodules. - -module parent - implicit none - - interface - - ! Test Fortran 2008 "module function" syntax - module function child_function() result(child_stuff) - logical :: child_stuff - end function - - ! Test Fortran 2008 "module subroutine" syntax - module subroutine grandchild_subroutine() - end subroutine - - end interface - -end module parent - -! Test the notation for a 1st-generation direct -! descendant of a parent module -submodule ( parent ) child - implicit none -contains - module function child_function() result(child_stuff) - logical :: child_stuff - child_stuff=.true. - end function -end submodule child - -! Empty submodule for checking disambiguation of -! nodes at the same vertical level in the tree -submodule ( parent ) sibling -end submodule sibling - -! Test the notation for an Nth-generation descendant -! for N>1, which necessitates the colon. -submodule ( parent : child ) grandchild -contains - module subroutine grandchild_subroutine() - print *,"Test passed." - end subroutine -end submodule grandchild diff --git a/Tests/FortranModules/Submodules/sibling.f90 b/Tests/FortranModules/Submodules/sibling.f90 new file mode 100644 index 0000000..8c0943d --- /dev/null +++ b/Tests/FortranModules/Submodules/sibling.f90 @@ -0,0 +1,9 @@ +! Empty submodule for checking disambiguation of +! nodes at the same vertical level in the tree +submodule ( parent ) sibling +contains + module function sibling_function() result(sibling_stuff) + logical :: sibling_stuff + sibling_stuff=.true. + end function +end submodule sibling diff --git a/Tests/GeneratorExpression/CMakeLists.txt b/Tests/GeneratorExpression/CMakeLists.txt index 19d12e5..3d08704 100644 --- a/Tests/GeneratorExpression/CMakeLists.txt +++ b/Tests/GeneratorExpression/CMakeLists.txt @@ -57,6 +57,11 @@ add_custom_target(check-part1 ALL -Dtest_strequal_angle_r_comma=$<STREQUAL:$<ANGLE-R>,$<COMMA>> -Dtest_strequal_both_empty=$<STREQUAL:,> -Dtest_strequal_one_empty=$<STREQUAL:something,> + -Dtest_inlist_true=$<IN_LIST:a,a$<SEMICOLON>b> + -Dtest_inlist_false=$<IN_LIST:c,a$<SEMICOLON>b> + -Dtest_inlist_empty_1=$<IN_LIST:a,> + -Dtest_inlist_empty_2=$<IN_LIST:,a> + -Dtest_inlist_empty_3=$<IN_LIST:,> -Dtest_angle_r=$<ANGLE-R> -Dtest_comma=$<COMMA> -Dtest_semicolon=$<SEMICOLON> diff --git a/Tests/GeneratorExpression/check-part1.cmake b/Tests/GeneratorExpression/check-part1.cmake index 60b193f..41bcd6d 100644 --- a/Tests/GeneratorExpression/check-part1.cmake +++ b/Tests/GeneratorExpression/check-part1.cmake @@ -49,6 +49,11 @@ check(test_strequal_semicolon "1") check(test_strequal_angle_r_comma "0") check(test_strequal_both_empty "1") check(test_strequal_one_empty "0") +check(test_inlist_true "1") +check(test_inlist_false "0") +check(test_inlist_empty_1 "0") +check(test_inlist_empty_2 "0") +check(test_inlist_empty_3 "0") check(test_angle_r ">") check(test_comma ",") check(test_semicolon ";") diff --git a/Tests/IncludeDirectories/CMakeLists.txt b/Tests/IncludeDirectories/CMakeLists.txt index db18462..b7b8320 100644 --- a/Tests/IncludeDirectories/CMakeLists.txt +++ b/Tests/IncludeDirectories/CMakeLists.txt @@ -65,6 +65,10 @@ else() PROPERTIES COMPILE_FLAGS "-ITarProp") endif() +add_library(ordertest ordertest.cpp) +target_include_directories(ordertest SYSTEM PUBLIC SystemIncludeDirectories/systemlib) +target_include_directories(ordertest PUBLIC SystemIncludeDirectories/userlib) + add_subdirectory(StandardIncludeDirectories) add_subdirectory(TargetIncludeDirectories) diff --git a/Tests/IncludeDirectories/SystemIncludeDirectories/systemlib/ordertest.h b/Tests/IncludeDirectories/SystemIncludeDirectories/systemlib/ordertest.h new file mode 100644 index 0000000..28915e6 --- /dev/null +++ b/Tests/IncludeDirectories/SystemIncludeDirectories/systemlib/ordertest.h @@ -0,0 +1 @@ +#error ordertest.h includes from systemlib diff --git a/Tests/IncludeDirectories/SystemIncludeDirectories/userlib/ordertest.h b/Tests/IncludeDirectories/SystemIncludeDirectories/userlib/ordertest.h new file mode 100644 index 0000000..fa882cb --- /dev/null +++ b/Tests/IncludeDirectories/SystemIncludeDirectories/userlib/ordertest.h @@ -0,0 +1 @@ +/* empty file */ diff --git a/Tests/IncludeDirectories/ordertest.cpp b/Tests/IncludeDirectories/ordertest.cpp new file mode 100644 index 0000000..7e24f77 --- /dev/null +++ b/Tests/IncludeDirectories/ordertest.cpp @@ -0,0 +1 @@ +#include "ordertest.h" diff --git a/Tests/Module/ExternalData/Data5/CMakeLists.txt b/Tests/Module/ExternalData/Data5/CMakeLists.txt index 13c7fab..ea67f05 100644 --- a/Tests/Module/ExternalData/Data5/CMakeLists.txt +++ b/Tests/Module/ExternalData/Data5/CMakeLists.txt @@ -2,21 +2,21 @@ ExternalData_Add_Test(Data5.A NAME Data5Check.A COMMAND ${CMAKE_COMMAND} - -D Data5=DATA{../Data.dat} + -D Data5=DATA{Data5.dat} -P ${CMAKE_CURRENT_SOURCE_DIR}/Data5Check.cmake ) ExternalData_Add_Target(Data5.A) ExternalData_Add_Test(Data5.B NAME Data5Check.B COMMAND ${CMAKE_COMMAND} - -D Data5=DATA{../Data.dat} + -D Data5=DATA{Data5.dat} -P ${CMAKE_CURRENT_SOURCE_DIR}/Data5Check.cmake ) ExternalData_Add_Target(Data5.B) ExternalData_Add_Test(Data5.C NAME Data5Check.C COMMAND ${CMAKE_COMMAND} - -D Data5=DATA{../Data.dat} + -D Data5=DATA{Data5.dat} -P ${CMAKE_CURRENT_SOURCE_DIR}/Data5Check.cmake ) ExternalData_Add_Target(Data5.C) diff --git a/Tests/Module/ExternalData/Data5/Data5.dat.md5 b/Tests/Module/ExternalData/Data5/Data5.dat.md5 new file mode 100644 index 0000000..70e39bd --- /dev/null +++ b/Tests/Module/ExternalData/Data5/Data5.dat.md5 @@ -0,0 +1 @@ +8c018830e3efa5caf3c7415028335a57 diff --git a/Tests/Module/WriteCompilerDetectionHeader/CMakeLists.txt b/Tests/Module/WriteCompilerDetectionHeader/CMakeLists.txt index 52d4613..45bb229 100644 --- a/Tests/Module/WriteCompilerDetectionHeader/CMakeLists.txt +++ b/Tests/Module/WriteCompilerDetectionHeader/CMakeLists.txt @@ -190,7 +190,7 @@ write_compiler_detection_header( ALLOW_UNKNOWN_COMPILERS ) -# intentionally abuse the TEST_NULLPR variable: this will only work +# intentionally abuse the TEST_NULLPTR variable: this will only work # with the fallback code. check_cxx_source_compiles("#include \"${CMAKE_CURRENT_BINARY_DIR}/test_compiler_detection_allow_unknown.h\" int main() {\n int i = TEST_NULLPTR;\n return 0; }\n" @@ -199,3 +199,16 @@ int main() {\n int i = TEST_NULLPTR;\n return 0; }\n" if (NOT file_include_works_allow_unknown) message(SEND_ERROR "Inclusion of ${CMAKE_CURRENT_BINARY_DIR}/test_compiler_detection_allow_unknown.h was expected to work, but did not.") endif() + +# test for BARE_FEATURES + +write_compiler_detection_header( + FILE "${CMAKE_CURRENT_BINARY_DIR}/test_compiler_detection_bare_features.h" + PREFIX TEST + COMPILERS GNU Clang AppleClang MSVC SunPro Intel + VERSION 3.1 + BARE_FEATURES cxx_nullptr cxx_override cxx_noexcept cxx_final +) + +add_executable(WriteCompilerDetectionHeaderBareFeatures main_bare.cpp) +set_property(TARGET WriteCompilerDetectionHeaderBareFeatures PROPERTY CXX_STANDARD 11) diff --git a/Tests/Module/WriteCompilerDetectionHeader/main_bare.cpp b/Tests/Module/WriteCompilerDetectionHeader/main_bare.cpp new file mode 100644 index 0000000..6954318 --- /dev/null +++ b/Tests/Module/WriteCompilerDetectionHeader/main_bare.cpp @@ -0,0 +1,23 @@ +#include "test_compiler_detection_bare_features.h" + +class base +{ +public: + virtual ~base() {} + virtual void baz() = 0; +}; + +class foo final +{ +public: + virtual ~foo() {} + char* bar; + void baz() noexcept override { bar = nullptr; } +}; + +int main() +{ + foo f; + + return 0; +} diff --git a/Tests/OutOfSource/OutOfSourceSubdir/CMakeLists.txt b/Tests/OutOfSource/OutOfSourceSubdir/CMakeLists.txt index 10a2f59..76a93d2 100644 --- a/Tests/OutOfSource/OutOfSourceSubdir/CMakeLists.txt +++ b/Tests/OutOfSource/OutOfSourceSubdir/CMakeLists.txt @@ -16,11 +16,11 @@ if ("${PROJECT_SOURCE_DIR}" STREQUAL "${ANOTHER_PROJ_SOURCE_DIR}") # Use a separate variable for computation. set(MAXPATH "${CMAKE_OBJECT_PATH_MAX}") - # VS8 adds "OutOfSource/SubDir/OutOfSourceSubdir/../../../" to the + # VS adds "OutOfSource/SubDir/OutOfSourceSubdir/../../../" to the # path of the source file for no good reason. Reduce the length # limit by 46 characters to account for it. It should still be long # enough to require special object file name conversion. - if(${CMAKE_GENERATOR} MATCHES "Visual Studio (8|10)") + if(${CMAKE_GENERATOR} MATCHES "Visual Studio") math(EXPR MAXPATH "${MAXPATH} - 46") endif() diff --git a/Tests/PolicyScope/CMakeLists.txt b/Tests/PolicyScope/CMakeLists.txt index 413195a..353842b 100644 --- a/Tests/PolicyScope/CMakeLists.txt +++ b/Tests/PolicyScope/CMakeLists.txt @@ -52,6 +52,10 @@ if(1) # CMP0002 should be changed when this function is invoked cmake_policy(GET CMP0002 cmp) check(CMP0002 "OLD" "${cmp}") + + # The undocumented PARENT_SCOPE option sees the caller's setting. + cmake_policy(GET CMP0002 cmp PARENT_SCOPE) + check(CMP0002 "NEW" "${cmp}") endfunction() # Unset CMP0002 @@ -61,6 +65,10 @@ if(1) cmake_policy(GET CMP0002 cmp) check(CMP0002 "" "${cmp}") + # The undocumented PARENT_SCOPE option sees the caller's setting. + cmake_policy(GET CMP0002 cmp PARENT_SCOPE) + check(CMP0002 "NEW" "${cmp}") + # Setting the policy should work here and also in the caller. cmake_policy(SET CMP0002 OLD) cmake_policy(GET CMP0002 cmp) diff --git a/Tests/QtAutogen/RerunRccDepends/CMakeLists.txt b/Tests/QtAutogen/RerunRccDepends/CMakeLists.txt index 2e6a5bd..52e2488 100644 --- a/Tests/QtAutogen/RerunRccDepends/CMakeLists.txt +++ b/Tests/QtAutogen/RerunRccDepends/CMakeLists.txt @@ -45,8 +45,7 @@ file(TIMESTAMP "${rccDepBinGen}" rdGenBefore "${timeformat}") # - Change a resource files listed in the .qrc file # - Rebuild execute_process(COMMAND "${CMAKE_COMMAND}" -E sleep 1) -execute_process(COMMAND "${CMAKE_COMMAND}" -E touch "${rccDepBD}/resPlain/input.txt") -execute_process(COMMAND "${CMAKE_COMMAND}" -E touch "${rccDepBD}/resGen/input.txt") +file(TOUCH "${rccDepBD}/resPlain/input.txt" "${rccDepBD}/resGen/input.txt") execute_process(COMMAND "${CMAKE_COMMAND}" --build . WORKING_DIRECTORY "${rccDepBD}" RESULT_VARIABLE result) if (result) message(SEND_ERROR "Second build of rccDepends failed.") @@ -63,7 +62,7 @@ if (NOT rdGenAfter GREATER rdGenBefore) endif() -message("Changing a the .qrc file") +message("Changing the .qrc file") # - Acquire binary timestamps before the build file(TIMESTAMP "${rccDepBinPlain}" rdPlainBefore "${timeformat}") file(TIMESTAMP "${rccDepBinGen}" rdGenBefore "${timeformat}") @@ -97,8 +96,7 @@ file(TIMESTAMP "${rccDepBinGen}" rdGenBefore "${timeformat}") # - Change a newly added resource files listed in the .qrc file # - Rebuild execute_process(COMMAND "${CMAKE_COMMAND}" -E sleep 1) -execute_process(COMMAND "${CMAKE_COMMAND}" -E touch "${rccDepBD}/resPlain/inputAdded.txt") -execute_process(COMMAND "${CMAKE_COMMAND}" -E touch "${rccDepBD}/resGen/inputAdded.txt") +file(TOUCH "${rccDepBD}/resPlain/inputAdded.txt" "${rccDepBD}/resGen/inputAdded.txt") execute_process(COMMAND "${CMAKE_COMMAND}" --build . WORKING_DIRECTORY "${rccDepBD}" RESULT_VARIABLE result) if (result) message(SEND_ERROR "Fourth build of rccDepends failed.") diff --git a/Tests/RunCMake/Android/RunCMakeTest.cmake b/Tests/RunCMake/Android/RunCMakeTest.cmake index 86a9896..2027c4f 100644 --- a/Tests/RunCMake/Android/RunCMakeTest.cmake +++ b/Tests/RunCMake/Android/RunCMakeTest.cmake @@ -88,12 +88,14 @@ foreach(ndk IN LISTS TEST_ANDROID_NDK) -DCMAKE_ANDROID_ARM_MODE=0 ) run_cmake(ndk-badarm) - set(RunCMake_TEST_OPTIONS - -DCMAKE_SYSTEM_NAME=Android - -DCMAKE_ANDROID_NDK=${ndk} - -DCMAKE_ANDROID_ARM_NEON=0 - ) - run_cmake(ndk-badneon) + if("armeabi" IN_LIST _abis_) + set(RunCMake_TEST_OPTIONS + -DCMAKE_SYSTEM_NAME=Android + -DCMAKE_ANDROID_NDK=${ndk} + -DCMAKE_ANDROID_ARM_NEON=0 + ) + run_cmake(ndk-badneon) + endif() set(RunCMake_TEST_OPTIONS -DCMAKE_SYSTEM_NAME=Android -DCMAKE_ANDROID_NDK=${ndk} diff --git a/Tests/RunCMake/Android/android_lib.cxx b/Tests/RunCMake/Android/android_lib.cxx new file mode 100644 index 0000000..82f9d27 --- /dev/null +++ b/Tests/RunCMake/Android/android_lib.cxx @@ -0,0 +1,4 @@ +int android_lib() +{ + return 0; +} diff --git a/Tests/RunCMake/Android/check_binary.cmake b/Tests/RunCMake/Android/check_binary.cmake new file mode 100644 index 0000000..1d1b01a --- /dev/null +++ b/Tests/RunCMake/Android/check_binary.cmake @@ -0,0 +1,8 @@ +if(NOT EXISTS "${file}") + message(FATAL_ERROR "Missing file:\n ${file}") +endif() +execute_process(COMMAND "${objdump}" -p ${file} OUTPUT_VARIABLE out) +if(out MATCHES "NEEDED[^\n]*stdc\\+\\+") + string(REPLACE "\n" "\n " out " ${out}") + message(FATAL_ERROR "File:\n ${file}\ndepends on libstdc++:\n${out}") +endif() diff --git a/Tests/RunCMake/Android/common.cmake b/Tests/RunCMake/Android/common.cmake index 015f202..f931be1 100644 --- a/Tests/RunCMake/Android/common.cmake +++ b/Tests/RunCMake/Android/common.cmake @@ -92,6 +92,23 @@ if(CMAKE_ANDROID_ARCH_ABI STREQUAL "armeabi-v7a") endif() add_executable(android_c android.c) add_executable(android_cxx android.cxx) +add_library(android_cxx_lib SHARED android_lib.cxx) + +set(objdump "${CMAKE_CXX_ANDROID_TOOLCHAIN_PREFIX}objdump") +if(NOT EXISTS "${objdump}") + message(FATAL_ERROR "Expected tool missing:\n ${objdump}") +endif() + +if(NOT CMAKE_ANDROID_STL_TYPE MATCHES "^(system|stlport_static|stlport_shared)$") + foreach(tgt android_cxx android_cxx_lib) + add_custom_command(TARGET ${tgt} POST_BUILD + COMMAND ${CMAKE_COMMAND} + -Dobjdump=${objdump} + -Dfile=$<TARGET_FILE:${tgt}> + -P ${CMAKE_CURRENT_SOURCE_DIR}/check_binary.cmake + ) + endforeach() +endif() # Test that an explicit /usr/include is ignored in favor of # appearing as a standard include directory at the end. diff --git a/Tests/RunCMake/Android/ndk-badvernum-stderr.txt b/Tests/RunCMake/Android/ndk-badvernum-stderr.txt index 25bbaf9..adacaf1 100644 --- a/Tests/RunCMake/Android/ndk-badvernum-stderr.txt +++ b/Tests/RunCMake/Android/ndk-badvernum-stderr.txt @@ -1,5 +1,5 @@ ^CMake Error at .*/Modules/Platform/Android/Determine-Compiler-NDK.cmake:[0-9]+ \(message\): - Android: No toolchain for ABI 'armeabi' found in the NDK: + Android: No toolchain for ABI 'armeabi(-v7a)?' found in the NDK: .* diff --git a/Tests/RunCMake/CMakeLists.txt b/Tests/RunCMake/CMakeLists.txt index c52f44e..f5dd528 100644 --- a/Tests/RunCMake/CMakeLists.txt +++ b/Tests/RunCMake/CMakeLists.txt @@ -121,6 +121,9 @@ if(CMAKE_GENERATOR STREQUAL "Ninja") -DCMAKE_C_OUTPUT_EXTENSION=${CMAKE_C_OUTPUT_EXTENSION} -DCMAKE_SHARED_LIBRARY_PREFIX=${CMAKE_SHARED_LIBRARY_PREFIX} -DCMAKE_SHARED_LIBRARY_SUFFIX=${CMAKE_SHARED_LIBRARY_SUFFIX}) + if(CMAKE_Fortran_COMPILER) + list(APPEND Ninja_ARGS -DTEST_Fortran=1) + endif() add_RunCMake_test(Ninja) endif() add_RunCMake_test(CTest) @@ -188,6 +191,7 @@ if (QT4_FOUND) endif() add_RunCMake_test(CompatibleInterface) add_RunCMake_test(Syntax) +add_RunCMake_test(WorkingDirectory) add_RunCMake_test(add_custom_command) add_RunCMake_test(add_custom_target) @@ -305,13 +309,13 @@ endif() if("${CMAKE_GENERATOR}" MATCHES "Visual Studio") add_RunCMake_test(include_external_msproject) - if("${CMAKE_GENERATOR}" MATCHES "Visual Studio ([89]|10)" AND NOT CMAKE_VS_DEVENV_COMMAND) + if("${CMAKE_GENERATOR}" MATCHES "Visual Studio (9|10)" AND NOT CMAKE_VS_DEVENV_COMMAND) set(NO_USE_FOLDERS 1) endif() add_RunCMake_test(VSSolution -DNO_USE_FOLDERS=${NO_USE_FOLDERS}) endif() -if("${CMAKE_GENERATOR}" MATCHES "Visual Studio ([^89]|[89][0-9])") +if("${CMAKE_GENERATOR}" MATCHES "Visual Studio ([^9]|9[0-9])") add_RunCMake_test(VS10Project) endif() @@ -340,6 +344,9 @@ add_RunCMake_test(CPackConfig) add_RunCMake_test(CPackInstallProperties) add_RunCMake_test(ExternalProject) add_RunCMake_test(FetchContent) +if(NOT CMake_TEST_EXTERNAL_CMAKE) + set(CTestCommandLine_ARGS -DTEST_AFFINITY=$<TARGET_FILE:testAffinity>) +endif() add_RunCMake_test(CTestCommandLine) add_RunCMake_test(CacheNewline) # Only run this test on unix platforms that support @@ -355,8 +362,16 @@ set(IfacePaths_SOURCES_ARGS -DTEST_PROP=SOURCES) add_RunCMake_test(IfacePaths_SOURCES TEST_DIR IfacePaths) # Matlab module related tests -if(CMake_TEST_FindMatlab) - add_RunCMake_test(FindMatlab) +if(CMake_TEST_FindMatlab OR CMake_TEST_FindMatlab_MCR OR (NOT "${CMake_TEST_FindMatlab_MCR_ROOT_DIR}" STREQUAL "")) + set(FindMatlab_additional_test_options ) + if(CMake_TEST_FindMatlab_MCR OR NOT "${CMake_TEST_FindMatlab_MCR_ROOT_DIR}" STREQUAL "") + set(FindMatlab_additional_test_options -DIS_MCR=TRUE) + endif() + if(NOT "${CMake_TEST_FindMatlab_MCR_ROOT_DIR}" STREQUAL "") + set(FindMatlab_additional_test_options ${FindMatlab_additional_test_options} "-DMCR_ROOT:FILEPATH=${CMake_TEST_FindMatlab_MCR_ROOT_DIR}") + endif() + + add_RunCMake_test(FindMatlab ${FindMatlab_additional_test_options}) endif() add_executable(pseudo_emulator pseudo_emulator.c) @@ -426,6 +441,6 @@ if(CMake_TEST_ANDROID_NDK OR CMake_TEST_ANDROID_STANDALONE_TOOLCHAIN) set_property(TEST RunCMake.Android PROPERTY TIMEOUT ${CMake_TEST_ANDROID_TIMEOUT}) endif() -if(${CMAKE_GENERATOR} MATCHES "Visual Studio ([^89]|[89][0-9])") +if(${CMAKE_GENERATOR} MATCHES "Visual Studio ([^9]|9[0-9])") add_RunCMake_test(CSharpCustomCommand) endif() diff --git a/Tests/RunCMake/CTestCommandLine/RunCMakeTest.cmake b/Tests/RunCMake/CTestCommandLine/RunCMakeTest.cmake index 0fafea5..3033c9c 100644 --- a/Tests/RunCMake/CTestCommandLine/RunCMakeTest.cmake +++ b/Tests/RunCMake/CTestCommandLine/RunCMakeTest.cmake @@ -141,3 +141,23 @@ function(run_TestOutputSize) ) endfunction() run_TestOutputSize() + +function(run_TestAffinity) + set(RunCMake_TEST_BINARY_DIR ${RunCMake_BINARY_DIR}/TestAffinity) + set(RunCMake_TEST_NO_CLEAN 1) + file(REMOVE_RECURSE "${RunCMake_TEST_BINARY_DIR}") + file(MAKE_DIRECTORY "${RunCMake_TEST_BINARY_DIR}") + # Create a test with affinity enabled. The default PROCESSORS + # value is 1, so our expected output checks that this is the + # number of processors in the mask. + file(WRITE "${RunCMake_TEST_BINARY_DIR}/CTestTestfile.cmake" " + add_test(Affinity \"${TEST_AFFINITY}\") + set_tests_properties(Affinity PROPERTIES PROCESSOR_AFFINITY ON) +") + # Run ctest with a large parallel level so that the value is + # not responsible for capping the number of processors available. + run_cmake_command(TestAffinity ${CMAKE_CTEST_COMMAND} -V -j 64) +endfunction() +if(TEST_AFFINITY) + run_TestAffinity() +endif() diff --git a/Tests/RunCMake/CTestCommandLine/TestAffinity-stdout.txt b/Tests/RunCMake/CTestCommandLine/TestAffinity-stdout.txt new file mode 100644 index 0000000..e23d30b --- /dev/null +++ b/Tests/RunCMake/CTestCommandLine/TestAffinity-stdout.txt @@ -0,0 +1 @@ +1: CPU affinity (mask count is '1'|not supported on this platform)\. diff --git a/Tests/RunCMake/CheckModules/CMP0075-stderr.txt b/Tests/RunCMake/CheckModules/CMP0075-stderr.txt new file mode 100644 index 0000000..960fe94 --- /dev/null +++ b/Tests/RunCMake/CheckModules/CMP0075-stderr.txt @@ -0,0 +1,50 @@ +^CMake Warning \(dev\) at [^ +]*/Modules/CheckIncludeFile.cmake:[0-9]+ \(message\): + Policy CMP0075 is not set: Include file check macros honor + CMAKE_REQUIRED_LIBRARIES. Run "cmake --help-policy CMP0075" for policy + details. Use the cmake_policy command to set the policy and suppress this + warning. + + CMAKE_REQUIRED_LIBRARIES is set to: + + does_not_exist + + For compatibility with CMake 3.11 and below this check is ignoring it. +Call Stack \(most recent call first\): + CMP0075.cmake:11 \(check_include_file\) + CMakeLists.txt:[0-9]+ \(include\) +This warning is for project developers. Use -Wno-dev to suppress it. ++ +CMake Warning \(dev\) at [^ +]*/Modules/CheckIncludeFileCXX.cmake:[0-9]+ \(message\): + Policy CMP0075 is not set: Include file check macros honor + CMAKE_REQUIRED_LIBRARIES. Run "cmake --help-policy CMP0075" for policy + details. Use the cmake_policy command to set the policy and suppress this + warning. + + CMAKE_REQUIRED_LIBRARIES is set to: + + does_not_exist + + For compatibility with CMake 3.11 and below this check is ignoring it. +Call Stack \(most recent call first\): + CMP0075.cmake:26 \(check_include_file_cxx\) + CMakeLists.txt:[0-9]+ \(include\) +This warning is for project developers. Use -Wno-dev to suppress it. ++ +CMake Warning \(dev\) at [^ +]*/Modules/CheckIncludeFiles.cmake:[0-9]+ \(message\): + Policy CMP0075 is not set: Include file check macros honor + CMAKE_REQUIRED_LIBRARIES. Run "cmake --help-policy CMP0075" for policy + details. Use the cmake_policy command to set the policy and suppress this + warning. + + CMAKE_REQUIRED_LIBRARIES is set to: + + does_not_exist + + For compatibility with CMake 3.11 and below this check is ignoring it. +Call Stack \(most recent call first\): + CMP0075.cmake:41 \(check_include_files\) + CMakeLists.txt:[0-9]+ \(include\) +This warning is for project developers. Use -Wno-dev to suppress it.$ diff --git a/Tests/RunCMake/CheckModules/CMP0075.cmake b/Tests/RunCMake/CheckModules/CMP0075.cmake new file mode 100644 index 0000000..4a3b720 --- /dev/null +++ b/Tests/RunCMake/CheckModules/CMP0075.cmake @@ -0,0 +1,124 @@ +enable_language(C) +enable_language(CXX) +include(CheckIncludeFile) +include(CheckIncludeFileCXX) +include(CheckIncludeFiles) + +set(CMAKE_REQUIRED_LIBRARIES does_not_exist) + +#============================================================================ + +check_include_file("stddef.h" HAVE_STDDEF_H_1) +if(NOT HAVE_STDDEF_H_1) + message(SEND_ERROR "HAVE_STDDEF_H_1 failed but should have passed.") +endif() +if(NOT _CIF_CMP0075_WARNED) + message(SEND_ERROR "HAVE_STDDEF_H_1 did not warn but should have") +endif() +check_include_file("stddef.h" HAVE_STDDEF_H_2) # second does not warn +if(NOT HAVE_STDDEF_H_2) + message(SEND_ERROR "HAVE_STDDEF_H_2 failed but should have passed.") +endif() +unset(_CIF_CMP0075_WARNED) + +#---------------------------------------------------------------------------- + +check_include_file_cxx("stddef.h" HAVE_STDDEF_H_CXX_1) +if(NOT HAVE_STDDEF_H_CXX_1) + message(SEND_ERROR "HAVE_STDDEF_H_CXX_1 failed but should have passed.") +endif() +if(NOT _CIF_CMP0075_WARNED) + message(SEND_ERROR "HAVE_STDDEF_H_CXX_1 did not warn but should have") +endif() +check_include_file_cxx("stddef.h" HAVE_STDDEF_H_CXX_2) # second does not warn +if(NOT HAVE_STDDEF_H_CXX_2) + message(SEND_ERROR "HAVE_STDDEF_H_CXX_2 failed but should have passed.") +endif() +unset(_CIF_CMP0075_WARNED) + +#---------------------------------------------------------------------------- + +check_include_files("stddef.h;stdlib.h" HAVE_STDLIB_H_1) +if(NOT HAVE_STDLIB_H_1) + message(SEND_ERROR "HAVE_STDLIB_H_1 failed but should have passed.") +endif() +if(NOT _CIF_CMP0075_WARNED) + message(SEND_ERROR "HAVE_STDLIB_H_1 did not warn but should have") +endif() +check_include_files("stddef.h;stdlib.h" HAVE_STDLIB_H_2) # second does not warn +if(NOT HAVE_STDLIB_H_2) + message(SEND_ERROR "HAVE_STDLIB_H_2 failed but should have passed.") +endif() +unset(_CIF_CMP0075_WARNED) + +#============================================================================ +cmake_policy(SET CMP0075 OLD) +# These should not warn. +# These should pass the checks due to ignoring 'does_not_exist'. + +check_include_file("stddef.h" HAVE_STDDEF_H_3) +if(NOT HAVE_STDDEF_H_3) + message(SEND_ERROR "HAVE_STDDEF_H_3 failed but should have passed.") +endif() +if(_CIF_CMP0075_WARNED) + message(SEND_ERROR "HAVE_STDDEF_H_3 warned but should not have") +endif() +unset(_CIF_CMP0075_WARNED) + +#---------------------------------------------------------------------------- + +check_include_file_cxx("stddef.h" HAVE_STDDEF_H_CXX_3) +if(NOT HAVE_STDDEF_H_CXX_3) + message(SEND_ERROR "HAVE_STDDEF_H_CXX_3 failed but should have passed.") +endif() +if(_CIF_CMP0075_WARNED) + message(SEND_ERROR "HAVE_STDDEF_H_CXX_3 warned but should not have") +endif() +unset(_CIF_CMP0075_WARNED) + +#---------------------------------------------------------------------------- + +check_include_files("stddef.h;stdlib.h" HAVE_STDLIB_H_3) +if(NOT HAVE_STDLIB_H_3) + message(SEND_ERROR "HAVE_STDLIB_H_3 failed but should have passed.") +endif() +if(_CIF_CMP0075_WARNED) + message(SEND_ERROR "HAVE_STDLIB_H_3 warned but should not have") +endif() +unset(_CIF_CMP0075_WARNED) + +#============================================================================ +cmake_policy(SET CMP0075 NEW) +# These should not warn. +# These should fail the checks due to requiring 'does_not_exist'. + +check_include_file("stddef.h" HAVE_STDDEF_H_4) +if(HAVE_STDDEF_H_4) + message(SEND_ERROR "HAVE_STDDEF_H_4 passed but should have failed.") +endif() +if(_CIF_CMP0075_WARNED) + message(SEND_ERROR "HAVE_STDDEF_H_4 warned but should not have") +endif() +unset(_CIF_CMP0075_WARNED) + +#---------------------------------------------------------------------------- + +check_include_file_cxx("stddef.h" HAVE_STDDEF_H_CXX_4) +if(HAVE_STDDEF_H_CXX_4) + message(SEND_ERROR "HAVE_STDDEF_H_CXX_4 passed but should have failed.") +endif() +if(_CIF_CMP0075_WARNED) + message(SEND_ERROR "HAVE_STDDEF_H_CXX_4 warned but should not have") +endif() +unset(_CIF_CMP0075_WARNED) + +#---------------------------------------------------------------------------- + +check_include_files("stddef.h;stdlib.h" HAVE_STDLIB_H_4) +if(HAVE_STDLIB_H_4) + message(SEND_ERROR "HAVE_STDLIB_H_4 passed but should have failed.") +endif() +if(_CIF_CMP0075_WARNED) + message(SEND_ERROR "HAVE_STDLIB_H_4 warned but should not have") +endif() +unset(_CIF_CMP0075_WARNED) diff --git a/Tests/RunCMake/CheckModules/RunCMakeTest.cmake b/Tests/RunCMake/CheckModules/RunCMakeTest.cmake index c5aaa64..8a046e1 100644 --- a/Tests/RunCMake/CheckModules/RunCMakeTest.cmake +++ b/Tests/RunCMake/CheckModules/RunCMakeTest.cmake @@ -1,5 +1,7 @@ include(RunCMake) +run_cmake(CMP0075) + run_cmake(CheckStructHasMemberOk) run_cmake(CheckStructHasMemberUnknownLanguage) run_cmake(CheckStructHasMemberMissingLanguage) diff --git a/Tests/RunCMake/CommandLine/DeprecateVS8-WARN-OFF.cmake b/Tests/RunCMake/CommandLine/DeprecateVS8-WARN-OFF.cmake deleted file mode 100644 index e69de29..0000000 --- a/Tests/RunCMake/CommandLine/DeprecateVS8-WARN-OFF.cmake +++ /dev/null diff --git a/Tests/RunCMake/CommandLine/DeprecateVS8-WARN-ON-stderr.txt b/Tests/RunCMake/CommandLine/DeprecateVS8-WARN-ON-stderr.txt deleted file mode 100644 index 2f2cbd3..0000000 --- a/Tests/RunCMake/CommandLine/DeprecateVS8-WARN-ON-stderr.txt +++ /dev/null @@ -1,5 +0,0 @@ -^CMake Warning: - The "Visual Studio 8 2005" generator is deprecated and will be removed in a - future version of CMake. - - Add CMAKE_WARN_VS8=OFF to the cache to disable this warning.$ diff --git a/Tests/RunCMake/CommandLine/RunCMakeTest.cmake b/Tests/RunCMake/CommandLine/RunCMakeTest.cmake index 120a472..d8dbeec 100644 --- a/Tests/RunCMake/CommandLine/RunCMakeTest.cmake +++ b/Tests/RunCMake/CommandLine/RunCMakeTest.cmake @@ -78,13 +78,6 @@ if(RunCMake_GENERATOR STREQUAL "Ninja") unset(RunCMake_TEST_NO_CLEAN) endif() -if(RunCMake_GENERATOR MATCHES "^Visual Studio 8 2005") - set(RunCMake_WARN_VS8 1) - run_cmake(DeprecateVS8-WARN-ON) - unset(RunCMake_WARN_VS8) - run_cmake(DeprecateVS8-WARN-OFF) -endif() - if(UNIX) run_cmake_command(E_create_symlink-no-arg ${CMAKE_COMMAND} -E create_symlink diff --git a/Tests/RunCMake/FindMatlab/MatlabTest1.cmake b/Tests/RunCMake/FindMatlab/MatlabTest1.cmake index 1cbc1c2..b4cc741 100644 --- a/Tests/RunCMake/FindMatlab/MatlabTest1.cmake +++ b/Tests/RunCMake/FindMatlab/MatlabTest1.cmake @@ -3,6 +3,9 @@ cmake_minimum_required (VERSION 2.8.12) enable_testing() project(test_should_fail) +if(NOT "${matlab_root}" STREQUAL "") + set(Matlab_ROOT_DIR ${matlab_root}) +endif() find_package(Matlab REQUIRED COMPONENTS MX_LIBRARY) matlab_add_mex( diff --git a/Tests/RunCMake/FindMatlab/MatlabTest2.cmake b/Tests/RunCMake/FindMatlab/MatlabTest2.cmake index d5b0e6d..4295d3c 100644 --- a/Tests/RunCMake/FindMatlab/MatlabTest2.cmake +++ b/Tests/RunCMake/FindMatlab/MatlabTest2.cmake @@ -6,4 +6,8 @@ if(NOT DEFINED matlab_required) set(matlab_required REQUIRED) endif() +if(NOT DEFINED Matlab_ROOT_DIR AND NOT "${matlab_root}" STREQUAL "") + set(Matlab_ROOT_DIR ${matlab_root}) +endif() + find_package(Matlab ${matlab_required} COMPONENTS MX_LIBRARY) diff --git a/Tests/RunCMake/FindMatlab/RunCMakeTest.cmake b/Tests/RunCMake/FindMatlab/RunCMakeTest.cmake index f0eb6b4..deebf89 100644 --- a/Tests/RunCMake/FindMatlab/RunCMakeTest.cmake +++ b/Tests/RunCMake/FindMatlab/RunCMakeTest.cmake @@ -1,5 +1,13 @@ include(RunCMake) + + +if(NOT "${MCR_ROOT}" STREQUAL "") + if(NOT EXISTS "${MCR_ROOT}") + message(FATAL_ERROR "MCR does not exist ${MCR_ROOT}") + endif() + set(RunCMake_TEST_OPTIONS "-Dmatlab_root=${MCR_ROOT}") +endif() run_cmake(MatlabTest1) if(RunCMake_GENERATOR MATCHES "Make" AND UNIX) @@ -11,6 +19,9 @@ if(RunCMake_GENERATOR MATCHES "Make" AND UNIX) message(STATUS "RerunFindMatlab: first configuration to extract real Matlab_ROOT_DIR") set(RunCMake_TEST_OPTIONS "-Dmatlab_required=REQUIRED") + if(NOT "${MCR_ROOT}" STREQUAL "") + set(RunCMake_TEST_OPTIONS ${RunCMake_TEST_OPTIONS} "-Dmatlab_root=${MCR_ROOT}") + endif() run_cmake(MatlabTest2) message(STATUS "RerunFindMatlab: flushing the variables") diff --git a/Tests/RunCMake/GeneratorExpression/GENEX_EVAL-check.cmake b/Tests/RunCMake/GeneratorExpression/GENEX_EVAL-check.cmake new file mode 100644 index 0000000..df76740 --- /dev/null +++ b/Tests/RunCMake/GeneratorExpression/GENEX_EVAL-check.cmake @@ -0,0 +1,6 @@ +file(READ "${RunCMake_TEST_BINARY_DIR}/GENEX_EVAL-generated.txt" content) + +set(expected "BEFORE_PROPERTY1_AFTER") +if(NOT content STREQUAL expected) + set(RunCMake_TEST_FAILED "actual content:\n [[${content}]]\nbut expected:\n [[${expected}]]") +endif() diff --git a/Tests/RunCMake/add_library/OBJECTwithOnlyObjectSources-result.txt b/Tests/RunCMake/GeneratorExpression/GENEX_EVAL-recursion1-result.txt index d00491f..d00491f 100644 --- a/Tests/RunCMake/add_library/OBJECTwithOnlyObjectSources-result.txt +++ b/Tests/RunCMake/GeneratorExpression/GENEX_EVAL-recursion1-result.txt diff --git a/Tests/RunCMake/GeneratorExpression/GENEX_EVAL-recursion1-stderr.txt b/Tests/RunCMake/GeneratorExpression/GENEX_EVAL-recursion1-stderr.txt new file mode 100644 index 0000000..012dff6 --- /dev/null +++ b/Tests/RunCMake/GeneratorExpression/GENEX_EVAL-recursion1-stderr.txt @@ -0,0 +1,26 @@ +^CMake Error at GENEX_EVAL-recursion1.cmake:7 \(add_custom_target\): + Error evaluating generator expression: + + \$<GENEX_EVAL:\$<TARGET_PROPERTY:CUSTOM_PROPERTY>> + + Dependency loop found. +Call Stack \(most recent call first\): + CMakeLists.txt:3 \(include\) + + +CMake Error at GENEX_EVAL-recursion1.cmake:7 \(add_custom_target\): + Loop step 1 + + \$<GENEX_EVAL:\$<TARGET_PROPERTY:CUSTOM_PROPERTY>> + +Call Stack \(most recent call first\): + CMakeLists.txt:3 \(include\) + + +CMake Error at GENEX_EVAL-recursion1.cmake:7 \(add_custom_target\): + Loop step 2 + + \$<TARGET_GENEX_EVAL:recursion,\$<TARGET_PROPERTY:recursion,CUSTOM_PROPERTY>> + +Call Stack \(most recent call first\): + CMakeLists.txt:3 \(include\) diff --git a/Tests/RunCMake/GeneratorExpression/GENEX_EVAL-recursion1.cmake b/Tests/RunCMake/GeneratorExpression/GENEX_EVAL-recursion1.cmake new file mode 100644 index 0000000..6596a81 --- /dev/null +++ b/Tests/RunCMake/GeneratorExpression/GENEX_EVAL-recursion1.cmake @@ -0,0 +1,9 @@ + +enable_language(C) + +add_library (recursion SHARED empty.c) +set_property (TARGET recursion PROPERTY CUSTOM_PROPERTY "$<GENEX_EVAL:$<TARGET_PROPERTY:CUSTOM_PROPERTY>>") + +add_custom_target (drive + COMMAND echo "$<TARGET_GENEX_EVAL:recursion,$<TARGET_PROPERTY:recursion,CUSTOM_PROPERTY>>" + DEPENDS recursion) diff --git a/Tests/RunCMake/ObjectLibrary/ObjWithObj-result.txt b/Tests/RunCMake/GeneratorExpression/GENEX_EVAL-recursion2-result.txt index d00491f..d00491f 100644 --- a/Tests/RunCMake/ObjectLibrary/ObjWithObj-result.txt +++ b/Tests/RunCMake/GeneratorExpression/GENEX_EVAL-recursion2-result.txt diff --git a/Tests/RunCMake/GeneratorExpression/GENEX_EVAL-recursion2-stderr.txt b/Tests/RunCMake/GeneratorExpression/GENEX_EVAL-recursion2-stderr.txt new file mode 100644 index 0000000..fd954e6 --- /dev/null +++ b/Tests/RunCMake/GeneratorExpression/GENEX_EVAL-recursion2-stderr.txt @@ -0,0 +1,26 @@ +^CMake Error at GENEX_EVAL-recursion2.cmake:8 \(add_custom_target\): + Error evaluating generator expression: + + \$<GENEX_EVAL:\$<TARGET_PROPERTY:CUSTOM_PROPERTY1>> + + Dependency loop found. +Call Stack \(most recent call first\): + CMakeLists.txt:3 \(include\) + + +CMake Error at GENEX_EVAL-recursion2.cmake:8 \(add_custom_target\): + Loop step 1 + + \$<GENEX_EVAL:\$<TARGET_PROPERTY:CUSTOM_PROPERTY2>> + +Call Stack \(most recent call first\): + CMakeLists.txt:3 \(include\) + + +CMake Error at GENEX_EVAL-recursion2.cmake:8 \(add_custom_target\): + Loop step 2 + + \$<TARGET_GENEX_EVAL:recursion,\$<TARGET_PROPERTY:recursion,CUSTOM_PROPERTY1>> + +Call Stack \(most recent call first\): + CMakeLists.txt:3 \(include\) diff --git a/Tests/RunCMake/GeneratorExpression/GENEX_EVAL-recursion2.cmake b/Tests/RunCMake/GeneratorExpression/GENEX_EVAL-recursion2.cmake new file mode 100644 index 0000000..773749f --- /dev/null +++ b/Tests/RunCMake/GeneratorExpression/GENEX_EVAL-recursion2.cmake @@ -0,0 +1,10 @@ + +enable_language(C) + +add_library(recursion SHARED empty.c) +set_property (TARGET recursion PROPERTY CUSTOM_PROPERTY1 "$<GENEX_EVAL:$<TARGET_PROPERTY:CUSTOM_PROPERTY2>>") +set_property (TARGET recursion PROPERTY CUSTOM_PROPERTY2 "$<GENEX_EVAL:$<TARGET_PROPERTY:CUSTOM_PROPERTY1>>") + +add_custom_target (drive + COMMAND echo "$<TARGET_GENEX_EVAL:recursion,$<TARGET_PROPERTY:recursion,CUSTOM_PROPERTY1>>" + DEPENDS recursion) diff --git a/Tests/RunCMake/GeneratorExpression/GENEX_EVAL.cmake b/Tests/RunCMake/GeneratorExpression/GENEX_EVAL.cmake new file mode 100644 index 0000000..ab8988b --- /dev/null +++ b/Tests/RunCMake/GeneratorExpression/GENEX_EVAL.cmake @@ -0,0 +1,11 @@ + +cmake_policy(VERSION 3.11) + +enable_language(C) + +add_library (example SHARED empty.c) +set_property (TARGET example PROPERTY CUSTOM_PROPERTY1 "PROPERTY1") +set_property (TARGET example PROPERTY CUSTOM_PROPERTY2 "$<TARGET_PROPERTY:CUSTOM_PROPERTY1>") +set_property (TARGET example PROPERTY CUSTOM_PROPERTY3 "$<GENEX_EVAL:BEFORE_$<TARGET_PROPERTY:CUSTOM_PROPERTY2>_AFTER>") + +file(GENERATE OUTPUT "GENEX_EVAL-generated.txt" CONTENT "$<TARGET_GENEX_EVAL:example,$<TARGET_PROPERTY:example,CUSTOM_PROPERTY3>>") diff --git a/Tests/RunCMake/GeneratorExpression/RunCMakeTest.cmake b/Tests/RunCMake/GeneratorExpression/RunCMakeTest.cmake index 2486259..3905c5f 100644 --- a/Tests/RunCMake/GeneratorExpression/RunCMakeTest.cmake +++ b/Tests/RunCMake/GeneratorExpression/RunCMakeTest.cmake @@ -34,6 +34,23 @@ run_cmake(OUTPUT_NAME-recursion) run_cmake(TARGET_PROPERTY-LOCATION) run_cmake(TARGET_PROPERTY-SOURCES) run_cmake(LINK_ONLY-not-linking) +run_cmake(TARGET_EXISTS-no-arg) +run_cmake(TARGET_EXISTS-empty-arg) +run_cmake(TARGET_EXISTS) +run_cmake(TARGET_EXISTS-not-a-target) +run_cmake(TARGET_NAME_IF_EXISTS-no-arg) +run_cmake(TARGET_NAME_IF_EXISTS-empty-arg) +run_cmake(TARGET_NAME_IF_EXISTS) +run_cmake(TARGET_NAME_IF_EXISTS-not-a-target) +run_cmake(TARGET_GENEX_EVAL-no-arg) +run_cmake(TARGET_GENEX_EVAL-no-target) +run_cmake(TARGET_GENEX_EVAL-non-valid-target) +run_cmake(TARGET_GENEX_EVAL-recursion1) +run_cmake(TARGET_GENEX_EVAL-recursion2) +run_cmake(TARGET_GENEX_EVAL) +run_cmake(GENEX_EVAL-recursion1) +run_cmake(GENEX_EVAL-recursion2) +run_cmake(GENEX_EVAL) run_cmake(ImportedTarget-TARGET_BUNDLE_DIR) run_cmake(ImportedTarget-TARGET_BUNDLE_CONTENT_DIR) diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_EXISTS-check.cmake b/Tests/RunCMake/GeneratorExpression/TARGET_EXISTS-check.cmake new file mode 100644 index 0000000..c4c3a51 --- /dev/null +++ b/Tests/RunCMake/GeneratorExpression/TARGET_EXISTS-check.cmake @@ -0,0 +1,6 @@ +file(READ "${RunCMake_TEST_BINARY_DIR}/TARGET_EXISTS-generated.txt" content) + +set(expected "1") +if(NOT content STREQUAL expected) + set(RunCMake_TEST_FAILED "actual content:\n [[${content}]]\nbut expected:\n [[${expected}]]") +endif() diff --git a/Tests/RunCMake/ObjectLibrary/LinkObjRHS2-result.txt b/Tests/RunCMake/GeneratorExpression/TARGET_EXISTS-empty-arg-result.txt index d00491f..d00491f 100644 --- a/Tests/RunCMake/ObjectLibrary/LinkObjRHS2-result.txt +++ b/Tests/RunCMake/GeneratorExpression/TARGET_EXISTS-empty-arg-result.txt diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_EXISTS-empty-arg-stderr.txt b/Tests/RunCMake/GeneratorExpression/TARGET_EXISTS-empty-arg-stderr.txt new file mode 100644 index 0000000..1df6e28 --- /dev/null +++ b/Tests/RunCMake/GeneratorExpression/TARGET_EXISTS-empty-arg-stderr.txt @@ -0,0 +1,8 @@ +CMake Error at TARGET_EXISTS-empty-arg.cmake:2 \(file\): + Error evaluating generator expression: + + \$<TARGET_EXISTS:> + + \$<TARGET_EXISTS:tgt> expression requires a non-empty valid target name. +Call Stack \(most recent call first\): + CMakeLists.txt:[0-9]+ \(include\) diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_EXISTS-empty-arg.cmake b/Tests/RunCMake/GeneratorExpression/TARGET_EXISTS-empty-arg.cmake new file mode 100644 index 0000000..e387abc --- /dev/null +++ b/Tests/RunCMake/GeneratorExpression/TARGET_EXISTS-empty-arg.cmake @@ -0,0 +1,2 @@ +cmake_policy(SET CMP0070 NEW) +file(GENERATE OUTPUT TARGET_EXISTS-generated.txt CONTENT "$<TARGET_EXISTS:${empty}>") diff --git a/Tests/RunCMake/ObjectLibrary/LinkObjRHS1-result.txt b/Tests/RunCMake/GeneratorExpression/TARGET_EXISTS-no-arg-result.txt index d00491f..d00491f 100644 --- a/Tests/RunCMake/ObjectLibrary/LinkObjRHS1-result.txt +++ b/Tests/RunCMake/GeneratorExpression/TARGET_EXISTS-no-arg-result.txt diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_EXISTS-no-arg-stderr.txt b/Tests/RunCMake/GeneratorExpression/TARGET_EXISTS-no-arg-stderr.txt new file mode 100644 index 0000000..69e6130 --- /dev/null +++ b/Tests/RunCMake/GeneratorExpression/TARGET_EXISTS-no-arg-stderr.txt @@ -0,0 +1,8 @@ +CMake Error at TARGET_EXISTS-no-arg.cmake:2 \(file\): + Error evaluating generator expression: + + \$<TARGET_EXISTS> + + \$<TARGET_EXISTS> expression requires exactly one parameter. +Call Stack \(most recent call first\): + CMakeLists.txt:[0-9]+ \(include\) diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_EXISTS-no-arg.cmake b/Tests/RunCMake/GeneratorExpression/TARGET_EXISTS-no-arg.cmake new file mode 100644 index 0000000..0a5ce32 --- /dev/null +++ b/Tests/RunCMake/GeneratorExpression/TARGET_EXISTS-no-arg.cmake @@ -0,0 +1,2 @@ +cmake_policy(SET CMP0070 NEW) +file(GENERATE OUTPUT TARGET_EXISTS-generated.txt CONTENT "$<TARGET_EXISTS>") diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_EXISTS-not-a-target-check.cmake b/Tests/RunCMake/GeneratorExpression/TARGET_EXISTS-not-a-target-check.cmake new file mode 100644 index 0000000..35ba267 --- /dev/null +++ b/Tests/RunCMake/GeneratorExpression/TARGET_EXISTS-not-a-target-check.cmake @@ -0,0 +1,6 @@ +file(READ "${RunCMake_TEST_BINARY_DIR}/TARGET_EXISTS-not-a-target-generated.txt" content) + +set(expected "0") +if(NOT content STREQUAL expected) + set(RunCMake_TEST_FAILED "actual content:\n [[${content}]]\nbut expected:\n [[${expected}]]") +endif() diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_EXISTS-not-a-target.cmake b/Tests/RunCMake/GeneratorExpression/TARGET_EXISTS-not-a-target.cmake new file mode 100644 index 0000000..d8a8d3e --- /dev/null +++ b/Tests/RunCMake/GeneratorExpression/TARGET_EXISTS-not-a-target.cmake @@ -0,0 +1,2 @@ +cmake_policy(SET CMP0070 NEW) +file(GENERATE OUTPUT TARGET_EXISTS-not-a-target-generated.txt CONTENT "$<TARGET_EXISTS:just-random-string>") diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_EXISTS.cmake b/Tests/RunCMake/GeneratorExpression/TARGET_EXISTS.cmake new file mode 100644 index 0000000..9a83b34 --- /dev/null +++ b/Tests/RunCMake/GeneratorExpression/TARGET_EXISTS.cmake @@ -0,0 +1,3 @@ +cmake_policy(SET CMP0070 NEW) +add_custom_target(foo) +file(GENERATE OUTPUT TARGET_EXISTS-generated.txt CONTENT "$<TARGET_EXISTS:foo>") diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-check.cmake b/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-check.cmake new file mode 100644 index 0000000..124a583 --- /dev/null +++ b/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-check.cmake @@ -0,0 +1,6 @@ +file(READ "${RunCMake_TEST_BINARY_DIR}/TARGET_GENEX_EVAL-generated.txt" content) + +set(expected "BEFORE_PROPERTY1_AFTER") +if(NOT content STREQUAL expected) + set(RunCMake_TEST_FAILED "actual content:\n [[${content}]]\nbut expected:\n [[${expected}]]") +endif() diff --git a/Tests/RunCMake/ObjectLibrary/LinkObjLHS-result.txt b/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-no-arg-result.txt index d00491f..d00491f 100644 --- a/Tests/RunCMake/ObjectLibrary/LinkObjLHS-result.txt +++ b/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-no-arg-result.txt diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-no-arg-stderr.txt b/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-no-arg-stderr.txt new file mode 100644 index 0000000..9b0844f --- /dev/null +++ b/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-no-arg-stderr.txt @@ -0,0 +1,9 @@ +^CMake Error at TARGET_GENEX_EVAL-no-arg.cmake:4 \(add_custom_command\): + Error evaluating generator expression: + + \$<TARGET_GENEX_EVAL:> + + \$<TARGET_GENEX_EVAL> expression requires 2 comma separated parameters, but + got 1 instead. +Call Stack \(most recent call first\): + CMakeLists.txt:3 \(include\) diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-no-arg.cmake b/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-no-arg.cmake new file mode 100644 index 0000000..2dc13ea --- /dev/null +++ b/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-no-arg.cmake @@ -0,0 +1,7 @@ + +cmake_policy(VERSION 3.11) + +add_custom_command(OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/copied_file.c" + COMMAND "${CMAKE_COMMAND}" -E copy "${CMAKE_CURRENT_SOURCE_DIR}/empty.c" "${CMAKE_CURRENT_BINARY_DIR}/copied_file$<TARGET_GENEX_EVAL:>.c" +) +add_custom_target(drive DEPENDS "${CMAKE_CURRENT_BINARY_DIR}/copied_file.c") diff --git a/Tests/RunCMake/ObjectLibrary/ExportNotSupported-result.txt b/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-no-target-result.txt index d00491f..d00491f 100644 --- a/Tests/RunCMake/ObjectLibrary/ExportNotSupported-result.txt +++ b/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-no-target-result.txt diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-no-target-stderr.txt b/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-no-target-stderr.txt new file mode 100644 index 0000000..647fd85 --- /dev/null +++ b/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-no-target-stderr.txt @@ -0,0 +1,9 @@ +^CMake Error at TARGET_GENEX_EVAL-no-target.cmake:2 \(add_custom_command\): + Error evaluating generator expression: + + \$<TARGET_GENEX_EVAL:,> + + \$<TARGET_GENEX_EVAL:tgt, ...> expression requires a non-empty valid target + name. +Call Stack \(most recent call first\): + CMakeLists.txt:3 \(include\) diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-no-target.cmake b/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-no-target.cmake new file mode 100644 index 0000000..df4f0ea --- /dev/null +++ b/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-no-target.cmake @@ -0,0 +1,5 @@ + +add_custom_command(OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/copied_file.c" + COMMAND "${CMAKE_COMMAND}" -E copy "${CMAKE_CURRENT_SOURCE_DIR}/empty.c" "${CMAKE_CURRENT_BINARY_DIR}/copied_file$<TARGET_GENEX_EVAL:,>.c" +) +add_custom_target(drive DEPENDS "${CMAKE_CURRENT_BINARY_DIR}/copied_file.c") diff --git a/Tests/RunCMake/ObjectLibrary/BadObjSource2-result.txt b/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-non-valid-target-result.txt index d00491f..d00491f 100644 --- a/Tests/RunCMake/ObjectLibrary/BadObjSource2-result.txt +++ b/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-non-valid-target-result.txt diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-non-valid-target-stderr.txt b/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-non-valid-target-stderr.txt new file mode 100644 index 0000000..cc44d4b --- /dev/null +++ b/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-non-valid-target-stderr.txt @@ -0,0 +1,8 @@ +^CMake Error at TARGET_GENEX_EVAL-non-valid-target.cmake:2 \(add_custom_command\): + Error evaluating generator expression: + + \$<TARGET_GENEX_EVAL:bad-target,> + + \$<TARGET_GENEX_EVAL:tgt, ...> target "bad-target" not found. +Call Stack \(most recent call first\): + CMakeLists.txt:3 \(include\) diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-non-valid-target.cmake b/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-non-valid-target.cmake new file mode 100644 index 0000000..8db7375 --- /dev/null +++ b/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-non-valid-target.cmake @@ -0,0 +1,5 @@ + +add_custom_command(OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/copied_file.c" + COMMAND "${CMAKE_COMMAND}" -E copy "${CMAKE_CURRENT_SOURCE_DIR}/empty.c" "${CMAKE_CURRENT_BINARY_DIR}/copied_file$<TARGET_GENEX_EVAL:bad-target,>.c" +) +add_custom_target(drive DEPENDS "${CMAKE_CURRENT_BINARY_DIR}/copied_file.c") diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-recursion1-result.txt b/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-recursion1-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-recursion1-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-recursion1-stderr.txt b/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-recursion1-stderr.txt new file mode 100644 index 0000000..bba2234 --- /dev/null +++ b/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-recursion1-stderr.txt @@ -0,0 +1,9 @@ +^CMake Error at TARGET_GENEX_EVAL-recursion1.cmake:7 \(add_custom_target\): + Error evaluating generator expression: + + \$<TARGET_GENEX_EVAL:recursion,\$<TARGET_PROPERTY:CUSTOM_PROPERTY>> + + Self reference on target "recursion". + +Call Stack \(most recent call first\): + CMakeLists.txt:3 \(include\) diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-recursion1.cmake b/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-recursion1.cmake new file mode 100644 index 0000000..b75d211 --- /dev/null +++ b/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-recursion1.cmake @@ -0,0 +1,9 @@ + +enable_language(C) + +add_library (recursion SHARED empty.c) +set_property (TARGET recursion PROPERTY CUSTOM_PROPERTY "$<TARGET_GENEX_EVAL:recursion,$<TARGET_PROPERTY:CUSTOM_PROPERTY>>") + +add_custom_target (drive + COMMAND echo "$<TARGET_GENEX_EVAL:recursion,$<TARGET_PROPERTY:recursion,CUSTOM_PROPERTY>>" + DEPENDS recursion) diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-recursion2-result.txt b/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-recursion2-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-recursion2-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-recursion2-stderr.txt b/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-recursion2-stderr.txt new file mode 100644 index 0000000..73f6b77 --- /dev/null +++ b/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-recursion2-stderr.txt @@ -0,0 +1,26 @@ +^CMake Error at TARGET_GENEX_EVAL-recursion2.cmake:10 \(add_custom_target\): + Error evaluating generator expression: + + \$<TARGET_GENEX_EVAL:recursion1,\$<TARGET_PROPERTY:recursion1,CUSTOM_PROPERTY1>> + + Dependency loop found. +Call Stack \(most recent call first\): + CMakeLists.txt:3 \(include\) + + +CMake Error at TARGET_GENEX_EVAL-recursion2.cmake:10 \(add_custom_target\): + Loop step 1 + + \$<TARGET_GENEX_EVAL:recursion2,\$<TARGET_PROPERTY:recursion2,CUSTOM_PROPERTY2>> + +Call Stack \(most recent call first\): + CMakeLists.txt:3 \(include\) + + +CMake Error at TARGET_GENEX_EVAL-recursion2.cmake:10 \(add_custom_target\): + Loop step 2 + + \$<TARGET_GENEX_EVAL:recursion1,\$<TARGET_PROPERTY:recursion1,CUSTOM_PROPERTY1>> + +Call Stack \(most recent call first\): + CMakeLists.txt:3 \(include\) diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-recursion2.cmake b/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-recursion2.cmake new file mode 100644 index 0000000..a28dfc3 --- /dev/null +++ b/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-recursion2.cmake @@ -0,0 +1,12 @@ + +enable_language(C) + +add_library (recursion1 SHARED empty.c) +set_property (TARGET recursion1 PROPERTY CUSTOM_PROPERTY1 "$<TARGET_GENEX_EVAL:recursion2,$<TARGET_PROPERTY:recursion2,CUSTOM_PROPERTY2>>") + +add_library (recursion2 SHARED empty.c) +set_property (TARGET recursion2 PROPERTY CUSTOM_PROPERTY2 "$<TARGET_GENEX_EVAL:recursion1,$<TARGET_PROPERTY:recursion1,CUSTOM_PROPERTY1>>") + +add_custom_target (drive + COMMAND echo "$<TARGET_GENEX_EVAL:recursion1,$<TARGET_PROPERTY:recursion1,CUSTOM_PROPERTY1>>" + DEPENDS recursion) diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL.cmake b/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL.cmake new file mode 100644 index 0000000..68b3712 --- /dev/null +++ b/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL.cmake @@ -0,0 +1,10 @@ + +cmake_policy(VERSION 3.11) + +enable_language(C) + +add_library (example SHARED empty.c) +set_property (TARGET example PROPERTY CUSTOM_PROPERTY1 "PROPERTY1") +set_property (TARGET example PROPERTY CUSTOM_PROPERTY2 "BEFORE_$<TARGET_PROPERTY:CUSTOM_PROPERTY1>_AFTER") + +file(GENERATE OUTPUT "TARGET_GENEX_EVAL-generated.txt" CONTENT "$<TARGET_GENEX_EVAL:example,$<TARGET_PROPERTY:example,CUSTOM_PROPERTY2>>") diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_NAME_IF_EXISTS-check.cmake b/Tests/RunCMake/GeneratorExpression/TARGET_NAME_IF_EXISTS-check.cmake new file mode 100644 index 0000000..2f57430 --- /dev/null +++ b/Tests/RunCMake/GeneratorExpression/TARGET_NAME_IF_EXISTS-check.cmake @@ -0,0 +1,6 @@ +file(READ "${RunCMake_TEST_BINARY_DIR}/TARGET_NAME_IF_EXISTS-generated.txt" content) + +set(expected "foo") +if(NOT content STREQUAL expected) + set(RunCMake_TEST_FAILED "actual content:\n [[${content}]]\nbut expected:\n [[${expected}]]") +endif() diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_NAME_IF_EXISTS-empty-arg-result.txt b/Tests/RunCMake/GeneratorExpression/TARGET_NAME_IF_EXISTS-empty-arg-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/GeneratorExpression/TARGET_NAME_IF_EXISTS-empty-arg-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_NAME_IF_EXISTS-empty-arg-stderr.txt b/Tests/RunCMake/GeneratorExpression/TARGET_NAME_IF_EXISTS-empty-arg-stderr.txt new file mode 100644 index 0000000..5ee13b7 --- /dev/null +++ b/Tests/RunCMake/GeneratorExpression/TARGET_NAME_IF_EXISTS-empty-arg-stderr.txt @@ -0,0 +1,9 @@ +CMake Error at TARGET_NAME_IF_EXISTS-empty-arg.cmake:2 \(file\): + Error evaluating generator expression: + + \$<TARGET_NAME_IF_EXISTS:> + + \$<TARGET_NAME_IF_EXISTS:tgt> expression requires a non-empty valid target + name. +Call Stack \(most recent call first\): + CMakeLists.txt:[0-9]+ \(include\) diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_NAME_IF_EXISTS-empty-arg.cmake b/Tests/RunCMake/GeneratorExpression/TARGET_NAME_IF_EXISTS-empty-arg.cmake new file mode 100644 index 0000000..f5034f4 --- /dev/null +++ b/Tests/RunCMake/GeneratorExpression/TARGET_NAME_IF_EXISTS-empty-arg.cmake @@ -0,0 +1,2 @@ +cmake_policy(SET CMP0070 NEW) +file(GENERATE OUTPUT TARGET_NAME_IF_EXISTS-generated.txt CONTENT "$<TARGET_NAME_IF_EXISTS:${empty}>") diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_NAME_IF_EXISTS-no-arg-result.txt b/Tests/RunCMake/GeneratorExpression/TARGET_NAME_IF_EXISTS-no-arg-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/GeneratorExpression/TARGET_NAME_IF_EXISTS-no-arg-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_NAME_IF_EXISTS-no-arg-stderr.txt b/Tests/RunCMake/GeneratorExpression/TARGET_NAME_IF_EXISTS-no-arg-stderr.txt new file mode 100644 index 0000000..4122425 --- /dev/null +++ b/Tests/RunCMake/GeneratorExpression/TARGET_NAME_IF_EXISTS-no-arg-stderr.txt @@ -0,0 +1,8 @@ +CMake Error at TARGET_NAME_IF_EXISTS-no-arg.cmake:2 \(file\): + Error evaluating generator expression: + + \$<TARGET_NAME_IF_EXISTS> + + \$<TARGET_NAME_IF_EXISTS> expression requires exactly one parameter. +Call Stack \(most recent call first\): + CMakeLists.txt:[0-9]+ \(include\) diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_NAME_IF_EXISTS-no-arg.cmake b/Tests/RunCMake/GeneratorExpression/TARGET_NAME_IF_EXISTS-no-arg.cmake new file mode 100644 index 0000000..3293094 --- /dev/null +++ b/Tests/RunCMake/GeneratorExpression/TARGET_NAME_IF_EXISTS-no-arg.cmake @@ -0,0 +1,2 @@ +cmake_policy(SET CMP0070 NEW) +file(GENERATE OUTPUT TARGET_NAME_IF_EXISTS-generated.txt CONTENT "$<TARGET_NAME_IF_EXISTS>") diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_NAME_IF_EXISTS-not-a-target-check.cmake b/Tests/RunCMake/GeneratorExpression/TARGET_NAME_IF_EXISTS-not-a-target-check.cmake new file mode 100644 index 0000000..2085c16 --- /dev/null +++ b/Tests/RunCMake/GeneratorExpression/TARGET_NAME_IF_EXISTS-not-a-target-check.cmake @@ -0,0 +1,5 @@ +file(READ "${RunCMake_TEST_BINARY_DIR}/TARGET_NAME_IF_EXISTS-not-a-target-generated.txt" content) + +if(content) + set(RunCMake_TEST_FAILED "actual content:\n [[${content}]]\nbut expected an empty string") +endif() diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_NAME_IF_EXISTS-not-a-target.cmake b/Tests/RunCMake/GeneratorExpression/TARGET_NAME_IF_EXISTS-not-a-target.cmake new file mode 100644 index 0000000..a054e6c --- /dev/null +++ b/Tests/RunCMake/GeneratorExpression/TARGET_NAME_IF_EXISTS-not-a-target.cmake @@ -0,0 +1,2 @@ +cmake_policy(SET CMP0070 NEW) +file(GENERATE OUTPUT TARGET_NAME_IF_EXISTS-not-a-target-generated.txt CONTENT "$<TARGET_NAME_IF_EXISTS:just-random-string>") diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_NAME_IF_EXISTS.cmake b/Tests/RunCMake/GeneratorExpression/TARGET_NAME_IF_EXISTS.cmake new file mode 100644 index 0000000..0ce3b1d --- /dev/null +++ b/Tests/RunCMake/GeneratorExpression/TARGET_NAME_IF_EXISTS.cmake @@ -0,0 +1,3 @@ +cmake_policy(SET CMP0070 NEW) +add_custom_target(foo) +file(GENERATE OUTPUT TARGET_NAME_IF_EXISTS-generated.txt CONTENT "$<TARGET_NAME_IF_EXISTS:foo>") diff --git a/Tests/RunCMake/Ninja/NoWorkToDo-nowork-stdout.txt b/Tests/RunCMake/Ninja/NoWorkToDo-nowork-stdout.txt new file mode 100644 index 0000000..60a9228 --- /dev/null +++ b/Tests/RunCMake/Ninja/NoWorkToDo-nowork-stdout.txt @@ -0,0 +1 @@ +^ninja: no work to do diff --git a/Tests/RunCMake/Ninja/NoWorkToDo.cmake b/Tests/RunCMake/Ninja/NoWorkToDo.cmake new file mode 100644 index 0000000..a2fa0cb --- /dev/null +++ b/Tests/RunCMake/Ninja/NoWorkToDo.cmake @@ -0,0 +1,2 @@ +enable_language(C) +add_executable(hello hello.c) diff --git a/Tests/RunCMake/Ninja/RspFileC.cmake b/Tests/RunCMake/Ninja/RspFileC.cmake new file mode 100644 index 0000000..4a40682 --- /dev/null +++ b/Tests/RunCMake/Ninja/RspFileC.cmake @@ -0,0 +1,2 @@ +set(ENV{CMAKE_NINJA_FORCE_RESPONSE_FILE} 1) +enable_language(C) diff --git a/Tests/RunCMake/Ninja/RspFileCXX.cmake b/Tests/RunCMake/Ninja/RspFileCXX.cmake new file mode 100644 index 0000000..9e61ffe --- /dev/null +++ b/Tests/RunCMake/Ninja/RspFileCXX.cmake @@ -0,0 +1,2 @@ +set(ENV{CMAKE_NINJA_FORCE_RESPONSE_FILE} 1) +enable_language(CXX) diff --git a/Tests/RunCMake/Ninja/RspFileFortran.cmake b/Tests/RunCMake/Ninja/RspFileFortran.cmake new file mode 100644 index 0000000..8c18e37 --- /dev/null +++ b/Tests/RunCMake/Ninja/RspFileFortran.cmake @@ -0,0 +1,2 @@ +set(ENV{CMAKE_NINJA_FORCE_RESPONSE_FILE} 1) +enable_language(Fortran) diff --git a/Tests/RunCMake/Ninja/RunCMakeTest.cmake b/Tests/RunCMake/Ninja/RunCMakeTest.cmake index b3720fb..b6e6cd4 100644 --- a/Tests/RunCMake/Ninja/RunCMakeTest.cmake +++ b/Tests/RunCMake/Ninja/RunCMakeTest.cmake @@ -21,6 +21,15 @@ function(run_NinjaToolMissing) endfunction() run_NinjaToolMissing() +function(run_NoWorkToDo) + run_cmake(NoWorkToDo) + set(RunCMake_TEST_NO_CLEAN 1) + set(RunCMake_TEST_BINARY_DIR ${RunCMake_BINARY_DIR}/NoWorkToDo-build) + run_cmake_command(NoWorkToDo-build ${CMAKE_COMMAND} --build .) + run_cmake_command(NoWorkToDo-nowork ${CMAKE_COMMAND} --build . -- -d explain) +endfunction() +run_NoWorkToDo() + function(run_CMP0058 case) # Use a single build tree for a few tests without cleaning. set(RunCMake_TEST_BINARY_DIR ${RunCMake_BINARY_DIR}/CMP0058-${case}-build) @@ -40,6 +49,12 @@ run_CMP0058(NEW-by) run_cmake(CustomCommandDepfile) +run_cmake(RspFileC) +run_cmake(RspFileCXX) +if(TEST_Fortran) + run_cmake(RspFileFortran) +endif() + function(run_CommandConcat) set(RunCMake_TEST_BINARY_DIR ${RunCMake_BINARY_DIR}/CommandConcat-build) set(RunCMake_TEST_NO_CLEAN 1) diff --git a/Tests/RunCMake/ObjectLibrary/BadObjSource2-stderr.txt b/Tests/RunCMake/ObjectLibrary/BadObjSource2-stderr.txt deleted file mode 100644 index b91ffd0..0000000 --- a/Tests/RunCMake/ObjectLibrary/BadObjSource2-stderr.txt +++ /dev/null @@ -1,9 +0,0 @@ -CMake Error at BadObjSource2.cmake:1 \(add_library\): - OBJECT library "A" contains: - - bad.obj - - but may contain only sources that compile, header files, and other files - that would not affect linking of a normal library. -Call Stack \(most recent call first\): - CMakeLists.txt:3 \(include\) diff --git a/Tests/RunCMake/ObjectLibrary/CMakeLists.txt b/Tests/RunCMake/ObjectLibrary/CMakeLists.txt index a17c8cd..d1b0d2c 100644 --- a/Tests/RunCMake/ObjectLibrary/CMakeLists.txt +++ b/Tests/RunCMake/ObjectLibrary/CMakeLists.txt @@ -1,3 +1,3 @@ -cmake_minimum_required(VERSION 2.8.4) +cmake_minimum_required(VERSION 3.10) project(${RunCMake_TEST} C) include(${RunCMake_TEST}.cmake) diff --git a/Tests/RunCMake/ObjectLibrary/ExportNotSupported-stderr.txt b/Tests/RunCMake/ObjectLibrary/ExportNotSupported-stderr.txt deleted file mode 100644 index 5420159..0000000 --- a/Tests/RunCMake/ObjectLibrary/ExportNotSupported-stderr.txt +++ /dev/null @@ -1,5 +0,0 @@ -CMake Error at ExportNotSupported.cmake:[0-9]+ \(export\): - export given OBJECT library "A" which may not be exported under Xcode with - multiple architectures. -Call Stack \(most recent call first\): - CMakeLists.txt:3 \(include\) diff --git a/Tests/RunCMake/ObjectLibrary/ExportNotSupported.cmake b/Tests/RunCMake/ObjectLibrary/ExportNotSupported.cmake deleted file mode 100644 index a3f104e..0000000 --- a/Tests/RunCMake/ObjectLibrary/ExportNotSupported.cmake +++ /dev/null @@ -1,2 +0,0 @@ -add_library(A OBJECT a.c) -export(TARGETS A FILE AExport.cmake) diff --git a/Tests/RunCMake/ObjectLibrary/InstallLinkedObj1-result.txt b/Tests/RunCMake/ObjectLibrary/InstallLinkedObj1-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/ObjectLibrary/InstallLinkedObj1-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/ObjectLibrary/InstallLinkedObj1-stderr.txt b/Tests/RunCMake/ObjectLibrary/InstallLinkedObj1-stderr.txt new file mode 100644 index 0000000..f2f0f94 --- /dev/null +++ b/Tests/RunCMake/ObjectLibrary/InstallLinkedObj1-stderr.txt @@ -0,0 +1 @@ +CMake Error: install\(EXPORT "exp" ...\) includes target "UseA" which requires target "A" that is not in the export set. diff --git a/Tests/RunCMake/ObjectLibrary/InstallLinkedObj1.cmake b/Tests/RunCMake/ObjectLibrary/InstallLinkedObj1.cmake new file mode 100644 index 0000000..9e24609 --- /dev/null +++ b/Tests/RunCMake/ObjectLibrary/InstallLinkedObj1.cmake @@ -0,0 +1,6 @@ +add_library(A OBJECT a.c) +add_library(UseA STATIC) +target_link_libraries(UseA PUBLIC A) + +install(TARGETS UseA EXPORT exp ARCHIVE DESTINATION lib) +install(EXPORT exp DESTINATION lib/cmake/exp) diff --git a/Tests/RunCMake/ObjectLibrary/InstallLinkedObj2.cmake b/Tests/RunCMake/ObjectLibrary/InstallLinkedObj2.cmake new file mode 100644 index 0000000..cdda962 --- /dev/null +++ b/Tests/RunCMake/ObjectLibrary/InstallLinkedObj2.cmake @@ -0,0 +1,6 @@ +add_library(A OBJECT a.c) +add_library(UseA STATIC) +target_link_libraries(UseA PUBLIC A) + +install(TARGETS UseA A EXPORT exp ARCHIVE DESTINATION lib) +install(EXPORT exp DESTINATION lib/cmake/exp) diff --git a/Tests/RunCMake/ObjectLibrary/InstallNotSupported-stderr.txt b/Tests/RunCMake/ObjectLibrary/InstallNotSupported-stderr.txt index 35a0e4f..a7004c1 100644 --- a/Tests/RunCMake/ObjectLibrary/InstallNotSupported-stderr.txt +++ b/Tests/RunCMake/ObjectLibrary/InstallNotSupported-stderr.txt @@ -1,5 +1,5 @@ CMake Error at InstallNotSupported.cmake:[0-9]+ \(install\): - install TARGETS given OBJECT library "A" which may not be installed under - Xcode with multiple architectures. + install TARGETS given OBJECT library "A" whose objects may not be installed + under Xcode with multiple architectures. Call Stack \(most recent call first\): CMakeLists.txt:3 \(include\) diff --git a/Tests/RunCMake/ObjectLibrary/LinkObjLHS-stderr.txt b/Tests/RunCMake/ObjectLibrary/LinkObjLHS-stderr.txt deleted file mode 100644 index 90e828b..0000000 --- a/Tests/RunCMake/ObjectLibrary/LinkObjLHS-stderr.txt +++ /dev/null @@ -1,4 +0,0 @@ -CMake Error at LinkObjLHS.cmake:2 \(target_link_libraries\): - Object library target "AnObjLib" may not link to anything. -Call Stack \(most recent call first\): - CMakeLists.txt:3 \(include\) diff --git a/Tests/RunCMake/ObjectLibrary/LinkObjLHS.cmake b/Tests/RunCMake/ObjectLibrary/LinkObjLHS.cmake deleted file mode 100644 index 5d7831a..0000000 --- a/Tests/RunCMake/ObjectLibrary/LinkObjLHS.cmake +++ /dev/null @@ -1,2 +0,0 @@ -add_library(AnObjLib OBJECT a.c) -target_link_libraries(AnObjLib OtherLib) diff --git a/Tests/RunCMake/ObjectLibrary/LinkObjLHSShared.cmake b/Tests/RunCMake/ObjectLibrary/LinkObjLHSShared.cmake new file mode 100644 index 0000000..4aa7bba --- /dev/null +++ b/Tests/RunCMake/ObjectLibrary/LinkObjLHSShared.cmake @@ -0,0 +1,7 @@ +project(LinkObjLHSShared C) + +add_library(OtherLib SHARED a.c) +target_compile_definitions(OtherLib INTERFACE REQUIRED) + +add_library(AnObjLib OBJECT requires.c) +target_link_libraries(AnObjLib OtherLib) diff --git a/Tests/RunCMake/ObjectLibrary/LinkObjLHSStatic.cmake b/Tests/RunCMake/ObjectLibrary/LinkObjLHSStatic.cmake new file mode 100644 index 0000000..261bee7 --- /dev/null +++ b/Tests/RunCMake/ObjectLibrary/LinkObjLHSStatic.cmake @@ -0,0 +1,7 @@ +project(LinkObjLHSStatic C) + +add_library(OtherLib STATIC a.c) +target_compile_definitions(OtherLib INTERFACE REQUIRED) + +add_library(AnObjLib OBJECT requires.c) +target_link_libraries(AnObjLib OtherLib) diff --git a/Tests/RunCMake/ObjectLibrary/LinkObjRHS1-stderr.txt b/Tests/RunCMake/ObjectLibrary/LinkObjRHS1-stderr.txt deleted file mode 100644 index d5ee4f9..0000000 --- a/Tests/RunCMake/ObjectLibrary/LinkObjRHS1-stderr.txt +++ /dev/null @@ -1,6 +0,0 @@ -CMake Error at LinkObjRHS1.cmake:3 \(target_link_libraries\): - Target "AnObjLib" of type OBJECT_LIBRARY may not be linked into another - target. One may link only to INTERFACE, STATIC or SHARED libraries, or to - executables with the ENABLE_EXPORTS property set. -Call Stack \(most recent call first\): - CMakeLists.txt:3 \(include\) diff --git a/Tests/RunCMake/ObjectLibrary/LinkObjRHS1.cmake b/Tests/RunCMake/ObjectLibrary/LinkObjRHS1.cmake deleted file mode 100644 index 113d6a8..0000000 --- a/Tests/RunCMake/ObjectLibrary/LinkObjRHS1.cmake +++ /dev/null @@ -1,3 +0,0 @@ -add_library(A STATIC a.c) -add_library(AnObjLib OBJECT a.c) -target_link_libraries(A AnObjLib) diff --git a/Tests/RunCMake/ObjectLibrary/LinkObjRHS2-stderr.txt b/Tests/RunCMake/ObjectLibrary/LinkObjRHS2-stderr.txt deleted file mode 100644 index 3295fca..0000000 --- a/Tests/RunCMake/ObjectLibrary/LinkObjRHS2-stderr.txt +++ /dev/null @@ -1,6 +0,0 @@ -CMake Error at LinkObjRHS2.cmake:1 \(add_library\): - Target "A" links to OBJECT library "AnObjLib" but this is not allowed. One - may link only to STATIC or SHARED libraries, or to executables with the - ENABLE_EXPORTS property set. -Call Stack \(most recent call first\): - CMakeLists.txt:3 \(include\) diff --git a/Tests/RunCMake/ObjectLibrary/LinkObjRHS2.cmake b/Tests/RunCMake/ObjectLibrary/LinkObjRHS2.cmake deleted file mode 100644 index 6163729..0000000 --- a/Tests/RunCMake/ObjectLibrary/LinkObjRHS2.cmake +++ /dev/null @@ -1,3 +0,0 @@ -add_library(A SHARED a.c) -target_link_libraries(A AnObjLib) -add_library(AnObjLib OBJECT a.c) diff --git a/Tests/RunCMake/ObjectLibrary/LinkObjRHSObject-build-result.txt b/Tests/RunCMake/ObjectLibrary/LinkObjRHSObject-build-result.txt new file mode 100644 index 0000000..e27f06b --- /dev/null +++ b/Tests/RunCMake/ObjectLibrary/LinkObjRHSObject-build-result.txt @@ -0,0 +1 @@ +[1-9][0-9]* diff --git a/Tests/RunCMake/ObjectLibrary/LinkObjRHSObject-build-stdout.txt b/Tests/RunCMake/ObjectLibrary/LinkObjRHSObject-build-stdout.txt new file mode 100644 index 0000000..4eeb096 --- /dev/null +++ b/Tests/RunCMake/ObjectLibrary/LinkObjRHSObject-build-stdout.txt @@ -0,0 +1 @@ +REQUIRED needs to be defined diff --git a/Tests/RunCMake/ObjectLibrary/LinkObjRHSObject.cmake b/Tests/RunCMake/ObjectLibrary/LinkObjRHSObject.cmake new file mode 100644 index 0000000..db571a3 --- /dev/null +++ b/Tests/RunCMake/ObjectLibrary/LinkObjRHSObject.cmake @@ -0,0 +1,12 @@ +cmake_policy(SET CMP0022 NEW) + +enable_language(C) + +add_library(AnObjLib OBJECT a.c) +target_compile_definitions(AnObjLib INTERFACE REQUIRED) + +add_library(AnotherObjLib OBJECT b.c) +target_link_libraries(AnotherObjLib PRIVATE AnObjLib) + +add_executable(exe exe.c) +target_link_libraries(exe AnotherObjLib) diff --git a/Tests/RunCMake/ObjectLibrary/LinkObjRHSObject2-build-result.txt b/Tests/RunCMake/ObjectLibrary/LinkObjRHSObject2-build-result.txt new file mode 100644 index 0000000..e27f06b --- /dev/null +++ b/Tests/RunCMake/ObjectLibrary/LinkObjRHSObject2-build-result.txt @@ -0,0 +1 @@ +[1-9][0-9]* diff --git a/Tests/RunCMake/ObjectLibrary/LinkObjRHSObject2.cmake b/Tests/RunCMake/ObjectLibrary/LinkObjRHSObject2.cmake new file mode 100644 index 0000000..6bb8d5e --- /dev/null +++ b/Tests/RunCMake/ObjectLibrary/LinkObjRHSObject2.cmake @@ -0,0 +1,12 @@ +cmake_policy(SET CMP0022 NEW) + +enable_language(C) + +add_library(AnObjLib OBJECT a.c) +target_compile_definitions(AnObjLib INTERFACE REQUIRED) + +add_library(AnotherObjLib OBJECT b.c) +target_link_libraries(AnotherObjLib PUBLIC AnObjLib) + +add_executable(exe exe.c) +target_link_libraries(exe AnotherObjLib) diff --git a/Tests/RunCMake/ObjectLibrary/LinkObjRHSShared.cmake b/Tests/RunCMake/ObjectLibrary/LinkObjRHSShared.cmake new file mode 100644 index 0000000..b9030b3 --- /dev/null +++ b/Tests/RunCMake/ObjectLibrary/LinkObjRHSShared.cmake @@ -0,0 +1,13 @@ +enable_language(C) + +add_definitions(-DCOMPILE_FOR_SHARED_LIB) + +add_library(AnObjLib OBJECT a.c) +target_compile_definitions(AnObjLib INTERFACE REQUIRED) +set_target_properties(AnObjLib PROPERTIES POSITION_INDEPENDENT_CODE ON) + +add_library(A SHARED b.c $<TARGET_OBJECTS:AnObjLib>) +target_link_libraries(A PUBLIC AnObjLib) + +add_executable(exe exe.c) +target_link_libraries(exe A) diff --git a/Tests/RunCMake/ObjectLibrary/LinkObjRHSShared2.cmake b/Tests/RunCMake/ObjectLibrary/LinkObjRHSShared2.cmake new file mode 100644 index 0000000..e2e5fa2 --- /dev/null +++ b/Tests/RunCMake/ObjectLibrary/LinkObjRHSShared2.cmake @@ -0,0 +1,14 @@ +enable_language(C) + +add_definitions(-DCOMPILE_FOR_SHARED_LIB) + +add_library(AnObjLib OBJECT a.c) +target_compile_definitions(AnObjLib INTERFACE REQUIRED) +set_target_properties(AnObjLib PROPERTIES POSITION_INDEPENDENT_CODE ON) + +add_library(A SHARED b.c) +target_link_libraries(A PRIVATE AnObjLib) +target_compile_definitions(A INTERFACE $<TARGET_PROPERTY:AnObjLib,INTERFACE_COMPILE_DEFINITIONS>) + +add_executable(exe exe.c) +target_link_libraries(exe A) diff --git a/Tests/RunCMake/ObjectLibrary/LinkObjRHSStatic.cmake b/Tests/RunCMake/ObjectLibrary/LinkObjRHSStatic.cmake new file mode 100644 index 0000000..73fad06 --- /dev/null +++ b/Tests/RunCMake/ObjectLibrary/LinkObjRHSStatic.cmake @@ -0,0 +1,10 @@ +enable_language(C) + +add_library(AnObjLib OBJECT a.c) +target_compile_definitions(AnObjLib INTERFACE REQUIRED) + +add_library(A STATIC b.c $<TARGET_OBJECTS:AnObjLib>) +target_link_libraries(A PUBLIC AnObjLib) + +add_executable(exe exe.c) +target_link_libraries(exe A) diff --git a/Tests/RunCMake/ObjectLibrary/LinkObjRHSStatic2.cmake b/Tests/RunCMake/ObjectLibrary/LinkObjRHSStatic2.cmake new file mode 100644 index 0000000..9e1ab6d --- /dev/null +++ b/Tests/RunCMake/ObjectLibrary/LinkObjRHSStatic2.cmake @@ -0,0 +1,11 @@ +enable_language(C) + +add_library(AnObjLib OBJECT a.c) +target_compile_definitions(AnObjLib INTERFACE REQUIRED) + +add_library(A STATIC b.c) +target_link_libraries(A PRIVATE AnObjLib) +target_compile_definitions(A INTERFACE $<TARGET_PROPERTY:AnObjLib,INTERFACE_COMPILE_DEFINITIONS>) + +add_executable(exe exe.c) +target_link_libraries(exe A) diff --git a/Tests/RunCMake/ObjectLibrary/ObjWithObj-stderr.txt b/Tests/RunCMake/ObjectLibrary/ObjWithObj-stderr.txt deleted file mode 100644 index d67b4ae..0000000 --- a/Tests/RunCMake/ObjectLibrary/ObjWithObj-stderr.txt +++ /dev/null @@ -1,4 +0,0 @@ -CMake Error at ObjWithObj.cmake:2 \(add_library\): - Only executables and non-OBJECT libraries may reference target objects. -Call Stack \(most recent call first\): - CMakeLists.txt:3 \(include\) diff --git a/Tests/RunCMake/ObjectLibrary/RunCMakeTest.cmake b/Tests/RunCMake/ObjectLibrary/RunCMakeTest.cmake index b8eed73..c73732f 100644 --- a/Tests/RunCMake/ObjectLibrary/RunCMakeTest.cmake +++ b/Tests/RunCMake/ObjectLibrary/RunCMakeTest.cmake @@ -6,17 +6,46 @@ run_cmake(BadSourceExpression3) run_cmake(BadObjSource1) run_cmake(BadObjSource2) if(RunCMake_GENERATOR STREQUAL "Xcode" AND "$ENV{CMAKE_OSX_ARCHITECTURES}" MATCHES "[;$]") - run_cmake(ExportNotSupported) run_cmake(ImportNotSupported) run_cmake(InstallNotSupported) else() - run_cmake(Export) run_cmake(Import) run_cmake(Install) + run_cmake(InstallLinkedObj1) + run_cmake(InstallLinkedObj2) endif() -run_cmake(LinkObjLHS) -run_cmake(LinkObjRHS1) -run_cmake(LinkObjRHS2) +run_cmake(Export) + +function (run_object_lib_build name) + # Use a single build tree for a few tests without cleaning. + set(RunCMake_TEST_BINARY_DIR ${RunCMake_BINARY_DIR}/${name}-build) + set(RunCMake_TEST_NO_CLEAN 1) + file(REMOVE_RECURSE "${RunCMake_TEST_BINARY_DIR}") + file(MAKE_DIRECTORY "${RunCMake_TEST_BINARY_DIR}") + run_cmake(${name}) + run_cmake_command(${name}-build ${CMAKE_COMMAND} --build .) +endfunction () + +function (run_object_lib_build2 name) + # Use a single build tree for a few tests without cleaning. + set(RunCMake_TEST_BINARY_DIR ${RunCMake_BINARY_DIR}/${name}-build) + set(RunCMake_TEST_NO_CLEAN 1) + file(REMOVE_RECURSE "${RunCMake_TEST_BINARY_DIR}") + file(MAKE_DIRECTORY "${RunCMake_TEST_BINARY_DIR}") + run_cmake(${name}) + set(RunCMake_TEST_OUTPUT_MERGE 1) + run_cmake_command(${name}-build ${CMAKE_COMMAND} --build .) +endfunction () + +run_object_lib_build(LinkObjLHSShared) +run_object_lib_build(LinkObjLHSStatic) +run_object_lib_build(LinkObjRHSShared) +run_object_lib_build(LinkObjRHSStatic) +run_object_lib_build2(LinkObjRHSObject) +run_object_lib_build(LinkObjRHSShared2) +run_object_lib_build(LinkObjRHSStatic2) +run_object_lib_build2(LinkObjRHSObject2) + run_cmake(MissingSource) run_cmake(ObjWithObj) run_cmake(OwnSources) diff --git a/Tests/RunCMake/ObjectLibrary/a.c b/Tests/RunCMake/ObjectLibrary/a.c index 1636303..5beb3f1 100644 --- a/Tests/RunCMake/ObjectLibrary/a.c +++ b/Tests/RunCMake/ObjectLibrary/a.c @@ -1,4 +1,10 @@ -int a(void) +#if defined(_WIN32) && defined(COMPILE_FOR_SHARED_LIB) +#define EXPORT __declspec(dllexport) +#else +#define EXPORT +#endif + +EXPORT int a(void) { return 0; } diff --git a/Tests/RunCMake/ObjectLibrary/b.c b/Tests/RunCMake/ObjectLibrary/b.c index 6751907..7549abf 100644 --- a/Tests/RunCMake/ObjectLibrary/b.c +++ b/Tests/RunCMake/ObjectLibrary/b.c @@ -1,4 +1,14 @@ -int b(void) +#if defined(_WIN32) && defined(COMPILE_FOR_SHARED_LIB) +#define EXPORT __declspec(dllexport) +#else +#define EXPORT +#endif + +extern int a(void); +EXPORT int b() { - return 0; + return a(); } +#ifndef REQUIRED +#error "REQUIRED needs to be defined" +#endif diff --git a/Tests/RunCMake/ObjectLibrary/exe.c b/Tests/RunCMake/ObjectLibrary/exe.c new file mode 100644 index 0000000..6efdae7 --- /dev/null +++ b/Tests/RunCMake/ObjectLibrary/exe.c @@ -0,0 +1,14 @@ +#if defined(_WIN32) && defined(COMPILE_FOR_SHARED_LIB) +#define IMPORT __declspec(dllimport) +#else +#define IMPORT +#endif + +extern IMPORT int b(void); +int main() +{ + return b(); +} +#ifndef REQUIRED +#error "REQUIRED needs to be defined" +#endif diff --git a/Tests/RunCMake/ObjectLibrary/requires.c b/Tests/RunCMake/ObjectLibrary/requires.c new file mode 100644 index 0000000..d524952 --- /dev/null +++ b/Tests/RunCMake/ObjectLibrary/requires.c @@ -0,0 +1,8 @@ +#ifdef REQUIRED +int required() +{ + return 0; +} +#else +#error "REQUIRED not defined" +#endif diff --git a/Tests/RunCMake/RunCMake.cmake b/Tests/RunCMake/RunCMake.cmake index e688830..b2b38ef 100644 --- a/Tests/RunCMake/RunCMake.cmake +++ b/Tests/RunCMake/RunCMake.cmake @@ -51,9 +51,6 @@ function(run_cmake test) if(APPLE) list(APPEND RunCMake_TEST_OPTIONS -DCMAKE_POLICY_DEFAULT_CMP0025=NEW) endif() - if(RunCMake_GENERATOR MATCHES "^Visual Studio 8 2005" AND NOT RunCMake_WARN_VS8) - list(APPEND RunCMake_TEST_OPTIONS -DCMAKE_WARN_VS8=OFF) - endif() if(RunCMake_MAKE_PROGRAM) list(APPEND RunCMake_TEST_OPTIONS "-DCMAKE_MAKE_PROGRAM=${RunCMake_MAKE_PROGRAM}") endif() @@ -112,6 +109,8 @@ function(run_cmake test) "|clang[^:]*: warning: the object size sanitizer has no effect at -O0, but is explicitly enabled:" "|Error kstat returned" "|Hit xcodebuild bug" + "|ld: 0711-224 WARNING: Duplicate symbol: .__init_aix_libgcc_cxa_atexit" + "|ld: 0711-345 Use the -bloadmap or -bnoquiet option to obtain more information" "|[^\n]*is a member of multiple groups" "|[^\n]*from Time Machine by path" "|[^\n]*Bullseye Testing Technology" diff --git a/Tests/RunCMake/TargetPolicies/PolicyList-stderr.txt b/Tests/RunCMake/TargetPolicies/PolicyList-stderr.txt index 8d5139d..5af6fcd 100644 --- a/Tests/RunCMake/TargetPolicies/PolicyList-stderr.txt +++ b/Tests/RunCMake/TargetPolicies/PolicyList-stderr.txt @@ -23,6 +23,7 @@ \* CMP0065 \* CMP0068 \* CMP0069 + \* CMP0073 Call Stack \(most recent call first\): CMakeLists.txt:3 \(include\) diff --git a/Tests/RunCMake/VS10Project/RunCMakeTest.cmake b/Tests/RunCMake/VS10Project/RunCMakeTest.cmake index a8d806f..0d178ce 100644 --- a/Tests/RunCMake/VS10Project/RunCMakeTest.cmake +++ b/Tests/RunCMake/VS10Project/RunCMakeTest.cmake @@ -6,6 +6,8 @@ run_cmake(VsConfigurationType) run_cmake(VsTargetsFileReferences) run_cmake(VsCustomProps) run_cmake(VsDebuggerWorkingDir) +run_cmake(VsDebuggerCommand) run_cmake(VsCSharpCustomTags) run_cmake(VsCSharpReferenceProps) run_cmake(VsCSharpWithoutSources) +run_cmake(VsSdkDirectories) diff --git a/Tests/RunCMake/VS10Project/VsCSharpCustomTags.cmake b/Tests/RunCMake/VS10Project/VsCSharpCustomTags.cmake index 45766a0..96be54b 100644 --- a/Tests/RunCMake/VS10Project/VsCSharpCustomTags.cmake +++ b/Tests/RunCMake/VS10Project/VsCSharpCustomTags.cmake @@ -16,8 +16,7 @@ set(fileNames) foreach(e ${fileExtensions}) set(currentFile "${CMAKE_CURRENT_BINARY_DIR}/foo.${e}") list(APPEND fileNames ${currentFile}) - execute_process(COMMAND ${CMAKE_COMMAND} -E touch - "${currentFile}") + file(TOUCH "${currentFile}") string(TOUPPER ${e} eUC) set_source_files_properties("${currentFile}" PROPERTIES diff --git a/Tests/RunCMake/VS10Project/VsDebuggerCommand-check.cmake b/Tests/RunCMake/VS10Project/VsDebuggerCommand-check.cmake new file mode 100644 index 0000000..0ded780 --- /dev/null +++ b/Tests/RunCMake/VS10Project/VsDebuggerCommand-check.cmake @@ -0,0 +1,22 @@ +set(vcProjectFile "${RunCMake_TEST_BINARY_DIR}/foo.vcxproj") +if(NOT EXISTS "${vcProjectFile}") + set(RunCMake_TEST_FAILED "Project file ${vcProjectFile} does not exist.") + return() +endif() + +set(debuggerCommandSet FALSE) + +file(STRINGS "${vcProjectFile}" lines) +foreach(line IN LISTS lines) + if(line MATCHES "^ *<LocalDebuggerCommand[^>]*>([^<>]+)</LocalDebuggerCommand>$") + if("${CMAKE_MATCH_1}" STREQUAL "my-debugger-command") + message(STATUS "foo.vcxproj has debugger command set") + set(debuggerCommandSet TRUE) + endif() + endif() +endforeach() + +if(NOT debuggerCommandSet) + set(RunCMake_TEST_FAILED "LocalDebuggerCommand not found or not set correctly.") + return() +endif() diff --git a/Tests/RunCMake/VS10Project/VsDebuggerCommand.cmake b/Tests/RunCMake/VS10Project/VsDebuggerCommand.cmake new file mode 100644 index 0000000..e29adc4 --- /dev/null +++ b/Tests/RunCMake/VS10Project/VsDebuggerCommand.cmake @@ -0,0 +1,5 @@ +enable_language(CXX) +add_library(foo foo.cpp) + +set_target_properties(foo PROPERTIES + VS_DEBUGGER_COMMAND "my-debugger-command") diff --git a/Tests/RunCMake/VS10Project/VsSdkDirectories-check.cmake b/Tests/RunCMake/VS10Project/VsSdkDirectories-check.cmake new file mode 100644 index 0000000..c21afb6 --- /dev/null +++ b/Tests/RunCMake/VS10Project/VsSdkDirectories-check.cmake @@ -0,0 +1,88 @@ +set(vcProjectFile "${RunCMake_TEST_BINARY_DIR}/foo.vcxproj") +if(NOT EXISTS "${vcProjectFile}") + set(RunCMake_TEST_FAILED "Project file ${vcProjectFile} does not exist.") + return() +endif() + +set(ExecutablePathSet FALSE) +set(IncludePathSet FALSE) +set(ReferencePathSet FALSE) +set(LibraryPathSet FALSE) +set(LibraryWPathSet FALSE) +set(SourcePathSet FALSE) +set(ExcludePathSet FALSE) + +file(STRINGS "${vcProjectFile}" lines) +foreach(line IN LISTS lines) + if(line MATCHES "^ *<ExecutablePath[^>]*>([^<>]+)</ExecutablePath>$") + if("${CMAKE_MATCH_1}" STREQUAL "$(VC_ExecutablePath_x86);C:\\Program Files\\Custom-SDK\\;") + message(STATUS "foo.vcxproj has executable path set") + set(ExecutablePathSet TRUE) + endif() + elseif(line MATCHES "^ *<IncludePath[^>]*>([^<>]+)</IncludePath>$") + if("${CMAKE_MATCH_1}" STREQUAL "$(VC_IncludePath);C:\\Program Files\\Custom-SDK\\;") + message(STATUS "foo.vcxproj has include path set") + set(IncludePathSet TRUE) + endif() + elseif(line MATCHES "^ *<ReferencePath[^>]*>([^<>]+)</ReferencePath>$") + if("${CMAKE_MATCH_1}" STREQUAL "$(VC_ReferencesPath_x86);C:\\Program Files\\Custom-SDK\\;") + message(STATUS "foo.vcxproj has reference path set") + set(ReferencePathSet TRUE) + endif() + elseif(line MATCHES "^ *<LibraryPath[^>]*>([^<>]+)</LibraryPath>$") + if("${CMAKE_MATCH_1}" STREQUAL "$(VC_LibraryPath_x86);C:\\Program Files\\Custom-SDK\\;") + message(STATUS "foo.vcxproj has library path set") + set(LibraryPathSet TRUE) + endif() + elseif(line MATCHES "^ *<LibraryWPath[^>]*>([^<>]+)</LibraryWPath>$") + if("${CMAKE_MATCH_1}" STREQUAL "$(WindowsSDK_MetadataPath);C:\\Program Files\\Custom-SDK\\;") + message(STATUS "foo.vcxproj has library WinRT path set") + set(LibraryWPathSet TRUE) + endif() + elseif(line MATCHES "^ *<SourcePath[^>]*>([^<>]+)</SourcePath>$") + if("${CMAKE_MATCH_1}" STREQUAL "$(VC_SourcePath);C:\\Program Files\\Custom-SDK\\;") + message(STATUS "foo.vcxproj has source path set") + set(SourcePathSet TRUE) + endif() + elseif(line MATCHES "^ *<ExcludePath[^>]*>([^<>]+)</ExcludePath>$") + if("${CMAKE_MATCH_1}" STREQUAL "$(VC_IncludePath);C:\\Program Files\\Custom-SDK\\;") + message(STATUS "foo.vcxproj has exclude path set") + set(ExcludePathSet TRUE) + endif() + endif() +endforeach() + +if(NOT ExecutablePathSet) + set(RunCMake_TEST_FAILED "ExecutablePath not found or not set correctly.") + return() +endif() + +if(NOT IncludePathSet) + set(RunCMake_TEST_FAILED "IncludePath not found or not set correctly.") + return() +endif() + +if(NOT ReferencePathSet) + set(RunCMake_TEST_FAILED "ReferencePath not found or not set correctly.") + return() +endif() + +if(NOT LibraryPathSet) + set(RunCMake_TEST_FAILED "LibraryPath not found or not set correctly.") + return() +endif() + +if(NOT LibraryWPathSet) + set(RunCMake_TEST_FAILED "LibraryWPath not found or not set correctly.") + return() +endif() + +if(NOT SourcePathSet) + set(RunCMake_TEST_FAILED "SourcePath not found or not set correctly.") + return() +endif() + +if(NOT ExcludePathSet) + set(RunCMake_TEST_FAILED "ExcludePath not found or not set correctly.") + return() +endif() diff --git a/Tests/RunCMake/VS10Project/VsSdkDirectories.cmake b/Tests/RunCMake/VS10Project/VsSdkDirectories.cmake new file mode 100644 index 0000000..c8f2a5a --- /dev/null +++ b/Tests/RunCMake/VS10Project/VsSdkDirectories.cmake @@ -0,0 +1,11 @@ +enable_language(CXX) + +set(CMAKE_VS_SDK_EXECUTABLE_DIRECTORIES "$(VC_ExecutablePath_x86);C:\\Program Files\\Custom-SDK\\;") +set(CMAKE_VS_SDK_INCLUDE_DIRECTORIES "$(VC_IncludePath);C:\\Program Files\\Custom-SDK\\;") +set(CMAKE_VS_SDK_REFERENCE_DIRECTORIES "$(VC_ReferencesPath_x86);C:\\Program Files\\Custom-SDK\\;") +set(CMAKE_VS_SDK_LIBRARY_DIRECTORIES "$(VC_LibraryPath_x86);C:\\Program Files\\Custom-SDK\\;") +set(CMAKE_VS_SDK_LIBRARY_WINRT_DIRECTORIES "$(WindowsSDK_MetadataPath);C:\\Program Files\\Custom-SDK\\;") +set(CMAKE_VS_SDK_SOURCE_DIRECTORIES "$(VC_SourcePath);C:\\Program Files\\Custom-SDK\\;") +set(CMAKE_VS_SDK_EXCLUDE_DIRECTORIES "$(VC_IncludePath);C:\\Program Files\\Custom-SDK\\;") + +add_library(foo foo.cpp) diff --git a/Tests/RunCMake/WorkingDirectory/CMakeLists.txt.in b/Tests/RunCMake/WorkingDirectory/CMakeLists.txt.in new file mode 100644 index 0000000..46047b8 --- /dev/null +++ b/Tests/RunCMake/WorkingDirectory/CMakeLists.txt.in @@ -0,0 +1,3 @@ +cmake_minimum_required(VERSION 3.11) +project(@CASE_NAME@ NONE) +include("@RunCMake_SOURCE_DIR@/@CASE_NAME@.cmake") diff --git a/Tests/RunCMake/WorkingDirectory/CTestConfig.cmake.in b/Tests/RunCMake/WorkingDirectory/CTestConfig.cmake.in new file mode 100644 index 0000000..0226230 --- /dev/null +++ b/Tests/RunCMake/WorkingDirectory/CTestConfig.cmake.in @@ -0,0 +1 @@ +set(CTEST_PROJECT_NAME "CTestTestWorkingDir.@CASE_NAME@") diff --git a/Tests/RunCMake/WorkingDirectory/RunCMakeTest.cmake b/Tests/RunCMake/WorkingDirectory/RunCMakeTest.cmake new file mode 100644 index 0000000..a7685ae --- /dev/null +++ b/Tests/RunCMake/WorkingDirectory/RunCMakeTest.cmake @@ -0,0 +1,9 @@ +include(RunCTest) + +run_ctest(dirNotExist) +run_ctest(buildAndTestNoBuildDir + --build-and-test + ${RunCMake_BINARY_DIR}/buildAndTestNoBuildDir + ${RunCMake_BINARY_DIR}/buildAndTestNoBuildDir/CMakeLists.txt # Deliberately a file + --build-generator "${RunCMake_GENERATOR}" +) diff --git a/Tests/RunCMake/WorkingDirectory/buildAndTestNoBuildDir-check.cmake b/Tests/RunCMake/WorkingDirectory/buildAndTestNoBuildDir-check.cmake new file mode 100644 index 0000000..fcfe461 --- /dev/null +++ b/Tests/RunCMake/WorkingDirectory/buildAndTestNoBuildDir-check.cmake @@ -0,0 +1,3 @@ +if(EXISTS ${RunCMake_TEST_BINARY_DIR}/CMakeCache.txt) + set(RunCMake_TEST_FAILED "Default build dir ${RunCMake_TEST_BINARY_DIR} was used, should not have been") +endif() diff --git a/Tests/RunCMake/WorkingDirectory/buildAndTestNoBuildDir-result.txt b/Tests/RunCMake/WorkingDirectory/buildAndTestNoBuildDir-result.txt new file mode 100644 index 0000000..0617a38 --- /dev/null +++ b/Tests/RunCMake/WorkingDirectory/buildAndTestNoBuildDir-result.txt @@ -0,0 +1 @@ +^[^0][0-9]*$ diff --git a/Tests/RunCMake/WorkingDirectory/buildAndTestNoBuildDir-stdout.txt b/Tests/RunCMake/WorkingDirectory/buildAndTestNoBuildDir-stdout.txt new file mode 100644 index 0000000..da89317 --- /dev/null +++ b/Tests/RunCMake/WorkingDirectory/buildAndTestNoBuildDir-stdout.txt @@ -0,0 +1 @@ +Failed to change working directory to .*[/\\]buildAndTestNoBuildDir[/\\]CMakeLists.txt : diff --git a/Tests/RunCMake/WorkingDirectory/buildAndTestNoBuildDir.cmake b/Tests/RunCMake/WorkingDirectory/buildAndTestNoBuildDir.cmake new file mode 100644 index 0000000..ad795c4 --- /dev/null +++ b/Tests/RunCMake/WorkingDirectory/buildAndTestNoBuildDir.cmake @@ -0,0 +1,7 @@ +# We want a single test that always passes. We should never actually get to +# configure with this file, so we use a successful configure-build-test +# sequence to denote failure of the test case. +include(CTest) +add_test(NAME willPass + COMMAND ${CMAKE_COMMAND} -E touch someFile.txt +) diff --git a/Tests/RunCMake/WorkingDirectory/dirNotExist-result.txt b/Tests/RunCMake/WorkingDirectory/dirNotExist-result.txt new file mode 100644 index 0000000..b57e2de --- /dev/null +++ b/Tests/RunCMake/WorkingDirectory/dirNotExist-result.txt @@ -0,0 +1 @@ +(-1|255) diff --git a/Tests/RunCMake/WorkingDirectory/dirNotExist-stderr.txt b/Tests/RunCMake/WorkingDirectory/dirNotExist-stderr.txt new file mode 100644 index 0000000..3cea890 --- /dev/null +++ b/Tests/RunCMake/WorkingDirectory/dirNotExist-stderr.txt @@ -0,0 +1 @@ +Failed to change working directory to .*[/\\]dirNotExist-build[/\\]thisDirWillNotExist : diff --git a/Tests/RunCMake/WorkingDirectory/dirNotExist-stdout.txt b/Tests/RunCMake/WorkingDirectory/dirNotExist-stdout.txt new file mode 100644 index 0000000..58aa6e4 --- /dev/null +++ b/Tests/RunCMake/WorkingDirectory/dirNotExist-stdout.txt @@ -0,0 +1,10 @@ +Test project .*/Tests/RunCMake/WorkingDirectory/dirNotExist-build +.* +Start 1: dirNotExist +1/1 Test #1: dirNotExist +\.+\*\*\*Not Run +[0-9.]+ sec ++ +0% tests passed, 1 tests failed out of 1 ++ +Total Test time \(real\) = +[0-9.]+ sec ++ +The following tests FAILED: +.* +1 - dirNotExist \(Not Run\)$ diff --git a/Tests/RunCMake/WorkingDirectory/dirNotExist.cmake b/Tests/RunCMake/WorkingDirectory/dirNotExist.cmake new file mode 100644 index 0000000..642386e --- /dev/null +++ b/Tests/RunCMake/WorkingDirectory/dirNotExist.cmake @@ -0,0 +1,6 @@ +include(CTest) + +add_test(NAME dirNotExist + COMMAND ${CMAKE_COMMAND} -E touch someFile.txt + WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/thisDirWillNotExist +) diff --git a/Tests/RunCMake/WorkingDirectory/test.cmake.in b/Tests/RunCMake/WorkingDirectory/test.cmake.in new file mode 100644 index 0000000..8eccd79 --- /dev/null +++ b/Tests/RunCMake/WorkingDirectory/test.cmake.in @@ -0,0 +1,15 @@ +cmake_minimum_required(VERSION 3.11) + +set(CTEST_SITE "test-site") +set(CTEST_BUILD_NAME "test-build-name") +set(CTEST_SOURCE_DIRECTORY "@RunCMake_BINARY_DIR@/@CASE_NAME@") +set(CTEST_BINARY_DIRECTORY "@RunCMake_BINARY_DIR@/@CASE_NAME@-build") +set(CTEST_CMAKE_GENERATOR "@RunCMake_GENERATOR@") +set(CTEST_CMAKE_GENERATOR_PLATFORM "@RunCMake_GENERATOR_PLATFORM@") +set(CTEST_CMAKE_GENERATOR_TOOLSET "@RunCMake_GENERATOR_TOOLSET@") +set(CTEST_BUILD_CONFIGURATION "$ENV{CMAKE_CONFIG_TYPE}") + +ctest_start(Experimental) +ctest_configure() +ctest_build() +ctest_test() diff --git a/Tests/RunCMake/WriteCompilerDetectionHeader/InvalidFeature-stderr.txt b/Tests/RunCMake/WriteCompilerDetectionHeader/InvalidFeature-stderr.txt index 0445744..f444992 100644 --- a/Tests/RunCMake/WriteCompilerDetectionHeader/InvalidFeature-stderr.txt +++ b/Tests/RunCMake/WriteCompilerDetectionHeader/InvalidFeature-stderr.txt @@ -1,5 +1,6 @@ CMake Error at .*Modules/WriteCompilerDetectionHeader.cmake:[0-9]+ \(message\): Unsupported feature not_a_feature. Call Stack \(most recent call first\): + .*Modules/WriteCompilerDetectionHeader.cmake:[0-9]+ \(_check_feature_lists\) InvalidFeature.cmake:4 \(write_compiler_detection_header\) CMakeLists.txt:3 \(include\) diff --git a/Tests/RunCMake/add_custom_command/AssigningMultipleTargets.cmake b/Tests/RunCMake/add_custom_command/AssigningMultipleTargets.cmake new file mode 100644 index 0000000..fe1cceb --- /dev/null +++ b/Tests/RunCMake/add_custom_command/AssigningMultipleTargets.cmake @@ -0,0 +1,13 @@ +enable_language(CXX) + +add_custom_command(OUTPUT generated.cpp + MAIN_DEPENDENCY a.c + COMMAND ${CMAKE_COMMAND} -P ${CMAKE_CURRENT_SOURCE_DIR}/generate-once.cmake ${CMAKE_CURRENT_BINARY_DIR}/generated.cpp + VERBATIM) + +add_executable(exe1 ${CMAKE_CURRENT_BINARY_DIR}/generated.cpp) +add_executable(exe2 ${CMAKE_CURRENT_BINARY_DIR}/generated.cpp) +add_executable(exe3 ${CMAKE_CURRENT_BINARY_DIR}/generated.cpp) + +add_dependencies(exe1 exe2) +add_dependencies(exe3 exe1) diff --git a/Tests/RunCMake/add_custom_command/RunCMakeTest.cmake b/Tests/RunCMake/add_custom_command/RunCMakeTest.cmake index c12e5aa..0387dbb 100644 --- a/Tests/RunCMake/add_custom_command/RunCMakeTest.cmake +++ b/Tests/RunCMake/add_custom_command/RunCMakeTest.cmake @@ -14,3 +14,10 @@ run_cmake(TargetNotInDir) if(${RunCMake_GENERATOR} MATCHES "Visual Studio ([^89]|[89][0-9])") run_cmake(RemoveEmptyCommands) endif() + +run_cmake(AssigningMultipleTargets) +set(RunCMake_TEST_BINARY_DIR ${RunCMake_BINARY_DIR}/AssigningMultipleTargets-build) +set(RunCMake_TEST_NO_CLEAN 1) +run_cmake_command(AssigningMultipleTargets-build ${CMAKE_COMMAND} --build .) +unset(RunCMake_TEST_BINARY_DIR) +unset(RunCMake_TEST_NO_CLEAN) diff --git a/Tests/RunCMake/add_custom_command/a.c b/Tests/RunCMake/add_custom_command/a.c new file mode 100644 index 0000000..707c1c3 --- /dev/null +++ b/Tests/RunCMake/add_custom_command/a.c @@ -0,0 +1,3 @@ +void a() +{ +} diff --git a/Tests/RunCMake/add_custom_command/generate-once.cmake b/Tests/RunCMake/add_custom_command/generate-once.cmake new file mode 100644 index 0000000..2a8e843 --- /dev/null +++ b/Tests/RunCMake/add_custom_command/generate-once.cmake @@ -0,0 +1,8 @@ +if (${CMAKE_ARGC} LESS 4) + message(FATAL_ERROR "Too few arguments") +endif() +set(output "${CMAKE_ARGV3}") +if(EXISTS ${output}) + message(FATAL_ERROR "${output} already exists") +endif() +file(WRITE ${output} "int main() { return 0; }\n") diff --git a/Tests/RunCMake/add_library/CMP0073-stdout.txt b/Tests/RunCMake/add_library/CMP0073-stdout.txt new file mode 100644 index 0000000..84645b8 --- /dev/null +++ b/Tests/RunCMake/add_library/CMP0073-stdout.txt @@ -0,0 +1,3 @@ +-- warn_LIB_DEPENDS='general;bar;' +-- old_LIB_DEPENDS='general;bar;' +-- new_LIB_DEPENDS='' diff --git a/Tests/RunCMake/add_library/CMP0073.cmake b/Tests/RunCMake/add_library/CMP0073.cmake new file mode 100644 index 0000000..b34f5dc --- /dev/null +++ b/Tests/RunCMake/add_library/CMP0073.cmake @@ -0,0 +1,18 @@ +enable_language(C) + +add_library(warn empty.c) +target_link_libraries(warn bar) +message(STATUS "warn_LIB_DEPENDS='${warn_LIB_DEPENDS}'") + +cmake_policy(SET CMP0073 OLD) +add_library(old empty.c) +target_link_libraries(old bar) +message(STATUS "old_LIB_DEPENDS='${old_LIB_DEPENDS}'") + +cmake_policy(SET CMP0073 NEW) +add_library(new empty.c) +target_link_libraries(new bar) +message(STATUS "new_LIB_DEPENDS='${new_LIB_DEPENDS}'") +if(DEFINED new_LIB_DEPENDS) + message(FATAL_ERROR "new_LIB_DEPENDS set but should not be") +endif() diff --git a/Tests/RunCMake/add_library/OBJECTwithNoSourcesButLinkObjects-stderr.txt b/Tests/RunCMake/add_library/OBJECTwithNoSourcesButLinkObjects-stderr.txt index cd6f1e0..1bcc114 100644 --- a/Tests/RunCMake/add_library/OBJECTwithNoSourcesButLinkObjects-stderr.txt +++ b/Tests/RunCMake/add_library/OBJECTwithNoSourcesButLinkObjects-stderr.txt @@ -1,5 +1,4 @@ -^CMake Error at OBJECTwithNoSourcesButLinkObjects.cmake:[0-9]+ \(target_link_libraries\): - Object library target \"TestObjectLibWithoutSources\" may not link to - anything. +^CMake Error at OBJECTwithNoSourcesButLinkObjects.cmake:[0-9]+ \(add_library\): + No SOURCES given to target: TestObjectLibWithoutSources Call Stack \(most recent call first\): CMakeLists.txt:[0-9]+ \(include\)$ diff --git a/Tests/RunCMake/add_library/OBJECTwithOnlyObjectSources-stderr.txt b/Tests/RunCMake/add_library/OBJECTwithOnlyObjectSources-stderr.txt deleted file mode 100644 index 77a72f1..0000000 --- a/Tests/RunCMake/add_library/OBJECTwithOnlyObjectSources-stderr.txt +++ /dev/null @@ -1,16 +0,0 @@ -^CMake Error at OBJECTwithOnlyObjectSources.cmake:[0-9]+ \(add_library\): - OBJECT library \"TestObjectLibWithoutSources\" contains: - - [^ -]*test(\.cpp)?\.o(bj)? - - but may contain only sources that compile, header files, and other files - that would not affect linking of a normal library. -Call Stack \(most recent call first\): - CMakeLists.txt:[0-9]+ \(include\) - - -CMake Error at OBJECTwithOnlyObjectSources.cmake:[0-9]+ \(add_library\): - Only executables and non-OBJECT libraries may reference target objects. -Call Stack \(most recent call first\): - CMakeLists.txt:[0-9]+ \(include\)$ diff --git a/Tests/RunCMake/add_library/RunCMakeTest.cmake b/Tests/RunCMake/add_library/RunCMakeTest.cmake index 0ba6216..dfadb8f 100644 --- a/Tests/RunCMake/add_library/RunCMakeTest.cmake +++ b/Tests/RunCMake/add_library/RunCMakeTest.cmake @@ -1,5 +1,7 @@ include(RunCMake) +run_cmake(CMP0073) + run_cmake(INTERFACEwithNoSources) run_cmake(OBJECTwithNoSources) run_cmake(STATICwithNoSources) diff --git a/Tests/RunCMake/CommandLine/DeprecateVS8-WARN-ON.cmake b/Tests/RunCMake/add_library/empty.c index e69de29..e69de29 100644 --- a/Tests/RunCMake/CommandLine/DeprecateVS8-WARN-ON.cmake +++ b/Tests/RunCMake/add_library/empty.c diff --git a/Tests/RunCMake/cmake_minimum_required/Future.cmake b/Tests/RunCMake/cmake_minimum_required/Future.cmake new file mode 100644 index 0000000..2b5c445 --- /dev/null +++ b/Tests/RunCMake/cmake_minimum_required/Future.cmake @@ -0,0 +1 @@ +cmake_minimum_required(VERSION 3.11...99.0 SOME_FUTURE_OPTION) diff --git a/Tests/RunCMake/cmake_minimum_required/Range-stderr.txt b/Tests/RunCMake/cmake_minimum_required/Range-stderr.txt new file mode 100644 index 0000000..7d2bdae --- /dev/null +++ b/Tests/RunCMake/cmake_minimum_required/Range-stderr.txt @@ -0,0 +1,4 @@ +^CMAKE_MINIMUM_REQUIRED_VERSION='3\.10' +CMP0071='NEW' +CMP0072='NEW' +CMP0073=''$ diff --git a/Tests/RunCMake/cmake_minimum_required/Range.cmake b/Tests/RunCMake/cmake_minimum_required/Range.cmake new file mode 100644 index 0000000..0080092 --- /dev/null +++ b/Tests/RunCMake/cmake_minimum_required/Range.cmake @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.10...3.11) +message("CMAKE_MINIMUM_REQUIRED_VERSION='${CMAKE_MINIMUM_REQUIRED_VERSION}'") +foreach(policy CMP0071 CMP0072 CMP0073) + cmake_policy(GET ${policy} status) + message("${policy}='${status}'") +endforeach() diff --git a/Tests/RunCMake/cmake_minimum_required/RangeBad-result.txt b/Tests/RunCMake/cmake_minimum_required/RangeBad-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/cmake_minimum_required/RangeBad-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/cmake_minimum_required/RangeBad-stderr.txt b/Tests/RunCMake/cmake_minimum_required/RangeBad-stderr.txt new file mode 100644 index 0000000..b2c62fb --- /dev/null +++ b/Tests/RunCMake/cmake_minimum_required/RangeBad-stderr.txt @@ -0,0 +1,56 @@ +^CMake Error at RangeBad.cmake:1 \(cmake_minimum_required\): + cmake_minimum_required VERSION "3.11..." does not have a version on both + sides of "...". +Call Stack \(most recent call first\): + CMakeLists.txt:3 \(include\) ++ +CMake Error at RangeBad.cmake:2 \(cmake_minimum_required\): + cmake_minimum_required VERSION "...3.11" does not have a version on both + sides of "...". +Call Stack \(most recent call first\): + CMakeLists.txt:3 \(include\) ++ +CMake Error at RangeBad.cmake:3 \(cmake_minimum_required\): + cmake_minimum_required VERSION "..." does not have a version on both sides + of "...". +Call Stack \(most recent call first\): + CMakeLists.txt:3 \(include\) ++ +CMake Error at RangeBad.cmake:4 \(cmake_minimum_required\): + Invalid policy max version value "4". A numeric + major.minor\[.patch\[.tweak\]\] must be given. +Call Stack \(most recent call first\): + CMakeLists.txt:3 \(include\) ++ +CMake Error at RangeBad.cmake:5 \(cmake_minimum_required\): + Policy VERSION range "3.11...3.10" specifies a larger minimum than maximum. +Call Stack \(most recent call first\): + CMakeLists.txt:3 \(include\) ++ +CMake Error at RangeBad.cmake:6 \(cmake_policy\): + cmake_policy VERSION "3.11..." does not have a version on both sides of + "...". +Call Stack \(most recent call first\): + CMakeLists.txt:3 \(include\) ++ +CMake Error at RangeBad.cmake:7 \(cmake_policy\): + cmake_policy VERSION "...3.11" does not have a version on both sides of + "...". +Call Stack \(most recent call first\): + CMakeLists.txt:3 \(include\) ++ +CMake Error at RangeBad.cmake:8 \(cmake_policy\): + cmake_policy VERSION "..." does not have a version on both sides of "...". +Call Stack \(most recent call first\): + CMakeLists.txt:3 \(include\) ++ +CMake Error at RangeBad.cmake:9 \(cmake_policy\): + Invalid policy max version value "4". A numeric + major.minor\[.patch\[.tweak\]\] must be given. +Call Stack \(most recent call first\): + CMakeLists.txt:3 \(include\) ++ +CMake Error at RangeBad.cmake:10 \(cmake_policy\): + Policy VERSION range "3.11...3.10" specifies a larger minimum than maximum. +Call Stack \(most recent call first\): + CMakeLists.txt:3 \(include\)$ diff --git a/Tests/RunCMake/cmake_minimum_required/RangeBad.cmake b/Tests/RunCMake/cmake_minimum_required/RangeBad.cmake new file mode 100644 index 0000000..2a2dade --- /dev/null +++ b/Tests/RunCMake/cmake_minimum_required/RangeBad.cmake @@ -0,0 +1,10 @@ +cmake_minimum_required(VERSION 3.11...) +cmake_minimum_required(VERSION ...3.11) +cmake_minimum_required(VERSION ...) +cmake_minimum_required(VERSION 3.11...4) +cmake_minimum_required(VERSION 3.11...3.10) +cmake_policy(VERSION 3.11...) +cmake_policy(VERSION ...3.11) +cmake_policy(VERSION ...) +cmake_policy(VERSION 3.11...4) +cmake_policy(VERSION 3.11...3.10) diff --git a/Tests/RunCMake/cmake_minimum_required/RunCMakeTest.cmake b/Tests/RunCMake/cmake_minimum_required/RunCMakeTest.cmake index e4c65e3..1030211 100644 --- a/Tests/RunCMake/cmake_minimum_required/RunCMakeTest.cmake +++ b/Tests/RunCMake/cmake_minimum_required/RunCMakeTest.cmake @@ -2,4 +2,8 @@ include(RunCMake) run_cmake(Before24) run_cmake(CompatBefore24) +run_cmake(Future) run_cmake(PolicyBefore24) +run_cmake(Range) +run_cmake(RangeBad) +run_cmake(Unknown) diff --git a/Tests/RunCMake/cmake_minimum_required/Unknown-result.txt b/Tests/RunCMake/cmake_minimum_required/Unknown-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/cmake_minimum_required/Unknown-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/cmake_minimum_required/Unknown-stderr.txt b/Tests/RunCMake/cmake_minimum_required/Unknown-stderr.txt new file mode 100644 index 0000000..d698642 --- /dev/null +++ b/Tests/RunCMake/cmake_minimum_required/Unknown-stderr.txt @@ -0,0 +1,4 @@ +^CMake Error at Unknown.cmake:1 \(cmake_minimum_required\): + cmake_minimum_required called with unknown argument "SOME_UNKNOWN_OPTION". +Call Stack \(most recent call first\): + CMakeLists.txt:[0-9]+ \(include\)$ diff --git a/Tests/RunCMake/cmake_minimum_required/Unknown.cmake b/Tests/RunCMake/cmake_minimum_required/Unknown.cmake new file mode 100644 index 0000000..6c70f91 --- /dev/null +++ b/Tests/RunCMake/cmake_minimum_required/Unknown.cmake @@ -0,0 +1 @@ +cmake_minimum_required(VERSION 3.11 SOME_UNKNOWN_OPTION) diff --git a/Tests/RunCMake/export/ForbiddenToExportImportedProperties-result.txt b/Tests/RunCMake/export/ForbiddenToExportImportedProperties-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/export/ForbiddenToExportImportedProperties-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/export/ForbiddenToExportImportedProperties-stderr.txt b/Tests/RunCMake/export/ForbiddenToExportImportedProperties-stderr.txt new file mode 100644 index 0000000..ab03943 --- /dev/null +++ b/Tests/RunCMake/export/ForbiddenToExportImportedProperties-stderr.txt @@ -0,0 +1,3 @@ +CMake Error in CMakeLists.txt: + Target \"foo\" contains property \"IMPORTED_FOOBAR\" in EXPORT_PROPERTIES but + IMPORTED_\* and INTERFACE_\* properties are reserved. diff --git a/Tests/RunCMake/export/ForbiddenToExportImportedProperties.cmake b/Tests/RunCMake/export/ForbiddenToExportImportedProperties.cmake new file mode 100644 index 0000000..9c8653d --- /dev/null +++ b/Tests/RunCMake/export/ForbiddenToExportImportedProperties.cmake @@ -0,0 +1,12 @@ +enable_language(CXX) +add_library(foo empty.cpp) +set_target_properties(foo PROPERTIES + IMPORTED_FOOBAR "Some other string" + EXPORT_PROPERTIES "IMPORTED_FOOBAR" +) +export(TARGETS foo FILE "${CMAKE_CURRENT_BINARY_DIR}/foo.cmake") +install(TARGETS foo EXPORT fooExport + RUNTIME DESTINATION bin + LIBRARY DESTINATION lib + ARCHIVE DESTINATION lib +) diff --git a/Tests/RunCMake/export/ForbiddenToExportInterfaceProperties-result.txt b/Tests/RunCMake/export/ForbiddenToExportInterfaceProperties-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/export/ForbiddenToExportInterfaceProperties-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/export/ForbiddenToExportInterfaceProperties-stderr.txt b/Tests/RunCMake/export/ForbiddenToExportInterfaceProperties-stderr.txt new file mode 100644 index 0000000..577602b --- /dev/null +++ b/Tests/RunCMake/export/ForbiddenToExportInterfaceProperties-stderr.txt @@ -0,0 +1,3 @@ +CMake Error in CMakeLists.txt: + Target \"foo\" contains property \"INTERFACE_FOOBAR\" in EXPORT_PROPERTIES but + IMPORTED_\* and INTERFACE_\* properties are reserved. diff --git a/Tests/RunCMake/export/ForbiddenToExportInterfaceProperties.cmake b/Tests/RunCMake/export/ForbiddenToExportInterfaceProperties.cmake new file mode 100644 index 0000000..bab8de0 --- /dev/null +++ b/Tests/RunCMake/export/ForbiddenToExportInterfaceProperties.cmake @@ -0,0 +1,12 @@ +enable_language(CXX) +add_library(foo empty.cpp) +set_target_properties(foo PROPERTIES + INTERFACE_FOOBAR "Some string" + EXPORT_PROPERTIES "INTERFACE_FOOBAR" +) +export(TARGETS foo FILE "${CMAKE_CURRENT_BINARY_DIR}/foo.cmake") +install(TARGETS foo EXPORT fooExport + RUNTIME DESTINATION bin + LIBRARY DESTINATION lib + ARCHIVE DESTINATION lib +) diff --git a/Tests/RunCMake/export/ForbiddenToExportPropertyWithGenExp-result.txt b/Tests/RunCMake/export/ForbiddenToExportPropertyWithGenExp-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/export/ForbiddenToExportPropertyWithGenExp-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/export/ForbiddenToExportPropertyWithGenExp-stderr.txt b/Tests/RunCMake/export/ForbiddenToExportPropertyWithGenExp-stderr.txt new file mode 100644 index 0000000..56488e6 --- /dev/null +++ b/Tests/RunCMake/export/ForbiddenToExportPropertyWithGenExp-stderr.txt @@ -0,0 +1,3 @@ +CMake Error in CMakeLists.txt: + Target \"foo\" contains property \"JUST_A_PROPERTY\" in EXPORT_PROPERTIES but + this property contains a generator expression. This is not allowed. diff --git a/Tests/RunCMake/export/ForbiddenToExportPropertyWithGenExp.cmake b/Tests/RunCMake/export/ForbiddenToExportPropertyWithGenExp.cmake new file mode 100644 index 0000000..065cdbc --- /dev/null +++ b/Tests/RunCMake/export/ForbiddenToExportPropertyWithGenExp.cmake @@ -0,0 +1,12 @@ +enable_language(CXX) +add_library(foo empty.cpp) +set_target_properties(foo PROPERTIES + JUST_A_PROPERTY "$<C_COMPILER_VERSION:0>" + EXPORT_PROPERTIES "JUST_A_PROPERTY" +) +export(TARGETS foo FILE "${CMAKE_CURRENT_BINARY_DIR}/foo.cmake") +install(TARGETS foo EXPORT fooExport + RUNTIME DESTINATION bin + LIBRARY DESTINATION lib + ARCHIVE DESTINATION lib +) diff --git a/Tests/RunCMake/export/RunCMakeTest.cmake b/Tests/RunCMake/export/RunCMakeTest.cmake index 6d0b7ca..10ced90 100644 --- a/Tests/RunCMake/export/RunCMakeTest.cmake +++ b/Tests/RunCMake/export/RunCMakeTest.cmake @@ -5,3 +5,6 @@ run_cmake(TargetNotFound) run_cmake(AppendExport) run_cmake(OldIface) run_cmake(NoExportSet) +run_cmake(ForbiddenToExportInterfaceProperties) +run_cmake(ForbiddenToExportImportedProperties) +run_cmake(ForbiddenToExportPropertyWithGenExp) diff --git a/Tests/RunCMake/export/empty.cpp b/Tests/RunCMake/export/empty.cpp new file mode 100644 index 0000000..11ec041 --- /dev/null +++ b/Tests/RunCMake/export/empty.cpp @@ -0,0 +1,7 @@ +#ifdef _WIN32 +__declspec(dllexport) +#endif + int empty() +{ + return 0; +} diff --git a/Tests/RunCMake/file/GLOB-CONFIGURE_DEPENDS-RerunCMake-build-stdout.txt b/Tests/RunCMake/file/GLOB-CONFIGURE_DEPENDS-RerunCMake-build-stdout.txt new file mode 100644 index 0000000..71ab721 --- /dev/null +++ b/Tests/RunCMake/file/GLOB-CONFIGURE_DEPENDS-RerunCMake-build-stdout.txt @@ -0,0 +1 @@ +.*b9fbdd8803c036dbe9f5ea6b74db4b9670c78a72 diff --git a/Tests/RunCMake/file/GLOB-CONFIGURE_DEPENDS-RerunCMake-rebuild_first-stdout.txt b/Tests/RunCMake/file/GLOB-CONFIGURE_DEPENDS-RerunCMake-rebuild_first-stdout.txt new file mode 100644 index 0000000..ff90f9c --- /dev/null +++ b/Tests/RunCMake/file/GLOB-CONFIGURE_DEPENDS-RerunCMake-rebuild_first-stdout.txt @@ -0,0 +1,2 @@ +.*Running CMake on GLOB-CONFIGURE_DEPENDS-RerunCMake +.*6bc141b40c0f851d20fa9a1fe5fbdae94acc5de0 diff --git a/Tests/RunCMake/file/GLOB-CONFIGURE_DEPENDS-RerunCMake-rebuild_second-stdout.txt b/Tests/RunCMake/file/GLOB-CONFIGURE_DEPENDS-RerunCMake-rebuild_second-stdout.txt new file mode 100644 index 0000000..cf2a5af --- /dev/null +++ b/Tests/RunCMake/file/GLOB-CONFIGURE_DEPENDS-RerunCMake-rebuild_second-stdout.txt @@ -0,0 +1,2 @@ +.*Running CMake on GLOB-CONFIGURE_DEPENDS-RerunCMake +.*0c3ceab9daa7914fde7410c34cae4049e140aa51 diff --git a/Tests/RunCMake/file/GLOB-CONFIGURE_DEPENDS-RerunCMake-stdout.txt b/Tests/RunCMake/file/GLOB-CONFIGURE_DEPENDS-RerunCMake-stdout.txt new file mode 100644 index 0000000..66b6c44 --- /dev/null +++ b/Tests/RunCMake/file/GLOB-CONFIGURE_DEPENDS-RerunCMake-stdout.txt @@ -0,0 +1 @@ +.*Running CMake on GLOB-CONFIGURE_DEPENDS-RerunCMake diff --git a/Tests/RunCMake/file/GLOB-CONFIGURE_DEPENDS-RerunCMake.cmake b/Tests/RunCMake/file/GLOB-CONFIGURE_DEPENDS-RerunCMake.cmake new file mode 100644 index 0000000..fe87c78 --- /dev/null +++ b/Tests/RunCMake/file/GLOB-CONFIGURE_DEPENDS-RerunCMake.cmake @@ -0,0 +1,10 @@ +message(STATUS "Running CMake on GLOB-CONFIGURE_DEPENDS-RerunCMake") +file(GLOB_RECURSE + CONTENT_LIST + CONFIGURE_DEPENDS + LIST_DIRECTORIES false + RELATIVE "${CMAKE_CURRENT_BINARY_DIR}" + "${CMAKE_CURRENT_BINARY_DIR}/test/*" + ) +string(SHA1 CONTENT_LIST_HASH "${CONTENT_LIST}") +add_custom_target(CONTENT_ECHO ALL ${CMAKE_COMMAND} -E echo ${CONTENT_LIST_HASH}) diff --git a/Tests/RunCMake/file/GLOB-error-CONFIGURE_DEPENDS-SCRIPT_MODE-result.txt b/Tests/RunCMake/file/GLOB-error-CONFIGURE_DEPENDS-SCRIPT_MODE-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/file/GLOB-error-CONFIGURE_DEPENDS-SCRIPT_MODE-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/file/GLOB-error-CONFIGURE_DEPENDS-SCRIPT_MODE-stderr.txt b/Tests/RunCMake/file/GLOB-error-CONFIGURE_DEPENDS-SCRIPT_MODE-stderr.txt new file mode 100644 index 0000000..40083c1 --- /dev/null +++ b/Tests/RunCMake/file/GLOB-error-CONFIGURE_DEPENDS-SCRIPT_MODE-stderr.txt @@ -0,0 +1 @@ +.*CONFIGURE_DEPENDS is invalid for script and find package modes\. diff --git a/Tests/RunCMake/file/GLOB-error-CONFIGURE_DEPENDS-SCRIPT_MODE.cmake b/Tests/RunCMake/file/GLOB-error-CONFIGURE_DEPENDS-SCRIPT_MODE.cmake new file mode 100644 index 0000000..9dc0f03 --- /dev/null +++ b/Tests/RunCMake/file/GLOB-error-CONFIGURE_DEPENDS-SCRIPT_MODE.cmake @@ -0,0 +1 @@ +file(GLOB CONTENT_LIST CONFIGURE_DEPENDS) diff --git a/Tests/RunCMake/file/GLOB-error-CONFIGURE_DEPENDS-modified-result.txt b/Tests/RunCMake/file/GLOB-error-CONFIGURE_DEPENDS-modified-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/file/GLOB-error-CONFIGURE_DEPENDS-modified-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/file/GLOB-error-CONFIGURE_DEPENDS-modified-stderr.txt b/Tests/RunCMake/file/GLOB-error-CONFIGURE_DEPENDS-modified-stderr.txt new file mode 100644 index 0000000..d7b36eb --- /dev/null +++ b/Tests/RunCMake/file/GLOB-error-CONFIGURE_DEPENDS-modified-stderr.txt @@ -0,0 +1,7 @@ +^CMake Error: The glob expression +.* at GLOB-error-CONFIGURE_DEPENDS-modified\.cmake:[0-9]+ \(file\) +was already present in the glob cache but the directory +contents have changed during the configuration run. +Matching glob expressions: + CONTENT_LIST_1 at GLOB-error-CONFIGURE_DEPENDS-modified\.cmake:[0-9]+ \(file\) + CONTENT_LIST_2 at GLOB-error-CONFIGURE_DEPENDS-modified\.cmake:[0-9]+ \(file\)$ diff --git a/Tests/RunCMake/file/GLOB-error-CONFIGURE_DEPENDS-modified.cmake b/Tests/RunCMake/file/GLOB-error-CONFIGURE_DEPENDS-modified.cmake new file mode 100644 index 0000000..8d74dea --- /dev/null +++ b/Tests/RunCMake/file/GLOB-error-CONFIGURE_DEPENDS-modified.cmake @@ -0,0 +1,21 @@ +file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/test/first") +file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/test/second") +file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/test/third") + +file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/test/first/one" "one") +file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/test/second/two" "two") +file(GLOB_RECURSE CONTENT_LIST_1 + CONFIGURE_DEPENDS + "${CMAKE_CURRENT_BINARY_DIR}/test/*" + ) + +file(GLOB_RECURSE CONTENT_LIST_2 + CONFIGURE_DEPENDS + "${CMAKE_CURRENT_BINARY_DIR}/test/*" + ) + +file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/test/third/three" "three") +file(GLOB_RECURSE CONTENT_LIST_3 + CONFIGURE_DEPENDS + "${CMAKE_CURRENT_BINARY_DIR}/test/*" + ) diff --git a/Tests/RunCMake/file/GLOB-error-FOLLOW_SYMLINKS-result.txt b/Tests/RunCMake/file/GLOB-error-FOLLOW_SYMLINKS-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/file/GLOB-error-FOLLOW_SYMLINKS-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/file/GLOB-error-FOLLOW_SYMLINKS-stderr.txt b/Tests/RunCMake/file/GLOB-error-FOLLOW_SYMLINKS-stderr.txt new file mode 100644 index 0000000..af3cb2e --- /dev/null +++ b/Tests/RunCMake/file/GLOB-error-FOLLOW_SYMLINKS-stderr.txt @@ -0,0 +1,4 @@ +^CMake Error at GLOB-error-FOLLOW_SYMLINKS\.cmake:[0-9]+ \(file\): + file FOLLOW_SYMLINKS is not a valid parameter for GLOB\. +Call Stack \(most recent call first\): + CMakeLists\.txt:[0-9]+ \(include\)$ diff --git a/Tests/RunCMake/file/GLOB-error-FOLLOW_SYMLINKS.cmake b/Tests/RunCMake/file/GLOB-error-FOLLOW_SYMLINKS.cmake new file mode 100644 index 0000000..6d467a0 --- /dev/null +++ b/Tests/RunCMake/file/GLOB-error-FOLLOW_SYMLINKS.cmake @@ -0,0 +1 @@ +file(GLOB CONTENT_LIST FOLLOW_SYMLINKS) diff --git a/Tests/RunCMake/file/GLOB-error-RELATIVE-no-arg-result.txt b/Tests/RunCMake/file/GLOB-error-RELATIVE-no-arg-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/file/GLOB-error-RELATIVE-no-arg-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/file/GLOB-error-RELATIVE-no-arg-stderr.txt b/Tests/RunCMake/file/GLOB-error-RELATIVE-no-arg-stderr.txt new file mode 100644 index 0000000..30cec89 --- /dev/null +++ b/Tests/RunCMake/file/GLOB-error-RELATIVE-no-arg-stderr.txt @@ -0,0 +1,4 @@ +^CMake Error at GLOB-error-RELATIVE-no-arg\.cmake:[0-9]+ \(file\): + file GLOB requires a directory after the RELATIVE tag\. +Call Stack \(most recent call first\): + CMakeLists\.txt:[0-9]+ \(include\)$ diff --git a/Tests/RunCMake/file/GLOB-error-RELATIVE-no-arg.cmake b/Tests/RunCMake/file/GLOB-error-RELATIVE-no-arg.cmake new file mode 100644 index 0000000..a555881 --- /dev/null +++ b/Tests/RunCMake/file/GLOB-error-RELATIVE-no-arg.cmake @@ -0,0 +1 @@ +file(GLOB CONTENT_LIST RELATIVE) diff --git a/Tests/RunCMake/file/GLOB-noexp-CONFIGURE_DEPENDS-result.txt b/Tests/RunCMake/file/GLOB-noexp-CONFIGURE_DEPENDS-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/file/GLOB-noexp-CONFIGURE_DEPENDS-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/file/GLOB-noexp-CONFIGURE_DEPENDS-stderr.txt b/Tests/RunCMake/file/GLOB-noexp-CONFIGURE_DEPENDS-stderr.txt new file mode 100644 index 0000000..01d204f --- /dev/null +++ b/Tests/RunCMake/file/GLOB-noexp-CONFIGURE_DEPENDS-stderr.txt @@ -0,0 +1,4 @@ +^CMake Error at GLOB-noexp-CONFIGURE_DEPENDS\.cmake:[0-9]+ \(file\): + file GLOB requires a glob expression after CONFIGURE_DEPENDS\. +Call Stack \(most recent call first\): + CMakeLists\.txt:[0-9]+ \(include\)$ diff --git a/Tests/RunCMake/file/GLOB-noexp-CONFIGURE_DEPENDS.cmake b/Tests/RunCMake/file/GLOB-noexp-CONFIGURE_DEPENDS.cmake new file mode 100644 index 0000000..9dc0f03 --- /dev/null +++ b/Tests/RunCMake/file/GLOB-noexp-CONFIGURE_DEPENDS.cmake @@ -0,0 +1 @@ +file(GLOB CONTENT_LIST CONFIGURE_DEPENDS) diff --git a/Tests/RunCMake/file/GLOB-noexp-LIST_DIRECTORIES-result.txt b/Tests/RunCMake/file/GLOB-noexp-LIST_DIRECTORIES-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/file/GLOB-noexp-LIST_DIRECTORIES-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/file/GLOB-noexp-LIST_DIRECTORIES-stderr.txt b/Tests/RunCMake/file/GLOB-noexp-LIST_DIRECTORIES-stderr.txt new file mode 100644 index 0000000..ee6cb0b --- /dev/null +++ b/Tests/RunCMake/file/GLOB-noexp-LIST_DIRECTORIES-stderr.txt @@ -0,0 +1,4 @@ +^CMake Error at GLOB-noexp-LIST_DIRECTORIES\.cmake:[0-9]+ \(file\): + file GLOB requires a glob expression after the bool\. +Call Stack \(most recent call first\): + CMakeLists\.txt:[0-9]+ \(include\)$ diff --git a/Tests/RunCMake/file/GLOB-noexp-RELATIVE-result.txt b/Tests/RunCMake/file/GLOB-noexp-RELATIVE-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/file/GLOB-noexp-RELATIVE-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/file/GLOB-noexp-RELATIVE-stderr.txt b/Tests/RunCMake/file/GLOB-noexp-RELATIVE-stderr.txt new file mode 100644 index 0000000..9c66631 --- /dev/null +++ b/Tests/RunCMake/file/GLOB-noexp-RELATIVE-stderr.txt @@ -0,0 +1,4 @@ +^CMake Error at GLOB-noexp-RELATIVE\.cmake:[0-9]+ \(file\): + file GLOB requires a glob expression after the directory\. +Call Stack \(most recent call first\): + CMakeLists\.txt:[0-9]+ \(include\)$ diff --git a/Tests/RunCMake/file/GLOB-noexp-RELATIVE.cmake b/Tests/RunCMake/file/GLOB-noexp-RELATIVE.cmake new file mode 100644 index 0000000..7b2d404 --- /dev/null +++ b/Tests/RunCMake/file/GLOB-noexp-RELATIVE.cmake @@ -0,0 +1 @@ +file(GLOB CONTENT_LIST RELATIVE "${CMAKE_CURRENT_BINARY_DIR}") diff --git a/Tests/RunCMake/file/GLOB-sort-dedup-stderr.txt b/Tests/RunCMake/file/GLOB-sort-dedup-stderr.txt new file mode 100644 index 0000000..d2565e4 --- /dev/null +++ b/Tests/RunCMake/file/GLOB-sort-dedup-stderr.txt @@ -0,0 +1,2 @@ +content: 7[ ] +1aAb/\.hide;1aAb/1\.log;1aAb/1\.txt;1aAb/xkcd\.txt;a/1\.log;a/1\.txt;a/boot\.ini diff --git a/Tests/RunCMake/file/GLOB-sort-dedup.cmake b/Tests/RunCMake/file/GLOB-sort-dedup.cmake new file mode 100644 index 0000000..1e1c579 --- /dev/null +++ b/Tests/RunCMake/file/GLOB-sort-dedup.cmake @@ -0,0 +1,21 @@ +file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/test/a") +file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/test/1aAb") + +file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/test/a/1.log" "") +file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/test/a/1.txt" "") +file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/test/a/boot.ini" "") + +file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/test/1aAb/.hide" "") +file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/test/1aAb/1.txt" "") +file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/test/1aAb/1.log" "") +file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/test/1aAb/xkcd.txt" "") + +file(GLOB CONTENT_LIST + LIST_DIRECTORIES false + RELATIVE "${CMAKE_CURRENT_BINARY_DIR}/test" + "${CMAKE_CURRENT_BINARY_DIR}/test/a/*" + "${CMAKE_CURRENT_BINARY_DIR}/test/*/*" + ) +list(LENGTH CONTENT_LIST CONTENT_COUNT) +message("content: ${CONTENT_COUNT} ") +message("${CONTENT_LIST}") diff --git a/Tests/RunCMake/file/GLOB-warn-CONFIGURE_DEPENDS-late-stderr.txt b/Tests/RunCMake/file/GLOB-warn-CONFIGURE_DEPENDS-late-stderr.txt new file mode 100644 index 0000000..af722a4 --- /dev/null +++ b/Tests/RunCMake/file/GLOB-warn-CONFIGURE_DEPENDS-late-stderr.txt @@ -0,0 +1,6 @@ +^CMake Warning \(dev\) at GLOB-warn-CONFIGURE_DEPENDS-late\.cmake:[0-9]+ \(file\): + CONFIGURE_DEPENDS flag was given after a glob expression was already + evaluated\. +Call Stack \(most recent call first\): + CMakeLists\.txt:[0-9]+ \(include\) +This warning is for project developers\. Use -Wno-dev to suppress it\.$ diff --git a/Tests/RunCMake/file/GLOB-warn-CONFIGURE_DEPENDS-late.cmake b/Tests/RunCMake/file/GLOB-warn-CONFIGURE_DEPENDS-late.cmake new file mode 100644 index 0000000..0b69552 --- /dev/null +++ b/Tests/RunCMake/file/GLOB-warn-CONFIGURE_DEPENDS-late.cmake @@ -0,0 +1,11 @@ +file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/test/first") +file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/test/second") + +file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/test/first/one" "Hi, Mom!") +file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/test/second/two" "Love you!") + +file(GLOB CONTENT_LIST + "${CMAKE_CURRENT_BINARY_DIR}/test/first/*" + CONFIGURE_DEPENDS + "${CMAKE_CURRENT_BINARY_DIR}/test/second/*" + ) diff --git a/Tests/RunCMake/file/GLOB_RECURSE-noexp-FOLLOW_SYMLINKS-result.txt b/Tests/RunCMake/file/GLOB_RECURSE-noexp-FOLLOW_SYMLINKS-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/file/GLOB_RECURSE-noexp-FOLLOW_SYMLINKS-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/file/GLOB_RECURSE-noexp-FOLLOW_SYMLINKS-stderr.txt b/Tests/RunCMake/file/GLOB_RECURSE-noexp-FOLLOW_SYMLINKS-stderr.txt new file mode 100644 index 0000000..d0b2bff --- /dev/null +++ b/Tests/RunCMake/file/GLOB_RECURSE-noexp-FOLLOW_SYMLINKS-stderr.txt @@ -0,0 +1,4 @@ +^CMake Error at GLOB_RECURSE-noexp-FOLLOW_SYMLINKS\.cmake:[0-9]+ \(file\): + file GLOB_RECURSE requires a glob expression after FOLLOW_SYMLINKS\. +Call Stack \(most recent call first\): + CMakeLists\.txt:[0-9]+ \(include\)$ diff --git a/Tests/RunCMake/file/GLOB_RECURSE-noexp-FOLLOW_SYMLINKS.cmake b/Tests/RunCMake/file/GLOB_RECURSE-noexp-FOLLOW_SYMLINKS.cmake new file mode 100644 index 0000000..5e5ce92 --- /dev/null +++ b/Tests/RunCMake/file/GLOB_RECURSE-noexp-FOLLOW_SYMLINKS.cmake @@ -0,0 +1 @@ +file(GLOB_RECURSE CONTENT_LIST FOLLOW_SYMLINKS) diff --git a/Tests/RunCMake/file/GLOB_RECURSE-warn-CONFIGURE_DEPENDS-ninja-version-stderr.txt b/Tests/RunCMake/file/GLOB_RECURSE-warn-CONFIGURE_DEPENDS-ninja-version-stderr.txt new file mode 100644 index 0000000..8d22332 --- /dev/null +++ b/Tests/RunCMake/file/GLOB_RECURSE-warn-CONFIGURE_DEPENDS-ninja-version-stderr.txt @@ -0,0 +1,13 @@ +^CMake Warning \(dev\): + The detected version of Ninja: + + .* + + is less than the version of Ninja required by CMake for adding restat + dependencies to the build\.ninja manifest regeneration target: + + 1\.8 + + Any pre-check scripts, such as those generated for file\(GLOB + CONFIGURE_DEPENDS\), will not be run by Ninja\. +This warning is for project developers\. Use -Wno-dev to suppress it\.$ diff --git a/Tests/RunCMake/file/GLOB_RECURSE-warn-CONFIGURE_DEPENDS-ninja-version.cmake b/Tests/RunCMake/file/GLOB_RECURSE-warn-CONFIGURE_DEPENDS-ninja-version.cmake new file mode 100644 index 0000000..8e80895 --- /dev/null +++ b/Tests/RunCMake/file/GLOB_RECURSE-warn-CONFIGURE_DEPENDS-ninja-version.cmake @@ -0,0 +1,6 @@ +file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/test/first") +file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/test/first/one" "one") +file(GLOB_RECURSE CONTENT_LIST + CONFIGURE_DEPENDS + "${CMAKE_CURRENT_BINARY_DIR}/test/*" + ) diff --git a/Tests/RunCMake/file/RunCMakeTest.cmake b/Tests/RunCMake/file/RunCMakeTest.cmake index 3be4fb7..342606b 100644 --- a/Tests/RunCMake/file/RunCMakeTest.cmake +++ b/Tests/RunCMake/file/RunCMakeTest.cmake @@ -5,6 +5,9 @@ run_cmake(DOWNLOAD-unused-argument) run_cmake(DOWNLOAD-httpheader-not-set) run_cmake(DOWNLOAD-netrc-bad) run_cmake(DOWNLOAD-pass-not-set) +run_cmake(TOUCH) +run_cmake(TOUCH-error-in-source-directory) +run_cmake(TOUCH-error-missing-directory) run_cmake(UPLOAD-unused-argument) run_cmake(UPLOAD-httpheader-not-set) run_cmake(UPLOAD-netrc-bad) @@ -32,13 +35,87 @@ run_cmake(LOCK-lowercase) run_cmake(READ_ELF) run_cmake(GLOB) run_cmake(GLOB_RECURSE) -# test is valid both for GLOB and GLOB_RECURSE +run_cmake(GLOB_RECURSE-noexp-FOLLOW_SYMLINKS) + +# tests are valid both for GLOB and GLOB_RECURSE +run_cmake(GLOB-sort-dedup) +run_cmake(GLOB-error-FOLLOW_SYMLINKS) run_cmake(GLOB-error-LIST_DIRECTORIES-not-boolean) -# test is valid both for GLOB and GLOB_RECURSE run_cmake(GLOB-error-LIST_DIRECTORIES-no-arg) +run_cmake(GLOB-error-RELATIVE-no-arg) +run_cmake(GLOB-error-CONFIGURE_DEPENDS-modified) +run_cmake(GLOB-noexp-CONFIGURE_DEPENDS) run_cmake(GLOB-noexp-LIST_DIRECTORIES) +run_cmake(GLOB-noexp-RELATIVE) +run_cmake_command(GLOB-error-CONFIGURE_DEPENDS-SCRIPT_MODE ${CMAKE_COMMAND} -P + ${RunCMake_SOURCE_DIR}/GLOB-error-CONFIGURE_DEPENDS-SCRIPT_MODE.cmake) if(NOT WIN32 OR CYGWIN) run_cmake(GLOB_RECURSE-cyclic-recursion) run_cmake(INSTALL-SYMLINK) endif() + +if(RunCMake_GENERATOR STREQUAL "Ninja") + # Detect ninja version so we know what tests can be supported. + execute_process( + COMMAND "${RunCMake_MAKE_PROGRAM}" --version + OUTPUT_VARIABLE ninja_out + ERROR_VARIABLE ninja_out + RESULT_VARIABLE ninja_res + OUTPUT_STRIP_TRAILING_WHITESPACE + ) + if(ninja_res EQUAL 0 AND "x${ninja_out}" MATCHES "^x[0-9]+\\.[0-9]+") + set(ninja_version "${ninja_out}") + message(STATUS "ninja version: ${ninja_version}") + else() + message(FATAL_ERROR "'ninja --version' reported:\n${ninja_out}") + endif() + + if("${ninja_version}" VERSION_LESS 1.8) + message(STATUS "Ninja is too old for GLOB CONFIGURE_DEPENDS; expect a warning.") + endif() +endif() + +if(RunCMake_GENERATOR STREQUAL "Ninja" AND "${ninja_version}" VERSION_LESS 1.8) + run_cmake(GLOB_RECURSE-warn-CONFIGURE_DEPENDS-ninja-version) +else() + run_cmake(GLOB-warn-CONFIGURE_DEPENDS-late) + + # Use a single build tree for a few tests without cleaning. + set(RunCMake_TEST_BINARY_DIR ${RunCMake_BINARY_DIR}/GLOB-CONFIGURE_DEPENDS-RerunCMake-build) + set(RunCMake_TEST_NO_CLEAN 1) + set(RunCMake_DEFAULT_stderr ".*") + if(RunCMake_GENERATOR STREQUAL "Borland Makefiles" OR + RunCMake_GENERATOR STREQUAL "Watcom WMake") + set(fs_delay 3) + else() + set(fs_delay 1.125) + endif() + + file(REMOVE_RECURSE "${RunCMake_TEST_BINARY_DIR}") + file(MAKE_DIRECTORY "${RunCMake_TEST_BINARY_DIR}/test") + set(tf_1 "${RunCMake_TEST_BINARY_DIR}/test/1.txt") + file(WRITE "${tf_1}" "1") + + message(STATUS "GLOB-RerunCMake: first configuration...") + run_cmake(GLOB-CONFIGURE_DEPENDS-RerunCMake) + run_cmake_command(GLOB-CONFIGURE_DEPENDS-RerunCMake-build ${CMAKE_COMMAND} --build .) + + execute_process(COMMAND ${CMAKE_COMMAND} -E sleep ${fs_delay}) + message(STATUS "GLOB-CONFIGURE_DEPENDS-RerunCMake: add another file...") + file(MAKE_DIRECTORY "${RunCMake_TEST_BINARY_DIR}/test/sub") + set(tf_2 "${RunCMake_TEST_BINARY_DIR}/test/sub/2.txt") + file(WRITE "${tf_2}" "2") + run_cmake_command(GLOB-CONFIGURE_DEPENDS-RerunCMake-rebuild_first ${CMAKE_COMMAND} --build .) + run_cmake_command(GLOB-CONFIGURE_DEPENDS-RerunCMake-nowork ${CMAKE_COMMAND} --build .) + + execute_process(COMMAND ${CMAKE_COMMAND} -E sleep ${fs_delay}) + message(STATUS "GLOB-CONFIGURE_DEPENDS-RerunCMake: remove first test file...") + file(REMOVE "${RunCMake_TEST_BINARY_DIR}/test/1.txt") + run_cmake_command(GLOB-CONFIGURE_DEPENDS-RerunCMake-rebuild_second ${CMAKE_COMMAND} --build .) + run_cmake_command(GLOB-CONFIGURE_DEPENDS-RerunCMake-nowork ${CMAKE_COMMAND} --build .) + + unset(RunCMake_TEST_BINARY_DIR) + unset(RunCMake_TEST_NO_CLEAN) + unset(RunCMake_DEFAULT_stderr) +endif() diff --git a/Tests/RunCMake/file/TOUCH-error-in-source-directory-result.txt b/Tests/RunCMake/file/TOUCH-error-in-source-directory-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/file/TOUCH-error-in-source-directory-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/file/TOUCH-error-in-source-directory-stderr.txt b/Tests/RunCMake/file/TOUCH-error-in-source-directory-stderr.txt new file mode 100644 index 0000000..f899c75 --- /dev/null +++ b/Tests/RunCMake/file/TOUCH-error-in-source-directory-stderr.txt @@ -0,0 +1 @@ +.*file attempted to touch a file: diff --git a/Tests/RunCMake/file/TOUCH-error-in-source-directory.cmake b/Tests/RunCMake/file/TOUCH-error-in-source-directory.cmake new file mode 100644 index 0000000..9aa7c56 --- /dev/null +++ b/Tests/RunCMake/file/TOUCH-error-in-source-directory.cmake @@ -0,0 +1,2 @@ +set(CMAKE_DISABLE_SOURCE_CHANGES ON) +file(TOUCH "${CMAKE_CURRENT_SOURCE_DIR}/touch_test") diff --git a/Tests/RunCMake/file/TOUCH-error-missing-directory-result.txt b/Tests/RunCMake/file/TOUCH-error-missing-directory-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/file/TOUCH-error-missing-directory-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/file/TOUCH-error-missing-directory-stderr.txt b/Tests/RunCMake/file/TOUCH-error-missing-directory-stderr.txt new file mode 100644 index 0000000..f52e11a --- /dev/null +++ b/Tests/RunCMake/file/TOUCH-error-missing-directory-stderr.txt @@ -0,0 +1 @@ +.*file problem touching file: diff --git a/Tests/RunCMake/file/TOUCH-error-missing-directory.cmake b/Tests/RunCMake/file/TOUCH-error-missing-directory.cmake new file mode 100644 index 0000000..0cfb8d9 --- /dev/null +++ b/Tests/RunCMake/file/TOUCH-error-missing-directory.cmake @@ -0,0 +1 @@ +file(TOUCH "${CMAKE_CURRENT_BINARY_DIR}/missing/directory/file.to-touch") diff --git a/Tests/RunCMake/file/TOUCH-result.txt b/Tests/RunCMake/file/TOUCH-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/file/TOUCH-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/file/TOUCH-stderr.txt b/Tests/RunCMake/file/TOUCH-stderr.txt new file mode 100644 index 0000000..9f31676 --- /dev/null +++ b/Tests/RunCMake/file/TOUCH-stderr.txt @@ -0,0 +1,9 @@ +^CMake Error at TOUCH\.cmake:[0-9]+ \(file\): + file must be called with at least two arguments\. +Call Stack \(most recent call first\): + CMakeLists\.txt:[0-9]+ \(include\) ++ +CMake Error at TOUCH\.cmake:[0-9]+ \(file\): + file must be called with at least two arguments\. +Call Stack \(most recent call first\): + CMakeLists\.txt:[0-9]+ \(include\) diff --git a/Tests/RunCMake/file/TOUCH.cmake b/Tests/RunCMake/file/TOUCH.cmake new file mode 100644 index 0000000..8931eb5 --- /dev/null +++ b/Tests/RunCMake/file/TOUCH.cmake @@ -0,0 +1,16 @@ +set(file "${CMAKE_CURRENT_BINARY_DIR}/file-to-touch") + +file(REMOVE "${file}") +file(TOUCH_NOCREATE "${file}") +if(EXISTS "${file}") + message(FATAL_ERROR "error: TOUCH_NOCREATE created a file!") +endif() + +file(TOUCH "${file}") +if(NOT EXISTS "${file}") + message(FATAL_ERROR "error: TOUCH did not create a file!") +endif() +file(REMOVE "${file}") + +file(TOUCH) +file(TOUCH_NOCREATE) diff --git a/Tests/RunCMake/find_package/CMP0074-OLD-stderr.txt b/Tests/RunCMake/find_package/CMP0074-OLD-stderr.txt new file mode 100644 index 0000000..4c2e517 --- /dev/null +++ b/Tests/RunCMake/find_package/CMP0074-OLD-stderr.txt @@ -0,0 +1,12 @@ +---------- +Foo_ROOT :<base>/foo/cmake_root +ENV{Foo_ROOT} :<base>/foo/env_root + +find_package\(Foo\) +FOO_TEST_FILE_FOO :FOO_TEST_FILE_FOO-NOTFOUND +FOO_TEST_FILE_ZOT :FOO_TEST_FILE_ZOT-NOTFOUND +FOO_TEST_PATH_FOO :FOO_TEST_PATH_FOO-NOTFOUND +FOO_TEST_PATH_ZOT :FOO_TEST_PATH_ZOT-NOTFOUND +FOO_TEST_PROG_FOO :FOO_TEST_PROG_FOO-NOTFOUND + +---------- diff --git a/Tests/RunCMake/find_package/CMP0074-OLD.cmake b/Tests/RunCMake/find_package/CMP0074-OLD.cmake new file mode 100644 index 0000000..4358317 --- /dev/null +++ b/Tests/RunCMake/find_package/CMP0074-OLD.cmake @@ -0,0 +1,2 @@ +cmake_policy(SET CMP0074 OLD) +include(CMP0074-common.cmake) diff --git a/Tests/RunCMake/find_package/CMP0074-WARN-stderr.txt b/Tests/RunCMake/find_package/CMP0074-WARN-stderr.txt new file mode 100644 index 0000000..27fbb86 --- /dev/null +++ b/Tests/RunCMake/find_package/CMP0074-WARN-stderr.txt @@ -0,0 +1,32 @@ +---------- +Foo_ROOT :<base>/foo/cmake_root +ENV{Foo_ROOT} :<base>/foo/env_root ++ +CMake Warning \(dev\) at CMP0074-common.cmake:[0-9]+ \(find_package\): + Policy CMP0074 is not set: find_package uses PackageName_ROOT variables. + Run "cmake --help-policy CMP0074" for policy details. Use the cmake_policy + command to set the policy and suppress this warning. + + CMake variable Foo_ROOT is set to: + + .*/Tests/RunCMake/find_package/PackageRoot/foo/cmake_root + + Environment variable Foo_ROOT is set to: + + .*/Tests/RunCMake/find_package/PackageRoot/foo/env_root + + For compatibility, CMake is ignoring the variable. +Call Stack \(most recent call first\): + CMP0074-common.cmake:[0-9]+ \(RunPackageRootTest\) + CMP0074-WARN.cmake:[0-9]+ \(include\) + CMakeLists.txt:[0-9]+ \(include\) +This warning is for project developers. Use -Wno-dev to suppress it. ++ +find_package\(Foo\) +FOO_TEST_FILE_FOO :FOO_TEST_FILE_FOO-NOTFOUND +FOO_TEST_FILE_ZOT :FOO_TEST_FILE_ZOT-NOTFOUND +FOO_TEST_PATH_FOO :FOO_TEST_PATH_FOO-NOTFOUND +FOO_TEST_PATH_ZOT :FOO_TEST_PATH_ZOT-NOTFOUND +FOO_TEST_PROG_FOO :FOO_TEST_PROG_FOO-NOTFOUND + +---------- diff --git a/Tests/RunCMake/find_package/CMP0074-WARN.cmake b/Tests/RunCMake/find_package/CMP0074-WARN.cmake new file mode 100644 index 0000000..0d4ada7 --- /dev/null +++ b/Tests/RunCMake/find_package/CMP0074-WARN.cmake @@ -0,0 +1,2 @@ +# (do not set CMP0074) +include(CMP0074-common.cmake) diff --git a/Tests/RunCMake/find_package/CMP0074-common.cmake b/Tests/RunCMake/find_package/CMP0074-common.cmake new file mode 100644 index 0000000..bfacd82 --- /dev/null +++ b/Tests/RunCMake/find_package/CMP0074-common.cmake @@ -0,0 +1,46 @@ +# (includer selects CMP0074) +cmake_policy(SET CMP0057 NEW) +list(INSERT CMAKE_MODULE_PATH 0 ${CMAKE_CURRENT_SOURCE_DIR}/PackageRoot) +set(PackageRoot_BASE ${CMAKE_CURRENT_SOURCE_DIR}/PackageRoot) + +function(PrintPath label path) + string(REPLACE "${PackageRoot_BASE}" "<base>" out "${path}") + message("${label}${out}") +endfunction() + +macro(CleanUpPackageRootTest) + unset(Foo_ROOT) + unset(ENV{Foo_ROOT}) + unset(FOO_TEST_FILE_FOO) + unset(FOO_TEST_FILE_ZOT) + unset(FOO_TEST_PATH_FOO) + unset(FOO_TEST_PATH_ZOT) + unset(FOO_TEST_PROG_FOO) + unset(FOO_TEST_FILE_FOO CACHE) + unset(FOO_TEST_FILE_ZOT CACHE) + unset(FOO_TEST_PATH_FOO CACHE) + unset(FOO_TEST_PATH_ZOT CACHE) + unset(FOO_TEST_PROG_FOO CACHE) +endmacro() + +macro(RunPackageRootTest) + message("----------") + PrintPath("Foo_ROOT :" "${Foo_ROOT}") + PrintPath("ENV{Foo_ROOT} :" "$ENV{Foo_ROOT}") + message("") + + find_package(Foo) + message("find_package(Foo)") + PrintPath("FOO_TEST_FILE_FOO :" "${FOO_TEST_FILE_FOO}") + PrintPath("FOO_TEST_FILE_ZOT :" "${FOO_TEST_FILE_ZOT}") + PrintPath("FOO_TEST_PATH_FOO :" "${FOO_TEST_PATH_FOO}") + PrintPath("FOO_TEST_PATH_ZOT :" "${FOO_TEST_PATH_ZOT}") + PrintPath("FOO_TEST_PROG_FOO :" "${FOO_TEST_PROG_FOO}") + CleanUpPackageRootTest() + message("") +endmacro() + +set(Foo_ROOT ${PackageRoot_BASE}/foo/cmake_root) +set(ENV{Foo_ROOT} ${PackageRoot_BASE}/foo/env_root) +RunPackageRootTest() +message("----------") diff --git a/Tests/RunCMake/find_package/PackageRoot.cmake b/Tests/RunCMake/find_package/PackageRoot.cmake index 4c4f4c2..aa12e9b 100644 --- a/Tests/RunCMake/find_package/PackageRoot.cmake +++ b/Tests/RunCMake/find_package/PackageRoot.cmake @@ -1,5 +1,5 @@ -set(__UNDOCUMENTED_CMAKE_FIND_PACKAGE_ROOT 1) cmake_policy(SET CMP0057 NEW) +cmake_policy(SET CMP0074 NEW) list(INSERT CMAKE_MODULE_PATH 0 ${CMAKE_CURRENT_SOURCE_DIR}/PackageRoot) set(PackageRoot_BASE ${CMAKE_CURRENT_SOURCE_DIR}/PackageRoot) diff --git a/Tests/RunCMake/find_package/PackageRootNestedConfig.cmake b/Tests/RunCMake/find_package/PackageRootNestedConfig.cmake index ba06c09..1ef32cb 100644 --- a/Tests/RunCMake/find_package/PackageRootNestedConfig.cmake +++ b/Tests/RunCMake/find_package/PackageRootNestedConfig.cmake @@ -1,5 +1,5 @@ -set(__UNDOCUMENTED_CMAKE_FIND_PACKAGE_ROOT 1) cmake_policy(SET CMP0057 NEW) +cmake_policy(SET CMP0074 NEW) list(INSERT CMAKE_MODULE_PATH 0 ${CMAKE_CURRENT_SOURCE_DIR}/PackageRoot) set(PackageRoot_BASE ${CMAKE_CURRENT_SOURCE_DIR}/PackageRoot) diff --git a/Tests/RunCMake/find_package/PackageRootNestedModule.cmake b/Tests/RunCMake/find_package/PackageRootNestedModule.cmake index 2795cd4..017834c 100644 --- a/Tests/RunCMake/find_package/PackageRootNestedModule.cmake +++ b/Tests/RunCMake/find_package/PackageRootNestedModule.cmake @@ -1,5 +1,5 @@ -set(__UNDOCUMENTED_CMAKE_FIND_PACKAGE_ROOT 1) cmake_policy(SET CMP0057 NEW) +cmake_policy(SET CMP0074 NEW) list(INSERT CMAKE_MODULE_PATH 0 ${CMAKE_CURRENT_SOURCE_DIR}/PackageRoot) set(PackageRoot_BASE ${CMAKE_CURRENT_SOURCE_DIR}/PackageRoot) diff --git a/Tests/RunCMake/find_package/RunCMakeTest.cmake b/Tests/RunCMake/find_package/RunCMakeTest.cmake index d548da0..c068402 100644 --- a/Tests/RunCMake/find_package/RunCMakeTest.cmake +++ b/Tests/RunCMake/find_package/RunCMakeTest.cmake @@ -1,5 +1,7 @@ include(RunCMake) +run_cmake(CMP0074-WARN) +run_cmake(CMP0074-OLD) run_cmake(ComponentRequiredAndOptional) run_cmake(MissingNormal) run_cmake(MissingNormalRequired) diff --git a/Tests/RunCMake/get_property/directory_properties-stderr.txt b/Tests/RunCMake/get_property/directory_properties-stderr.txt index 6d5bcdb..89f5618 100644 --- a/Tests/RunCMake/get_property/directory_properties-stderr.txt +++ b/Tests/RunCMake/get_property/directory_properties-stderr.txt @@ -19,4 +19,12 @@ get_property: -->[^<;]*/Tests/RunCMake/get_property<-- get_directory_property: -->[^<;]*/Tests/RunCMake/get_property/directory_properties-build/directory_properties<-- get_property: -->[^<;]*/Tests/RunCMake/get_property/directory_properties-build/directory_properties<-- get_directory_property: -->[^<;]*/Tests/RunCMake/get_property/directory_properties<-- -get_property: -->[^<;]*/Tests/RunCMake/get_property/directory_properties<--$ +get_property: -->[^<;]*/Tests/RunCMake/get_property/directory_properties<-- +get_directory_property: --><-- +get_property: --><-- +get_directory_property: -->test1;test2<-- +get_property: -->test1;test2<-- +get_directory_property: -->test1;test2;test3<-- +get_property: -->test1;test2;test3<-- +get_directory_property: -->Sub/test1;Sub/test2<-- +get_property: -->Sub/test1;Sub/test2<--$ diff --git a/Tests/RunCMake/get_property/directory_properties.cmake b/Tests/RunCMake/get_property/directory_properties.cmake index 4e68738..9b978fd 100644 --- a/Tests/RunCMake/get_property/directory_properties.cmake +++ b/Tests/RunCMake/get_property/directory_properties.cmake @@ -28,3 +28,12 @@ check_directory_property("${CMAKE_CURRENT_SOURCE_DIR}" BINARY_DIR) check_directory_property("${CMAKE_CURRENT_SOURCE_DIR}" SOURCE_DIR) check_directory_property("${CMAKE_CURRENT_SOURCE_DIR}/directory_properties" BINARY_DIR) check_directory_property("${CMAKE_CURRENT_SOURCE_DIR}/directory_properties" SOURCE_DIR) + +check_directory_property("${CMAKE_CURRENT_SOURCE_DIR}" TESTS) +add_test(NAME test1 COMMAND "${CMAKE_COMMAND}" -E echo "test1") +add_test(NAME test2 COMMAND "${CMAKE_COMMAND}" -E echo "test2") +check_directory_property("${CMAKE_CURRENT_SOURCE_DIR}" TESTS) +add_test(NAME test3 COMMAND "${CMAKE_COMMAND}" -E echo "test3") +check_directory_property("${CMAKE_CURRENT_SOURCE_DIR}" TESTS) + +check_directory_property("${CMAKE_CURRENT_SOURCE_DIR}/directory_properties" TESTS) diff --git a/Tests/RunCMake/get_property/directory_properties/CMakeLists.txt b/Tests/RunCMake/get_property/directory_properties/CMakeLists.txt index 7318b97..95106ad 100644 --- a/Tests/RunCMake/get_property/directory_properties/CMakeLists.txt +++ b/Tests/RunCMake/get_property/directory_properties/CMakeLists.txt @@ -4,3 +4,6 @@ subdirs(sub2) add_custom_target(CustomSub) add_library(InterfaceSub INTERFACE) add_library(my::InterfaceSub ALIAS InterfaceSub) + +add_test(Sub/test1 COMMAND "${CMAKE_COMMAND}" -E echo "Sub/test1") +add_test(Sub/test2 COMMAND "${CMAKE_COMMAND}" -E echo "Sub/test2") diff --git a/Tests/RunCMake/list/JOIN-NoArguments-result.txt b/Tests/RunCMake/list/JOIN-NoArguments-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/list/JOIN-NoArguments-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/list/JOIN-NoArguments-stderr.txt b/Tests/RunCMake/list/JOIN-NoArguments-stderr.txt new file mode 100644 index 0000000..5e1b98f --- /dev/null +++ b/Tests/RunCMake/list/JOIN-NoArguments-stderr.txt @@ -0,0 +1,4 @@ +^CMake Error at JOIN-NoArguments.cmake:1 \(list\): + list sub-command JOIN requires three arguments \(1 found\). +Call Stack \(most recent call first\): + CMakeLists.txt:3 \(include\)$ diff --git a/Tests/RunCMake/list/JOIN-NoArguments.cmake b/Tests/RunCMake/list/JOIN-NoArguments.cmake new file mode 100644 index 0000000..2ab449a --- /dev/null +++ b/Tests/RunCMake/list/JOIN-NoArguments.cmake @@ -0,0 +1 @@ +list(JOIN mylist) diff --git a/Tests/RunCMake/list/JOIN-NoVariable-result.txt b/Tests/RunCMake/list/JOIN-NoVariable-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/list/JOIN-NoVariable-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/list/JOIN-NoVariable-stderr.txt b/Tests/RunCMake/list/JOIN-NoVariable-stderr.txt new file mode 100644 index 0000000..db1d773 --- /dev/null +++ b/Tests/RunCMake/list/JOIN-NoVariable-stderr.txt @@ -0,0 +1,4 @@ +^CMake Error at JOIN-NoVariable.cmake:1 \(list\): + list sub-command JOIN requires three arguments \(2 found\). +Call Stack \(most recent call first\): + CMakeLists.txt:3 \(include\)$ diff --git a/Tests/RunCMake/list/JOIN-NoVariable.cmake b/Tests/RunCMake/list/JOIN-NoVariable.cmake new file mode 100644 index 0000000..b60d8f1 --- /dev/null +++ b/Tests/RunCMake/list/JOIN-NoVariable.cmake @@ -0,0 +1 @@ +list(JOIN mylist "glue") diff --git a/Tests/RunCMake/list/JOIN-TooManyArguments-result.txt b/Tests/RunCMake/list/JOIN-TooManyArguments-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/list/JOIN-TooManyArguments-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/list/JOIN-TooManyArguments-stderr.txt b/Tests/RunCMake/list/JOIN-TooManyArguments-stderr.txt new file mode 100644 index 0000000..2b09e22 --- /dev/null +++ b/Tests/RunCMake/list/JOIN-TooManyArguments-stderr.txt @@ -0,0 +1,4 @@ +^CMake Error at JOIN-TooManyArguments.cmake:1 \(list\): + list sub-command JOIN requires three arguments \(4 found\). +Call Stack \(most recent call first\): + CMakeLists.txt:3 \(include\)$ diff --git a/Tests/RunCMake/list/JOIN-TooManyArguments.cmake b/Tests/RunCMake/list/JOIN-TooManyArguments.cmake new file mode 100644 index 0000000..dc651f6 --- /dev/null +++ b/Tests/RunCMake/list/JOIN-TooManyArguments.cmake @@ -0,0 +1 @@ +list(JOIN mylist "glue" out one_too_many) diff --git a/Tests/RunCMake/list/JOIN.cmake b/Tests/RunCMake/list/JOIN.cmake new file mode 100644 index 0000000..24a623e --- /dev/null +++ b/Tests/RunCMake/list/JOIN.cmake @@ -0,0 +1,18 @@ +list(JOIN undefList % out) +if(NOT out STREQUAL "") + message(FATAL_ERROR "\"list(JOIN undefList % out)\" set out to \"${out}\"") +endif() +set(myList a) +list(JOIN myList % out) +if(NOT out STREQUAL "a") + message(FATAL_ERROR "\"list(JOIN \"a\" % out)\" set out to \"${out}\"") +endif() +set(myList a b) +list(JOIN myList % out) +if(NOT out STREQUAL "a%b") + message(FATAL_ERROR "\"list(JOIN \"a;b\" % out)\" set out to \"${out}\"") +endif() +list(JOIN myList "" out) +if(NOT out STREQUAL "ab") + message(FATAL_ERROR "\"list(JOIN \"a;b\" \"\" out a)\" set out to \"${out}\"") +endif() diff --git a/Tests/RunCMake/list/RunCMakeTest.cmake b/Tests/RunCMake/list/RunCMakeTest.cmake index b002ab3..bdc23a4 100644 --- a/Tests/RunCMake/list/RunCMakeTest.cmake +++ b/Tests/RunCMake/list/RunCMakeTest.cmake @@ -13,12 +13,15 @@ run_cmake(FILTER-REGEX-InvalidRegex) run_cmake(GET-InvalidIndex) run_cmake(INSERT-InvalidIndex) run_cmake(REMOVE_AT-InvalidIndex) +run_cmake(SUBLIST-InvalidIndex) run_cmake(FILTER-REGEX-TooManyArguments) +run_cmake(JOIN-TooManyArguments) run_cmake(LENGTH-TooManyArguments) run_cmake(REMOVE_DUPLICATES-TooManyArguments) run_cmake(REVERSE-TooManyArguments) run_cmake(SORT-TooManyArguments) +run_cmake(SUBLIST-TooManyArguments) run_cmake(FILTER-NotList) run_cmake(REMOVE_AT-NotList) @@ -31,3 +34,53 @@ run_cmake(FILTER-REGEX-InvalidMode) run_cmake(FILTER-REGEX-InvalidOperator) run_cmake(FILTER-REGEX-Valid0) run_cmake(FILTER-REGEX-Valid1) + +run_cmake(JOIN-NoArguments) +run_cmake(JOIN-NoVariable) +run_cmake(JOIN) + +run_cmake(SUBLIST-NoArguments) +run_cmake(SUBLIST-NoVariable) +run_cmake(SUBLIST-InvalidLength) +run_cmake(SUBLIST) + +run_cmake(TRANSFORM-NoAction) +run_cmake(TRANSFORM-InvalidAction) +# 'action' oriented tests +run_cmake(TRANSFORM-TOUPPER-TooManyArguments) +run_cmake(TRANSFORM-TOLOWER-TooManyArguments) +run_cmake(TRANSFORM-STRIP-TooManyArguments) +run_cmake(TRANSFORM-GENEX_STRIP-TooManyArguments) +run_cmake(TRANSFORM-APPEND-NoArguments) +run_cmake(TRANSFORM-APPEND-TooManyArguments) +run_cmake(TRANSFORM-PREPEND-NoArguments) +run_cmake(TRANSFORM-PREPEND-TooManyArguments) +run_cmake(TRANSFORM-REPLACE-NoArguments) +run_cmake(TRANSFORM-REPLACE-NoEnoughArguments) +run_cmake(TRANSFORM-REPLACE-TooManyArguments) +run_cmake(TRANSFORM-REPLACE-InvalidRegex) +run_cmake(TRANSFORM-REPLACE-InvalidReplace1) +run_cmake(TRANSFORM-REPLACE-InvalidReplace2) +# 'selector' oriented tests +run_cmake(TRANSFORM-Selector-REGEX-NoArguments) +run_cmake(TRANSFORM-Selector-REGEX-TooManyArguments) +run_cmake(TRANSFORM-Selector-REGEX-InvalidRegex) +run_cmake(TRANSFORM-Selector-AT-NoArguments) +run_cmake(TRANSFORM-Selector-AT-BadArgument) +run_cmake(TRANSFORM-Selector-AT-InvalidIndex) +run_cmake(TRANSFORM-Selector-FOR-NoArguments) +run_cmake(TRANSFORM-Selector-FOR-NoEnoughArguments) +run_cmake(TRANSFORM-Selector-FOR-TooManyArguments) +run_cmake(TRANSFORM-Selector-FOR-BadArgument) +run_cmake(TRANSFORM-Selector-FOR-InvalidIndex) +# 'output' oriented tests +run_cmake(TRANSFORM-Output-OUTPUT_VARIABLE-NoArguments) +run_cmake(TRANSFORM-Output-OUTPUT_VARIABLE-TooManyArguments) +# Successful tests +run_cmake(TRANSFORM-TOUPPER) +run_cmake(TRANSFORM-TOLOWER) +run_cmake(TRANSFORM-STRIP) +run_cmake(TRANSFORM-GENEX_STRIP) +run_cmake(TRANSFORM-APPEND) +run_cmake(TRANSFORM-PREPEND) +run_cmake(TRANSFORM-REPLACE) diff --git a/Tests/RunCMake/list/SUBLIST-InvalidIndex-result.txt b/Tests/RunCMake/list/SUBLIST-InvalidIndex-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/list/SUBLIST-InvalidIndex-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/list/SUBLIST-InvalidIndex-stderr.txt b/Tests/RunCMake/list/SUBLIST-InvalidIndex-stderr.txt new file mode 100644 index 0000000..5e67b27 --- /dev/null +++ b/Tests/RunCMake/list/SUBLIST-InvalidIndex-stderr.txt @@ -0,0 +1,4 @@ +^CMake Error at SUBLIST-InvalidIndex.cmake:2 \(list\): + list begin index: 3 is out of range 0 - 2 +Call Stack \(most recent call first\): + CMakeLists.txt:3 \(include\)$ diff --git a/Tests/RunCMake/list/SUBLIST-InvalidIndex.cmake b/Tests/RunCMake/list/SUBLIST-InvalidIndex.cmake new file mode 100644 index 0000000..565b9dc --- /dev/null +++ b/Tests/RunCMake/list/SUBLIST-InvalidIndex.cmake @@ -0,0 +1,2 @@ +set(mylist alpha bravo charlie) +list(SUBLIST mylist 3 -1 result) diff --git a/Tests/RunCMake/list/SUBLIST-InvalidLength-result.txt b/Tests/RunCMake/list/SUBLIST-InvalidLength-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/list/SUBLIST-InvalidLength-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/list/SUBLIST-InvalidLength-stderr.txt b/Tests/RunCMake/list/SUBLIST-InvalidLength-stderr.txt new file mode 100644 index 0000000..16c6ecb --- /dev/null +++ b/Tests/RunCMake/list/SUBLIST-InvalidLength-stderr.txt @@ -0,0 +1,4 @@ +^CMake Error at SUBLIST-InvalidLength.cmake:2 \(list\): + list length: -2 should be -1 or greater +Call Stack \(most recent call first\): + CMakeLists.txt:3 \(include\)$ diff --git a/Tests/RunCMake/list/SUBLIST-InvalidLength.cmake b/Tests/RunCMake/list/SUBLIST-InvalidLength.cmake new file mode 100644 index 0000000..1dab83f --- /dev/null +++ b/Tests/RunCMake/list/SUBLIST-InvalidLength.cmake @@ -0,0 +1,2 @@ +set(mylist alpha bravo charlie) +list(SUBLIST mylist 0 -2 result) diff --git a/Tests/RunCMake/list/SUBLIST-NoArguments-result.txt b/Tests/RunCMake/list/SUBLIST-NoArguments-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/list/SUBLIST-NoArguments-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/list/SUBLIST-NoArguments-stderr.txt b/Tests/RunCMake/list/SUBLIST-NoArguments-stderr.txt new file mode 100644 index 0000000..073173c --- /dev/null +++ b/Tests/RunCMake/list/SUBLIST-NoArguments-stderr.txt @@ -0,0 +1,4 @@ +^CMake Error at SUBLIST-NoArguments.cmake:1 \(list\): + list sub-command SUBLIST requires four arguments \(1 found\). +Call Stack \(most recent call first\): + CMakeLists.txt:3 \(include\)$ diff --git a/Tests/RunCMake/list/SUBLIST-NoArguments.cmake b/Tests/RunCMake/list/SUBLIST-NoArguments.cmake new file mode 100644 index 0000000..df38b87 --- /dev/null +++ b/Tests/RunCMake/list/SUBLIST-NoArguments.cmake @@ -0,0 +1 @@ +list(SUBLIST mylist) diff --git a/Tests/RunCMake/list/SUBLIST-NoVariable-result.txt b/Tests/RunCMake/list/SUBLIST-NoVariable-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/list/SUBLIST-NoVariable-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/list/SUBLIST-NoVariable-stderr.txt b/Tests/RunCMake/list/SUBLIST-NoVariable-stderr.txt new file mode 100644 index 0000000..6f80c1a --- /dev/null +++ b/Tests/RunCMake/list/SUBLIST-NoVariable-stderr.txt @@ -0,0 +1,4 @@ +^CMake Error at SUBLIST-NoVariable.cmake:2 \(list\): + list sub-command SUBLIST requires four arguments \(3 found\). +Call Stack \(most recent call first\): + CMakeLists.txt:3 \(include\)$ diff --git a/Tests/RunCMake/list/SUBLIST-NoVariable.cmake b/Tests/RunCMake/list/SUBLIST-NoVariable.cmake new file mode 100644 index 0000000..83edae9 --- /dev/null +++ b/Tests/RunCMake/list/SUBLIST-NoVariable.cmake @@ -0,0 +1,2 @@ +set(mylist alpha bravo charlie) +list(SUBLIST mylist 0 -1) diff --git a/Tests/RunCMake/list/SUBLIST-TooManyArguments-result.txt b/Tests/RunCMake/list/SUBLIST-TooManyArguments-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/list/SUBLIST-TooManyArguments-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/list/SUBLIST-TooManyArguments-stderr.txt b/Tests/RunCMake/list/SUBLIST-TooManyArguments-stderr.txt new file mode 100644 index 0000000..eb46844 --- /dev/null +++ b/Tests/RunCMake/list/SUBLIST-TooManyArguments-stderr.txt @@ -0,0 +1,4 @@ +^CMake Error at SUBLIST-TooManyArguments.cmake:1 \(list\): + list sub-command SUBLIST requires four arguments \(5 found\). +Call Stack \(most recent call first\): + CMakeLists.txt:3 \(include\)$ diff --git a/Tests/RunCMake/list/SUBLIST-TooManyArguments.cmake b/Tests/RunCMake/list/SUBLIST-TooManyArguments.cmake new file mode 100644 index 0000000..28f20c1 --- /dev/null +++ b/Tests/RunCMake/list/SUBLIST-TooManyArguments.cmake @@ -0,0 +1 @@ +list(SUBLIST mylist 0 -1 result one_too_many) diff --git a/Tests/RunCMake/list/SUBLIST.cmake b/Tests/RunCMake/list/SUBLIST.cmake new file mode 100644 index 0000000..fd15c28 --- /dev/null +++ b/Tests/RunCMake/list/SUBLIST.cmake @@ -0,0 +1,46 @@ +set(mylist alpha bravo charlie delta) +list(SUBLIST mylist 1 2 result) + +if (NOT result STREQUAL "bravo;charlie") + message (FATAL_ERROR "SUBLIST is \"${result}\", expected is \"bravo;charlie\"") +endif() + + +unset(result) +list(SUBLIST mylist 0 2 result) + +if (NOT result STREQUAL "alpha;bravo") + message (FATAL_ERROR "SUBLIST is \"${result}\", expected is \"alpha;bravo\"") +endif() + + +unset(result) +list(SUBLIST mylist 3 2 result) + +if (NOT result STREQUAL "delta") + message (FATAL_ERROR "SUBLIST is \"${result}\", expected is \"delta\"") +endif() + + +unset(result) +list(SUBLIST mylist 2 0 result) +list(LENGTH result length) +if (NOT length EQUAL 0) + message (FATAL_ERROR "SUBLIST is \"${result}\", expected is an empty list") +endif() + + +unset(result) +list(SUBLIST mylist 1 5 result) + +if (NOT result STREQUAL "bravo;charlie;delta") + message (FATAL_ERROR "SUBLIST is \"${result}\", expected is \"bravo;charlie;delta\"") +endif() + + +unset(result) +list(SUBLIST mylist 1 -1 result) + +if (NOT result STREQUAL "bravo;charlie;delta") + message (FATAL_ERROR "SUBLIST is \"${result}\", expected is \"bravo;charlie;delta\"") +endif() diff --git a/Tests/RunCMake/list/TRANSFORM-APPEND-NoArguments-result.txt b/Tests/RunCMake/list/TRANSFORM-APPEND-NoArguments-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-APPEND-NoArguments-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/list/TRANSFORM-APPEND-NoArguments-stderr.txt b/Tests/RunCMake/list/TRANSFORM-APPEND-NoArguments-stderr.txt new file mode 100644 index 0000000..028f8d5 --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-APPEND-NoArguments-stderr.txt @@ -0,0 +1,4 @@ +^CMake Error at TRANSFORM-APPEND-NoArguments.cmake:2 \(list\): + list sub-command TRANSFORM, action APPEND expects 1 argument\(s\). +Call Stack \(most recent call first\): + CMakeLists.txt:3 \(include\)$ diff --git a/Tests/RunCMake/list/TRANSFORM-APPEND-NoArguments.cmake b/Tests/RunCMake/list/TRANSFORM-APPEND-NoArguments.cmake new file mode 100644 index 0000000..f161187 --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-APPEND-NoArguments.cmake @@ -0,0 +1,2 @@ +set(mylist alpha bravo charlie) +list(TRANSFORM mylist APPEND) diff --git a/Tests/RunCMake/list/TRANSFORM-APPEND-TooManyArguments-result.txt b/Tests/RunCMake/list/TRANSFORM-APPEND-TooManyArguments-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-APPEND-TooManyArguments-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/list/TRANSFORM-APPEND-TooManyArguments-stderr.txt b/Tests/RunCMake/list/TRANSFORM-APPEND-TooManyArguments-stderr.txt new file mode 100644 index 0000000..aeb646d --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-APPEND-TooManyArguments-stderr.txt @@ -0,0 +1,4 @@ +^CMake Error at TRANSFORM-APPEND-TooManyArguments.cmake:2 \(list\): + list sub-command TRANSFORM, 'one_too_many': unexpected argument\(s\). +Call Stack \(most recent call first\): + CMakeLists.txt:3 \(include\)$ diff --git a/Tests/RunCMake/list/TRANSFORM-APPEND-TooManyArguments.cmake b/Tests/RunCMake/list/TRANSFORM-APPEND-TooManyArguments.cmake new file mode 100644 index 0000000..8430a4c --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-APPEND-TooManyArguments.cmake @@ -0,0 +1,2 @@ +set(mylist alpha bravo charlie) +list(TRANSFORM mylist APPEND delta one_too_many) diff --git a/Tests/RunCMake/list/TRANSFORM-APPEND.cmake b/Tests/RunCMake/list/TRANSFORM-APPEND.cmake new file mode 100644 index 0000000..9639088 --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-APPEND.cmake @@ -0,0 +1,48 @@ +set(mylist alpha bravo charlie delta) + +list(TRANSFORM mylist APPEND "_A" OUTPUT_VARIABLE output) +if (NOT output STREQUAL "alpha_A;bravo_A;charlie_A;delta_A") + message (FATAL_ERROR "TRANSFORM(APPEND) is \"${output}\", expected is \"alpha_A;bravo_A;charlie_A;delta_A\"") +endif() + +unset(output) +list(TRANSFORM mylist APPEND "_A" AT 1 3 OUTPUT_VARIABLE output) +if (NOT output STREQUAL "alpha;bravo_A;charlie;delta_A") + message (FATAL_ERROR "TRANSFORM(APPEND) is \"${output}\", expected is \"alpha;bravo_A;charlie;delta_A\"") +endif() + +unset(output) +list(TRANSFORM mylist APPEND "_A" AT 1 -2 OUTPUT_VARIABLE output) +if (NOT output STREQUAL "alpha;bravo_A;charlie_A;delta") + message (FATAL_ERROR "TRANSFORM(APPEND) is \"${output}\", expected is \"alpha;bravo_A;charlie_A;delta\"") +endif() + +unset(output) +list(TRANSFORM mylist APPEND "_A" FOR 1 2 OUTPUT_VARIABLE output) +if (NOT output STREQUAL "alpha;bravo_A;charlie_A;delta") + message (FATAL_ERROR "TRANSFORM(APPEND) is \"${output}\", expected is \"alpha;bravo_A;charlie_A;delta\"") +endif() + +unset(output) +list(TRANSFORM mylist APPEND "_A" FOR 1 -1 OUTPUT_VARIABLE output) +if (NOT output STREQUAL "alpha;bravo_A;charlie_A;delta_A") + message (FATAL_ERROR "TRANSFORM(APPEND) is \"${output}\", expected is \"alpha;bravo_A;charlie_A;delta_A\"") +endif() + +unset(output) +list(TRANSFORM mylist APPEND "_A" FOR 0 -1 2 OUTPUT_VARIABLE output) +if (NOT output STREQUAL "alpha_A;bravo;charlie_A;delta") + message (FATAL_ERROR "TRANSFORM(APPEND) is \"${output}\", expected is \"alpha_A;bravo;charlie_A;delta\"") +endif() + +unset(output) +list(TRANSFORM mylist APPEND "_A" REGEX "(r|t)a" OUTPUT_VARIABLE output) +if (NOT output STREQUAL "alpha;bravo_A;charlie;delta_A") + message (FATAL_ERROR "TRANSFORM(APPEND) is \"${output}\", expected is \"alpha;bravo_A;charlie;delta_A\"") +endif() + +unset(output) +list(TRANSFORM mylist APPEND "_A" REGEX "(r|t)a") +if (NOT mylist STREQUAL "alpha;bravo_A;charlie;delta_A") + message (FATAL_ERROR "TRANSFORM(APPEND) is \"${mylist}\", expected is \"alpha;bravo_A;charlie;delta_A\"") +endif() diff --git a/Tests/RunCMake/list/TRANSFORM-GENEX_STRIP-TooManyArguments-result.txt b/Tests/RunCMake/list/TRANSFORM-GENEX_STRIP-TooManyArguments-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-GENEX_STRIP-TooManyArguments-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/list/TRANSFORM-GENEX_STRIP-TooManyArguments-stderr.txt b/Tests/RunCMake/list/TRANSFORM-GENEX_STRIP-TooManyArguments-stderr.txt new file mode 100644 index 0000000..6071a00 --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-GENEX_STRIP-TooManyArguments-stderr.txt @@ -0,0 +1,4 @@ +^CMake Error at TRANSFORM-GENEX_STRIP-TooManyArguments.cmake:2 \(list\): + list sub-command TRANSFORM, 'one_too_many': unexpected argument\(s\). +Call Stack \(most recent call first\): + CMakeLists.txt:3 \(include\)$ diff --git a/Tests/RunCMake/list/TRANSFORM-GENEX_STRIP-TooManyArguments.cmake b/Tests/RunCMake/list/TRANSFORM-GENEX_STRIP-TooManyArguments.cmake new file mode 100644 index 0000000..257d7fe --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-GENEX_STRIP-TooManyArguments.cmake @@ -0,0 +1,2 @@ +set(mylist alpha bravo charlie) +list(TRANSFORM mylist GENEX_STRIP one_too_many) diff --git a/Tests/RunCMake/list/TRANSFORM-GENEX_STRIP.cmake b/Tests/RunCMake/list/TRANSFORM-GENEX_STRIP.cmake new file mode 100644 index 0000000..8045eef --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-GENEX_STRIP.cmake @@ -0,0 +1,49 @@ +set(mylist one "$<1:two\;three>" four "$<TARGET_OBJECTS:some_target>") + +list(TRANSFORM mylist GENEX_STRIP OUTPUT_VARIABLE output) +if (NOT output STREQUAL "one;;four;") + message (FATAL_ERROR "TRANSFORM(GENEX_STRIP) is \"${output}\", expected is \"one;;four;\"") +endif() + +set(mylist "one $<CONFIG>" "$<1:two\;three>-$<PLATFORM_ID>" "$<ANGLE-R>four" "$<TARGET_OBJECTS:some_target>") +unset(output) +list(TRANSFORM mylist GENEX_STRIP AT 1 3 OUTPUT_VARIABLE output) +if (NOT output STREQUAL "one $<CONFIG>;-;$<ANGLE-R>four;") + message (FATAL_ERROR "TRANSFORM(GENEX_STRIP) is \"${output}\", expected is \"one $<CONFIG>;-;$<ANGLE-R>four;\"") +endif() + +unset(output) +list(TRANSFORM mylist GENEX_STRIP AT 1 -2 OUTPUT_VARIABLE output) +if (NOT output STREQUAL "one $<CONFIG>;-;four;$<TARGET_OBJECTS:some_target>") + message (FATAL_ERROR "TRANSFORM(GENEX_STRIP) is \"${output}\", expected is \"one $<CONFIG>;-;four;$<TARGET_OBJECTS:some_target>\"") +endif() + +unset(output) +list(TRANSFORM mylist GENEX_STRIP FOR 1 2 OUTPUT_VARIABLE output) +if (NOT output STREQUAL "one $<CONFIG>;-;four;$<TARGET_OBJECTS:some_target>") + message (FATAL_ERROR "TRANSFORM(GENEX_STRIP) is \"${output}\", expected is \"one $<CONFIG>;-;four;$<TARGET_OBJECTS:some_target>\"") +endif() + +unset(output) +list(TRANSFORM mylist GENEX_STRIP FOR 1 -1 OUTPUT_VARIABLE output) +if (NOT output STREQUAL "one $<CONFIG>;-;four;") + message (FATAL_ERROR "TRANSFORM(GENEX_STRIP) is \"${output}\", expected is \"one $<CONFIG>;-;four;\"") +endif() + +unset(output) +list(TRANSFORM mylist GENEX_STRIP FOR 0 -1 2 OUTPUT_VARIABLE output) +if (NOT output STREQUAL "one ;$<1:two;three>-$<PLATFORM_ID>;four;$<TARGET_OBJECTS:some_target>") + message (FATAL_ERROR "TRANSFORM(GENEX_STRIP) is \"${output}\", expected is \"one ;$<1:two;three>-$<PLATFORM_ID>;four;$<TARGET_OBJECTS:some_target>\"") +endif() + +unset(output) +list(TRANSFORM mylist GENEX_STRIP REGEX "(D|G)>" OUTPUT_VARIABLE output) +if (NOT output STREQUAL "one ;-;$<ANGLE-R>four;$<TARGET_OBJECTS:some_target>") + message (FATAL_ERROR "TRANSFORM(GENEX_STRIP) is \"${output}\", expected is \"one ;-;$<ANGLE-R>four;$<TARGET_OBJECTS:some_target>\"") +endif() + +unset(output) +list(TRANSFORM mylist GENEX_STRIP REGEX "(D|G)>") +if (NOT mylist STREQUAL "one ;-;$<ANGLE-R>four;$<TARGET_OBJECTS:some_target>") + message (FATAL_ERROR "TRANSFORM(GENEX_STRIP) is \"${mylist}\", expected is \"one ;-;$<ANGLE-R>four;$<TARGET_OBJECTS:some_target>\"") +endif() diff --git a/Tests/RunCMake/list/TRANSFORM-InvalidAction-result.txt b/Tests/RunCMake/list/TRANSFORM-InvalidAction-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-InvalidAction-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/list/TRANSFORM-InvalidAction-stderr.txt b/Tests/RunCMake/list/TRANSFORM-InvalidAction-stderr.txt new file mode 100644 index 0000000..0fa45c9 --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-InvalidAction-stderr.txt @@ -0,0 +1,4 @@ +^CMake Error at TRANSFORM-InvalidAction.cmake:2 \(list\): + list sub-command TRANSFORM, BAD_ACTION invalid action. +Call Stack \(most recent call first\): + CMakeLists.txt:3 \(include\)$ diff --git a/Tests/RunCMake/list/TRANSFORM-InvalidAction.cmake b/Tests/RunCMake/list/TRANSFORM-InvalidAction.cmake new file mode 100644 index 0000000..fb2cc30 --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-InvalidAction.cmake @@ -0,0 +1,2 @@ +set(mylist alpha bravo charlie) +list(TRANSFORM mylist BAD_ACTION) diff --git a/Tests/RunCMake/list/TRANSFORM-NoAction-result.txt b/Tests/RunCMake/list/TRANSFORM-NoAction-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-NoAction-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/list/TRANSFORM-NoAction-stderr.txt b/Tests/RunCMake/list/TRANSFORM-NoAction-stderr.txt new file mode 100644 index 0000000..68e9e9d --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-NoAction-stderr.txt @@ -0,0 +1,4 @@ +^CMake Error at TRANSFORM-NoAction.cmake:2 \(list\): + list sub-command TRANSFORM requires an action to be specified. +Call Stack \(most recent call first\): + CMakeLists.txt:3 \(include\)$ diff --git a/Tests/RunCMake/list/TRANSFORM-NoAction.cmake b/Tests/RunCMake/list/TRANSFORM-NoAction.cmake new file mode 100644 index 0000000..3690f14 --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-NoAction.cmake @@ -0,0 +1,2 @@ +set(mylist alpha bravo charlie) +list(TRANSFORM mylist) diff --git a/Tests/RunCMake/list/TRANSFORM-Output-OUTPUT_VARIABLE-NoArguments-result.txt b/Tests/RunCMake/list/TRANSFORM-Output-OUTPUT_VARIABLE-NoArguments-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-Output-OUTPUT_VARIABLE-NoArguments-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/list/TRANSFORM-Output-OUTPUT_VARIABLE-NoArguments-stderr.txt b/Tests/RunCMake/list/TRANSFORM-Output-OUTPUT_VARIABLE-NoArguments-stderr.txt new file mode 100644 index 0000000..b4f4e06 --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-Output-OUTPUT_VARIABLE-NoArguments-stderr.txt @@ -0,0 +1,4 @@ +^CMake Error at TRANSFORM-Output-OUTPUT_VARIABLE-NoArguments.cmake:2 \(list\): + list sub-command TRANSFORM, OUTPUT_VARIABLE expects variable name argument. +Call Stack \(most recent call first\): + CMakeLists.txt:3 \(include\)$ diff --git a/Tests/RunCMake/list/TRANSFORM-Output-OUTPUT_VARIABLE-NoArguments.cmake b/Tests/RunCMake/list/TRANSFORM-Output-OUTPUT_VARIABLE-NoArguments.cmake new file mode 100644 index 0000000..acc4094 --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-Output-OUTPUT_VARIABLE-NoArguments.cmake @@ -0,0 +1,2 @@ +set(mylist alpha bravo charlie) +list(TRANSFORM mylist TOUPPER OUTPUT_VARIABLE) diff --git a/Tests/RunCMake/list/TRANSFORM-Output-OUTPUT_VARIABLE-TooManyArguments-result.txt b/Tests/RunCMake/list/TRANSFORM-Output-OUTPUT_VARIABLE-TooManyArguments-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-Output-OUTPUT_VARIABLE-TooManyArguments-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/list/TRANSFORM-Output-OUTPUT_VARIABLE-TooManyArguments-stderr.txt b/Tests/RunCMake/list/TRANSFORM-Output-OUTPUT_VARIABLE-TooManyArguments-stderr.txt new file mode 100644 index 0000000..9a58346 --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-Output-OUTPUT_VARIABLE-TooManyArguments-stderr.txt @@ -0,0 +1,4 @@ +^CMake Error at TRANSFORM-Output-OUTPUT_VARIABLE-TooManyArguments.cmake:2 \(list\): + list sub-command TRANSFORM, 'one_too_many': unexpected argument\(s\). +Call Stack \(most recent call first\): + CMakeLists.txt:3 \(include\)$ diff --git a/Tests/RunCMake/list/TRANSFORM-Output-OUTPUT_VARIABLE-TooManyArguments.cmake b/Tests/RunCMake/list/TRANSFORM-Output-OUTPUT_VARIABLE-TooManyArguments.cmake new file mode 100644 index 0000000..c4da864 --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-Output-OUTPUT_VARIABLE-TooManyArguments.cmake @@ -0,0 +1,2 @@ +set(mylist alpha bravo charlie) +list(TRANSFORM mylist TOUPPER OUTPUT_VARIABLE output one_too_many) diff --git a/Tests/RunCMake/list/TRANSFORM-PREPEND-NoArguments-result.txt b/Tests/RunCMake/list/TRANSFORM-PREPEND-NoArguments-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-PREPEND-NoArguments-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/list/TRANSFORM-PREPEND-NoArguments-stderr.txt b/Tests/RunCMake/list/TRANSFORM-PREPEND-NoArguments-stderr.txt new file mode 100644 index 0000000..413ce30 --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-PREPEND-NoArguments-stderr.txt @@ -0,0 +1,4 @@ +^CMake Error at TRANSFORM-PREPEND-NoArguments.cmake:2 \(list\): + list sub-command TRANSFORM, action PREPEND expects 1 argument\(s\). +Call Stack \(most recent call first\): + CMakeLists.txt:3 \(include\)$ diff --git a/Tests/RunCMake/list/TRANSFORM-PREPEND-NoArguments.cmake b/Tests/RunCMake/list/TRANSFORM-PREPEND-NoArguments.cmake new file mode 100644 index 0000000..a8e4530 --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-PREPEND-NoArguments.cmake @@ -0,0 +1,2 @@ +set(mylist alpha bravo charlie) +list(TRANSFORM mylist PREPEND) diff --git a/Tests/RunCMake/list/TRANSFORM-PREPEND-TooManyArguments-result.txt b/Tests/RunCMake/list/TRANSFORM-PREPEND-TooManyArguments-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-PREPEND-TooManyArguments-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/list/TRANSFORM-PREPEND-TooManyArguments-stderr.txt b/Tests/RunCMake/list/TRANSFORM-PREPEND-TooManyArguments-stderr.txt new file mode 100644 index 0000000..6ff1b89 --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-PREPEND-TooManyArguments-stderr.txt @@ -0,0 +1,4 @@ +^CMake Error at TRANSFORM-PREPEND-TooManyArguments.cmake:2 \(list\): + list sub-command TRANSFORM, 'one_too_many': unexpected argument\(s\). +Call Stack \(most recent call first\): + CMakeLists.txt:3 \(include\)$ diff --git a/Tests/RunCMake/list/TRANSFORM-PREPEND-TooManyArguments.cmake b/Tests/RunCMake/list/TRANSFORM-PREPEND-TooManyArguments.cmake new file mode 100644 index 0000000..1f904ad --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-PREPEND-TooManyArguments.cmake @@ -0,0 +1,2 @@ +set(mylist alpha bravo charlie) +list(TRANSFORM mylist PREPEND delta one_too_many) diff --git a/Tests/RunCMake/list/TRANSFORM-PREPEND.cmake b/Tests/RunCMake/list/TRANSFORM-PREPEND.cmake new file mode 100644 index 0000000..55b8867 --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-PREPEND.cmake @@ -0,0 +1,48 @@ +set(mylist alpha bravo charlie delta) + +list(TRANSFORM mylist PREPEND "P_" OUTPUT_VARIABLE output) +if (NOT output STREQUAL "P_alpha;P_bravo;P_charlie;P_delta") + message (FATAL_ERROR "TRANSFORM(PREPEND) is \"${output}\", expected is \"P_alpha;P_bravo;P_charlie;P_delta\"") +endif() + +unset(output) +list(TRANSFORM mylist PREPEND "P_" AT 1 3 OUTPUT_VARIABLE output) +if (NOT output STREQUAL "alpha;P_bravo;charlie;P_delta") + message (FATAL_ERROR "TRANSFORM(PREPEND) is \"${output}\", expected is \"alpha;P_bravo;charlie;P_delta\"") +endif() + +unset(output) +list(TRANSFORM mylist PREPEND "P_" AT 1 -2 OUTPUT_VARIABLE output) +if (NOT output STREQUAL "alpha;P_bravo;P_charlie;delta") + message (FATAL_ERROR "TRANSFORM(PREPEND) is \"${output}\", expected is \"alpha;P_bravo;P_charlie;delta\"") +endif() + +unset(output) +list(TRANSFORM mylist PREPEND "P_" FOR 1 2 OUTPUT_VARIABLE output) +if (NOT output STREQUAL "alpha;P_bravo;P_charlie;delta") + message (FATAL_ERROR "TRANSFORM(PREPEND) is \"${output}\", expected is \"alpha;P_bravo;P_charlie;delta\"") +endif() + +unset(output) +list(TRANSFORM mylist PREPEND "P_" FOR 1 -1 OUTPUT_VARIABLE output) +if (NOT output STREQUAL "alpha;P_bravo;P_charlie;P_delta") + message (FATAL_ERROR "TRANSFORM(PREPEND) is \"${output}\", expected is \"alpha;P_bravo;P_charlie;P_delta\"") +endif() + +unset(output) +list(TRANSFORM mylist PREPEND "P_" FOR 0 -1 2 OUTPUT_VARIABLE output) +if (NOT output STREQUAL "P_alpha;bravo;P_charlie;delta") + message (FATAL_ERROR "TRANSFORM(PREPEND) is \"${output}\", expected is \"P_alpha;bravo;P_charlie;delta\"") +endif() + +unset(output) +list(TRANSFORM mylist PREPEND "P_" REGEX "(r|t)a" OUTPUT_VARIABLE output) +if (NOT output STREQUAL "alpha;P_bravo;charlie;P_delta") + message (FATAL_ERROR "TRANSFORM(PREPEND) is \"${output}\", expected is \"alpha;P_bravo;charlie;P_delta\"") +endif() + +unset(output) +list(TRANSFORM mylist PREPEND "P_" REGEX "(r|t)a") +if (NOT mylist STREQUAL "alpha;P_bravo;charlie;P_delta") + message (FATAL_ERROR "TRANSFORM(PREPEND) is \"${mylist}\", expected is \"alpha;P_bravo;charlie;P_delta\"") +endif() diff --git a/Tests/RunCMake/list/TRANSFORM-REPLACE-InvalidRegex-result.txt b/Tests/RunCMake/list/TRANSFORM-REPLACE-InvalidRegex-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-REPLACE-InvalidRegex-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/list/TRANSFORM-REPLACE-InvalidRegex-stderr.txt b/Tests/RunCMake/list/TRANSFORM-REPLACE-InvalidRegex-stderr.txt new file mode 100644 index 0000000..334c96e --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-REPLACE-InvalidRegex-stderr.txt @@ -0,0 +1,5 @@ +^CMake Error at TRANSFORM-REPLACE-InvalidRegex.cmake:2 \(list\): + list sub-command TRANSFORM, action REPLACE: Failed to compile regex + "\^\(alpha\$". +Call Stack \(most recent call first\): + CMakeLists.txt:3 \(include\)$ diff --git a/Tests/RunCMake/list/TRANSFORM-REPLACE-InvalidRegex.cmake b/Tests/RunCMake/list/TRANSFORM-REPLACE-InvalidRegex.cmake new file mode 100644 index 0000000..f440c35 --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-REPLACE-InvalidRegex.cmake @@ -0,0 +1,2 @@ +set(mylist alpha bravo charlie) +list(TRANSFORM mylist REPLACE "^(alpha$" "zulu") diff --git a/Tests/RunCMake/list/TRANSFORM-REPLACE-InvalidReplace-result.txt b/Tests/RunCMake/list/TRANSFORM-REPLACE-InvalidReplace-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-REPLACE-InvalidReplace-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/list/TRANSFORM-REPLACE-InvalidReplace1-result.txt b/Tests/RunCMake/list/TRANSFORM-REPLACE-InvalidReplace1-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-REPLACE-InvalidReplace1-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/list/TRANSFORM-REPLACE-InvalidReplace1-stderr.txt b/Tests/RunCMake/list/TRANSFORM-REPLACE-InvalidReplace1-stderr.txt new file mode 100644 index 0000000..7671c83 --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-REPLACE-InvalidReplace1-stderr.txt @@ -0,0 +1,5 @@ +^CMake Error at TRANSFORM-REPLACE-InvalidReplace1.cmake:2 \(list\): + list sub-command TRANSFORM, action REPLACE: replace-expression ends in a + backslash. +Call Stack \(most recent call first\): + CMakeLists.txt:3 \(include\)$ diff --git a/Tests/RunCMake/list/TRANSFORM-REPLACE-InvalidReplace1.cmake b/Tests/RunCMake/list/TRANSFORM-REPLACE-InvalidReplace1.cmake new file mode 100644 index 0000000..35387f0 --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-REPLACE-InvalidReplace1.cmake @@ -0,0 +1,2 @@ +set(mylist alpha bravo charlie) +list(TRANSFORM mylist REPLACE "^alpha$" "zulu\\") diff --git a/Tests/RunCMake/list/TRANSFORM-REPLACE-InvalidReplace2-result.txt b/Tests/RunCMake/list/TRANSFORM-REPLACE-InvalidReplace2-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-REPLACE-InvalidReplace2-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/list/TRANSFORM-REPLACE-InvalidReplace2-stderr.txt b/Tests/RunCMake/list/TRANSFORM-REPLACE-InvalidReplace2-stderr.txt new file mode 100644 index 0000000..e0aabd7 --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-REPLACE-InvalidReplace2-stderr.txt @@ -0,0 +1,5 @@ +^CMake Error at TRANSFORM-REPLACE-InvalidReplace2.cmake:2 \(list\): + list sub-command TRANSFORM, action REPLACE: Unknown escape "\\z" in + replace-expression. +Call Stack \(most recent call first\): + CMakeLists.txt:3 \(include\)$ diff --git a/Tests/RunCMake/list/TRANSFORM-REPLACE-InvalidReplace2.cmake b/Tests/RunCMake/list/TRANSFORM-REPLACE-InvalidReplace2.cmake new file mode 100644 index 0000000..2f1f2c7 --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-REPLACE-InvalidReplace2.cmake @@ -0,0 +1,2 @@ +set(mylist alpha bravo charlie) +list(TRANSFORM mylist REPLACE "^alpha$" "\\zulu") diff --git a/Tests/RunCMake/list/TRANSFORM-REPLACE-NoArguments-result.txt b/Tests/RunCMake/list/TRANSFORM-REPLACE-NoArguments-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-REPLACE-NoArguments-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/list/TRANSFORM-REPLACE-NoArguments-stderr.txt b/Tests/RunCMake/list/TRANSFORM-REPLACE-NoArguments-stderr.txt new file mode 100644 index 0000000..3d39e72 --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-REPLACE-NoArguments-stderr.txt @@ -0,0 +1,4 @@ +^CMake Error at TRANSFORM-REPLACE-NoArguments.cmake:2 \(list\): + list sub-command TRANSFORM, action REPLACE expects 2 argument\(s\). +Call Stack \(most recent call first\): + CMakeLists.txt:3 \(include\)$ diff --git a/Tests/RunCMake/list/TRANSFORM-REPLACE-NoArguments.cmake b/Tests/RunCMake/list/TRANSFORM-REPLACE-NoArguments.cmake new file mode 100644 index 0000000..b7b1e9d --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-REPLACE-NoArguments.cmake @@ -0,0 +1,2 @@ +set(mylist alpha bravo charlie) +list(TRANSFORM mylist REPLACE) diff --git a/Tests/RunCMake/list/TRANSFORM-REPLACE-NoEnoughArguments-result.txt b/Tests/RunCMake/list/TRANSFORM-REPLACE-NoEnoughArguments-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-REPLACE-NoEnoughArguments-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/list/TRANSFORM-REPLACE-NoEnoughArguments-stderr.txt b/Tests/RunCMake/list/TRANSFORM-REPLACE-NoEnoughArguments-stderr.txt new file mode 100644 index 0000000..dc80f33 --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-REPLACE-NoEnoughArguments-stderr.txt @@ -0,0 +1,4 @@ +^CMake Error at TRANSFORM-REPLACE-NoEnoughArguments.cmake:2 \(list\): + list sub-command TRANSFORM, action REPLACE expects 2 argument\(s\). +Call Stack \(most recent call first\): + CMakeLists.txt:3 \(include\)$ diff --git a/Tests/RunCMake/list/TRANSFORM-REPLACE-NoEnoughArguments.cmake b/Tests/RunCMake/list/TRANSFORM-REPLACE-NoEnoughArguments.cmake new file mode 100644 index 0000000..1d418c0 --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-REPLACE-NoEnoughArguments.cmake @@ -0,0 +1,2 @@ +set(mylist alpha bravo charlie) +list(TRANSFORM mylist REPLACE "^alpha$") diff --git a/Tests/RunCMake/list/TRANSFORM-REPLACE-TooManyArguments-result.txt b/Tests/RunCMake/list/TRANSFORM-REPLACE-TooManyArguments-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-REPLACE-TooManyArguments-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/list/TRANSFORM-REPLACE-TooManyArguments-stderr.txt b/Tests/RunCMake/list/TRANSFORM-REPLACE-TooManyArguments-stderr.txt new file mode 100644 index 0000000..3d4e15a --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-REPLACE-TooManyArguments-stderr.txt @@ -0,0 +1,4 @@ +^CMake Error at TRANSFORM-REPLACE-TooManyArguments.cmake:2 \(list\): + list sub-command TRANSFORM, 'one_too_many': unexpected argument\(s\). +Call Stack \(most recent call first\): + CMakeLists.txt:3 \(include\)$ diff --git a/Tests/RunCMake/list/TRANSFORM-REPLACE-TooManyArguments.cmake b/Tests/RunCMake/list/TRANSFORM-REPLACE-TooManyArguments.cmake new file mode 100644 index 0000000..baed0af --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-REPLACE-TooManyArguments.cmake @@ -0,0 +1,2 @@ +set(mylist alpha bravo charlie) +list(TRANSFORM mylist REPLACE "^alpha$" "zulu" "one_too_many") diff --git a/Tests/RunCMake/list/TRANSFORM-REPLACE.cmake b/Tests/RunCMake/list/TRANSFORM-REPLACE.cmake new file mode 100644 index 0000000..256b1b8 --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-REPLACE.cmake @@ -0,0 +1,48 @@ +set(mylist alpha bravo charlie delta) + +list(TRANSFORM mylist REPLACE "(.+a)$" "\\1_\\1" OUTPUT_VARIABLE output) +if (NOT output STREQUAL "alpha_alpha;bravo;charlie;delta_delta") + message (FATAL_ERROR "TRANSFORM(REPLACE) is \"${output}\", expected is \"alpha_alpha;bravo;charlie;delta_delta\"") +endif() + +unset(output) +list(TRANSFORM mylist REPLACE "(.+a)$" "\\1_\\1" AT 1 3 OUTPUT_VARIABLE output) +if (NOT output STREQUAL "alpha;bravo;charlie;delta_delta") + message (FATAL_ERROR "TRANSFORM(REPLACE) is \"${output}\", expected is \"alpha;bravo;charlie;delta_delta\"") +endif() + +unset(output) +list(TRANSFORM mylist REPLACE "(.+e)$" "\\1_\\1" AT 1 -2 OUTPUT_VARIABLE output) +if (NOT output STREQUAL "alpha;bravo;charlie_charlie;delta") + message (FATAL_ERROR "TRANSFORM(REPLACE) is \"${output}\", expected is \"alpha;bravo;charlie_charlie;delta\"") +endif() + +unset(output) +list(TRANSFORM mylist REPLACE "(.+e)$" "\\1_\\1" FOR 1 2 OUTPUT_VARIABLE output) +if (NOT output STREQUAL "alpha;bravo;charlie_charlie;delta") + message (FATAL_ERROR "TRANSFORM(REPLACE) is \"${output}\", expected is \"alpha;bravo;charlie_charlie;delta\"") +endif() + +unset(output) +list(TRANSFORM mylist REPLACE "(.+a)$" "\\1_\\1" FOR 1 -1 OUTPUT_VARIABLE output) +if (NOT output STREQUAL "alpha;bravo;charlie;delta_delta") + message (FATAL_ERROR "TRANSFORM(REPLACE) is \"${output}\", expected is \"alpha;bravo;charlie_A;delta_delta\"") +endif() + +unset(output) +list(TRANSFORM mylist REPLACE "(.+a)$" "\\1_\\1" FOR 0 -1 2 OUTPUT_VARIABLE output) +if (NOT output STREQUAL "alpha_alpha;bravo;charlie;delta") + message (FATAL_ERROR "TRANSFORM(REPLACE) is \"${output}\", expected is \"alpha_alpha;bravo;charlie;delta\"") +endif() + +unset(output) +list(TRANSFORM mylist REPLACE "(.+a)$" "\\1_\\1" REGEX "(r|t)a" OUTPUT_VARIABLE output) +if (NOT output STREQUAL "alpha;bravo;charlie;delta_delta") + message (FATAL_ERROR "TRANSFORM(REPLACE) is \"${output}\", expected is \"alpha;bravo;charlie;delta_delta\"") +endif() + +unset(output) +list(TRANSFORM mylist REPLACE "(.+a)$" "\\1_\\1" REGEX "(r|t)a") +if (NOT mylist STREQUAL "alpha;bravo;charlie;delta_delta") + message (FATAL_ERROR "TRANSFORM(REPLACE) is \"${mylist}\", expected is \"alpha;bravo;charlie;delta_delta\"") +endif() diff --git a/Tests/RunCMake/list/TRANSFORM-STRIP-TooManyArguments-result.txt b/Tests/RunCMake/list/TRANSFORM-STRIP-TooManyArguments-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-STRIP-TooManyArguments-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/list/TRANSFORM-STRIP-TooManyArguments-stderr.txt b/Tests/RunCMake/list/TRANSFORM-STRIP-TooManyArguments-stderr.txt new file mode 100644 index 0000000..534f940 --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-STRIP-TooManyArguments-stderr.txt @@ -0,0 +1,4 @@ +^CMake Error at TRANSFORM-STRIP-TooManyArguments.cmake:2 \(list\): + list sub-command TRANSFORM, 'one_too_many': unexpected argument\(s\). +Call Stack \(most recent call first\): + CMakeLists.txt:3 \(include\)$ diff --git a/Tests/RunCMake/list/TRANSFORM-STRIP-TooManyArguments.cmake b/Tests/RunCMake/list/TRANSFORM-STRIP-TooManyArguments.cmake new file mode 100644 index 0000000..c6a8213 --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-STRIP-TooManyArguments.cmake @@ -0,0 +1,2 @@ +set(mylist alpha bravo charlie) +list(TRANSFORM mylist STRIP one_too_many) diff --git a/Tests/RunCMake/list/TRANSFORM-STRIP.cmake b/Tests/RunCMake/list/TRANSFORM-STRIP.cmake new file mode 100644 index 0000000..366c63a --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-STRIP.cmake @@ -0,0 +1,49 @@ +set(mylist " alpha" "bravo " " charlie " delta) + +list(TRANSFORM mylist STRIP OUTPUT_VARIABLE output) +if (NOT output STREQUAL "alpha;bravo;charlie;delta") + message (FATAL_ERROR "TRANSFORM(STRIP) is \"${output}\", expected is \"alpha;bravo;charlie;delta\"") +endif() + +set(mylist " alpha" "bravo " " charlie " "delta ") +unset(output) +list(TRANSFORM mylist STRIP AT 1 3 OUTPUT_VARIABLE output) +if (NOT output STREQUAL " alpha;bravo; charlie ;delta") + message (FATAL_ERROR "TRANSFORM(STRIP) is \"${output}\", expected is \" alpha;bravo; charlie ;delta\"") +endif() + +unset(output) +list(TRANSFORM mylist STRIP AT 1 -2 OUTPUT_VARIABLE output) +if (NOT output STREQUAL " alpha;bravo;charlie;delta ") + message (FATAL_ERROR "TRANSFORM(STRIP) is \"${output}\", expected is \" alpha;bravo;charlie;delta \"") +endif() + +unset(output) +list(TRANSFORM mylist STRIP FOR 1 2 OUTPUT_VARIABLE output) +if (NOT output STREQUAL " alpha;bravo;charlie;delta ") + message (FATAL_ERROR "TRANSFORM(STRIP) is \"${output}\", expected is \" alpha;bravo;charlie;delta \"") +endif() + +unset(output) +list(TRANSFORM mylist STRIP FOR 1 -1 OUTPUT_VARIABLE output) +if (NOT output STREQUAL " alpha;bravo;charlie;delta") + message (FATAL_ERROR "TRANSFORM(STRIP) is \"${output}\", expected is \" alpha;bravo;charlie;delta\"") +endif() + +unset(output) +list(TRANSFORM mylist STRIP FOR 0 -1 2 OUTPUT_VARIABLE output) +if (NOT output STREQUAL "alpha;bravo ;charlie;delta ") + message (FATAL_ERROR "TRANSFORM(STRIP) is \"${output}\", expected is \"alpha;bravo ;charlie;delta \"") +endif() + +unset(output) +list(TRANSFORM mylist STRIP REGEX "(r|t)a" OUTPUT_VARIABLE output) +if (NOT output STREQUAL " alpha;bravo; charlie ;delta") + message (FATAL_ERROR "TRANSFORM(STRIP) is \"${output}\", expected is \" alpha;bravo; charlie ;delta\"") +endif() + +unset(output) +list(TRANSFORM mylist STRIP REGEX "(r|t)a") +if (NOT mylist STREQUAL " alpha;bravo; charlie ;delta") + message (FATAL_ERROR "TRANSFORM(STRIP) is \"${mylist}\", expected is \" alpha;bravo; charlie ;delta\"") +endif() diff --git a/Tests/RunCMake/list/TRANSFORM-Selector-AT-BadArgument-result.txt b/Tests/RunCMake/list/TRANSFORM-Selector-AT-BadArgument-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-Selector-AT-BadArgument-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/list/TRANSFORM-Selector-AT-BadArgument-stderr.txt b/Tests/RunCMake/list/TRANSFORM-Selector-AT-BadArgument-stderr.txt new file mode 100644 index 0000000..cec520f --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-Selector-AT-BadArgument-stderr.txt @@ -0,0 +1,4 @@ +^CMake Error at TRANSFORM-Selector-AT-BadArgument.cmake:2 \(list\): + list sub-command TRANSFORM, '1x 2': unexpected argument\(s\). +Call Stack \(most recent call first\): + CMakeLists.txt:3 \(include\)$ diff --git a/Tests/RunCMake/list/TRANSFORM-Selector-AT-BadArgument.cmake b/Tests/RunCMake/list/TRANSFORM-Selector-AT-BadArgument.cmake new file mode 100644 index 0000000..f61b86b --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-Selector-AT-BadArgument.cmake @@ -0,0 +1,2 @@ +set(mylist alpha bravo charlie) +list(TRANSFORM mylist TOUPPER AT 0 1x 2) diff --git a/Tests/RunCMake/list/TRANSFORM-Selector-AT-InvalidIndex-result.txt b/Tests/RunCMake/list/TRANSFORM-Selector-AT-InvalidIndex-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-Selector-AT-InvalidIndex-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/list/TRANSFORM-Selector-AT-InvalidIndex-stderr.txt b/Tests/RunCMake/list/TRANSFORM-Selector-AT-InvalidIndex-stderr.txt new file mode 100644 index 0000000..7e2898b --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-Selector-AT-InvalidIndex-stderr.txt @@ -0,0 +1,4 @@ +^CMake Error at TRANSFORM-Selector-AT-InvalidIndex.cmake:2 \(list\): + list sub-command TRANSFORM, selector AT, index: 3 out of range \(-3, 2\). +Call Stack \(most recent call first\): + CMakeLists.txt:3 \(include\)$ diff --git a/Tests/RunCMake/list/TRANSFORM-Selector-AT-InvalidIndex.cmake b/Tests/RunCMake/list/TRANSFORM-Selector-AT-InvalidIndex.cmake new file mode 100644 index 0000000..d33586c --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-Selector-AT-InvalidIndex.cmake @@ -0,0 +1,2 @@ +set(mylist alpha bravo charlie) +list(TRANSFORM mylist TOUPPER AT 0 3 2) diff --git a/Tests/RunCMake/list/TRANSFORM-Selector-AT-NoArguments-result.txt b/Tests/RunCMake/list/TRANSFORM-Selector-AT-NoArguments-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-Selector-AT-NoArguments-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/list/TRANSFORM-Selector-AT-NoArguments-stderr.txt b/Tests/RunCMake/list/TRANSFORM-Selector-AT-NoArguments-stderr.txt new file mode 100644 index 0000000..eaf5281 --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-Selector-AT-NoArguments-stderr.txt @@ -0,0 +1,4 @@ +^CMake Error at TRANSFORM-Selector-AT-NoArguments.cmake:2 \(list\): + list sub-command TRANSFORM, selector AT expects at least one numeric value. +Call Stack \(most recent call first\): + CMakeLists.txt:3 \(include\)$ diff --git a/Tests/RunCMake/list/TRANSFORM-Selector-AT-NoArguments.cmake b/Tests/RunCMake/list/TRANSFORM-Selector-AT-NoArguments.cmake new file mode 100644 index 0000000..052b79b --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-Selector-AT-NoArguments.cmake @@ -0,0 +1,2 @@ +set(mylist alpha bravo charlie) +list(TRANSFORM mylist TOUPPER AT) diff --git a/Tests/RunCMake/list/TRANSFORM-Selector-FOR-BadArgument-result.txt b/Tests/RunCMake/list/TRANSFORM-Selector-FOR-BadArgument-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-Selector-FOR-BadArgument-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/list/TRANSFORM-Selector-FOR-BadArgument-stderr.txt b/Tests/RunCMake/list/TRANSFORM-Selector-FOR-BadArgument-stderr.txt new file mode 100644 index 0000000..a0f701f --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-Selector-FOR-BadArgument-stderr.txt @@ -0,0 +1,5 @@ +^CMake Error at TRANSFORM-Selector-FOR-BadArgument.cmake:2 \(list\): + list sub-command TRANSFORM, selector FOR expects, at least, two numeric + values. +Call Stack \(most recent call first\): + CMakeLists.txt:3 \(include\)$ diff --git a/Tests/RunCMake/list/TRANSFORM-Selector-FOR-BadArgument.cmake b/Tests/RunCMake/list/TRANSFORM-Selector-FOR-BadArgument.cmake new file mode 100644 index 0000000..55527be --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-Selector-FOR-BadArgument.cmake @@ -0,0 +1,2 @@ +set(mylist alpha bravo charlie) +list(TRANSFORM mylist TOUPPER FOR 0 1x 2) diff --git a/Tests/RunCMake/list/TRANSFORM-Selector-FOR-InvalidIndex-result.txt b/Tests/RunCMake/list/TRANSFORM-Selector-FOR-InvalidIndex-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-Selector-FOR-InvalidIndex-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/list/TRANSFORM-Selector-FOR-InvalidIndex-stderr.txt b/Tests/RunCMake/list/TRANSFORM-Selector-FOR-InvalidIndex-stderr.txt new file mode 100644 index 0000000..c50cc0a --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-Selector-FOR-InvalidIndex-stderr.txt @@ -0,0 +1,4 @@ +^CMake Error at TRANSFORM-Selector-FOR-InvalidIndex.cmake:2 \(list\): + list sub-command TRANSFORM, selector FOR, index: 6 out of range \(-3, 2\). +Call Stack \(most recent call first\): + CMakeLists.txt:3 \(include\)$ diff --git a/Tests/RunCMake/list/TRANSFORM-Selector-FOR-InvalidIndex.cmake b/Tests/RunCMake/list/TRANSFORM-Selector-FOR-InvalidIndex.cmake new file mode 100644 index 0000000..6e2374e --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-Selector-FOR-InvalidIndex.cmake @@ -0,0 +1,2 @@ +set(mylist alpha bravo charlie) +list(TRANSFORM mylist TOUPPER FOR 0 6 2) diff --git a/Tests/RunCMake/list/TRANSFORM-Selector-FOR-NoArguments-result.txt b/Tests/RunCMake/list/TRANSFORM-Selector-FOR-NoArguments-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-Selector-FOR-NoArguments-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/list/TRANSFORM-Selector-FOR-NoArguments-stderr.txt b/Tests/RunCMake/list/TRANSFORM-Selector-FOR-NoArguments-stderr.txt new file mode 100644 index 0000000..5881b67 --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-Selector-FOR-NoArguments-stderr.txt @@ -0,0 +1,4 @@ +^CMake Error at TRANSFORM-Selector-FOR-NoArguments.cmake:2 \(list\): + list sub-command TRANSFORM, selector FOR expects, at least, two arguments. +Call Stack \(most recent call first\): + CMakeLists.txt:3 \(include\)$ diff --git a/Tests/RunCMake/list/TRANSFORM-Selector-FOR-NoArguments.cmake b/Tests/RunCMake/list/TRANSFORM-Selector-FOR-NoArguments.cmake new file mode 100644 index 0000000..4902cc9 --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-Selector-FOR-NoArguments.cmake @@ -0,0 +1,2 @@ +set(mylist alpha bravo charlie) +list(TRANSFORM mylist TOUPPER FOR) diff --git a/Tests/RunCMake/list/TRANSFORM-Selector-FOR-NoEnoughArguments-result.txt b/Tests/RunCMake/list/TRANSFORM-Selector-FOR-NoEnoughArguments-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-Selector-FOR-NoEnoughArguments-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/list/TRANSFORM-Selector-FOR-NoEnoughArguments-stderr.txt b/Tests/RunCMake/list/TRANSFORM-Selector-FOR-NoEnoughArguments-stderr.txt new file mode 100644 index 0000000..b1081d9 --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-Selector-FOR-NoEnoughArguments-stderr.txt @@ -0,0 +1,4 @@ +^CMake Error at TRANSFORM-Selector-FOR-NoEnoughArguments.cmake:2 \(list\): + list sub-command TRANSFORM, selector FOR expects, at least, two arguments. +Call Stack \(most recent call first\): + CMakeLists.txt:3 \(include\)$ diff --git a/Tests/RunCMake/list/TRANSFORM-Selector-FOR-NoEnoughArguments.cmake b/Tests/RunCMake/list/TRANSFORM-Selector-FOR-NoEnoughArguments.cmake new file mode 100644 index 0000000..81417de --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-Selector-FOR-NoEnoughArguments.cmake @@ -0,0 +1,2 @@ +set(mylist alpha bravo charlie) +list(TRANSFORM mylist TOUPPER FOR 1) diff --git a/Tests/RunCMake/list/TRANSFORM-Selector-FOR-TooManyArguments-result.txt b/Tests/RunCMake/list/TRANSFORM-Selector-FOR-TooManyArguments-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-Selector-FOR-TooManyArguments-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/list/TRANSFORM-Selector-FOR-TooManyArguments-stderr.txt b/Tests/RunCMake/list/TRANSFORM-Selector-FOR-TooManyArguments-stderr.txt new file mode 100644 index 0000000..2221cb3 --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-Selector-FOR-TooManyArguments-stderr.txt @@ -0,0 +1,4 @@ +^CMake Error at TRANSFORM-Selector-FOR-TooManyArguments.cmake:2 \(list\): + list sub-command TRANSFORM, '3': unexpected argument\(s\). +Call Stack \(most recent call first\): + CMakeLists.txt:3 \(include\)$ diff --git a/Tests/RunCMake/list/TRANSFORM-Selector-FOR-TooManyArguments.cmake b/Tests/RunCMake/list/TRANSFORM-Selector-FOR-TooManyArguments.cmake new file mode 100644 index 0000000..80917d6 --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-Selector-FOR-TooManyArguments.cmake @@ -0,0 +1,2 @@ +set(mylist alpha bravo charlie) +list(TRANSFORM mylist TOUPPER FOR 0 1 2 3) diff --git a/Tests/RunCMake/list/TRANSFORM-Selector-REGEX-InvalidRegex-result.txt b/Tests/RunCMake/list/TRANSFORM-Selector-REGEX-InvalidRegex-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-Selector-REGEX-InvalidRegex-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/list/TRANSFORM-Selector-REGEX-InvalidRegex-stderr.txt b/Tests/RunCMake/list/TRANSFORM-Selector-REGEX-InvalidRegex-stderr.txt new file mode 100644 index 0000000..31ba939 --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-Selector-REGEX-InvalidRegex-stderr.txt @@ -0,0 +1,5 @@ +^CMake Error at TRANSFORM-Selector-REGEX-InvalidRegex.cmake:2 \(list\): + list sub-command TRANSFORM, selector REGEX failed to compile regex + "\^\(alpha\$". +Call Stack \(most recent call first\): + CMakeLists.txt:3 \(include\)$ diff --git a/Tests/RunCMake/list/TRANSFORM-Selector-REGEX-InvalidRegex.cmake b/Tests/RunCMake/list/TRANSFORM-Selector-REGEX-InvalidRegex.cmake new file mode 100644 index 0000000..56e202b --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-Selector-REGEX-InvalidRegex.cmake @@ -0,0 +1,2 @@ +set(mylist alpha bravo charlie) +list(TRANSFORM mylist TOUPPER REGEX "^(alpha$") diff --git a/Tests/RunCMake/list/TRANSFORM-Selector-REGEX-NoArguments-result.txt b/Tests/RunCMake/list/TRANSFORM-Selector-REGEX-NoArguments-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-Selector-REGEX-NoArguments-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/list/TRANSFORM-Selector-REGEX-NoArguments-stderr.txt b/Tests/RunCMake/list/TRANSFORM-Selector-REGEX-NoArguments-stderr.txt new file mode 100644 index 0000000..2784785 --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-Selector-REGEX-NoArguments-stderr.txt @@ -0,0 +1,5 @@ +^CMake Error at TRANSFORM-Selector-REGEX-NoArguments.cmake:2 \(list\): + list sub-command TRANSFORM, selector REGEX expects 'regular expression' + argument. +Call Stack \(most recent call first\): + CMakeLists.txt:3 \(include\)$ diff --git a/Tests/RunCMake/list/TRANSFORM-Selector-REGEX-NoArguments.cmake b/Tests/RunCMake/list/TRANSFORM-Selector-REGEX-NoArguments.cmake new file mode 100644 index 0000000..f199d0e --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-Selector-REGEX-NoArguments.cmake @@ -0,0 +1,2 @@ +set(mylist alpha bravo charlie) +list(TRANSFORM mylist TOUPPER REGEX) diff --git a/Tests/RunCMake/list/TRANSFORM-Selector-REGEX-TooManyArguments-result.txt b/Tests/RunCMake/list/TRANSFORM-Selector-REGEX-TooManyArguments-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-Selector-REGEX-TooManyArguments-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/list/TRANSFORM-Selector-REGEX-TooManyArguments-stderr.txt b/Tests/RunCMake/list/TRANSFORM-Selector-REGEX-TooManyArguments-stderr.txt new file mode 100644 index 0000000..db5b1ff --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-Selector-REGEX-TooManyArguments-stderr.txt @@ -0,0 +1,4 @@ +^CMake Error at TRANSFORM-Selector-REGEX-TooManyArguments.cmake:2 \(list\): + list sub-command TRANSFORM, 'one_too_many': unexpected argument\(s\). +Call Stack \(most recent call first\): + CMakeLists.txt:3 \(include\)$ diff --git a/Tests/RunCMake/list/TRANSFORM-Selector-REGEX-TooManyArguments.cmake b/Tests/RunCMake/list/TRANSFORM-Selector-REGEX-TooManyArguments.cmake new file mode 100644 index 0000000..4aa1619 --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-Selector-REGEX-TooManyArguments.cmake @@ -0,0 +1,2 @@ +set(mylist alpha bravo charlie) +list(TRANSFORM mylist TOUPPER REGEX "^alpha$" "one_too_many") diff --git a/Tests/RunCMake/list/TRANSFORM-TOLOWER-TooManyArguments-result.txt b/Tests/RunCMake/list/TRANSFORM-TOLOWER-TooManyArguments-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-TOLOWER-TooManyArguments-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/list/TRANSFORM-TOLOWER-TooManyArguments-stderr.txt b/Tests/RunCMake/list/TRANSFORM-TOLOWER-TooManyArguments-stderr.txt new file mode 100644 index 0000000..90248ae --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-TOLOWER-TooManyArguments-stderr.txt @@ -0,0 +1,4 @@ +^CMake Error at TRANSFORM-TOLOWER-TooManyArguments.cmake:2 \(list\): + list sub-command TRANSFORM, 'one_too_many': unexpected argument\(s\). +Call Stack \(most recent call first\): + CMakeLists.txt:3 \(include\)$ diff --git a/Tests/RunCMake/list/TRANSFORM-TOLOWER-TooManyArguments.cmake b/Tests/RunCMake/list/TRANSFORM-TOLOWER-TooManyArguments.cmake new file mode 100644 index 0000000..1758e19 --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-TOLOWER-TooManyArguments.cmake @@ -0,0 +1,2 @@ +set(mylist alpha bravo charlie) +list(TRANSFORM mylist TOLOWER one_too_many) diff --git a/Tests/RunCMake/list/TRANSFORM-TOLOWER.cmake b/Tests/RunCMake/list/TRANSFORM-TOLOWER.cmake new file mode 100644 index 0000000..a2d7348 --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-TOLOWER.cmake @@ -0,0 +1,48 @@ +set(mylist ALPHA BRAVO CHARLIE DELTA) + +list(TRANSFORM mylist TOLOWER OUTPUT_VARIABLE output) +if (NOT output STREQUAL "alpha;bravo;charlie;delta") + message (FATAL_ERROR "TRANSFORM(TOLOWER) is \"${output}\", expected is \"alpha;bravo;charlie;delta\"") +endif() + +unset(output) +list(TRANSFORM mylist TOLOWER AT 1 3 OUTPUT_VARIABLE output) +if (NOT output STREQUAL "ALPHA;bravo;CHARLIE;delta") + message (FATAL_ERROR "TRANSFORM(TOLOWER) is \"${output}\", expected is \"ALPHA;bravo;CHARLIE;delta\"") +endif() + +unset(output) +list(TRANSFORM mylist TOLOWER AT 1 -2 OUTPUT_VARIABLE output) +if (NOT output STREQUAL "ALPHA;bravo;charlie;DELTA") + message (FATAL_ERROR "TRANSFORM(TOLOWER) is \"${output}\", expected is \"ALPHA;bravo;charlie;DELTA\"") +endif() + +unset(output) +list(TRANSFORM mylist TOLOWER FOR 1 2 OUTPUT_VARIABLE output) +if (NOT output STREQUAL "ALPHA;bravo;charlie;DELTA") + message (FATAL_ERROR "TRANSFORM(TOLOWER) is \"${output}\", expected is \"ALPHA;bravo;charlie;DELTA\"") +endif() + +unset(output) +list(TRANSFORM mylist TOLOWER FOR 1 -1 OUTPUT_VARIABLE output) +if (NOT output STREQUAL "ALPHA;bravo;charlie;delta") + message (FATAL_ERROR "TRANSFORM(TOLOWER) is \"${output}\", expected is \"ALPHA;bravo;charlie;delta\"") +endif() + +unset(output) +list(TRANSFORM mylist TOLOWER FOR 0 -1 2 OUTPUT_VARIABLE output) +if (NOT output STREQUAL "alpha;BRAVO;charlie;DELTA") + message (FATAL_ERROR "TRANSFORM(TOLOWER) is \"${output}\", expected is \"alpha;BRAVO;charlie;DELTA\"") +endif() + +unset(output) +list(TRANSFORM mylist TOLOWER REGEX "(R|T)A" OUTPUT_VARIABLE output) +if (NOT output STREQUAL "ALPHA;bravo;CHARLIE;delta") + message (FATAL_ERROR "TRANSFORM(TOLOWER) is \"${output}\", expected is \"ALPHA;bravo;CHARLIE;delta\"") +endif() + +unset(output) +list(TRANSFORM mylist TOLOWER REGEX "(R|T)A") +if (NOT mylist STREQUAL "ALPHA;bravo;CHARLIE;delta") + message (FATAL_ERROR "TRANSFORM(TOLOWER) is \"${mylist}\", expected is \"ALPHA;bravo;CHARLIE;delta\"") +endif() diff --git a/Tests/RunCMake/list/TRANSFORM-TOUPPER-TooManyArguments-result.txt b/Tests/RunCMake/list/TRANSFORM-TOUPPER-TooManyArguments-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-TOUPPER-TooManyArguments-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/list/TRANSFORM-TOUPPER-TooManyArguments-stderr.txt b/Tests/RunCMake/list/TRANSFORM-TOUPPER-TooManyArguments-stderr.txt new file mode 100644 index 0000000..9da241b --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-TOUPPER-TooManyArguments-stderr.txt @@ -0,0 +1,4 @@ +^CMake Error at TRANSFORM-TOUPPER-TooManyArguments.cmake:2 \(list\): + list sub-command TRANSFORM, 'one_too_many': unexpected argument\(s\). +Call Stack \(most recent call first\): + CMakeLists.txt:3 \(include\)$ diff --git a/Tests/RunCMake/list/TRANSFORM-TOUPPER-TooManyArguments.cmake b/Tests/RunCMake/list/TRANSFORM-TOUPPER-TooManyArguments.cmake new file mode 100644 index 0000000..58d6a8c --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-TOUPPER-TooManyArguments.cmake @@ -0,0 +1,2 @@ +set(mylist alpha bravo charlie) +list(TRANSFORM mylist TOUPPER one_too_many) diff --git a/Tests/RunCMake/list/TRANSFORM-TOUPPER.cmake b/Tests/RunCMake/list/TRANSFORM-TOUPPER.cmake new file mode 100644 index 0000000..5b1fcb6 --- /dev/null +++ b/Tests/RunCMake/list/TRANSFORM-TOUPPER.cmake @@ -0,0 +1,48 @@ +set(mylist alpha bravo charlie delta) + +list(TRANSFORM mylist TOUPPER OUTPUT_VARIABLE output) +if (NOT output STREQUAL "ALPHA;BRAVO;CHARLIE;DELTA") + message (FATAL_ERROR "TRANSFORM(TOUPPER) is \"${output}\", expected is \"ALPHA;BRAVO;CHARLIE;DELTA\"") +endif() + +unset(output) +list(TRANSFORM mylist TOUPPER AT 1 3 OUTPUT_VARIABLE output) +if (NOT output STREQUAL "alpha;BRAVO;charlie;DELTA") + message (FATAL_ERROR "TRANSFORM(TOUPPER) is \"${output}\", expected is \"alpha;BRAVO;charlie;DELTA\"") +endif() + +unset(output) +list(TRANSFORM mylist TOUPPER AT 1 -2 OUTPUT_VARIABLE output) +if (NOT output STREQUAL "alpha;BRAVO;CHARLIE;delta") + message (FATAL_ERROR "TRANSFORM(TOUPPER) is \"${output}\", expected is \"alpha;BRAVO;CHARLIE;delta\"") +endif() + +unset(output) +list(TRANSFORM mylist TOUPPER FOR 1 2 OUTPUT_VARIABLE output) +if (NOT output STREQUAL "alpha;BRAVO;CHARLIE;delta") + message (FATAL_ERROR "TRANSFORM(TOUPPER) is \"${output}\", expected is \"alpha;BRAVO;CHARLIE;delta\"") +endif() + +unset(output) +list(TRANSFORM mylist TOUPPER FOR 1 -1 OUTPUT_VARIABLE output) +if (NOT output STREQUAL "alpha;BRAVO;CHARLIE;DELTA") + message (FATAL_ERROR "TRANSFORM(TOUPPER) is \"${output}\", expected is \"alpha;BRAVO;CHARLIE;DELTA\"") +endif() + +unset(output) +list(TRANSFORM mylist TOUPPER FOR 0 -1 2 OUTPUT_VARIABLE output) +if (NOT output STREQUAL "ALPHA;bravo;CHARLIE;delta") + message (FATAL_ERROR "TRANSFORM(TOUPPER) is \"${output}\", expected is \"ALPHA;bravo;CHARLIE;delta\"") +endif() + +unset(output) +list(TRANSFORM mylist TOUPPER REGEX "(r|t)a" OUTPUT_VARIABLE output) +if (NOT output STREQUAL "alpha;BRAVO;charlie;DELTA") + message (FATAL_ERROR "TRANSFORM(TOUPPER) is \"${output}\", expected is \"alpha;BRAVO;charlie;DELTA\"") +endif() + +unset(output) +list(TRANSFORM mylist TOUPPER REGEX "(r|t)a") +if (NOT mylist STREQUAL "alpha;BRAVO;charlie;DELTA") + message (FATAL_ERROR "TRANSFORM(TOUPPER) is \"${mylist}\", expected is \"alpha;BRAVO;charlie;DELTA\"") +endif() diff --git a/Tests/RunCMake/project/LanguagesUnordered-stderr.txt b/Tests/RunCMake/project/LanguagesUnordered-stderr.txt new file mode 100644 index 0000000..5108670 --- /dev/null +++ b/Tests/RunCMake/project/LanguagesUnordered-stderr.txt @@ -0,0 +1 @@ + the following parameters must be specified after LANGUAGES keyword: C. diff --git a/Tests/RunCMake/project/LanguagesUnordered.cmake b/Tests/RunCMake/project/LanguagesUnordered.cmake new file mode 100644 index 0000000..cd3ba28 --- /dev/null +++ b/Tests/RunCMake/project/LanguagesUnordered.cmake @@ -0,0 +1 @@ +project(ProjectA C LANGUAGES CXX) diff --git a/Tests/RunCMake/project/ProjectDescriptionNoArg-stderr.txt b/Tests/RunCMake/project/ProjectDescriptionNoArg-stderr.txt new file mode 100644 index 0000000..910106f --- /dev/null +++ b/Tests/RunCMake/project/ProjectDescriptionNoArg-stderr.txt @@ -0,0 +1,2 @@ + DESCRIPTION keyword not followed by a value or was followed by a value that + expanded to nothing. diff --git a/Tests/RunCMake/project/ProjectDescriptionNoArg.cmake b/Tests/RunCMake/project/ProjectDescriptionNoArg.cmake new file mode 100644 index 0000000..25acff8 --- /dev/null +++ b/Tests/RunCMake/project/ProjectDescriptionNoArg.cmake @@ -0,0 +1,2 @@ +cmake_policy(SET CMP0048 NEW) +project(ProjectDescriptionTest VERSION 1.0.0 LANGUAGES NONE DESCRIPTION) diff --git a/Tests/RunCMake/project/ProjectDescriptionNoArg2-stderr.txt b/Tests/RunCMake/project/ProjectDescriptionNoArg2-stderr.txt new file mode 100644 index 0000000..910106f --- /dev/null +++ b/Tests/RunCMake/project/ProjectDescriptionNoArg2-stderr.txt @@ -0,0 +1,2 @@ + DESCRIPTION keyword not followed by a value or was followed by a value that + expanded to nothing. diff --git a/Tests/RunCMake/project/ProjectDescriptionNoArg2.cmake b/Tests/RunCMake/project/ProjectDescriptionNoArg2.cmake new file mode 100644 index 0000000..f50a2f6 --- /dev/null +++ b/Tests/RunCMake/project/ProjectDescriptionNoArg2.cmake @@ -0,0 +1,2 @@ +cmake_policy(SET CMP0048 NEW) +project(ProjectDescriptionTest VERSION 1.0.0 DESCRIPTION LANGUAGES NONE) diff --git a/Tests/RunCMake/project/ProjectHomepage-stdout.txt b/Tests/RunCMake/project/ProjectHomepage-stdout.txt new file mode 100644 index 0000000..253990f --- /dev/null +++ b/Tests/RunCMake/project/ProjectHomepage-stdout.txt @@ -0,0 +1,3 @@ +-- PROJECT_HOMEPAGE_URL=http://example.com +-- CMAKE_PROJECT_HOMEPAGE_URL=http://example.com +-- ProjectHomepageTest_HOMEPAGE_URL=http://example.com diff --git a/Tests/RunCMake/project/ProjectHomepage.cmake b/Tests/RunCMake/project/ProjectHomepage.cmake new file mode 100644 index 0000000..3307f1f --- /dev/null +++ b/Tests/RunCMake/project/ProjectHomepage.cmake @@ -0,0 +1,14 @@ +cmake_policy(SET CMP0048 NEW) +project(ProjectHomepageTest VERSION 1.0.0 HOMEPAGE_URL "http://example.com" LANGUAGES) +if(NOT PROJECT_HOMEPAGE_URL) + message(FATAL_ERROR "PROJECT_HOMEPAGE_URL expected to be set") +endif() +if(NOT CMAKE_PROJECT_HOMEPAGE_URL) + message(FATAL_ERROR "CMAKE_PROJECT_HOMEPAGE_URL expected to be set") +endif() +if(NOT ProjectHomepageTest_HOMEPAGE_URL) + message(FATAL_ERROR "ProjectHomepageTest_HOMEPAGE_URL expected to be set") +endif() +message(STATUS "PROJECT_HOMEPAGE_URL=${PROJECT_HOMEPAGE_URL}") +message(STATUS "CMAKE_PROJECT_HOMEPAGE_URL=${CMAKE_PROJECT_HOMEPAGE_URL}") +message(STATUS "ProjectHomepageTest_HOMEPAGE_URL=${ProjectHomepageTest_HOMEPAGE_URL}") diff --git a/Tests/RunCMake/project/ProjectHomepage2-result.txt b/Tests/RunCMake/project/ProjectHomepage2-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/project/ProjectHomepage2-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/project/ProjectHomepage2-stderr.txt b/Tests/RunCMake/project/ProjectHomepage2-stderr.txt new file mode 100644 index 0000000..4a0adc2 --- /dev/null +++ b/Tests/RunCMake/project/ProjectHomepage2-stderr.txt @@ -0,0 +1,4 @@ +^CMake Error at ProjectHomepage2.cmake:2 \(project\): + HOMEPAGE_URL may be specified at most once. +Call Stack \(most recent call first\): + CMakeLists.txt:[0-9]+ \(include\)$ diff --git a/Tests/RunCMake/project/ProjectHomepage2.cmake b/Tests/RunCMake/project/ProjectHomepage2.cmake new file mode 100644 index 0000000..184c392 --- /dev/null +++ b/Tests/RunCMake/project/ProjectHomepage2.cmake @@ -0,0 +1,2 @@ +cmake_policy(SET CMP0048 NEW) +project(ProjectDescriptionTest VERSION 1.0.0 HOMEPAGE_URL "http://example.com" HOMEPAGE_URL "http://example.com" LANGUAGES) diff --git a/Tests/RunCMake/project/ProjectHomepageNoArg-stderr.txt b/Tests/RunCMake/project/ProjectHomepageNoArg-stderr.txt new file mode 100644 index 0000000..c9503b7 --- /dev/null +++ b/Tests/RunCMake/project/ProjectHomepageNoArg-stderr.txt @@ -0,0 +1,5 @@ +^CMake Warning at ProjectHomepageNoArg.cmake:2 \(project\): + HOMEPAGE_URL keyword not followed by a value or was followed by a value + that expanded to nothing. +Call Stack \(most recent call first\): + CMakeLists.txt:[0-9]+ \(include\)$ diff --git a/Tests/RunCMake/project/ProjectHomepageNoArg.cmake b/Tests/RunCMake/project/ProjectHomepageNoArg.cmake new file mode 100644 index 0000000..4605541 --- /dev/null +++ b/Tests/RunCMake/project/ProjectHomepageNoArg.cmake @@ -0,0 +1,2 @@ +cmake_policy(SET CMP0048 NEW) +project(ProjectDescriptionTest VERSION 1.0.0 LANGUAGES NONE HOMEPAGE_URL) diff --git a/Tests/RunCMake/project/RunCMakeTest.cmake b/Tests/RunCMake/project/RunCMakeTest.cmake index 3d13e2e..e9fb929 100644 --- a/Tests/RunCMake/project/RunCMakeTest.cmake +++ b/Tests/RunCMake/project/RunCMakeTest.cmake @@ -7,8 +7,14 @@ run_cmake(LanguagesImplicit) run_cmake(LanguagesEmpty) run_cmake(LanguagesNONE) run_cmake(LanguagesTwice) +run_cmake(LanguagesUnordered) run_cmake(ProjectDescription) run_cmake(ProjectDescription2) +run_cmake(ProjectDescriptionNoArg) +run_cmake(ProjectDescriptionNoArg2) +run_cmake(ProjectHomepage) +run_cmake(ProjectHomepage2) +run_cmake(ProjectHomepageNoArg) run_cmake(VersionAndLanguagesEmpty) run_cmake(VersionEmpty) run_cmake(VersionInvalid) diff --git a/Tests/RunCMake/project/VersionMissingLanguages-stderr.txt b/Tests/RunCMake/project/VersionMissingLanguages-stderr.txt index 52433bc..576ac69 100644 --- a/Tests/RunCMake/project/VersionMissingLanguages-stderr.txt +++ b/Tests/RunCMake/project/VersionMissingLanguages-stderr.txt @@ -1,4 +1,5 @@ CMake Error at VersionMissingLanguages.cmake:2 \(project\): - project with VERSION must use LANGUAGES before language names. + project with VERSION, DESCRIPTION or HOMEPAGE_URL must use LANGUAGES before + language names. Call Stack \(most recent call first\): CMakeLists.txt:3 \(include\)$ diff --git a/Tests/RunCMake/project/VersionMissingValueOkay-stderr.txt b/Tests/RunCMake/project/VersionMissingValueOkay-stderr.txt new file mode 100644 index 0000000..3228df7 --- /dev/null +++ b/Tests/RunCMake/project/VersionMissingValueOkay-stderr.txt @@ -0,0 +1,2 @@ + VERSION keyword not followed by a value or was followed by a value that + expanded to nothing. diff --git a/Tests/RunCMake/set_property/RunCMakeTest.cmake b/Tests/RunCMake/set_property/RunCMakeTest.cmake index 5b5327d..b966e89 100644 --- a/Tests/RunCMake/set_property/RunCMakeTest.cmake +++ b/Tests/RunCMake/set_property/RunCMakeTest.cmake @@ -9,3 +9,4 @@ run_cmake(LINK_LIBRARIES) run_cmake(SOURCES) run_cmake(TYPE) run_cmake(USER_PROP) +run_cmake(USER_PROP_INHERITED) diff --git a/Tests/RunCMake/set_property/USER_PROP_INHERITED-stdout.txt b/Tests/RunCMake/set_property/USER_PROP_INHERITED-stdout.txt new file mode 100644 index 0000000..dcb0f87 --- /dev/null +++ b/Tests/RunCMake/set_property/USER_PROP_INHERITED-stdout.txt @@ -0,0 +1,29 @@ +-- TopDir-to-nothing chaining: '' +-- TopDir-to-global chaining: 'vGlobal' +-- TopDir no chaining required: 'vTopDir' +-- TopDir unset append chaining: 'aTopDir' +-- TopDir preset append chaining: 'vTopDir;aTopDir' +-- Subdir-to-parent chaining: 'vTopDir' +-- Subdir-to-global chaining: 'vGlobal' +-- Subdir no chaining required: 'vSubdir' +-- Subdir preset append chaining: 'vSubdir;aSubdir' +-- Subdir unset append chaining: 'aSubdir' +-- Subdir undefined append chaining: 'aSubdir' +-- Target-to-directory chaining: 'vTopDir' +-- Target unset append chaining: 'aTarget' +-- Target no chaining required: 'vTarget' +-- Target preset append chaining: 'vTarget;aTarget' +-- Target undefined get chaining: '' +-- Target undefined append chaining: 'aTarget' +-- Source-to-directory chaining: 'vTopDir' +-- Source unset append chaining: 'aSource' +-- Source no chaining required: 'vSource' +-- Source preset append chaining: 'vSource;aSource' +-- Source undefined get chaining: '' +-- Source undefined append chaining: 'aSource' +-- Test-to-directory chaining: 'vTopDir' +-- Test unset append chaining: 'aTest' +-- Test no chaining required: 'vTest' +-- Test preset append chaining: 'vTest;aTest' +-- Test undefined get chaining: '' +-- Test undefined append chaining: 'aTest' diff --git a/Tests/RunCMake/set_property/USER_PROP_INHERITED.cmake b/Tests/RunCMake/set_property/USER_PROP_INHERITED.cmake new file mode 100644 index 0000000..2429866 --- /dev/null +++ b/Tests/RunCMake/set_property/USER_PROP_INHERITED.cmake @@ -0,0 +1,83 @@ +# Needed for source property tests +enable_language(C) + +#================================================= +# Directory property chaining +#================================================= + +foreach(i RANGE 1 5) + foreach(propType DIRECTORY TARGET SOURCE TEST) + define_property(${propType} PROPERTY USER_PROP${i} INHERITED + BRIEF_DOCS "Brief" FULL_DOCS "Full" + ) + endforeach() +endforeach() + +get_property(val DIRECTORY PROPERTY USER_PROP1) +message(STATUS "TopDir-to-nothing chaining: '${val}'") + +set_property(GLOBAL PROPERTY USER_PROP1 vGlobal) +set_property(GLOBAL PROPERTY USER_PROP2 vGlobal) +set_property(DIRECTORY PROPERTY USER_PROP2 vTopDir) +set_property(GLOBAL PROPERTY USER_PROP3 vGlobal) +set_property(DIRECTORY PROPERTY USER_PROP4 vTopDir) + +get_property(val DIRECTORY PROPERTY USER_PROP1) +message(STATUS "TopDir-to-global chaining: '${val}'") + +get_property(val DIRECTORY PROPERTY USER_PROP2) +message(STATUS "TopDir no chaining required: '${val}'") + +set_property(DIRECTORY APPEND PROPERTY USER_PROP3 aTopDir) +get_property(val DIRECTORY PROPERTY USER_PROP3) +message(STATUS "TopDir unset append chaining: '${val}'") + +set_property(DIRECTORY APPEND PROPERTY USER_PROP4 aTopDir) +get_property(val DIRECTORY PROPERTY USER_PROP4) +message(STATUS "TopDir preset append chaining: '${val}'") + +add_subdirectory(USER_PROP_INHERITED) + +#================================================= +# The other property types all chain the same way +#================================================= +macro(__chainToDirTests propType) + string(TOUPPER ${propType} propTypeUpper) + + get_property(val ${propTypeUpper} ${propType}1 PROPERTY USER_PROP2) + message(STATUS "${propType}-to-directory chaining: '${val}'") + + set_property(${propTypeUpper} ${propType}1 APPEND PROPERTY USER_PROP2 a${propType}) + get_property(val ${propTypeUpper} ${propType}1 PROPERTY USER_PROP2) + message(STATUS "${propType} unset append chaining: '${val}'") + + set_property(${propTypeUpper} ${propType}1 PROPERTY USER_PROP1 v${propType}) + get_property(val ${propTypeUpper} ${propType}1 PROPERTY USER_PROP1) + message(STATUS "${propType} no chaining required: '${val}'") + + set_property(${propTypeUpper} ${propType}1 APPEND PROPERTY USER_PROP1 a${propType}) + get_property(val ${propTypeUpper} ${propType}1 PROPERTY USER_PROP1) + message(STATUS "${propType} preset append chaining: '${val}'") + + get_property(val ${propTypeUpper} ${propType}2 PROPERTY USER_PROP5) + message(STATUS "${propType} undefined get chaining: '${val}'") + + set_property(${propTypeUpper} ${propType}2 APPEND PROPERTY USER_PROP5 a${propType}) + get_property(val ${propTypeUpper} ${propType}2 PROPERTY USER_PROP5) + message(STATUS "${propType} undefined append chaining: '${val}'") +endmacro() + +add_custom_target(Target1) +add_custom_target(Target2) +__chainToDirTests(Target) + +foreach(i RANGE 1 2) + set(Source${i} "${CMAKE_CURRENT_BINARY_DIR}/src${i}.c") + file(WRITE ${Source${i}} "int foo${i}() { return ${i}; }") +endforeach() +add_library(srcProps OBJECT ${Source1} ${Source2}) +__chainToDirTests(Source) + +add_test(NAME Test1 COMMAND ${CMAKE_COMMAND} -E touch_nocreate iDoNotExist) +add_test(NAME Test2 COMMAND ${CMAKE_COMMAND} -E touch_nocreate iDoNotExist) +__chainToDirTests(Test) diff --git a/Tests/RunCMake/set_property/USER_PROP_INHERITED/CMakeLists.txt b/Tests/RunCMake/set_property/USER_PROP_INHERITED/CMakeLists.txt new file mode 100644 index 0000000..234f4ee --- /dev/null +++ b/Tests/RunCMake/set_property/USER_PROP_INHERITED/CMakeLists.txt @@ -0,0 +1,21 @@ +get_property(val DIRECTORY PROPERTY USER_PROP2) +message(STATUS "Subdir-to-parent chaining: '${val}'") + +get_property(val DIRECTORY PROPERTY USER_PROP1) +message(STATUS "Subdir-to-global chaining: '${val}'") + +set_property(DIRECTORY PROPERTY USER_PROP1 vSubdir) +get_property(val DIRECTORY PROPERTY USER_PROP1) +message(STATUS "Subdir no chaining required: '${val}'") + +set_property(DIRECTORY APPEND PROPERTY USER_PROP1 aSubdir) +get_property(val DIRECTORY PROPERTY USER_PROP1) +message(STATUS "Subdir preset append chaining: '${val}'") + +set_property(DIRECTORY APPEND PROPERTY USER_PROP2 aSubdir) +get_property(val DIRECTORY PROPERTY USER_PROP2) +message(STATUS "Subdir unset append chaining: '${val}'") + +set_property(DIRECTORY APPEND PROPERTY USER_PROP5 aSubdir) +get_property(val DIRECTORY PROPERTY USER_PROP5) +message(STATUS "Subdir undefined append chaining: '${val}'") diff --git a/Tests/RunCMake/string/Join.cmake b/Tests/RunCMake/string/Join.cmake new file mode 100644 index 0000000..081f1e4 --- /dev/null +++ b/Tests/RunCMake/string/Join.cmake @@ -0,0 +1,16 @@ +string(JOIN % out) +if(NOT out STREQUAL "") + message(FATAL_ERROR "\"string(JOIN % out)\" set out to \"${out}\"") +endif() +string(JOIN % out a) +if(NOT out STREQUAL "a") + message(FATAL_ERROR "\"string(JOIN % out a)\" set out to \"${out}\"") +endif() +string(JOIN % out a "b") +if(NOT out STREQUAL "a%b") + message(FATAL_ERROR "\"string(JOIN % out a \"b\")\" set out to \"${out}\"") +endif() +string(JOIN :: out a "b") +if(NOT out STREQUAL "a::b") + message(FATAL_ERROR "\"string(JOIN :: out a \"b\")\" set out to \"${out}\"") +endif() diff --git a/Tests/RunCMake/string/JoinNoArgs-result.txt b/Tests/RunCMake/string/JoinNoArgs-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/string/JoinNoArgs-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/string/JoinNoArgs-stderr.txt b/Tests/RunCMake/string/JoinNoArgs-stderr.txt new file mode 100644 index 0000000..d9dcec3 --- /dev/null +++ b/Tests/RunCMake/string/JoinNoArgs-stderr.txt @@ -0,0 +1,4 @@ +CMake Error at JoinNoArgs.cmake:1 \(string\): + string sub-command JOIN requires at least two arguments. +Call Stack \(most recent call first\): + CMakeLists.txt:3 \(include\) diff --git a/Tests/RunCMake/string/JoinNoArgs.cmake b/Tests/RunCMake/string/JoinNoArgs.cmake new file mode 100644 index 0000000..35ba4d9 --- /dev/null +++ b/Tests/RunCMake/string/JoinNoArgs.cmake @@ -0,0 +1 @@ +string(JOIN) diff --git a/Tests/RunCMake/string/JoinNoVar-result.txt b/Tests/RunCMake/string/JoinNoVar-result.txt new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Tests/RunCMake/string/JoinNoVar-result.txt @@ -0,0 +1 @@ +1 diff --git a/Tests/RunCMake/string/JoinNoVar-stderr.txt b/Tests/RunCMake/string/JoinNoVar-stderr.txt new file mode 100644 index 0000000..90701a9 --- /dev/null +++ b/Tests/RunCMake/string/JoinNoVar-stderr.txt @@ -0,0 +1,4 @@ +CMake Error at JoinNoVar.cmake:1 \(string\): + string sub-command JOIN requires at least two arguments. +Call Stack \(most recent call first\): + CMakeLists.txt:3 \(include\) diff --git a/Tests/RunCMake/string/JoinNoVar.cmake b/Tests/RunCMake/string/JoinNoVar.cmake new file mode 100644 index 0000000..35f7b92 --- /dev/null +++ b/Tests/RunCMake/string/JoinNoVar.cmake @@ -0,0 +1 @@ +string(JOIN ";") diff --git a/Tests/RunCMake/string/RunCMakeTest.cmake b/Tests/RunCMake/string/RunCMakeTest.cmake index 513d1e3..211337a 100644 --- a/Tests/RunCMake/string/RunCMakeTest.cmake +++ b/Tests/RunCMake/string/RunCMakeTest.cmake @@ -9,6 +9,10 @@ run_cmake(PrependNoArgs) run_cmake(Concat) run_cmake(ConcatNoArgs) +run_cmake(Join) +run_cmake(JoinNoArgs) +run_cmake(JoinNoVar) + run_cmake(Timestamp) run_cmake(TimestampEmpty) run_cmake(TimestampInvalid) diff --git a/Tests/RunCMake/variable_watch/RaiseInParentScope-stderr.txt b/Tests/RunCMake/variable_watch/RaiseInParentScope-stderr.txt new file mode 100644 index 0000000..51db19c --- /dev/null +++ b/Tests/RunCMake/variable_watch/RaiseInParentScope-stderr.txt @@ -0,0 +1,2 @@ +var MODIFIED_ACCESS a +var MODIFIED_ACCESS b diff --git a/Tests/RunCMake/variable_watch/RaiseInParentScope.cmake b/Tests/RunCMake/variable_watch/RaiseInParentScope.cmake new file mode 100644 index 0000000..207798e --- /dev/null +++ b/Tests/RunCMake/variable_watch/RaiseInParentScope.cmake @@ -0,0 +1,15 @@ + +function(watch variable access value) + message("${variable} ${access} ${value}") +endfunction () + +# -------------- + +variable_watch(var watch) +set(var "a") + +function(f) + set(var "b" PARENT_SCOPE) +endfunction(f) + +f() diff --git a/Tests/RunCMake/variable_watch/RunCMakeTest.cmake b/Tests/RunCMake/variable_watch/RunCMakeTest.cmake index 2fa6275..3883999 100644 --- a/Tests/RunCMake/variable_watch/RunCMakeTest.cmake +++ b/Tests/RunCMake/variable_watch/RunCMakeTest.cmake @@ -4,3 +4,4 @@ run_cmake(ModifiedAccess) run_cmake(NoWatcher) run_cmake(WatchTwice) run_cmake(ModifyWatchInCallback) +run_cmake(RaiseInParentScope) diff --git a/Tests/Server/CMakeLists.txt b/Tests/Server/CMakeLists.txt index 41d1131..8321edb 100644 --- a/Tests/Server/CMakeLists.txt +++ b/Tests/Server/CMakeLists.txt @@ -1,10 +1,10 @@ cmake_minimum_required(VERSION 3.4) project(Server CXX) -find_package(PythonInterp REQUIRED) +find_package(Python REQUIRED) macro(do_test bsname file type) - execute_process(COMMAND ${PYTHON_EXECUTABLE} + execute_process(COMMAND ${Python_EXECUTABLE} -B # no .pyc files "${CMAKE_SOURCE_DIR}/${type}-test.py" "${CMAKE_COMMAND}" diff --git a/Tests/SwigTest/runme.py b/Tests/SwigTest/runme.py deleted file mode 100644 index ed3909e..0000000 --- a/Tests/SwigTest/runme.py +++ /dev/null @@ -1,51 +0,0 @@ -# file: runme.py - -# This file illustrates the shadow-class C++ interface generated -# by SWIG. - -import example - -# ----- Object creation ----- - -print "Creating some objects:" -c = example.Circle(10) -print " Created circle", c -s = example.Square(10) -print " Created square", s - -# ----- Access a static member ----- - -print "\nA total of", example.cvar.Shape_nshapes,"shapes were created" - -# ----- Member data access ----- - -# Set the location of the object - -c.x = 20 -c.y = 30 - -s.x = -10 -s.y = 5 - -print "\nHere is their current position:" -print " Circle = (%f, %f)" % (c.x,c.y) -print " Square = (%f, %f)" % (s.x,s.y) - -# ----- Call some methods ----- - -print "\nHere are some properties of the shapes:" -for o in [c,s]: - print " ", o - print " area = ", o.area() - print " perimeter = ", o.perimeter() - -print "\nGuess I'll clean up now" - -# Note: this invokes the virtual destructor -del c -del s - -s = 3 -print example.cvar.Shape_nshapes,"shapes remain" -print "Goodbye" - diff --git a/Tests/Tutorial/Step7/build2.cmake b/Tests/Tutorial/Step7/build2.cmake deleted file mode 100644 index c2f2e2e..0000000 --- a/Tests/Tutorial/Step7/build2.cmake +++ /dev/null @@ -1,9 +0,0 @@ -set(CTEST_SOURCE_DIRECTORY "$ENV{HOME}/Dashboards/My Tests/CMake/Tests/Tutorial/Step7") -set(CTEST_BINARY_DIRECTORY "${CTEST_SOURCE_DIRECTORY}-build2") -set(CTEST_CMAKE_GENERATOR "Visual Studio 8 2005") - -CTEST_START("Experimental") -CTEST_CONFIGURE(BUILD "${CTEST_BINARY_DIRECTORY}") -CTEST_BUILD(BUILD "${CTEST_BINARY_DIRECTORY}") -CTEST_TEST(BUILD "${CTEST_BINARY_DIRECTORY}") -CTEST_SUBMIT() diff --git a/Tests/UseSWIG/BasicConfiguration.cmake b/Tests/UseSWIG/BasicConfiguration.cmake new file mode 100644 index 0000000..d025d2a --- /dev/null +++ b/Tests/UseSWIG/BasicConfiguration.cmake @@ -0,0 +1,79 @@ + +find_package(SWIG REQUIRED) +include(${SWIG_USE_FILE}) + +# Path separator +if (WIN32) + set (PS "$<SEMICOLON>") +else() + set (PS ":") +endif() + +unset(SWIG_LANG_TYPE) +unset(SWIG_LANG_INCLUDE_DIRECTORIES) +unset(SWIG_LANG_DEFINITIONS) +unset(SWIG_LANG_OPTIONS) +unset(SWIG_LANG_LIBRARIES) + +if(${language} MATCHES python) + find_package(Python REQUIRED COMPONENTS Interpreter Development) + set(SWIG_LANG_INCLUDE_DIRECTORIES ${Python_INCLUDE_DIRS}) + set(SWIG_LANG_LIBRARIES ${Python_LIBRARIES}) +endif() +if(${language} MATCHES perl) + find_package(Perl REQUIRED) + find_package(PerlLibs REQUIRED) + set(SWIG_LANG_INCLUDE_DIRECTORIES ${PERL_INCLUDE_PATH}) + separate_arguments(c_flags UNIX_COMMAND "${PERL_EXTRA_C_FLAGS}") + set(SWIG_LANG_OPTIONS ${c_flags}) + set(SWIG_LANG_LIBRARIES ${PERL_LIBRARY}) +endif() +if(${language} MATCHES tcl) + find_package(TCL REQUIRED) + set(SWIG_LANG_INCLUDE_DIRECTORIES ${TCL_INCLUDE_PATH}) + set(SWIG_LANG_LIBRARIES ${TCL_LIBRARY}) +endif() +if(${language} MATCHES ruby) + find_package(Ruby REQUIRED) + set(SWIG_LANG_INCLUDE_DIRECTORIES ${RUBY_INCLUDE_PATH}) + set(SWIG_LANG_LIBRARIES ${RUBY_LIBRARY}) +endif() +if(${language} MATCHES php4) + find_package(PHP4 REQUIRED) + set(SWIG_LANG_INCLUDE_DIRECTORIES ${PHP4_INCLUDE_PATH}) + set(SWIG_LANG_LIBRARIES ${PHP4_LIBRARY}) +endif() +if(${language} MATCHES pike) + find_package(Pike REQUIRED) + set(SWIG_LANG_INCLUDE_DIRECTORIES ${PIKE_INCLUDE_PATH}) + set(SWIG_LANG_LIBRARIES ${PIKE_LIBRARY}) +endif() +if(${language} MATCHES lua) + find_package(Lua REQUIRED) + set(SWIG_LANG_INCLUDE_DIRECTORIES ${LUA_INCLUDE_DIR}) + set(SWIG_LANG_TYPE TYPE SHARED) + set(SWIG_LANG_LIBRARIES ${LUA_LIBRARIES}) +endif() + +unset(CMAKE_SWIG_FLAGS) + +set (CMAKE_INCLUDE_CURRENT_DIR ON) + +set_property(SOURCE "${CMAKE_CURRENT_LIST_DIR}/example.i" PROPERTY CPLUSPLUS ON) +set_property(SOURCE "${CMAKE_CURRENT_LIST_DIR}/example.i" PROPERTY COMPILE_OPTIONS -includeall) + +set_property(SOURCE "${CMAKE_CURRENT_LIST_DIR}/example.i" + PROPERTY GENERATED_INCLUDE_DIRECTORIES ${SWIG_LANG_INCLUDE_DIRECTORIES} + "${CMAKE_CURRENT_LIST_DIR}") +set_property(SOURCE "${CMAKE_CURRENT_LIST_DIR}/example.i" + PROPERTY GENERATED_COMPILE_DEFINITIONS ${SWIG_LANG_DEFINITIONS}) +set_property(SOURCE "${CMAKE_CURRENT_LIST_DIR}/example.i" + PROPERTY GENERATED_COMPILE_OPTIONS ${SWIG_LANG_OPTIONS}) + + +SWIG_ADD_LIBRARY(example + LANGUAGE "${language}" + ${SWIG_LANG_TYPE} + SOURCES "${CMAKE_CURRENT_LIST_DIR}/example.i" + "${CMAKE_CURRENT_LIST_DIR}/example.cxx") +TARGET_LINK_LIBRARIES(example PRIVATE ${SWIG_LANG_LIBRARIES}) diff --git a/Tests/UseSWIG/BasicPerl/CMakeLists.txt b/Tests/UseSWIG/BasicPerl/CMakeLists.txt new file mode 100644 index 0000000..476ef0e --- /dev/null +++ b/Tests/UseSWIG/BasicPerl/CMakeLists.txt @@ -0,0 +1,14 @@ +cmake_minimum_required(VERSION 3.1) + +project(TestBasicPerl CXX) + +include(CTest) + +set(language "perl") + +include (../BasicConfiguration.cmake) + +add_test (NAME BasicPerl + COMMAND "${PERL_EXECUTABLE}" "-I${CMAKE_CURRENT_BINARY_DIR}" + "-I$<TARGET_FILE_DIR:example>" + "${CMAKE_CURRENT_SOURCE_DIR}/../runme.pl") diff --git a/Tests/UseSWIG/BasicPython/CMakeLists.txt b/Tests/UseSWIG/BasicPython/CMakeLists.txt new file mode 100644 index 0000000..cf1d821 --- /dev/null +++ b/Tests/UseSWIG/BasicPython/CMakeLists.txt @@ -0,0 +1,13 @@ +cmake_minimum_required(VERSION 3.1) + +project(TestBasicPython CXX) + +include(CTest) + +set(language "python") + +include (../BasicConfiguration.cmake) + +add_test (NAME BasicPython + COMMAND "${CMAKE_COMMAND}" -E env "PYTHONPATH=${CMAKE_CURRENT_BINARY_DIR}${PS}$<TARGET_FILE_DIR:example>" + "${Python_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/../runme.py") diff --git a/Tests/UseSWIG/CMakeLists.txt b/Tests/UseSWIG/CMakeLists.txt new file mode 100644 index 0000000..0c4ec8a --- /dev/null +++ b/Tests/UseSWIG/CMakeLists.txt @@ -0,0 +1,76 @@ +add_test(NAME UseSWIG.LegacyPython COMMAND + ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION> + --build-and-test + "${CMake_SOURCE_DIR}/Tests/UseSWIG/LegacyPython" + "${CMake_BINARY_DIR}/Tests/UseSWIG/LegacyPython" + ${build_generator_args} + --build-project TestLegacyPython + --build-options ${build_options} + --test-command ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION> + ) +add_test(NAME UseSWIG.LegacyPerl COMMAND + ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION> + --build-and-test + "${CMake_SOURCE_DIR}/Tests/UseSWIG/LegacyPerl" + "${CMake_BINARY_DIR}/Tests/UseSWIG/LegacyPerl" + ${build_generator_args} + --build-project TestLegacyPerl + --build-options ${build_options} + --test-command ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION> + ) + + +add_test(NAME UseSWIG.BasicPython COMMAND + ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION> + --build-and-test + "${CMake_SOURCE_DIR}/Tests/UseSWIG/BasicPython" + "${CMake_BINARY_DIR}/Tests/UseSWIG/BasicPython" + ${build_generator_args} + --build-project TestBasicPython + --build-options ${build_options} + --test-command ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION> + ) +add_test(NAME UseSWIG.BasicPerl COMMAND + ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION> + --build-and-test + "${CMake_SOURCE_DIR}/Tests/UseSWIG/BasicPerl" + "${CMake_BINARY_DIR}/Tests/UseSWIG/BasicPerl" + ${build_generator_args} + --build-project TestBasicPerl + --build-options ${build_options} + --test-command ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION> + ) + + +add_test(NAME UseSWIG.MultipleModules COMMAND + ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION> + --build-and-test + "${CMake_SOURCE_DIR}/Tests/UseSWIG/MultipleModules" + "${CMake_BINARY_DIR}/Tests/UseSWIG/MultipleModules" + ${build_generator_args} + --build-project TestMultipleModules + --build-options ${build_options} + --test-command ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION> + ) +add_test(NAME UseSWIG.MultiplePython COMMAND + ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION> + --build-and-test + "${CMake_SOURCE_DIR}/Tests/UseSWIG/MultiplePython" + "${CMake_BINARY_DIR}/Tests/UseSWIG/MultiplePython" + ${build_generator_args} + --build-project TestMultiplePython + --build-options ${build_options} + --test-command ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION> + ) + + +add_test(NAME UseSWIG.ModuleVersion2 COMMAND + ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION> + --build-and-test + "${CMake_SOURCE_DIR}/Tests/UseSWIG/ModuleVersion2" + "${CMake_BINARY_DIR}/Tests/UseSWIG/ModuleVersion2" + ${build_generator_args} + --build-project TestModuleVersion2 + --build-options ${build_options} + --test-command ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION> + ) diff --git a/Tests/SwigTest/CMakeLists.txt b/Tests/UseSWIG/LegacyConfiguration.cmake index 65f5c93..1acc05a 100644 --- a/Tests/SwigTest/CMakeLists.txt +++ b/Tests/UseSWIG/LegacyConfiguration.cmake @@ -1,59 +1,68 @@ -set(language "python") -cmake_minimum_required (VERSION 2.6) - -project(example_${language}_class) +# Prevent deprecated warnings from new UseSWIG module +set (CMAKE_WARN_DEPRECATED FALSE) find_package(SWIG REQUIRED) include(${SWIG_USE_FILE}) +# Path separator +if (WIN32) + set (PS "$<SEMICOLON>") +else() + set (PS ":") +endif() + unset(SWIG_LANG_TYPE) if(${language} MATCHES python) - find_package(PythonLibs) + find_package(PythonInterp REQUIRED) + find_package(PythonLibs REQUIRED) include_directories(${PYTHON_INCLUDE_PATH}) set(SWIG_LANG_LIBRARIES ${PYTHON_LIBRARIES}) endif() if(${language} MATCHES perl) - find_package(PerlLibs) + find_package(Perl REQUIRED) + find_package(PerlLibs REQUIRED) include_directories(${PERL_INCLUDE_PATH}) - add_definitions(${PERL_EXTRA_C_FLAGS}) + separate_arguments(c_flags UNIX_COMMAND "${PERL_EXTRA_C_FLAGS}") + add_compile_options(${c_flags}) set(SWIG_LANG_LIBRARIES ${PERL_LIBRARY}) endif() if(${language} MATCHES tcl) - find_package(TCL) + find_package(TCL REQUIRED) include_directories(${TCL_INCLUDE_PATH}) set(SWIG_LANG_LIBRARIES ${TCL_LIBRARY}) endif() if(${language} MATCHES ruby) - find_package(Ruby) + find_package(Ruby REQUIRED) include_directories(${RUBY_INCLUDE_PATH}) set(SWIG_LANG_LIBRARIES ${RUBY_LIBRARY}) endif() if(${language} MATCHES php4) - find_package(PHP4) + find_package(PHP4 REQUIRED) include_directories(${PHP4_INCLUDE_PATH}) set(SWIG_LANG_LIBRARIES ${PHP4_LIBRARY}) endif() if(${language} MATCHES pike) - find_package(Pike) + find_package(Pike REQUIRED) include_directories(${PIKE_INCLUDE_PATH}) set(SWIG_LANG_LIBRARIES ${PIKE_LIBRARY}) endif() if(${language} MATCHES lua) - find_package(Lua) + find_package(Lua REQUIRED) include_directories(${LUA_INCLUDE_DIR}) set(SWIG_LANG_TYPE TYPE SHARED) set(SWIG_LANG_LIBRARIES ${LUA_LIBRARIES}) endif() -include_directories(${CMAKE_CURRENT_SOURCE_DIR}) +unset(CMAKE_SWIG_FLAGS) -set(CMAKE_SWIG_FLAGS "") +include_directories(${CMAKE_CURRENT_LIST_DIR}) -set_source_files_properties(example.i PROPERTIES CPLUSPLUS ON) -set_source_files_properties(example.i PROPERTIES SWIG_FLAGS "-includeall") +set_source_files_properties("${CMAKE_CURRENT_LIST_DIR}/example.i" PROPERTIES CPLUSPLUS ON) +set_source_files_properties("${CMAKE_CURRENT_LIST_DIR}/example.i" PROPERTIES SWIG_FLAGS "-includeall") SWIG_ADD_LIBRARY(example LANGUAGE "${language}" ${SWIG_LANG_TYPE} - SOURCES example.i example.cxx) + SOURCES "${CMAKE_CURRENT_LIST_DIR}/example.i" + "${CMAKE_CURRENT_LIST_DIR}/example.cxx") SWIG_LINK_LIBRARIES(example ${SWIG_LANG_LIBRARIES}) diff --git a/Tests/UseSWIG/LegacyPerl/CMakeLists.txt b/Tests/UseSWIG/LegacyPerl/CMakeLists.txt new file mode 100644 index 0000000..90d92f4 --- /dev/null +++ b/Tests/UseSWIG/LegacyPerl/CMakeLists.txt @@ -0,0 +1,14 @@ +cmake_minimum_required(VERSION 3.1) + +project(TestLegacyPerl CXX) + +include(CTest) + +set(language "perl") + +include (../LegacyConfiguration.cmake) + +add_test (NAME LegacyPerl + COMMAND "${PERL_EXECUTABLE}" "-I${CMAKE_CURRENT_BINARY_DIR}" + "-I$<TARGET_FILE_DIR:${SWIG_MODULE_example_REAL_NAME}>" + "${CMAKE_CURRENT_SOURCE_DIR}/../runme.pl") diff --git a/Tests/UseSWIG/LegacyPython/CMakeLists.txt b/Tests/UseSWIG/LegacyPython/CMakeLists.txt new file mode 100644 index 0000000..03facb1 --- /dev/null +++ b/Tests/UseSWIG/LegacyPython/CMakeLists.txt @@ -0,0 +1,13 @@ +cmake_minimum_required(VERSION 3.1) + +project(TestLegacyPython CXX) + +include(CTest) + +set(language "python") + +include (../LegacyConfiguration.cmake) + +add_test (NAME LegacyPython + COMMAND "${CMAKE_COMMAND}" -E env "PYTHONPATH=${CMAKE_CURRENT_BINARY_DIR}${PS}$<TARGET_FILE_DIR:${SWIG_MODULE_example_REAL_NAME}>" + "${PYTHON_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/../runme.py") diff --git a/Tests/UseSWIG/ModuleVersion2/CMakeLists.txt b/Tests/UseSWIG/ModuleVersion2/CMakeLists.txt new file mode 100644 index 0000000..3f9d363 --- /dev/null +++ b/Tests/UseSWIG/ModuleVersion2/CMakeLists.txt @@ -0,0 +1,56 @@ +cmake_minimum_required(VERSION 3.1) + +project(TestModuleVersion2 CXX) + +include(CTest) + +find_package(SWIG REQUIRED) +include(${SWIG_USE_FILE}) + +find_package(Python2 REQUIRED COMPONENTS Interpreter Development) +find_package(Python3 REQUIRED COMPONENTS Interpreter Development) + +if (WIN32) + set (PS $<SEMICOLON>) +else() + set (PS ":") +endif() + +set (UseSWIG_MODULE_VERSION 2) +unset(CMAKE_SWIG_FLAGS) + +set_property(SOURCE "../example.i" PROPERTY CPLUSPLUS ON) +set_property(SOURCE "../example.i" PROPERTY COMPILE_OPTIONS -includeall) + +set_property(SOURCE "../example.i" + PROPERTY GENERATED_INCLUDE_DIRECTORIES "${CMAKE_CURRENT_SOURCE_DIR}/..") + +swig_add_library(example1 + LANGUAGE python + SOURCES ../example.i ../example.cxx) +set_target_properties (example1 PROPERTIES + OUTPUT_NAME example + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/Python2" + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/Python2" + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/Python2") +target_link_libraries(example1 PRIVATE Python2::Python) + +# re-use sample interface file for another plugin +swig_add_library(example2 + LANGUAGE python + SOURCES ../example.i ../example.cxx) +set_target_properties (example2 PROPERTIES + OUTPUT_NAME example + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/Python3" + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/Python3" + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/Python3") +target_link_libraries(example2 PRIVATE Python3::Python) + + +add_test (NAME ModuleVersion2.example1 + COMMAND "${CMAKE_COMMAND}" -E env "PYTHONPATH=$<TARGET_PROPERTY:example1,SWIG_SUPPORT_FILES_DIRECTORY>${PS}$<TARGET_FILE_DIR:example1>" + "${Python2_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/../runme.py") + +add_test (NAME ModuleVersion2.example2 + COMMAND "${CMAKE_COMMAND}" -E env "PYTHONPATH=$<TARGET_PROPERTY:example2,SWIG_SUPPORT_FILES_DIRECTORY>${PS}$<TARGET_FILE_DIR:example2>" + "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/../runme.py") diff --git a/Tests/UseSWIG/MultipleModules/CMakeLists.txt b/Tests/UseSWIG/MultipleModules/CMakeLists.txt new file mode 100644 index 0000000..578825f --- /dev/null +++ b/Tests/UseSWIG/MultipleModules/CMakeLists.txt @@ -0,0 +1,68 @@ +cmake_minimum_required(VERSION 3.1) + +project(TestMultipleModules CXX) + +include(CTest) + +find_package(SWIG REQUIRED) +include(${SWIG_USE_FILE}) + +find_package(Python REQUIRED COMPONENTS Interpreter Development) + +find_package(Perl REQUIRED) +find_package(PerlLibs REQUIRED) + +# Path separator +if (WIN32) + set (PS "$<SEMICOLON>") +else() + set (PS ":") +endif() + +unset(CMAKE_SWIG_FLAGS) + +set_property(SOURCE "../example.i" PROPERTY CPLUSPLUS ON) +set_property(SOURCE "../example.i" PROPERTY COMPILE_OPTIONS -includeall) + +set_property(SOURCE "../example.i" + PROPERTY GENERATED_INCLUDE_DIRECTORIES "${CMAKE_CURRENT_SOURCE_DIR}/..") + +swig_add_library(example1 + LANGUAGE python + OUTPUT_DIR "${CMAKE_CURRENT_BINARY_DIR}/Python" + SOURCES ../example.i ../example.cxx) +set_target_properties (example1 PROPERTIES + OUTPUT_NAME example + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/Python" + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/Python" + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/Python") +target_link_libraries(example1 PRIVATE Python::Python) + +# re-use sample interface file for another plugin +set_property(SOURCE "../example.i" APPEND PROPERTY + GENERATED_INCLUDE_DIRECTORIES ${PERL_INCLUDE_PATH}) +separate_arguments(c_flags UNIX_COMMAND "${PERL_EXTRA_C_FLAGS}") +set_property(SOURCE "../example.i" PROPERTY GENERATED_COMPILE_OPTIONS ${c_flags}) + +swig_add_library(example2 + LANGUAGE perl + OUTPUT_DIR "${CMAKE_CURRENT_BINARY_DIR}/Perl" + SOURCES ../example.i ../example.cxx) +set_target_properties (example2 PROPERTIES + OUTPUT_NAME example + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/Perl" + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/Perl" + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/Perl") +target_link_libraries(example2 PRIVATE ${PERL_LIBRARY}) + + + +add_test (NAME MultipleModules.Python + COMMAND "${CMAKE_COMMAND}" -E env "PYTHONPATH=${CMAKE_CURRENT_BINARY_DIR}/Python${PS}$<TARGET_FILE_DIR:example1>" + "${Python_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/../runme.py") + + +add_test (NAME MultipleModules.Perl + COMMAND "${PERL_EXECUTABLE}" "-I${CMAKE_CURRENT_BINARY_DIR}/Perl" + "-I$<TARGET_FILE_DIR:example2>" + "${CMAKE_CURRENT_SOURCE_DIR}/../runme.pl") diff --git a/Tests/UseSWIG/MultiplePython/CMakeLists.txt b/Tests/UseSWIG/MultiplePython/CMakeLists.txt new file mode 100644 index 0000000..a5e3eed --- /dev/null +++ b/Tests/UseSWIG/MultiplePython/CMakeLists.txt @@ -0,0 +1,59 @@ +cmake_minimum_required(VERSION 3.1) + +project(TestMultiplePython CXX) + +include(CTest) + +find_package(SWIG REQUIRED) +include(${SWIG_USE_FILE}) + +find_package(Python2 REQUIRED COMPONENTS Interpreter Development) +find_package(Python3 REQUIRED COMPONENTS Interpreter Development) + +# Path separator +if (WIN32) + set (PS "$<SEMICOLON>") +else() + set (PS ":") +endif() + +unset(CMAKE_SWIG_FLAGS) + +set_property(SOURCE "../example.i" PROPERTY CPLUSPLUS ON) +set_property(SOURCE "../example.i" PROPERTY COMPILE_OPTIONS -includeall) + +set_property(SOURCE "../example.i" + PROPERTY GENERATED_INCLUDE_DIRECTORIES "${CMAKE_CURRENT_SOURCE_DIR}/..") + +swig_add_library(example1 + LANGUAGE python + OUTPUT_DIR "${CMAKE_CURRENT_BINARY_DIR}/Python2" + SOURCES ../example.i ../example.cxx) +set_target_properties (example1 PROPERTIES + OUTPUT_NAME example + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/Python2" + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/Python2" + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/Python2") +target_link_libraries(example1 PRIVATE Python2::Python) + +# re-use sample interface file for another plugin +swig_add_library(example2 + LANGUAGE python + OUTPUT_DIR "${CMAKE_CURRENT_BINARY_DIR}/Python3" + SOURCES ../example.i ../example.cxx) +set_target_properties (example2 PROPERTIES + OUTPUT_NAME example + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/Python3" + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/Python3" + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/Python3") +target_link_libraries(example2 PRIVATE Python3::Python) + + + +add_test (NAME MultiplePython.example1 + COMMAND "${CMAKE_COMMAND}" -E env "PYTHONPATH=${CMAKE_CURRENT_BINARY_DIR}/Python2${PS}$<TARGET_FILE_DIR:example1>" + "${Python2_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/../runme.py") + +add_test (NAME MultiplePython.example2 + COMMAND "${CMAKE_COMMAND}" -E env "PYTHONPATH=${CMAKE_CURRENT_BINARY_DIR}/Python3${PS}$<TARGET_FILE_DIR:example2>" + "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/../runme.py") diff --git a/Tests/SwigTest/example.cxx b/Tests/UseSWIG/example.cxx index 961d6dd..961d6dd 100644 --- a/Tests/SwigTest/example.cxx +++ b/Tests/UseSWIG/example.cxx diff --git a/Tests/SwigTest/example.h b/Tests/UseSWIG/example.h index 366deb0..366deb0 100644 --- a/Tests/SwigTest/example.h +++ b/Tests/UseSWIG/example.h diff --git a/Tests/SwigTest/example.i b/Tests/UseSWIG/example.i index 75700b3..fbdf724 100644 --- a/Tests/SwigTest/example.i +++ b/Tests/UseSWIG/example.i @@ -7,4 +7,3 @@ /* Let's just grab the original header file here */ %include "example.h" - diff --git a/Tests/SwigTest/runme.php4 b/Tests/UseSWIG/runme.php4 index 653ced2..653ced2 100644 --- a/Tests/SwigTest/runme.php4 +++ b/Tests/UseSWIG/runme.php4 diff --git a/Tests/SwigTest/runme.pike b/Tests/UseSWIG/runme.pike index ec28dd7..ec28dd7 100755..100644 --- a/Tests/SwigTest/runme.pike +++ b/Tests/UseSWIG/runme.pike diff --git a/Tests/SwigTest/runme.pl b/Tests/UseSWIG/runme.pl index 5bfb3d8..965e063 100644 --- a/Tests/SwigTest/runme.pl +++ b/Tests/UseSWIG/runme.pl @@ -54,4 +54,3 @@ examplec::delete_Shape($s); print $examplec::Shape_nshapes," shapes remain\n"; print "Goodbye\n"; - diff --git a/Tests/UseSWIG/runme.py b/Tests/UseSWIG/runme.py new file mode 100644 index 0000000..af5e07d --- /dev/null +++ b/Tests/UseSWIG/runme.py @@ -0,0 +1,52 @@ +# file: runme.py + +# This file illustrates the shadow-class C++ interface generated +# by SWIG. + +from __future__ import print_function + +import example + +# ----- Object creation ----- + +print ("Creating some objects:") +c = example.Circle(10) +print (" Created circle", c) +s = example.Square(10) +print (" Created square", s) + +# ----- Access a static member ----- + +print ("\nA total of", example.cvar.Shape_nshapes,"shapes were created") + +# ----- Member data access ----- + +# Set the location of the object + +c.x = 20 +c.y = 30 + +s.x = -10 +s.y = 5 + +print ("\nHere is their current position:") +print (" Circle = (%f, %f)" % (c.x,c.y)) +print (" Square = (%f, %f)" % (s.x,s.y)) + +# ----- Call some methods ----- + +print ("\nHere are some properties of the shapes:") +for o in [c,s]: + print (" ", o) + print (" area = ", o.area()) + print (" perimeter = ", o.perimeter()) + +print ("\nGuess I'll clean up now") + +# Note: this invokes the virtual destructor +del c +del s + +s = 3 +print (example.cvar.Shape_nshapes,"shapes remain") +print ("Goodbye") diff --git a/Tests/SwigTest/runme.rb b/Tests/UseSWIG/runme.rb index de73bcd..de73bcd 100644 --- a/Tests/SwigTest/runme.rb +++ b/Tests/UseSWIG/runme.rb diff --git a/Tests/SwigTest/runme.tcl b/Tests/UseSWIG/runme.tcl index c7f4725..6055cf6 100644 --- a/Tests/SwigTest/runme.tcl +++ b/Tests/UseSWIG/runme.tcl @@ -47,4 +47,3 @@ rename s "" puts "$Shape_nshapes shapes remain" puts "Goodbye" - diff --git a/Tests/SwigTest/runme2.tcl b/Tests/UseSWIG/runme2.tcl index 88ec2f6..d0b5c21 100644 --- a/Tests/SwigTest/runme2.tcl +++ b/Tests/UseSWIG/runme2.tcl @@ -67,4 +67,3 @@ delete_Shape $s puts "$Shape_nshapes shapes remain" puts "Goodbye" - diff --git a/Utilities/Release/linux64_release.cmake b/Utilities/Release/linux64_release.cmake index 97fc33c..2fd4f12 100644 --- a/Utilities/Release/linux64_release.cmake +++ b/Utilities/Release/linux64_release.cmake @@ -34,7 +34,7 @@ OPENSSL_INCLUDE_DIR:PATH=/home/kitware/openssl-1.1.0g/include OPENSSL_SSL_LIBRARY:FILEPATH=/home/kitware/openssl-1.1.0g/lib/libssl.a PYTHON_EXECUTABLE:FILEPATH=/usr/bin/python3 CPACK_SYSTEM_NAME:STRING=Linux-x86_64 -BUILD_QtDialog:BOOL:=TRUE +BUILD_QtDialog:BOOL=TRUE CMAKE_SKIP_BOOTSTRAP_TEST:STRING=TRUE CMake_GUI_DISTRIBUTE_WITH_Qt_LGPL:STRING=3 CMAKE_PREFIX_PATH:STRING=${qt_prefix} diff --git a/Utilities/Release/win32_release.cmake b/Utilities/Release/win32_release.cmake index bdf002e..f9e35a5 100644 --- a/Utilities/Release/win32_release.cmake +++ b/Utilities/Release/win32_release.cmake @@ -21,7 +21,7 @@ CMAKE_USE_OPENSSL:BOOL=OFF CMAKE_SKIP_BOOTSTRAP_TEST:STRING=TRUE CMAKE_Fortran_COMPILER:FILEPATH=FALSE CMAKE_GENERATOR:INTERNAL=Ninja -BUILD_QtDialog:BOOL:=TRUE +BUILD_QtDialog:BOOL=TRUE CMake_GUI_DISTRIBUTE_WITH_Qt_LGPL:STRING=3 CMAKE_C_FLAGS_RELEASE:STRING=-MT -O2 -Ob2 -DNDEBUG CMAKE_CXX_FLAGS_RELEASE:STRING=-MT -O2 -Ob2 -DNDEBUG diff --git a/Utilities/Release/win64_release.cmake b/Utilities/Release/win64_release.cmake index 1c81f82..02e4096 100644 --- a/Utilities/Release/win64_release.cmake +++ b/Utilities/Release/win64_release.cmake @@ -21,7 +21,7 @@ CMAKE_USE_OPENSSL:BOOL=OFF CMAKE_SKIP_BOOTSTRAP_TEST:STRING=TRUE CMAKE_Fortran_COMPILER:FILEPATH=FALSE CMAKE_GENERATOR:INTERNAL=Ninja -BUILD_QtDialog:BOOL:=TRUE +BUILD_QtDialog:BOOL=TRUE CMake_GUI_DISTRIBUTE_WITH_Qt_LGPL:STRING=3 CMAKE_C_FLAGS_RELEASE:STRING=-MT -O2 -Ob2 -DNDEBUG CMAKE_CXX_FLAGS_RELEASE:STRING=-MT -O2 -Ob2 -DNDEBUG diff --git a/Utilities/Sphinx/cmake.py b/Utilities/Sphinx/cmake.py index cfda2d4..90ddd36 100644 --- a/Utilities/Sphinx/cmake.py +++ b/Utilities/Sphinx/cmake.py @@ -144,6 +144,7 @@ class _cmake_index_entry: _cmake_index_objs = { 'command': _cmake_index_entry('command'), + 'envvar': _cmake_index_entry('envvar'), 'generator': _cmake_index_entry('generator'), 'manual': _cmake_index_entry('manual'), 'module': _cmake_index_entry('module'), @@ -324,6 +325,7 @@ class CMakeDomain(Domain): label = 'CMake' object_types = { 'command': ObjType('command', 'command'), + 'envvar': ObjType('envvar', 'envvar'), 'generator': ObjType('generator', 'generator'), 'variable': ObjType('variable', 'variable'), 'module': ObjType('module', 'module'), @@ -339,6 +341,7 @@ class CMakeDomain(Domain): } directives = { 'command': CMakeObject, + 'envvar': CMakeObject, 'variable': CMakeObject, # Other object types cannot be created except by the CMakeTransform # 'generator': CMakeObject, @@ -355,6 +358,7 @@ class CMakeDomain(Domain): } roles = { 'command': CMakeXRefRole(fix_parens = True, lowercase = True), + 'envvar': CMakeXRefRole(), 'generator': CMakeXRefRole(), 'variable': CMakeXRefRole(), 'module': CMakeXRefRole(), diff --git a/Utilities/Sphinx/create_identifiers.py b/Utilities/Sphinx/create_identifiers.py index 3fe3fcb..e638950 100755 --- a/Utilities/Sphinx/create_identifiers.py +++ b/Utilities/Sphinx/create_identifiers.py @@ -21,7 +21,9 @@ newlines = [] for line in lines: mapping = (("command", "command"), + ("envvar", "envvar"), ("variable", "variable"), + ("generator", "generator"), ("target property", "prop_tgt"), ("test property", "prop_test"), ("source file property", "prop_sf"), diff --git a/Utilities/cmlibuv/include/uv.h b/Utilities/cmlibuv/include/uv.h index 328ce9e..875e30a 100644 --- a/Utilities/cmlibuv/include/uv.h +++ b/Utilities/cmlibuv/include/uv.h @@ -925,6 +925,19 @@ typedef struct uv_process_options_s { */ uv_uid_t uid; uv_gid_t gid; + /* + Libuv can set the child process' CPU affinity mask. This happens when + `cpumask` is non-NULL. It must point to an array of char values + of length `cpumask_size`, whose value must be at least that returned by + uv_cpumask_size(). Each byte in the mask can be either zero (false) + or non-zero (true) to indicate whether the corresponding processor at + that index is included. + + If enabled on an unsupported platform, uv_spawn() will fail with + UV_ENOTSUP. + */ + char* cpumask; + size_t cpumask_size; } uv_process_options_t; /* @@ -1094,6 +1107,7 @@ UV_EXTERN uv_pid_t uv_os_getppid(void); UV_EXTERN int uv_cpu_info(uv_cpu_info_t** cpu_infos, int* count); UV_EXTERN void uv_free_cpu_info(uv_cpu_info_t* cpu_infos, int count); +UV_EXTERN int uv_cpumask_size(void); UV_EXTERN int uv_interface_addresses(uv_interface_address_t** addresses, int* count); diff --git a/Utilities/cmlibuv/src/unix/core.c b/Utilities/cmlibuv/src/unix/core.c index c7e431e..faaf697 100644 --- a/Utilities/cmlibuv/src/unix/core.c +++ b/Utilities/cmlibuv/src/unix/core.c @@ -40,6 +40,7 @@ #include <sys/uio.h> /* writev */ #include <sys/resource.h> /* getrusage */ #include <pwd.h> +#include <sched.h> #ifdef __sun # include <netdb.h> /* MAXHOSTNAMELEN on Solaris */ @@ -63,6 +64,8 @@ # include <sys/sysctl.h> # include <sys/filio.h> # include <sys/wait.h> +# include <sys/param.h> +# include <sys/cpuset.h> # define UV__O_CLOEXEC O_CLOEXEC # if defined(__FreeBSD__) && __FreeBSD__ >= 10 # define uv__accept4 accept4 @@ -1340,6 +1343,15 @@ int uv_os_gethostname(char* buffer, size_t* size) { } +int uv_cpumask_size(void) { +#if defined(__linux__) || defined(__FreeBSD__) + return CPU_SETSIZE; +#else + return UV_ENOTSUP; +#endif +} + + uv_os_fd_t uv_get_osfhandle(int fd) { return fd; } diff --git a/Utilities/cmlibuv/src/unix/process.c b/Utilities/cmlibuv/src/unix/process.c index 9842710..47ab1dc 100644 --- a/Utilities/cmlibuv/src/unix/process.c +++ b/Utilities/cmlibuv/src/unix/process.c @@ -32,6 +32,7 @@ #include <unistd.h> #include <fcntl.h> #include <poll.h> +#include <sched.h> #if defined(__APPLE__) && !TARGET_OS_IPHONE # include <crt_externs.h> @@ -44,6 +45,16 @@ extern char **environ; # include <grp.h> #endif +#ifndef CMAKE_BOOTSTRAP +#if defined(__linux__) +# define uv__cpu_set_t cpu_set_t +#elif defined(__FreeBSD__) +# include <sys/param.h> +# include <sys/cpuset.h> +# include <pthread_np.h> +# define uv__cpu_set_t cpuset_t +#endif +#endif static void uv__chld(uv_signal_t* handle, int signum) { uv_process_t* process; @@ -285,6 +296,14 @@ static void uv__process_child_init(const uv_process_options_t* options, int err; int fd; int n; +#ifndef CMAKE_BOOTSTRAP +#if defined(__linux__) || defined(__FreeBSD__) + int r; + int i; + int cpumask_size; + uv__cpu_set_t cpuset; +#endif +#endif if (options->flags & UV_PROCESS_DETACHED) setsid(); @@ -375,6 +394,28 @@ static void uv__process_child_init(const uv_process_options_t* options, _exit(127); } +#ifndef CMAKE_BOOTSTRAP +#if defined(__linux__) || defined(__FreeBSD__) + if (options->cpumask != NULL) { + cpumask_size = uv_cpumask_size(); + assert(options->cpumask_size >= (size_t)cpumask_size); + + CPU_ZERO(&cpuset); + for (i = 0; i < cpumask_size; ++i) { + if (options->cpumask[i]) { + CPU_SET(i, &cpuset); + } + } + + r = -pthread_setaffinity_np(pthread_self(), sizeof(cpuset), &cpuset); + if (r != 0) { + uv__write_int(error_fd, r); + _exit(127); + } + } +#endif +#endif + if (options->env != NULL) { environ = options->env; } @@ -429,6 +470,20 @@ int uv_spawn(uv_loop_t* loop, int i; int status; + if (options->cpumask != NULL) { +#ifndef CMAKE_BOOTSTRAP +#if defined(__linux__) || defined(__FreeBSD__) + if (options->cpumask_size < (size_t)uv_cpumask_size()) { + return UV_EINVAL; + } +#else + return UV_ENOTSUP; +#endif +#else + return UV_ENOTSUP; +#endif + } + assert(options->file != NULL); assert(!(options->flags & ~(UV_PROCESS_DETACHED | UV_PROCESS_SETGID | diff --git a/Utilities/cmlibuv/src/win/core.c b/Utilities/cmlibuv/src/win/core.c index 9ed4e82..8d121b3 100644 --- a/Utilities/cmlibuv/src/win/core.c +++ b/Utilities/cmlibuv/src/win/core.c @@ -603,3 +603,7 @@ int uv__socket_sockopt(uv_handle_t* handle, int optname, int* value) { return 0; } + +int uv_cpumask_size(void) { + return (int)(sizeof(DWORD_PTR) * 8); +} diff --git a/Utilities/cmlibuv/src/win/process.c b/Utilities/cmlibuv/src/win/process.c index cc06d9e..f5f05af 100644 --- a/Utilities/cmlibuv/src/win/process.c +++ b/Utilities/cmlibuv/src/win/process.c @@ -954,6 +954,12 @@ int uv_spawn(uv_loop_t* loop, return UV_EINVAL; } + if (options->cpumask != NULL) { + if (options->cpumask_size < (size_t)uv_cpumask_size()) { + return UV_EINVAL; + } + } + assert(options->file != NULL); assert(!(options->flags & ~(UV_PROCESS_DETACHED | UV_PROCESS_SETGID | @@ -1084,6 +1090,12 @@ int uv_spawn(uv_loop_t* loop, process_flags |= DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP; } + if (options->cpumask != NULL) { + /* Create the child in a suspended state so we have a chance to set + its process affinity before it runs. */ + process_flags |= CREATE_SUSPENDED; + } + if (!CreateProcessW(application_path, arguments, NULL, @@ -1099,6 +1111,50 @@ int uv_spawn(uv_loop_t* loop, goto done; } + if (options->cpumask != NULL) { + /* The child is currently suspended. Set its process affinity + or terminate it if we can't. */ + int i; + int cpumasksize; + DWORD_PTR sysmask; + DWORD_PTR oldmask; + DWORD_PTR newmask; + + cpumasksize = uv_cpumask_size(); + + if (!GetProcessAffinityMask(info.hProcess, &oldmask, &sysmask)) { + err = GetLastError(); + TerminateProcess(info.hProcess, 1); + goto done; + } + + newmask = 0; + for (i = 0; i < cpumasksize; i++) { + if (options->cpumask[i]) { + if (oldmask & (((DWORD_PTR)1) << i)) { + newmask |= ((DWORD_PTR)1) << i; + } else { + err = UV_EINVAL; + TerminateProcess(info.hProcess, 1); + goto done; + } + } + } + + if (!SetProcessAffinityMask(info.hProcess, newmask)) { + err = GetLastError(); + TerminateProcess(info.hProcess, 1); + goto done; + } + + /* The process affinity of the child is set. Let it run. */ + if (ResumeThread(info.hThread) == ((DWORD)-1)) { + err = GetLastError(); + TerminateProcess(info.hProcess, 1); + goto done; + } + } + /* Spawn succeeded */ /* Beyond this point, failure is reported asynchronously. */ @@ -332,6 +332,7 @@ CMAKE_CXX_SOURCES="\ cmGlobalCommonGenerator \ cmGlobalGenerator \ cmGlobalUnixMakefileGenerator3 \ + cmGlobVerificationManager \ cmHexFileConverter \ cmIfCommand \ cmIncludeCommand \ @@ -399,6 +400,7 @@ CMAKE_CXX_SOURCES="\ cmState \ cmStateDirectory \ cmStateSnapshot \ + cmStringReplaceHelper \ cmStringCommand \ cmSubdirCommand \ cmSystemTools \ @@ -823,6 +825,11 @@ while test $# != 0; do --version) cmake_version_display ; exit 2 ;; --verbose) cmake_verbose=TRUE ;; --enable-ccache) cmake_ccache_enabled=TRUE ;; + CC=*) CC=`cmake_arg "$1"` ;; + CXX=*) CXX=`cmake_arg "$1"` ;; + CFLAGS=*) CFLAGS=`cmake_arg "$1"` ;; + CXXFLAGS=*) CXXFLAGS=`cmake_arg "$1"` ;; + LDFLAGS=*) LDFLAGS=`cmake_arg "$1"` ;; --) shift; break ;; *) die "Unknown option: $1" ;; esac @@ -1118,8 +1125,10 @@ done rm -f "${TMPFILE}.cxx" if [ -z "${cmake_cxx_compiler}" ]; then -cmake_error 7 "Cannot find a C++ compiler supporting C++11 on this system. +cmake_error 7 "Cannot find a C++ compiler that supports both C++11 and the specified C++ flags. Please specify one using environment variable CXX. +The C++ flags are \"$cmake_cxx_flags\". +They can be changed using the environment variable CXXFLAGS. See cmake_bootstrap.log for compilers attempted." fi echo "C++ compiler on this system is: ${cmake_cxx_compiler} ${cmake_cxx_flags}" @@ -1535,6 +1544,9 @@ MAKE="${cmake_make_processor}" export CC export CXX export MAKE +export CFLAGS +export CXXFLAGS +export LDFLAGS # Run bootstrap CMake to configure real CMake cmake_options="-DCMAKE_BOOTSTRAP=1" |