在项目中更改 CMAKE_CXX_FLAGS [英] Changing CMAKE_CXX_FLAGS in project

查看:36
本文介绍了在项目中更改 CMAKE_CXX_FLAGS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 CMakeLists.txt 中有以下内容:

I have the following content in my CMakeLists.txt:

project( Matfile )

SET ( CMAKE_CXX_FLAGS "-std=c++0x" )

set ( SOURCES
      "foo.cpp"
      "bar.cpp"
    )

add_library(
        Matfile
        ${SOURCES}
)

正如您想象的那样,我想要做的是使用标志 -std=c++0x 编译我的 C++ 源代码(我正在使用 gcc 并且我需要 C++11 功能).不幸的是,这不起作用,因为当我使用 cmake 生成 makefile 时,变量 CMAKE_CXX_FLAGS 完全无效.

As you may imagine, what I want to do is to compile my C++ sources using the flag -std=c++0x (I'm using gcc and I need the C++11 features). Unfortunately, this does not work, in the sense that, when I use cmake to generate the makefiles, the variable CMAKE_CXX_FLAGS is completely void.

如何在项目文件中设置这个变量?

How can I set this variable in the project file?

这似乎是一个非常愚蠢的问题,但我花了不少于两个小时试图弄清楚这一点.

It seems to be a very stupid question, but I just spent not less than two houres trying to figure this out.

推荐答案

最直接的解决方案应该是使用 add_compile_options() 如果您使用的是 2.8.12 或更新版本.对于旧版本,您可以滥用"add_definitions().虽然它仅用于添加 -D 标志,但它也适用于任何其他编译器标志.但是,我认为它不应该以这种方式使用,并且可能会在未来的版本中中断.

The most straightforward solution should be using add_compile_options() if you are using version 2.8.12 or newer. For older versions you can "abuse" add_definitions(). While it is only meant for add -D flags, it also works with any other compiler flag. However, I think it is not meant to be used that way and could break in a future version.

add_compile_options(-std=c++0x) # CMake 2.8.12 or newer

add_definitions(-std=c++0x) # CMake 2.8.11 or older

从 CMake 3.3 开始,您还可以使用奇怪的生成器表达式语法使此标志仅适用于特定语言(例如,仅适用于 C 或 C++):

Starting with CMake 3.3 you can also make this flag only apply to a specific language (e.g. only C or C++) using the strange generator expressions syntax:

 add_compile_options($<$<COMPILE_LANGUAGE:CXX>:-std=c++14> $<$<COMPILE_LANGUAGE:C>:-std=c99>)

但是这将 不适用于Visual Studio 生成器,因此请确保仅将其用于 Make/Ninja 生成器或使用 target_compile_options() 在每个目标范围内设置它.

However this will not work with the Visual studio generator, so make sure to only use this for Make/Ninja generators or use target_compile_options() to set it on a per-target scope.

这篇关于在项目中更改 CMAKE_CXX_FLAGS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆