Link against threading library only if necessary

1. The platform specific threads library is only needed if we actually
   use threads. In this case, the library is not optional opposed to
   previous logic.
2. Do not hide the find module output to allow the user to understand
   what happens in case of a CMake failure to locate Threads.
3. Finally, Threads is private dependency that does need to be
   propagated to consumers unless Ceres was compiled as a static
   library.

Change-Id: I8d9d9cd42930e1ed234f69a2dba70d0ee2755b4e
diff --git a/cmake/CeresConfig.cmake.in b/cmake/CeresConfig.cmake.in
index 06f0fdd..32108e4 100644
--- a/cmake/CeresConfig.cmake.in
+++ b/cmake/CeresConfig.cmake.in
@@ -1,5 +1,5 @@
 # Ceres Solver - A fast non-linear least squares minimizer
-# Copyright 2015 Google Inc. All rights reserved.
+# Copyright 2022 Google Inc. All rights reserved.
 # http://ceres-solver.org/
 #
 # Redistribution and use in source and binary forms, with or without
@@ -176,11 +176,10 @@
 set(CERES_VERSION @CERES_VERSION@)
 
 include(CMakeFindDependencyMacro)
-find_dependency(Threads)
-
 # Optional dependencies
-@SuiteSparse_DEPENDENCY@
 @OpenMP_DEPENDENCY@
+@SuiteSparse_DEPENDENCY@
+@Threads_DEPENDENCY@
 
 # As imported CMake targets are not re-exported when a dependent target is
 # exported, we must invoke find_package(XXX) here to reload the definition
diff --git a/internal/ceres/CMakeLists.txt b/internal/ceres/CMakeLists.txt
index d6babfb..4c9bfe7 100644
--- a/internal/ceres/CMakeLists.txt
+++ b/internal/ceres/CMakeLists.txt
@@ -28,10 +28,17 @@
 #
 # Author: keir@google.com (Keir Mierle)
 
+# Build the list of dependencies for Ceres based on the current configuration.
+
 # Avoid 'xxx.cc has no symbols' warnings from source files which are 'empty'
 # when their enclosing #ifdefs are disabled.
 if (CERES_THREADING_MODEL STREQUAL "CXX_THREADS")
   set(CERES_PARALLEL_FOR_SRC parallel_for_cxx.cc thread_pool.cc)
+  find_package(Threads REQUIRED)
+  list(APPEND CERES_LIBRARY_PRIVATE_DEPENDENCIES Threads::Threads)
+
+  # Make dependency visible to the parent CMakeLists.txt
+  set(Threads_DEPENDENCY "find_dependency (Threads)" PARENT_SCOPE)
 elseif (CERES_THREADING_MODEL STREQUAL "OPENMP")
   # OpenMP requires linking to the corresponding library.
   find_package(OpenMP REQUIRED COMPONENTS CXX)
@@ -100,10 +107,6 @@
   message(FATAL_ERROR "Unity build requires cmake 3.16 or newer.  Please unset CMAKE_UNITY_BUILD.")
 endif()
 
-# Build the list of dependencies for Ceres based on the current configuration.
-find_package(Threads QUIET)
-list(APPEND CERES_LIBRARY_PUBLIC_DEPENDENCIES Threads::Threads)
-
 if (NOT MINIGLOG AND GLOG_FOUND)
   list(APPEND CERES_LIBRARY_PUBLIC_DEPENDENCIES ${GLOG_LIBRARIES})
   if (gflags_FOUND)