宏定义中参数使用

1. 宏传递变长参数:

最近用C语言写一个程序,经常调用shell或者其他命令,代码中多处出现如下代码:

char script_cmd[CMD_MAX_LEN + 1] = {'\0'};

memset(script_cmd, 0, sizeof(script_cmd));
sprintf(script_cmd, "cmd %s %s", param1, param2);
system(script_cmd);

每调用一次就是三行代码,看着也十分不爽。偶然间学会通过宏传递参数,代码瞬间简化很多:

#define    EXECUTE_SCRIPT(script_cmd_array, format,args...) \
    memset(script_cmd_array, 0, sizeof(script_cmd_array)); \
    sprintf(script_cmd_array, format, ##args); \
    system(script_cmd_array);
    
char script_cmd[CMD_MAX_LEN + 1] = {'\0'};
EXECUTE_SCRIPT(script_cmd, "cmd %s %s", param1, param2);

2. 宏中参数当做字符串使用

 1 #define REMOVE_SHMEM(shmid) \
 2     if (shmid != -1) { \
 3         if (shmctl(shmid, IPC_RMID, NULL) == -1) { \
 4             printf("remove %s failed!\n", #shmid); \
 5         } \
 6     }
 7 
 8 int main (void)
 9 {
10     int myshm = 123;
11 
12     REMOVE_SHMEM(myshm);
13 }

输出:

 remove myshm failed!

 

猜你喜欢

转载自www.cnblogs.com/luoyingcai/p/11142244.html