本文介绍了当我调用CMake时,如何定义一个变量,使qtcreator知道它被定义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一段代码根据#define有条件地激活,如下所示:

I have a section of code that is conditionally activated depending on a #define, like this:

#ifdef VARIABLE
  code.function();
#endif

cmake脚本有一个'options'命令,设置VARIABLE :

The cmake script has an 'options' command that sets the VARIABLE like this:

option(VARIABLE "Want to use VARIABLE?" ON)

if(VARIABLE)
   message(STATUS "VARIABLE")
   set(VARIABLE_FLAG "-DVARIABLE")
endif()

set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${VARIABLE_FLAG} -Wall")



我使用cmake来构建项目和qtcreator作为IDE。我的问题是,qtcreator认为VARIABLE没有定义,所以我的代码没有突出显示,但当我在控制台上构建它,VARIABLE定义。所以,什么参数应该传递给qtcreator运行cmake,以便它知道VARIABLE定义和突出我的代码?有没有办法做到这一点?

I'm using cmake to build the project and qtcreator as IDE. My problem is that qtcreator thinks that VARIABLE is not defined so my code has is not highlighted, but when I build it on a console, VARIABLE is defined. So, what parameters should I pass to qtcreator to run cmake, so that it knows VARIABLE is defined and highlights my code? Is there a way to do this?

Ps:我只是使用qtcreator编辑文件,构建部分是通过控制台命令。

Ps: I just use qtcreator to edit files, the build part is done via console commands.

推荐答案

另一种替代方法是使用配置的头文件,并将其包含在需要定义的地方:

Another alternative would be to use a configured header file, and include it only where you need the definition:

# in CMakeLists.txt
configure_file(
  ${CMAKE_CURRENT_SOURCE_DIR}/my_defs.h.in
  ${CMAKE_CURRENT_BINARY_DIR}/my_defs.h
  )

include_directories(${CMAKE_CURRENT_BINARY_DIR})


b $ b

and

// in my_defs.h.in
#cmakedefine VARIABLE
  // configure_file converts #cmakedefine of a named CMake variable
  // into a C++ #define of a C++ pre-processor symbol

最后

// in various C++ source or header files, but only as needed:
#include "my_defs.h"
#ifdef VARIABLE
  doSome_VARIABLE_SpecificStuff();
#endif



我不经常使用QtCreator,所以我不知道技术在其语法高亮方面起作用,但我会假设它会,因为他们必须读头文件,以做一个正确的工作...

I do not use QtCreator regularly, so I don't know if this technique works in terms of their syntax highlighting, but I'd assume it would, since they must read header files in order to do a proper job of it...

这篇关于当我调用CMake时,如何定义一个变量,使qtcreator知道它被定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-21 22:02