How to get CMake to use the default compiler on system PATH?

Sap picture Sap · Apr 27, 2015 · Viewed 10.2k times · Source

There is the same question and the answer. The problem is that the answer seems to be wrong (actually is not the answer to the asked question). Can I re-ask the question? The problem:

$ echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games
$ whereis gcc
cc: /usr/bin/gcc /usr/lib/gcc /usr/local/bin/gcc /usr/libexec/gcc
$ which gcc
/usr/local/bin/gcc
$ /usr/bin/gcc -v
gcc version 4.1.2
$ /usr/local/bin/gcc -v
gcc version 4.8.4
$ gcc -v
gcc version 4.8.4
$ cmake .
-- The C compiler identification is GNU 4.1.2
...
...

The local GCC version if 4.8.4 and the system's default version is '4.1.2'. All other tool-chains respects the PATH environment variable and use the local (newer) GCC version. All except of CMAKE. Setting CC is not a good idea, because there might be other binary tools which could also be used. Setting CMAKE_PROGRAM_PATH and CMAKE_PREFIX_PATH in the beginning of the script doesn't help with detection of the compilers.
Is there any way to force CMAKE to respect the PATH variable?

Answer

sakra picture sakra · Apr 27, 2015

As is already written in the answer to the other question, CMake prefers the generic compiler names cc and c++ when searching for the C and C++ compilers. These probably refer to GNU version 4.1 compilers on your system.

Anyway, to force CMake to use the default compilers on the system path, add the following code to the beginning of your outermost CMakeLists.txt.

find_program(CMAKE_C_COMPILER NAMES $ENV{CC} gcc PATHS ENV PATH NO_DEFAULT_PATH)
find_program(CMAKE_CXX_COMPILER NAMES $ENV{CXX} g++ PATHS ENV PATH NO_DEFAULT_PATH)
...
project (Foo C CXX)

The find_program calls must occur before the call to project or enable_language.