precompiled header files

I am not sure if the title is saying what I am about to ask. My teacher talks about header files just having definitions and not declerations. I am writing a program that has a .h file and a related .cpp file along with a main.cpp it would be nice to have the .cpp file associated with the .h file compiled into an object file that would than just be referenced when the .h file is included. Am I making any sense?
Yes... imho it is good to have the .cpp file related to the .h file like you said.
I would suggest you, when you write an header file, to use this technique

1
2
3
4
5
6
7
8
//my_file.h

#ifndef MY_FILE_H
#define MY_FILE_H

//the real header context here

#endif 


(you can use any UNIQUE name for MY_FILE_H... ).
This thing will allow to include your header in a safer way (if it is included multiple time for some reason, it will not return any error becouse precompiler instructions will prevent the multiple declarations)

---------------

However, the .cpp separated from .h file is not a Precompiled header, but a module file (*.o). "Precompiled header" is a bit different thing, but usually - for basic .h files - it is not necessary
This isn't how headers works.
#include is a preprocessor directive which means "copy content of this file and paste it here" There is no difference between this:
1
2
3
4
5
6
7
8
//foo.h
int foo(int bar);
double baz();

//main.cpp
#include "foo.h"

int main() {}
and that:
1
2
3
4
5
//main.cpp
int foo(int bar);
double baz();

int main() {}

.h file merely have declaration of all functions and classes you use, and needed to tell compiler that these function/classes are exist somewhere.
Only thing you can do is to precompile your.cpp file and add it to your project link list: it will be static linked to your program and all other units can use its functions.
Last edited on
Topic archived. No new replies allowed.