Posted By: Anonymous
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
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(
I have tried to overwrite
/usr/local/bin/gcc, but it not work.
Do not overwrite
CMAKE_C_COMPILER, but export
CXX) before calling cmake:
export CC=/usr/local/bin/gcc export CXX=/usr/local/bin/g++ cmake /path/to/your/project make
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 comment
I 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:
- without cache, to create a normal variable
- with cache, to create a cached variable
- force cache, to always force the cache value when configuring
Let’s see what happens for the three possible calls to
set(CMAKE_C_COMPILER /usr/bin/clang) set(CMAKE_CXX_COMPILER /usr/bin/clang++)
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…
set(CMAKE_C_COMPILER /usr/bin/clang CACHE PATH "") set(CMAKE_CXX_COMPILER /usr/bin/clang++ CACHE PATH "")
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…
set(CMAKE_C_COMPILER /usr/bin/clang CACHE PATH "" FORCE) set(CMAKE_CXX_COMPILER /usr/bin/clang++ CACHE PATH "" FORCE)
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
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
ranlib. 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
ar is set to
/usr/bin/gcc-ar-7. When using an export before running CMake it is set to