CMake ignore Anaconda libraries and compilers

Anaconda Python conda activate puts Conda directories first on environment variable PATH. This leads CMake to prefer finding Anaconda binaries (find_library, find_program, …) and Anaconda GCC compilers (if installed) over later directories on system PATH. Anaconda libraries and compilers are generally incompatible with the system or desired compiler. For certain libraries like HDF5, Anaconda is particularly problematic at interfering with CMake.

Detect Anaconda environment by existence of environment variable CONDA_PREFIX.

Fix by putting in CMakeLists.txt like the following.

NOTE: CMAKE_IGNORE_PREFIX_PATH does not take effect if set within Find*.cmake.

cmake_minimum_required(VERSION ...)

# ignore Anaconda compilers, which are typically not compatible with the system
if(DEFINED ENV{CONDA_PREFIX})
  set(CMAKE_IGNORE_PATH $ENV{CONDA_PREFIX}/bin)
endif()

project(my LANGUAGES C)

# Optional next two lines if needing Python in CMake project
unset(CMAKE_IGNORE_PATH)
find_package(Python ...)
# end optional lines

# exclude Anaconda directories from search
if(DEFINED ENV{CONDA_PREFIX})
  list(APPEND CMAKE_IGNORE_PREFIX_PATH $ENV{CONDA_PREFIX})
  list(APPEND CMAKE_IGNORE_PATH $ENV{CONDA_PREFIX}/bin)
  # need CMAKE_IGNORE_PATH to ensure system env var PATH
  # doesn't interfere despite CMAKE_IGNORE_PREFIX_PATH
endif()

To totally omit environment variable PATH from CMake find_* use CMAKE_FIND_USE_SYSTEM_ENVIRONMENT_PATH:

set(CMAKE_FIND_USE_SYSTEM_ENVIRONMENT_PATH false)

However, this can be too aggressive i.e. it might miss other programs on PATH actually wanted.