【问题标题】:Cmake not applying compile option using add_compile_optionsCmake不使用add_compile_options应用编译选项
【发布时间】:2016-11-09 22:05:07
【问题描述】:

我试图通过 add_compile_options 将 cmake 与以下编译选项一起使用:add_compile_options(-pipe -O2 -std=c++98 -W -Wall -pedantic)

但是在编译的时候好像并没有实际使用。

make -n | grep pedantic 不返回任何内容

仅供参考,我的 cmake 命令及其返回的内容:

cmake -G"Unix Makefiles" -DARCH:STRING=x86 -Bosef -H. -DCMAKE_C_COMPILER=/usr/bin/gcc -DCMAKE_CXX_COMPILER=/usr/bin/g++
-- The C compiler identification is GNU 4.8.3
-- The CXX compiler identification is GNU 4.8.3
-- Check for working C compiler: /usr/bin/gcc
-- Check for working C compiler: /usr/bin/gcc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Check for working CXX compiler: /usr/bin/g++
-- Check for working CXX compiler: /usr/bin/g++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- cmake run for linux x86
-- Configuring done
-- Generating done
-- Build files have been written to: /home/davidlevy/WS/LC4/main/osef

我该怎么做才能真正应用这些选项?

PS : 我注意到它们没有被应用,因为 make 没有输出一个警告

编辑:如果我使用

set (
  CMAKE_CXX_FLAGS
  "${CMAKE_CXX_FLAGS} "
  "${CMAKE_CXX_FLAGS} -pipe -O2 -std=c++98 -W -Wall -pedantic"
)

Make /usr/bin/g++ ; -pipe -O2 -std=c++98 -W -Wall -pedantic -I ENDOFTHECOMMAND 我不知道这是在哪里做的;来自

【问题讨论】:

  • 您需要什么零件的示例?并且 Verbose 证实了我的想法,没有给 g++ 提供编译选项
  • 我们可以复制到我们的系统并试用的最小示例。您没有包含问题最可能所在的 CMake 代码,参见。 stackoverflow.com/help/mcve.

标签: cmake g++


【解决方案1】:

add_compile_options() 确实附加到COMPILE_OPTIONS 目录属性,并被视为在add_compile_options() 命令之后 出现的目标的所有COMPILE_OPTIONS 属性的默认值。

CMAKE_CXX_FLAGS 不同,后者适用于当前CMakeLists.txt 中的所有目标。

所以请确保add_compile_options() 命令是之前有问题的add_library()/add_executable

来自add_compile_options() 文档:

将选项添加到编译器命令行,用于当前目录及以下目录中的目标调用此命令之后添加。

参考文献

【讨论】:

  • 就是这样,谢谢。我不明白那句话是什么意思
【解决方案2】:

代替

set (
  CMAKE_CXX_FLAGS
  "${CMAKE_CXX_FLAGS} "
  "${CMAKE_CXX_FLAGS} -pipe -O2 -std=c++98 -W -Wall -pedantic"
)

应该是

set(
  CMAKE_CXX_FLAGS
  "${CMAKE_CXX_FLAGS} -pipe -O2 -std=c++98 -W -Wall -pedantic"
)

因为您要使用的合成器是set(variable value)。在您的情况下,您将 CMAKE_CXXFLAGS 设置为第二个(空字符串)和第三个参数(您添加的标志)的列表。

文档:https://cmake.org/cmake/help/v3.7/command/set.html

【讨论】:

  • 这项工作确实有效(这是回家前最后一次执行不佳的尝试)。但是add_compile_options 是添加编译器选项的更好方法,所以我接受其他答案。
  • 不,set() 不会忽略第三个参数。当您将三个或更多参数传递给set() 时,您最终会创建一个list。这就是您链接到的 CMake 文档中 <value>...... 部分的含义。 CMake 将列表表示为一个字符串,其中项目用分号分隔,这就是为什么原始问题后半部分的输出包含分号的原因。话虽如此,附加到CMAKE_CXX_FLAGS 的正确方法确实是这个答案所建议的。
  • @CraigScott 你说得对,谢谢提示,我更正了我的答案。
【解决方案3】:

CMake 文档很荒谬,他们删除了 Adds options to the compiler command line for targets in the current directory and below that are added after this command is invoked. 来自 add_compile_options() 手册。感谢弗洛里安的这个提示。

https://cmake.org/cmake/help/v3.21/command/add_compile_options.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-26
    • 2021-06-24
    • 1970-01-01
    • 2011-03-09
    • 1970-01-01
    • 2015-09-07
    相关资源
    最近更新 更多