Small or large introspective C / C ++ program

    Under Habrakat, a small sketch allows you to write small or large applications that contain their own code and look almost adequate.

    #include 
    #define REPEAT(...) #__VA_ARGS__;__VA_ARGS__
    char * ref = REPEAT(
    int main()
    {
    	printf("#include \n"
    		   "#define REPEAT(...) #__VA_ARGS__;__VA_ARGS__\n"
    		   "char * ref = REPEAT(%s)", ref);
    	return 0;
    }
    )
    

    As you can see from the source, you need to explicitly write off the code only from the header, because everything that is in the REPEAT block will be automatically zipped and saved.
    The REPEAT macro itself is structured as follows: it takes a variable number of arguments (so that they are not afraid of commas), then “string” what it was passed to it, and then it repeats what it was passed to it, but this time without quotes (to preserve the functionality).
    Here's what happens after preprocessing:
    g++ -E main.cpp

    char * ref = 
    "int main()"
    "{"
    "    printf(\"#include \\n\"" 
    "           \"#define REPEAT(...) #__VA_ARGS__;__VA_ARGS__\\n\"" 
    "           \"char * ref = REPEAT(%s)\", ref);"
    "    return 0;" 
    "}";
    int main() 
    { 
        printf("#include \n" 
               "#define REPEAT(...) #__VA_ARGS__;__VA_ARGS__\n" 
               "char * ref = REPEAT(%s)", ref); 
        return 0; 
    }
    

    Frankly, I changed the code and made it readable, because the preprocessor sculpts almost everything on one line. Nevertheless, except for hyphenation and extra quotes, everything is in place.
    After starting, a functionally identical source will be displayed in stdout. The design is only slightly wrinkled.

    PS #include can be added to a REPEAT block, then it can be omitted from writing explicitly in a line.

    Also popular now: