8

我想将特定的编译器 cxx 标志添加到发布模式。我在另一个线程中读到 -O2 是发布配置的好标志

set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -Wall -O2")

但如果我现在检查 CXX 标志

message(${CMAKE_CXX_FLAGS_RELEASE})

他给我写信

-O3 -DNDEBUG -Wall -O2
  1. 使用 -02 而不是 -03 有意义吗?
  2. 如何从标志中删除 -03?
  3. DNDEBUG 有什么用途?

此致

4

3 回答 3

13

Use compiler documentation to see difference between O2 and O3 and make your choice (: for example - gcc. Here you can found recommendation to use O2 for stability.


You can use this macro for removing flags:

macro(remove_cxx_flag flag)
  string(REPLACE "${flag}" "" CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}")
endmacro()

[usage]

  macro(remove_cxx_flag flag)
    string(REPLACE "${flag}" "" CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE}")
  endmacro()

  message(${CMAKE_CXX_FLAGS_RELEASE}) # print "-O3 -DNDEBUG"
  remove_cxx_flag("-O3")
  message(${CMAKE_CXX_FLAGS_RELEASE}) # print "-DNDEBUG"

Here is used macro because you need to update variable from parent scope, read this - http://www.cmake.org/cmake/help/v2.8.10/cmake.html#command:macro (or you can use function with PARENT_SCOPE modifier)


NDEBUG used for disabling assert, see What is the NDEBUG preprocessor macro used for (on different platforms)? for more info.

于 2013-08-14T14:46:22.637 回答
4

${val}引用一个变量。

您的set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -Wall -O2")

添加之前配置的 CMAKE_CXX_FLAGS_RELEASE 变量。

所以改成

set(CMAKE_CXX_FLAGS_RELEASE "-DNDEBUG -Wall -O2")

-DNDEBUG从您的代码中删除断言 - 跳过它。更多信息请访问http://en.cppreference.com/w/cpp/error/assert

于 2018-04-14T16:46:02.677 回答
2

修改标志

如果要覆盖设置为的默认值CMAKE_C_FLAGS_RELEASECMAKE_CXX_FLAGS_RELEASE变量,CMAKE_BUILD_TYPE release-O3 -DNDEBUG需要在该project行之前执行此操作。本质上,如果发布构建类型默认值不适合您,您需要自己动手。另一种可能性是在CMAKE_TOOLCHAIN_FILE

cmake_minimum_required( VERSION 3.8 )

set( CMAKE_C_FLAGS_DEBUG "" CACHE STRING "" )       
set( CMAKE_CXX_FLAGS_DEBUG "" CACHE STRING "" )
set( CMAKE_C_FLAGS_RELEASE "" CACHE STRING "" )
set( CMAKE_CXX_FLAGS_RELEASE "" CACHE STRING "" )

project(hello)

set( SOURCE_FILES
    hello.c foo.c )

add_executable( hello
    ${SOURCE_FILES} )


set_source_files_properties( foo.c 
    PROPERTIES
    COMPILE_FLAGS "-O3 -DNDEBUG" )

set_source_files_properties( hello.c 
    PROPERTIES
    COMPILE_FLAGS -O0 )
于 2017-12-21T21:02:40.750 回答