C/C++項目中.h和.inc文件區別

原問題:Difference between .h files and .inc files in curl

C/C++的標準慣例是將class、function的聲明信息寫在.h文件中。.c文件寫class實現、function實現、變量定義等等。然而對於template來講,它既不是class也不是function,而是能夠生成一組class或function的東西。編譯器(compiler)爲了給template生成代碼,他須要看到聲明(declaration )和定義(definition ),所以他們必須不被包含在.h裏面。.net

爲了使聲明、定義分隔開,定義瀉在本身文件內部,即.inc文件,而後在.h文件的末尾包含進來。固然除了.inc的形式,還可能有許多其餘的寫法.inc.imp.impl.tpp, etc.code

英文原版回答blog

.inc files are often associated with templated classes and functions.ci

Standard classes and functions are declared with a .h file and then defined with a .cpp file. However, a template is neither a class nor a function but a pattern that is used to generate a family of classes or functions. In order for the compiler to generate the code for the template, it needs to see both the declaration and definition and therefore they both must be included in the .h file.get

To keep the declaration and definition separate, the definition is placed in its own file and included at the end of the .h file. This file will have one of many possible file extensions .inc.imp.impl.tpp, etc.編譯器

Declaration example:it

// Foo.h
#ifndef FOO_H
#define FOO_H

template<typename T>
class Foo {
public:
    Foo();
    void DoSomething(T x);
private:
    T x;
};

#include "Foo.inc"
#endif // FOO_H

Definition example:io

// Foo.inc
#include "Foo.h"

template<typename T>
Foo<T>::Foo() {
    // ...
}

template<typename T>
void Foo<T>::DoSomething(T x) {
    // ...
}
相關文章
相關標籤/搜索