What does preprocessing exactly mean in compiler

后端 未结 6 2187
没有蜡笔的小新
没有蜡笔的小新 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条回答
  •  半阙折子戏
    2021-02-09 06:13

    The pre-processor is a program that runs before the compiler and essentially performs text substitution. When you write:

    #define X 10
    
    int main() 
    {
        int x = X;
    }
    

    The pre-processor take that file as input, does it's thing, and outputs:

    int main() 
    {
        int x = 10;
    }
    

    And then the compiler does its thing with the pre-processed output.

    typedef on the other hand is a construct that the compiler understands. When you write:

    typedef unsigned int uint_32;
    

    The compiler knows that uint32 is actually an alias for unsigned int. This alias is handled by the compiler itself and involves a bit more logic than simple text substitution. This becomes obvious with a simple example:

    typedef int my_int;
    
    int main()
    {
        unsigned my_int x;  // oops, error
    }
    

    If a typedef were a simple text substitution mechanism (like the pre-processor is) then that would work, but it is not allowed and will fail to compile.

提交回复
热议问题