开发者

is it possible to redefine { and } in C?

开发者 https://www.devze.com 2023-01-08 03:01 出处:网络
Is there any way you do something like... #define {{ printf(\"%s,%s\",_FUNCTION_, _LINE_); { this won\'t compile.But I\'m wondering if there is some kind of trick to effectively get the same funct

Is there any way you do something like...

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

this won't compile. But I'm wondering if there is some kind of trick to effectively get the same functionality? (other than writing a tool to hook at the preprocessing step)

The poin开发者_JAVA技巧t of doing this is a pondering on how to get a poor mans code coverage.


It's certainly not possible with a macro. The name of a macro must be an identifier. The brace characters are punctuators, not identifiers.


I've seen this done (not that I endorse it...) with #define BEGIN ... and #define END ....

e.g.

void foo(void)
BEGIN
    stuff();
END


Get rich-man's code coverage with the tools discussed in these questions, particularly gcov, which is part of GCC.


You can't change the way the compiler interprets {}'s. It's an assumption that they make to be able to syntaxically determine if the code is correct and what it is supposed to do.

If you indeed would like to do something like that, I suggest doing a search-and-replace on "{" "{ MY_MACRO;"


Not with standard macros, no. The C standard (C11) has a specific requirement for macros in 6.10.3 Macro replacement:

# define identifier replacement-list new-line

with identifier being explicitly defined in 6.4.2.1 Identifiers, General as:

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

So the only *possible loophole would be other implementation-defined characters but that's not covered by the standard, hence not really portable.

In any case, it wouldn't work very well with code like:

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

since it would rather annoyingly place a C statement where no statements should ever exist :-)

I think if you really want to do this, you're going to have pre-process your file with a more intelligent pre-processor (one that can tell where and where not the code should go), or modify the code to explicitly put in a macro where they should be, such as selecting behaviour with:

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

and using it with:

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

精彩评论

暂无评论...
验证码 换一张
取 消