c++ path - How does CMake choose gcc and g++for compiling?




system this (3)

I am newbie of CMake, and I was wondering for a C++/C project in the LINUX environmental how CMake can choose compilers between gcc and g++. More specifically, my questions are as follows:

  1. If a project is consisted of .c and .cpp file, is it true that the .c files will be compiled by gcc while the .cpp files will be compiled by g++?
  2. If a project has only c files or cpp files, what's the default compiling operation for CMake? Will it be possible to change it?

Answers

As far as I know CMake only look at the file extensions. So if you rename your .c file to .cpp it will, as far as I know, be compiled with g++.

It is easy to change that behaviour. CMake uses environment variables to see which compiler to use. If you would like to change compiler to e.g. clang and clang++, you can just do

export CC=clang export CXX=clang++

before running cmake.


Shortly, yes to both.

You can mangle with pretty much everything. There are flags and variables that bind extensions to language; and then language to compiler options/executables that define toolsets and build targets.

Check following links to documentation. Those are some pleasant short readings.

  1. Change compiler/toolset
  2. Per-language extensions
  3. LANGUAGE variable

Note: The wiki might be outdated but it should hold in case of important and educational matter.

PS. There is whole bunch of related options. For some longer read you can check following sections of documentation: Properties on Source Files and Variables for Languages. 2. and 3. come from these sections.


The explicit-keyword can be used to enforce a constructor to be called explicitly.

class C{
public:
    explicit C(void) = default;
};

int main(void){
    C c();
    return 0;
}

the explicit-keyword in front of the constructor C(void) tells the compiler that only explicit call to this constructor is allowed.

The explicit-keyword can also be used in user-defined type cast operators:

class C{
public:
    explicit inline operator bool(void) const{
        return true;
    }
};

int main(void){
    C c;
    bool b = static_cast<bool>(c);
    return 0;
}

Here, explicit-keyword enforces only explicit casts to be valid, so bool b = c; would be an invalid cast in this case. In situations like these explicit-keyword can help programmer to avoid implicit, unintended casts. This usage has been standardized in C++11.







c++ cmake