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!
