cmake: build the "all" examples source list dynamically

To allow building conditional examples, and to simplify by avoiding
cmake-version dependent code.

Follow-up to fe5225b5ea #18209
Cherry-picked from #18909
Closes #18911
This commit is contained in:
Viktor Szakats 2025-10-07 14:04:12 +02:00
parent 089afd78cb
commit 7ddbde4f73
No known key found for this signature in database
GPG key ID: B5ABD165E2AEF201

View file

@ -28,15 +28,14 @@ add_custom_target(curl-examples)
curl_transform_makefile_inc("Makefile.inc" "${CMAKE_CURRENT_BINARY_DIR}/Makefile.inc.cmake")
include("${CMAKE_CURRENT_BINARY_DIR}/Makefile.inc.cmake")
set(_all_src "")
set(_all_canary "")
set(_all "all")
foreach(_target IN LISTS check_PROGRAMS _all) # keep '_all' last
set(_target_name "curl-example-${_target}")
if(_target STREQUAL "all")
if(CMAKE_VERSION VERSION_GREATER_EQUAL 3.12)
set(_examples_c "${check_PROGRAMS}")
list(TRANSFORM _examples_c APPEND ".c")
add_library(${_target_name} OBJECT EXCLUDE_FROM_ALL ${_examples_c})
add_library(${_target_name} OBJECT EXCLUDE_FROM_ALL ${_all_src})
if(CMAKE_C_COMPILER_ID STREQUAL "MSVC") # MSVC but exclude clang-cl
# CMake generates a static library for the OBJECT target. Silence these 'lib.exe' warnings:
# warning LNK4006: main already defined in ....obj; second definition ignored
@ -49,16 +48,13 @@ foreach(_target IN LISTS check_PROGRAMS _all) # keep '_all' last
endif()
endif()
else()
set(_examples_c "")
foreach(_src IN LISTS check_PROGRAMS)
list(APPEND _examples_c "${_src}.c")
endforeach()
add_library(${_target_name} STATIC EXCLUDE_FROM_ALL ${_examples_c})
add_library(${_target_name} STATIC EXCLUDE_FROM_ALL ${_all_src})
endif()
add_custom_target(curl-examples-build) # Special target to compile all tests quickly and build a single test to probe linkage
add_dependencies(curl-examples-build ${_target_name} ${_all_canary}) # Include a full build of a single test
else()
set(_all_canary ${_target_name}) # Save the last test for the curl-examples-build target
list(APPEND _all_src "${_target}.c")
add_executable(${_target_name} EXCLUDE_FROM_ALL "${_target}.c")
add_dependencies(curl-examples ${_target_name})
endif()