Unable to specify the compiler with CMake

Pietro picture Pietro · Oct 24, 2012 · Viewed 121.5k times · Source

I have a problem with this CMakeLists.txt file:

cmake_minimum_required(VERSION 2.6)

SET(CMAKE_C_COMPILER C:/MinGW/bin/gcc)
SET(CMAKE_CXX_COMPILER C:/MinGW/bin/g++)

project(cmake_test)

add_executable(a.exe test.cpp)

Calling cmake with: cmake -G "MinGW Makefiles" , it fails with the following output:

c:\Users\pietro.mele\projects\tests\buildSystem_test\cmake_test>cmake -G "MinGW Makefiles" .
-- The C compiler identification is GNU 4.6.1
-- The CXX compiler identification is GNU 4.6.1
-- Check for working C compiler: C:/MinGW/bin/gcc
CMake Error: your C compiler: "C:/MinGW/bin/gcc" was not found.   Please set CMAKE_C_COMPILER to a valid compiler path or name.
CMake Error: Internal CMake error, TryCompile configure of cmake failed
-- Check for working C compiler: C:/MinGW/bin/gcc -- broken
CMake Error at C:/Program Files (x86)/CMake 2.8/share/cmake-2.8/Modules/CMakeTestCCompiler.cmake:52 (MESSAGE):
  The C compiler "C:/MinGW/bin/gcc" is not able to compile a simple test
  program.

CMake will not be able to correctly generate this project.
Call Stack (most recent call first):
CMakeLists.txt:10 (project)

CMake Error: your C compiler: "C:/MinGW/bin/gcc" was not found.   Please set CMAKE_C_COMPILER to a valid compiler path or name.
CMake Error: your CXX compiler: "C:/MinGW/bin/g++" was not found.   Please set CMAKE_CXX_COMPILER to a valid compiler path or name.
-- Configuring incomplete, errors occurred!

However the gcc compiler is in C:/MinGW/bin/ and it works.

Any idea?

Platform:

  • Windows 7
  • MinGW/GCC 4.6

Answer

DLRdave picture DLRdave · Oct 26, 2012

Never try to set the compiler in the CMakeLists.txt file.

See the CMake FAQ about how to use a different compiler:

https://gitlab.kitware.com/cmake/community/wikis/FAQ#how-do-i-use-a-different-compiler

(Note that you are attempting method #3 and the FAQ says "(avoid)"...)

We recommend avoiding the "in the CMakeLists" technique because there are problems with it when a different compiler was used for a first configure, and then the CMakeLists file changes to try setting a different compiler... And because the intent of a CMakeLists file should be to work with multiple compilers, according to the preference of the developer running CMake.

The best method is to set the environment variables CC and CXX before calling CMake for the very first time in a build tree.

After CMake detects what compilers to use, it saves them in the CMakeCache.txt file so that it can still generate proper build systems even if those variables disappear from the environment...

If you ever need to change compilers, you need to start with a fresh build tree.