#if vs #ifndef vs #ifdef

后端 未结 5 590
没有蜡笔的小新
没有蜡笔的小新 2021-01-03 00:27

My problem is first of all, understanding #ifndef and #ifdef. I also want to understand the difference between #if, #ifndef

5条回答
  •  醉梦人生
    2021-01-03 01:13

    Macros are expanded by the preprocessor who doesnt know anything about values of variables during runtime. It is only about textual replacement (or comparing symbols known to the preprocessor). Your line

    #if Compare == LINUX_GRAPHICS
    

    will expand to

    #if Compare == 011x101
    

    and as "Compare" is differnt from "011x101", it evaluates to false. Actually I am not even 100% sure about that, but the point is: you are mixing preprocessor directives with variables that are evaluated at runtime. That is non-sense. Preprocessor directives are not there to replace C++ statements.

    For most traditional use cases of macros there are better way nowadays. If you dont really need to use macros, it is better not to use them. It makes it extremly hard to read the code (eg. I dont understand how that macros in your code work and unless I really need it honstely I dont want to know :P) and there are other problems with macros that can lead to very hard to find bugs in your program. Before using macros I would advice you to first consider if there isnt a more natural C++ way of achieving the same.

    PS:

    #ifdef SYMBOL
        ifdef = "if defined"
        this part of the code is excluded before the compiler even sees it
        if SYMBOL is not defined (via #define)
    #endif
    
    #ifndef SYMBOL
        ifndef = "if not defined"
        this part of the code is excluded before the compiler even sees it
        if SYMBOL is defined (via #define)
    #endif
    

    I wrote "excluded" on purpose to emphazise the bad impact it has on readability of your code. If you overuse #ifdef or #ifndef inside normal blocks of code, it will be extremely hard to read.

提交回复
热议问题