如何在CLion中启用C++11?

20

我正在尝试在CLion中运行C++11代码,但它无法工作。它显示:

...
    /projects/CLion/untitled/main.cpp:7:1: note: C++11 ‘constexpr’ only available with -std=c++11 or -std=gnu++11
...

我尝试将CMAKE_C_FLAGS设置为-std=c++11-std=gnu++11,但仍然遇到同样的问题。普通的C++代码编译得很好。

我需要在CLion的CMake窗口中设置哪个标志才能编译我的C++11代码?

2个回答

27

我试图设置 CMAKE_C_FLAGS

根据文档CMAKE_C_FLAGS用于设置所有构建类型的 C 语言标志。对于 C++,您需要使用CMAKE_CXX_FLAGS来替代:

set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")

1
@hlin117,简短的回答是你不必担心先前初始化或声明这些变量。如果变量已经存在,则将使用它,否则将用空字符串替换。通常情况下,这种声明形式允许更改现有变量的值,而不是重写。 - Gluttton
为了启用C++14,我尝试使用“-std=c++14”,但它不起作用。有什么想法吗? - a06e
@becko,您使用的是哪种编译器以及版本? - Gluttton
@becko,看起来4.8.4不支持C++14(我无法证明这个假设),但你可以尝试通过添加“-std=c++y”来使用实验性的实现。 - Gluttton
尝试使用 -std=c++1y(不仅仅是 y)来编译支持早期 C++14 的编译器。 - U007D
显示剩余3条评论

12

对于CMake 3.1或更高版本,您可以将CMAKE_CXX_STANDARD变量设置为11

目标的CXX_STANDARD属性的默认值。

此变量用于在所有目标上初始化CXX_STANDARD属性。

CXX_STANDARD文档

The C++ standard whose features are requested to build this target.

This property specifies the C++ standard whose features are requested to build this target. For some compilers, this results in adding a flag such as -std=gnu++11 to the compile line.

Supported values are 98, 11 and 14.

If the value requested does not result in a compile flag being added for the compiler in use, a previous standard flag will be added instead. This means that using:

set_property(TARGET tgt PROPERTY CXX_STANDARD 11)

with a compiler which does not support -std=gnu++11 or an equivalent flag will not result in an error or warning, but will instead add the -std=gnu++98 flag if supported. This “decay” behavior may be controlled with the CXX_STANDARD_REQUIRED target property.

See the cmake-compile-features(7) manual for information on compile features.

This property is initialized by the value of the CMAKE_CXX_STANDARD variable if it is set when a target is created.


10
如果我想要 -std=c++11 而不是 -std=gnu++11,那么 CXX_STANDARD 11 如何区分这两者之间的差异? - Ela782

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接