10

Currently, I invoke CMake from my build directory as follows:

CXX="/opt/gcc-4.8/bin/g++" cmake ..

to get CMake to use this particular compiler. Otherwise it uses the operating system default compiler.

My PATH has "/opt/gcc-4.8/bin" in front of everything else. So, instead of prepending the environmental variable is there way to specify in the "`CMakeLists.txt" file to use the default g++ on the path?

Jeet
  • 38,594
  • 7
  • 49
  • 56
  • 2
    Sigh, yes, so annoying. If the project is your own (or if you can submit a pull request), you can refer to [this SO answer](https://stackoverflow.com/a/29904501/785213) for how to resolve this using a couple of `find_program`s in your `CMakeFiles.txt` to get the C and C++ compilers from the `$PATH` environment variable—no symlinks required. Especially in an HPC environment where we use [modules](http://modules.sourceforge.net/) extensively, this would seem to me to be the sensible default behavior, which is unfortunately _not_ the CMake default behavior. – TheDudeAbides Dec 10 '19 at 21:24

2 Answers2

11

CMake honors the setting of the PATH environment variable, but gives preference to the generic compiler names cc and c++. To determine which C compiler will be used by default under UNIX by CMake, run:

$ which cc

To determine the default C++ compiler, run:

$ which c++

If you generate a symbolic link c++ in /opt/gcc-4.8/bin which points to /opt/gcc-4.8/bin/g++, CMake should use GCC 4.8 by default.

sakra
  • 62,199
  • 16
  • 168
  • 151
  • OK, thanks. Turns out that the shell script that I was running messed up my PATH. Accepting this answer for the useful information "CMake honors the setting of the PATH environment variable, but gives preference to the generic compiler names cc and c++" anyway. – Jeet Apr 18 '13 at 15:53
2

The location of cc rather than c++ determines which c++ cmake is going to use. So for example, if you have /usr/local/bin/c++ but /usr/local/bin/cc, cmake would still pickup /usr/bin/c++, not /usr/local/bin/c++. In this case, creating a symbolic link at /usr/local/bin/cc pointing to /usr/local/bin/gcc would have cmake to use /usr/local/bin/c++.

Another approach would be to explicitly set the language of your project to C++:

project(foo CXX)

York
  • 2,056
  • 1
  • 15
  • 23
  • Thanks; this is helpful. Unfortunately, when I add a symlink like this, CMake also insists on picking up Python from the same directory (even though the Python I want is earlier in my PATH). Is there really no way to convince this thing just to get stuff from my PATH, like every other Unix utility since the beginning of time? – Nemo Feb 22 '19 at 22:43