try_compile: Honor CMP0128 setting in test project

Some projects pass a raw `-std=` flag to the compiler in the
`try_compile` project.  If they do not set CMP0128 to NEW,
we should not append a `-std=` flag where we did not before
the policy was added.

Fixes: #24063
This commit is contained in:
Brad King
2022-10-18 09:12:10 -04:00
parent 367f10f4cb
commit 50e90e2828
6 changed files with 72 additions and 0 deletions

View File

@@ -577,6 +577,12 @@ int cmCoreTryCompile::TryCompileCode(std::vector<std::string> const& argv,
fprintf(fout, "cmake_policy(SET CMP0126 OLD)\n");
}
/* Set language extensions policy to match outer project. */
if (this->Makefile->GetPolicyStatus(cmPolicies::CMP0128) !=
cmPolicies::NEW) {
fprintf(fout, "cmake_policy(SET CMP0128 OLD)\n");
}
std::string projectLangs;
for (std::string const& li : testLangs) {
projectLangs += " " + li;

View File

@@ -0,0 +1,7 @@
cmake_policy(SET CMP0128 NEW)
set(check_cxx_std "
#if __cplusplus > 199711L && __cplusplus <= 201103L
# error Compiler is incorrectly in C++11 mode.
#endif
")
include(CMP0128-common.cmake)

View File

@@ -0,0 +1,7 @@
set(check_cxx_std "
#if __cplusplus <= 199711L || __cplusplus > 201103L
# error Compiler is incorrectly not in C++11 mode.
#endif
")
include(CMP0128-common.cmake)

View File

@@ -0,0 +1,31 @@
cmake_policy(SET CMP0067 NEW)
enable_language(CXX)
# Isolate the one try_compile below in the error log.
set(CMakeError_log "${CMAKE_BINARY_DIR}/CMakeFiles/CMakeError.log")
file(REMOVE "${CMakeError_log}")
# Add our own -std= flag to the try_compile check.
set(CMAKE_REQUIRED_FLAGS -std=c++11)
# Tell CMP0128 NEW behavior to append a -std= flag (after ours).
if(CMAKE_CXX_EXTENSIONS_DEFAULT)
set(CMAKE_CXX_EXTENSIONS OFF)
else()
set(CMAKE_CXX_EXTENSIONS ON)
endif()
include(CheckSourceCompiles)
check_source_compiles(CXX "
${check_cxx_std}
int main()
{
return 0;
}
" SRC_COMPILED)
if(NOT SRC_COMPILED)
if(EXISTS "${CMakeError_log}")
file(READ "${CMakeError_log}" err_log)
endif()
message("${err_log}")
endif()

View File

@@ -0,0 +1,4 @@
enable_language(CXX)
file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/info.cmake" "
set(CMAKE_CXX_EXTENSIONS_DEFAULT \"${CMAKE_CXX_EXTENSIONS_DEFAULT}\")
")

View File

@@ -114,6 +114,23 @@ if(RunCMake_GENERATOR MATCHES "Make|Ninja")
unset(RunCMake_TEST_NO_CLEAN)
endif()
# Lookup CMAKE_CXX_EXTENSIONS_DEFAULT.
# FIXME: Someday we could move this to the top of the file and use it in
# place of some of the values passed by 'Tests/RunCMake/CMakeLists.txt'.
run_cmake(Inspect)
include("${RunCMake_BINARY_DIR}/Inspect-build/info.cmake")
# FIXME: Support more compilers and default standard levels.
if (CMAKE_CXX_COMPILER_ID MATCHES "^(GNU|AppleClang)$"
AND DEFINED CMAKE_CXX_STANDARD_DEFAULT
AND DEFINED CMAKE_CXX_EXTENSIONS_DEFAULT
)
run_cmake(CMP0128-WARN)
if(NOT CMAKE_CXX_STANDARD_DEFAULT EQUAL 11)
run_cmake(CMP0128-NEW)
endif()
endif()
if(UNIX)
run_cmake(CleanupNoFollowSymlink)
endif()