do header files get compiled

I write a program called main.cpp, i know the main.cpp get compiled into object file and get linked.

I wonder if header file(for example somethings.h) get compiled into object file or not.
The header file itself (as a separate entity) is not compiled.

It's presence in the executable (if it has any) will be via any #include statements in the source code. At compile time, the source the compiler sees is your prog.cpp with all the #include file's spliced in appropriately.

A header file containing only declarations won't have any visible imprint on the executable, except for perhaps appearing as a name in the debug information.

Eg.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// something.h
extern void something();

// something.cpp
#include "something.h"
void something( ) {
  // do something
}

// main.cpp
#include "something.h"
int main( ) {
  something();  // do something
}


However, if the header file contains things like inline functions, class member function definitions, templates, then things start to get interesting.
1
2
3
4
5
6
7
8
// something.h
extern void something();

class Foo {
  void method() {
    // stuff
  }
};


If nothing ever creates an instance of Foo and calls method(), then (at least in GCC), the compiled implementation of method() is not in the executable.

Historical early C++ compilers had a bit of a reputation for code bloat, but modern compilers should only give you what you actually use in the code.
I regularly compile my header files, not to produce an object file, but just to check that there are no errors and to make sure it does not rely on code that is not included in the header file.
ok thank you all
I regularly compile my header files, not to produce an object file, but just to check that there are no errors and to make sure it does not rely on code that is not included in the header file.

This is quite clever, and I might start doing it.
The recommended guideline which automates this, particularly for large scale projects is:
A component's .cpp file should have the #include of its corresponding .h file as its first substantive line of code.'
(Though well known earlier, this was first expounded by Lakos in his book 'Large-Scale C++ Software Design')
Okay, I suppose I'm already doing that.

It also occurs to me that the syntax checking feature of most IDEs would take care of this without any additional effort on the programmer's part.
Topic archived. No new replies allowed.