如何在CMake文件中添加链接器或编译标志? [英] How do I add a linker or compile flag in a CMake file?

查看:114
本文介绍了如何在CMake文件中添加链接器或编译标志?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 arm-linux-androideabi-g ++ 编译器。当我尝试编译一个简单的 Hello,World!时程序可以编译良好。当我通过在该代码中添加简单的异常处理对其进行测试时,它也可以工作(在添加 -fexceptions 之后。我猜它默认是禁用的)。

I am using the arm-linux-androideabi-g++ compiler. When I try to compile a simple "Hello, World!" program it compiles fine. When I test it by adding a simple exception handling in that code it works too (after adding -fexceptions .. I guess it is disabled by default).

这是用于Android设备,我只想使用CMake,而不是 ndk-build

This is for an Android device, and I only want to use CMake, not ndk-build.

例如- first.cpp

#include <iostream>

using namespace std;

int main()
{
   try
   {
   }
   catch (...)
   {
   }
   return 0;
}

。/arm-linux-androideadi-g ++- o first-test first.cpp -fexceptions

它没有问题...

问题 ...我正在尝试使用CMake文件编译该文件。

The problem ... I am trying to compile the file with a CMake file.

我想添加 -fexceptions 作为标志。我尝试了

I want to add the -fexceptions as a flag. I tried with

set (CMAKE_EXE_LINKER_FLAGS -fexceptions ) or set (CMAKE_EXE_LINKER_FLAGS "fexceptions" )

set ( CMAKE_C_FLAGS "fexceptions")

它仍然显示错误。

推荐答案

假设您要添加这些标志(最好在常量中声明它们):

Suppose you want to add those flags (better to declare them in a constant):

SET(GCC_COVERAGE_COMPILE_FLAGS "-fprofile-arcs -ftest-coverage")
SET(GCC_COVERAGE_LINK_FLAGS    "-lgcov")

有几种添加方法:


  1. 最简单的方法(不干净,但很容易且方便,并且仅适用于C和C ++编译标志):

  1. The easiest one (not clean, but easy and convenient, and works only for compile flags, C & C++ at once):

add_definitions(${GCC_COVERAGE_COMPILE_FLAGS})


  • 附加到相应的CMake变量:

  • Appending to corresponding CMake variables:

    SET(CMAKE_CXX_FLAGS  "${CMAKE_CXX_FLAGS} ${GCC_COVERAGE_COMPILE_FLAGS}")
    SET(CMAKE_EXE_LINKER_FLAGS  "${CMAKE_EXE_LINKER_FLAGS} ${GCC_COVERAGE_LINK_FLAGS}")
    


  • 使用目标属性,请参见。 doc CMake编译标志目标属性,并且需要知道目标名称。

  • Using target properties, cf. doc CMake compile flag target property and need to know the target name.

    get_target_property(TEMP ${THE_TARGET} COMPILE_FLAGS)
    if(TEMP STREQUAL "TEMP-NOTFOUND")
      SET(TEMP "") # Set to empty string
    else()
      SET(TEMP "${TEMP} ") # A space to cleanly separate from existing content
    endif()
    # Append our values
    SET(TEMP "${TEMP}${GCC_COVERAGE_COMPILE_FLAGS}" )
    set_target_properties(${THE_TARGET} PROPERTIES COMPILE_FLAGS ${TEMP} )
    


  • 现在我使用方法2。

    这篇关于如何在CMake文件中添加链接器或编译标志?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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