其他分享
首页 > 其他分享> > CMAKE(2)——GCC、Makefile、CMAKE中宏定义不同方式

CMAKE(2)——GCC、Makefile、CMAKE中宏定义不同方式

作者:互联网

CMAKE

1.官方的说明
Adds -D define flags to the compilation of source files.

add_definitions(-DFOO -DBAR …)
Adds definitions to the compiler command line for sources in the current directory and below. This command can be used to add any flags, but it is intended to add preprocessor definitions. Flags beginning in -D or /D that look like preprocessor definitions are automatically added to the COMPILE_DEFINITIONS directory property for the current directory. Definitions with non-trivial values may be left in the set of flags instead of being converted for reasons of backwards compatibility. See documentation of the directory, target, source file COMPILE_DEFINITIONS properties for details on adding preprocessor definitions to specific scopes and configurations.

https://cmake.org/cmake/help/v3.0/command/add_definitions.html2.

2.小例子:
CMakeLists.txt 中添加如下代码控制代码的开启和关闭.

OPTION(USE_MACRO_CMAKE

 "Build the project using macro"

 OFF)

 IF(USE_MACRO_CMAKE)

 add_definitions("-DUSE_MACRO_GCC")

endif(USE_MACRO_CMAKE)

3.运行构建项目的时候可以添加参数控制宏的开启和关闭.

开启时cmake带选项构建命令:

cmake  -DUSE_MACRO_CMAKE=on ..

关闭时cmake带选项构建命令:

cmake  -DUSE_MACRO_CMAKE=off .

注意 -DUSE_MACRO_CMAKE=on 是Cmake 自身的选项定义,与GCC编译时在代码中的宏定义不是一个层次上的定义

GCC

gcc -D:gcc的预定义功能

GCC编译器中使用:

   -D macro=string

等价于在头文件中定义:

#define   macro   string

例如:

-D TRUE=true

等价于:

#define   TRUE   true

 -D macro

等价于在头文件中定义:

 #define   macro   1

实际上也达到了定义:#define macro的目的。

例如:-D Linux,等价于:#define LINUX 1(与#define LINUX作用类似)。
–define-macro macro=string与-D macro=string作用相同。

-D name

Predefine name as a macro, with definition 1.

-D name=definition

Predefine name as a macro, with definition definition.

例子

int main()
{
    #ifdef HELLO
    printf("HELLO defined\n");
    #else
    printf("HELLO not define\n");
    #endif

    return 0;
}

在该程序中,判断是否已经定义了宏DEBUG,从而输出相应的语句。
如果编译该程序时采用了

gcc -DHELLO

则输出:

HELLO defined

(也可以在makefile中直接给变量赋值 DEFS = -D HAVE__PROGNAME=1)

Makefile

在Makefile中我们可以通过宏定义来控制源程序的编译。

只要在Makefile中的CFLAGS中通过选项-D来指定你于定义的宏即可。

就是编译时把后面的参数添加到编译选项里,比如

CFLAGS += -D TOSH_DATA_LENGTH=114

最后就类似调用

gcc -D TOSH_DATA_LENGTH=114 xx.c

而-D是用来定义宏的,即代码里#define那个

标签:GCC,CMAKE,定义,macro,中宏,MACRO,definitions,define
来源: https://blog.csdn.net/u012564117/article/details/93101163