代码之家  ›  专栏  ›  技术社区  ›  Keith Nicholas

有可能在C语言中重新定义{和}吗?

c
  •  2
  • Keith Nicholas  · 技术社区  · 14 年前

    你有没有什么办法。。。

    #define {  { printf("%s,%s",_FUNCTION_, _LINE_); { 
    

    这不会编译。但我想知道是否有某种技巧可以有效地获得相同的功能?(除了在预处理步骤编写钩子工具之外)

    这样做的目的是思考如何获得一个穷人的代码覆盖率。

    4 回复  |  直到 14 年前
        1
  •  7
  •   James McNellis    14 年前

    用宏肯定不行。宏的名称必须是标识符。大括号字符是标点符号,而不是标识符。

        2
  •  1
  •   bstpierre Edgar Aviles    14 年前

    我看过这件事(不是说我赞同…) #define BEGIN ... #define END ... .

    例如

    void foo(void)
    BEGIN
        stuff();
    END
    
        3
  •  1
  •   Community CDub    8 年前

    使用中讨论的工具获取Richman的代码覆盖率 these questions ,尤其是 gcov ,这是GCC的一部分。

        4
  •  0
  •   Simon    14 年前

    你不能改变编译器解释{}的方式。这是假设它们能够同步地确定代码是否正确和应该做什么。

    如果你真的想这样做,我建议在“{”“我的宏;”上搜索并替换

        5
  •  0
  •   paxdiablo    5 年前

    不是标准宏,不是。C标准(C11)对 6.10.3 Macro replacement :

    # define identifier replacement-list new-line
    

    具有 identifier 在中显式定义 6.4.2.1 Identifiers, General 作为:

    identifier:
        identifier-nondigit
        identifier identifier-nondigit
        identifier digit
    identifier-nondigit:
        nondigit
        universal-character-name
        other implementation-defined characters
    nondigit: one of
        _ a b c d e f g h i j k l m
        n o p q r s t u v w x y z
        A B C D E F G H I J K L M
        N O P Q R S T U V W X Y Z
    digit: one of
        0 1 2 3 4 5 6 7 8 9
    

    所以唯一可能的漏洞是 other implementation-defined characters 但这并没有包含在标准中,因此并不是真正的可移植性。

    在任何情况下,它都不能很好地处理如下代码:

    typedef struct {
        int field1;
        int field2;
    } tMyStruct;
    

    因为它很烦人地放置一个C语句,在那里不存在任何语句:

    我认为如果你真的想这样做,你需要用一个更智能的预处理器(一个可以知道代码应该去哪里和哪里的处理器)来预处理你的文件,或者修改代码以显式地将它们放在应该放在的宏中,比如选择行为:

    #ifdef PING_DEBUGGING
        #define MYPING printf("%s,%s", _FUNCTION_, _LINE_)
    #else
        #define MY_PING
    #endif
    

    并将其用于:

    void myFunc(void) { MYPING;
        // proper body of function.
    }