简体   繁体   English

如何在 cmake 中使用 DEBUG 宏?

[英]How to use DEBUG macro with cmake?

I'm new to cmake, so up front, my apologies this question is too basic..我是 cmake 的新手,所以在前面,我很抱歉这个问题太基础了..

Question is,问题是,

I have logs under #ifdef DEBUG which I want to print only for debug build.我在#ifdef DEBUG下有日志,我只想为调试构建打印这些日志。

Something like this..像这样的东西。。

void func () {

// some code here 

#ifdef DEBUG
    print_log(...) // this portion should execute only for debug builds
#endif 

// some code here

}

How can I achieve this with cmake?如何使用 cmake 实现这一目标?

I have already looked at #ifdef DEBUG with CMake independent from platform and cmakelists debug flag not executing code within "ifdef DEBUG" , suggestions here don't seem to work for me.我已经看过#ifdef DEBUG 和 CMake 独立于平台cmakelists 调试标志未在“ifdef DEBUG”中执行代码,这里的建议似乎对我不起作用

(project is on Linux platform) (项目在Linux平台上)

Modern CMake uses a target-based approach which allows you to specify settings that are restricted to a target as opposed to being global (and affecting all targets).现代 CMake 使用基于目标的方法,允许您指定仅限于目标而不是全局(并影响所有目标)的设置。 This then gives you the control to specify how the state from targets propagates transitively to dependent targets so as to reduce the visible scope of the state (include paths, library dependencies, compiler defines, compiler flags, etc) to dependent targets.然后,您可以控制指定目标中的 state 如何传递到依赖目标,以减少 state(包括编译器标志依赖项的路径、编译器标志依赖项等)的 state(包括路径、编译器标志依赖项等)的可见 state 的可见 scope。 The approach you decide to go with will depend largely on how complex your application is, for instance, how many targets (executable & libraries) exist in the system.您决定使用 go 的方法在很大程度上取决于您的应用程序的复杂程度,例如,系统中存在多少目标(可执行文件和库)。 The more complex the system the more benefits you in terms of reduced complexity and compile time that you will get from using the target-based approach.系统越复杂,您从使用基于目标的方法中获得的复杂性和编译时间就越少。 In the simplest case to set this up with the modern target based CMake approach you could use the following (where exe is the name of your executable:在最简单的情况下,使用基于现代目标的 CMake 方法进行设置,您可以使用以下内容(其中exe是可执行文件的名称:

add_executable(exe "")
target_sources(exe
    PRIVATE
        main.cpp
)
target_compile_definitions(exe
    PRIVATE
        # If the debug configuration pass the DEBUG define to the compiler 
        $<$<CONFIG:Debug>:-DDEBUG>>
)
  1. Added set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -DDEBUG") to CMakeLists.txt添加set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -DDEBUG")CMakeLists.txt
  2. Created Debug/ directory & cd Debug创建Debug/目录 & cd Debug
  3. cmake -DCMAKE_BUILD_TYPE="Debug"../

Worked !工作!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM