zoukankan      html  css  js  c++  java
  • C 预编译中的二次替换问题

    C 预编译中的二次替换问题

    今天在阅读linux看门狗驱动的时候,发现一段奇怪的代码:

    static int tmr_atboot       = CONFIG_S3C2410_WATCHDOG_ATBOOT;

    MODULE_PARM_DESC(tmr_atboot,

                  "Watchdog is started at boot time if set to 1, default="

                         __MODULE_STRING(CONFIG_S3C2410_WATCHDOG_ATBOOT));

    依次跟进去宏的具体定义:

           #define __MODULE_STRING(x) __stringify(x)

           #define __stringify_1(x...)    #x

    #define __stringify(x...) __stringify_1(x)

    这里一共使用了三处宏,分别是:__MODULE_STRING(x)、__stringify_1(x...)、__stringify(x...)。似乎这里的宏非常冗余。

    GNU CPP Manual中是这样指出来的:

        Macro arguments are completely macro-expanded before they are substituted into a macro body, unless they are stringified or pasted with other tokens. After substitution, the entire macro body, including the substituted arguments, is scanned again for macros to be expanded. The result is that the arguments are scanned twice to expand macro calls in them.

    上面的总体意思就是:二次替换的问题。

    具体使用例子来说明:

    Main1.c

    #include <stdio.h>

    #define BUF_SIZE abc

    #define __stringify(x) #x

    Int main()

    {

        Printf(“%s\n”, __stringify(BUF_SIZE));

        Return 0;

    }

    结果为: BUF_SIZE

    Main2.c

    #include <stdio.h>

    #define BUF_SIZE abc

    #define __stringify(x)  __stringify_1(x)

    #define __stringify_1(x)  #x

    Int main()

    {

        Printf(“%s\n”, __stringify(BUF_SIZE));

        Return 0;

    }

    结果为: abc

    总结,在宏替换时,如果出现标识字符串或者字符串连接的情况出现(“#”、“##”),那么宏替换会被截断,这个时候我们可以通过双层宏来完成深入替代的任务。

  • 相关阅读:
    四个足以警醒你一生的故事!
    人们通常不知道自己想要什么,除非你秀出产品给他们看。
    有些话应该记住
    禅语
    是笑话,是悲凉,是笑后的真实,是真实后的悲凉
    vb6.0分隔文本文件读写的两个例程
    boost Serialization源码分析(1)
    养成好习惯,好气质
    日记(海子)
    关于C#的委托与事件的一个小DEMO
  • 原文地址:https://www.cnblogs.com/wenhuisun/p/2578998.html
Copyright © 2011-2022 走看看