Home Diary Blog Photo Community Open Source
C语言宏定义中的字符串替换
    #在英语里面叫做 pound
    在C语言的宏定义中,一个#表示字符串化;两个#代表concatenate
    举例如下:

    #include <iostream>
    void quit_command(){
        printf("I am quit command\n");
    }   
    void help_command(){
        printf("I am help command\n");
    }   
    struct command
    {
    char * name;
    void (*function) (void);
    };  
    #define COMMAND(NAME) {#NAME,NAME##_command}
    #define PRINT(NAME) printf("token"#NAME"=%d\n", token##NAME)
    main(){
    int token9=9;
        PRINT(9);
    struct command commands[] = {
            COMMAND(quit),
            COMMAND(help),
        };  
        commands[0].function();
    } 

    得到的结果是:
    token9=9
    I am quit command



    ## 是连接符号,连接两个字符串
    #是把名字代替成参数中的字符串


    #define PRINTF(value) printf( #value " = %d/n", value );


    #define FUNC(arg)
    void print##arg(void) 
    { 
    printf(#arg " = %d", arg);
    }

    FUNC(size); 
    展开后生成代码:

    void printsize(void) 
    { 
    printf("size" " = %d", size );
    }