Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplest C++ Example to verify my compiler is c++14 compliant?

Tags:

c++

gcc

c++11

c++14

I am taking a class next week on C++11/14 and need to verify that my design tools are up to date and can actually compile C++11/14.

What is the simplest piece of code that I can put together to verify that I can actually compile and execute C++11/14 code on my Linux box? I know I need GCC 4.9.X or better, but I want to just be sure that everything is jiving before I show up.

Thanks for the help.

like image 261
It'sPete Avatar asked Jun 19 '15 14:06

It'sPete


2 Answers

You can initially compile with -std=c++14. If your gcc (or clang) is not c++14 compliant then compilation will fail (due to uknown flag) :

g++: error: unrecognized command line option '-std=c++14'

Regarding feature availability (querying the existence of specific features), you can perform feature testing. An example document can be found here : it all boils down to the use of macros to test the availability of the specified feature (therein you can also find what features to look for).

So even if you want to build with several compilers you can write code like this (naive example follows) :

#if __cpp_constexpr
constexpr 
#endif
int triple(int k) { return 3*k; } // compiles with c++98 as well

which is how cross platform developing overcomes the joys of supporting multiple compilers and their versions (more elaborate examples would show supporting sth one way in gcc and another way in cl due to different speed of standard implementation)

like image 93
Nikos Athanasiou Avatar answered Oct 26 '22 12:10

Nikos Athanasiou


The __cplusplus macro contains the C++ standard that the compiler is using. Each version of C++ has a specific value for this define. These may (counter intuitively) not match exactly with the name of the standard, so you can use gcc to determine what the values are. For example:

#include <stdio.h>
int main()
{
   printf("%ld\n", __cplusplus);
}

Compiled like so:

g++ -std=c++98 file.cpp
g++ -std=c++11 file.cpp
g++ -std=c++14 file.cpp

Gives the following respectively when run:

199711
201103
201300

You can then use the predefined macros to generate errors if the value you're looking for isn't available. For example:

#if __cplusplus < 201300
#error I require C++14 for this code, so die.
#endif
// ...

Then g++ -std=c++11 file.cpp will fail compilation.

like image 41
MuertoExcobito Avatar answered Oct 26 '22 12:10

MuertoExcobito