Significance of a .inl file in C++

后端 未结 5 1178
旧时难觅i
旧时难觅i 2020-12-02 05:22

What are the advantages of having declarations in a .inl file? When would I need to use the same?

5条回答
  •  既然无缘
    2020-12-02 05:26

    Nick Meyer is right: The compiler doesn't care about the extension of the file you're including, so things like ".h", ".hpp", ".hxx", ".hh", ".inl", ".inc", etc. are a simple convention, to make it clear what the files is supposed to contain.

    The best example is the STL header files which have no extension whatsoever.

    Usually, ".inl" files do contain inline code (hence the ".inl" extension).

    Those files ".inl" files are a necessity when you have a dependency cycle between header code.

    For example:

    // A.hpp
    struct A
    {
        void doSomethingElse()
        {
           // Etc.
        }
    
        void doSomething(B & b)
        {
           b.doSomethingElse() ;
        }
    } ;
    

    And:

    // B.hpp
    struct B
    {
        void doSomethingElse()
        {
           // Etc.
        }
    
        void doSomething(A & a)
        {
           a.doSomethingElse() ;
        }
    } ;
    

    There's no way you'll have it compile, including using forward declaration.

    The solution is then to break down definition and implementation into two kind of header files:

    • hpp for header declaration/definition
    • inl for header implementation

    Which breaks down into the following example:

    // A.hpp
    
    struct B ;
    
    struct A
    {
        void doSomethingElse() ;
        void doSomething(B & b) ;
    } ;
    

    And:

    // A.inl
    #include 
    #include 
    
    inline void A::doSomethingElse()
    {
       // Etc.
    }
    
    inline void A::doSomething(B & b)
    {
       b.doSomethingElse() ;
    }
    

    And:

    // B.hpp
    
    struct A ;
    
    struct B
    {
        void doSomethingElse() ;
        void doSomething(A & a) ;
    } ;
    

    And:

    // B.INL
    #include 
    #include 
    
    inline void B::doSomethingElse()
    {
       // Etc.
    }
    
    inline void B::doSomething(A & a)
    {
       a.doSomethingElse() ;
    }
    

    This way, you can include whatever ".inl" file you need in your own source, and it will work.

    Again, the suffix names of included files are not really important, only their uses.

提交回复
热议问题