What does preprocessing exactly mean in compiler

后端 未结 6 2111
没有蜡笔的小新
没有蜡笔的小新 2021-02-09 05:52

I am trying to understand the difference between a typedef and define. There are a lot of good posts specially at this previous question on SO, however I can\'t understand the p

6条回答
  •  旧时难觅i
    2021-02-09 06:14

    A preprocessor is a phase that occurs BEFORE any compilation starts. It reads specific macros and symbols to substitute. Its usually one to two pass. It scans the whole source file, and generates a symbol table to substitute or expand macros.

    After all the substitutions are done, the syntax analyzer takes over lexing-parsing the source file, generating abstract syntax trees, generating code, linking libraries and generating executables/binaries.

    In C/C++/ObjC Preprocessor DIRECTIVES start with '#' followed by the directive name such as "define", "ifdef", "ifndef", "elif", "if", "endif" etc.

    BEFORE PREPROCESSING:

    #define TEXT_MACRO(x) L##x
    #define RETURN return(0)   
    int main(int argc, char *argv[])
    {
        static wchar_t buffer[] = TEXT_MACRO("HELLO WORLD");
        RETURN ;
    }
    

    AFTER PREPROCESSING:

    int main(int argc, char *argv[])
    {
        static wchar_t buffer[] = L"HELLO WORLD";
        return (0);
    }
    

    If I remember correctly, the book "The C Programming Language" 2nd Edition, by Kernighan and Ritchie has an example, where they show how to create your own PREPROCESSOR and HOW IT WORKS. Also the Plan9 C Compiler separated the two processes(compilation and preprocessing). Allowing you to use your own PREPROCESSOR in it.

    Check out An interesting preprocessor for multiple languages and Write your own pre-processor. Seeing the input and output of these programs gives you a deeper understanding of what a preprocessor actually is.

    Another little secret: You can code C in latin/german/spanish if you have a preprocessor :)

提交回复
热议问题