Automatically select C ++ version 11 compatible g ++ in Makefile

Problem:

Version 2 of g ++ is installed on a computer running Ubuntu 12.04. These are versions 4.6 and 5.2.

I need to compile a C ++ 11 program using a Makefile. If I use g ++ as a compiler, it automatically calls version 4.6, it does not support C ++ 11, so compilation does not work. I followed the tutorial online, so now, if I call g ++, it will automatically call version 5.2, and now it works.

I find this solution not very good, since it only works on my PC. Is there a way to recognize in the Makefile if the g ++ version supports C ++ 11 by default and, if not, switch to a newer version?

Thanks!

+4
source share
6 answers

Is there a way to recognize in the Makefile if the g ++ version supports C ++ 11 by default and, if not, switch to a newer version?

You can definitely determine the default compiler version available PATHin your makefile. However, where are you looking for another version?

The standard approach is to allow the user to specify a C compiler through CC, and the C ++ compiler through the CXXmake variables, such as: make CC=/path/to/my/gcc CXX=/path/to/my/g++.

+6
source

You can always choose which gcc to use when calling make

make CXX=/gcc/path/of/your/choice

otherwise you may discover the version gccusing

ifdef CXX
     GCC_VERSION = $(shell $(CXX) -dumpversion)                                                                                               
else
     GCC_VERSION = $(shell g++ -dumpversion)
endif

Makefile , gcc >= 4.6

ifeq ($(shell expr $(GCC_VERSION) '>=' 4.6), 1)
+3

- make , , , , gcc . :

CXX=g++

ifeq (/usr/bin/g++-4.9,$(wildcard /usr/bin/g++-4.9*))
    CXX=g++-4.9
# else if... (a list of known-to-be-ok versions)
endif

, make script, , , ./configure. autotools, .

+2

, Makefile, . .

$(CXX) C++ g++ Linux. , clanging CXX .

, . :

program: program.cpp
    g++ -o program program.cpp

:

program: program.cpp
    $(CXX) -o program program.cpp

, :

CPPFLAGS = -Iinclude
CXXFLAGS = -std=c++14 -g3 -O0

CPPFLAGS CXXFLAGS LDLIBS.

Using default environment variables allows a person to compile a project with the ability to control compilation for their desired environment.

See GNU make manual

+1
source

You can check the gcc version in your source code and abort the compilation if you don't like it. Here 's how it works:

/* Test for GCC > 4.6 */
#if !(__GNUC__ > 3 && __GNUC_MINOR__ > 6)
#error gcc above version 4.6 required!
#endif
0
source

This works for me:

cmake_minimum_required(VERSION 2.8.11)
project(test)

if (${CMAKE_CXX_COMPILER_VERSION} LESS 5.0)
    message(FATAL_ERROR "You need a version of gcc > 5.0")
endif (${CMAKE_CXX_COMPILER_VERSION} LESS 5.0)

add_executable(test test.cpp)
0
source

Source: https://habr.com/ru/post/1627267/


All Articles