Why would one use #include_next in a project?

后端 未结 3 957
被撕碎了的回忆
被撕碎了的回忆 2020-12-02 13:07

To quote the iOS Documentation on Wrapper Headers:

#include_next does not distinguish between and \"file\" inclusion, nor do

3条回答
  •  离开以前
    2020-12-02 13:25

    It's handy if you're supporting multiple versions of something. For example, I'm writing code that supports PostgreSQL 9.4 and 9.6. A number of internal API changes exist, mostly new arguments to existing functions.

    Compatibility headers and wrapper functions

    I could write compatibility headers with static inline wrapper functions with new names for everything, basically a wrapper API, where I use the wrapper name everywhere in my code. Say something_compat.h with:

    #include "something.h"
    
    static inline something*
    get_something_compat(int thingid, bool missing_ok)
    {
        assert(!missing_ok);
        return get_something(thingid);
    }
    

    but it's ugly to scatter _compat or whatever suffixes everywhere.

    Wrapper header

    Instead, I can insert a compatibility header in the include path when building against the older version, e.g. compat94/something.h:

     #include_next "something.h"
    
     #define get_something(thingid, missing_ok) \
     ( \
         assert(!missing_ok), \
         get_something(thingid) \
     )
    

    so the rest of the code can just use the 9.6 signature. When building against 9.4 we'll prefix -Icompat94 to the header search path.

    Care is required to prevent multiple evaluation, but if you're using #include_next you clearly don't mind relying on gcc. In that case you can also use statement expressions.

    This approach is handy when the new version is the "primary" target, but backward compatibility for an older version is desired for some limited time period. So you're deprecating the older versions progressively and trying to keep your code clean with reference to the current version.

    Alternatives

    Or be a sensible person, use C++, and use overloaded functions and template inline functions :p

提交回复
热议问题