Leif Andersen
Leif Andersen

Reputation: 22332

Difference between .h files and .inc files in c

I have been looking at various open source projects, and they have a bunch of files written in C that have .inc as a file extension. As far as I can tell, they are used like header files.

I thought the standard convention was to use .h files for header files and .c for source files. So, is there a standard convention on when a header file should be an .inc file rather than being a .h file, or are these decided only at a per project basis? (Or am I just looking at weird projects that use .inc?)

Upvotes: 12

Views: 13468

Answers (3)

skm
skm

Reputation: 43

A good example of a .inc file would be ename.c.inc file which defines an array of strings, ename and those are the symbolic names corresponding to the errno values on the Linux/x86-32 system for example. It is hardware architecture specific though.

Source: The Linux Programming Interface book: Chapter 3, Page 57

Upvotes: 0

AllDay
AllDay

Reputation: 61

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

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.

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:

// 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:

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

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

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

Upvotes: 6

chqrlie
chqrlie

Reputation: 144695

The standard convention is to use .h for header files that contain only macro definitions and other declarations and .c for C source files that contain code and data definitions.

In some projects, code fragments are stored in separate files and included in C source files with some macro tricks to expand specifically in different files or circumstances. Sometimes, these files are even included multiple times in the same source file. To underscore the special semantics attached to such files, giving them a different extension may be a useful hint. These files may also have been generated as part of the build process: naming them specifically may prevent confusion with actual source files.

Look at the files you came across in these projects and verify if this explanation holds.

Upvotes: 10

Related Questions