简体   繁体   English

在GCC中欺骗预处理程序VARIADIC MACROS

[英]Tricking Preprocessor VARIADIC MACROS in GCC

I have a task at work to make the static library more secure , in order to do so I need to replace the formatted strings of printf for them to appear differently in the compiled static library , for this to happen it must be done in the pre processor stage . 我有一个工作要使静态库更安全,为此,我需要替换printf的格式化字符串,以使它们在已编译的静态库中以不同的方式出现,为此,必须在预编译中完成处理器阶段。

What I did (and it actually works in visual studio) is the following ( and it is just a pseudo example ): 我所做的(并且它实际上在Visual Studio中有效)是以下内容( 这只是一个伪示例 ):

char * my_array[] = {"abcd", "a %d", " b %d %s "};
#define GENERIC_ARRAY(x) my_array[x]

#define VARIADIC_DEBUG_PRINT(...)   DebugPrintFunction (__FILE__, __LINE__, __func__, __VA_ARGS__)
#define PRINT_BY_LEVEL(x)           VARIADIC_DEBUG_PRINT x
#define REPLACE_STRING(x,...)       PRINT_BY_LEVEL((GENERAL_LEVEL,GENERIC_ARRAY(__COUNTER__),__VA_ARGS__))

#define MY_PRINTF(x,...)      REPLACE_STRING((void*)0,(void*)0,__VA_ARGS__)

All of this overhead is for me to trick the compiler to accept prints without any arguments except the string 所有这些开销对我来说都是骗人的,使编译器接受不带任何参数(字符串除外)的打印

So when testing it in my main.c I tried the following And it worked : 因此,当在我的main.c中对其进行测试时,我尝试了以下操作,它确实有效:

MY_PRINTF("Hello World");
MY_PRINTF("My Val %d", i);
MY_PRINTF("MY VAL %d My String %s", i, s);

But when switching to GCC, he does not like the format of the first print ie : 但是当切换到GCC时,他不喜欢第一张纸的格式,即:

MY_PRINTF("Hello World");

And throws me an compilation error : 并抛出一个编译错误:

error: expected expression before ')' token

Any ideas how may I trick the compiler and accept it ? 有什么想法可以欺骗编译器并接受它吗? or maybe better ideas how to rename the string safely after compilation ? 还是更好的主意,如何在编译后安全地重命名字符串?

You can try something like : 您可以尝试类似:

#include <stdio.h>
#define PRINT(x, ...) printf(x, ##__VA_ARGS__)

int main (int argc, char *argv[]) {
    PRINT("Hello\n");
    PRINT("World %d\n", 42);
    return 0;
}

It works with gcc 4.8 (not tried with earlier version, but it should work too) 它适用于gcc 4.8(未尝试使用较早版本,但也应适用)

Using ##__VA_ARGS__ , you may try: 使用##__VA_ARGS__ ,您可以尝试:

#define MY_PRINTF(x, ...) \ 
    VARIADIC_DEBUG_PRINT(GENERAL_LEVEL, GENERIC_ARRAY(__COUNTER__), (void*)0, (void*)0, ##__VA_ARGS__)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM