My OS is centos which has a default gcc in path /usr/bin/gcc
. But it is old, I need a new version of gcc. So I install a new version in a new path /usr/local/bin/gcc
.
But when I run cmake
, it still uses the old version gcc path(/usr/bin/gcc
) . How can I specify the gcc to new path(/usr/local/bin/gcc
).
I have tried to overwrite /usr/bin/gcc
with /usr/local/bin/gcc
, but it not work.
Best Answer
Do not overwrite
CMAKE_C_COMPILER
, but exportCC
(andCXX
) before calling cmake:The export only needs to be done once, the first time you configure the project, then those values will be read from the CMake cache.
UPDATE: longer explanation on why not overriding
CMAKE_C(XX)_COMPILER
after Jake's commentI recommend against overriding the
CMAKE_C(XX)_COMPILER
value for two main reasons: because it won't play well with CMake's cache and because it breaks compiler checks and tooling detection.When using the
set
command, you have three options:Let's see what happens for the three possible calls to
set
:Without cache
When doing this, you create a "normal" variable
CMAKE_C(XX)_COMPILER
that hides the cache variable of the same name. That means your compiler is now hard-coded in your build script and you cannot give it a custom value. This will be a problem if you have multiple build environments with different compilers. You could just update your script each time you want to use a different compiler, but that removes the value of using CMake in the first place.Ok, then, let's update the cache...
With cache
This version will just "not work". The
CMAKE_C(XX)_COMPILER
variable is already in the cache, so it won't get updated unless you force it.Ah... let's use the force, then...
Force cache
This is almost the same as the "normal" variable version, the only difference is your value will be set in the cache, so users can see it. But any change will be overwritten by the
set
command.Breaking compiler checks and tooling
Early in the configuration process, CMake performs checks on the compiler: Does it work? Is it able to produce executables? etc. It also uses the compiler to detect related tools, like
ar
andranlib
. When you override the compiler value in a script, it's "too late", all checks and detections are already done.For instance, on my machine with gcc as default compiler, when using the
set
command to/usr/bin/clang
,ar
is set to/usr/bin/gcc-ar-7
. When using an export before running CMake it is set to/usr/lib/llvm-3.8/bin/llvm-ar
.