I've been writing in C++ lately and I'm getting confused with .cpp
vs .h
— when to use them and what should go in them. I've been reading that you should put function definitions in a separate .cpp
file, and headers should be used for declarations, but how do I use the separate .cpp
file? Do I #include
it or what? I'm looking for clarification on .h
and .cpp
and what should go where and how to include separate .cpp
files.
Asked
Active
Viewed 1,974 times
0

Jonathan Leffler
- 730,956
- 141
- 904
- 1,278

chickenwingding
- 11
- 6
-
do you mean normal functions or templates? – wimh Jan 31 '15 at 21:58
-
See also [C++ code in header files](http://stackoverflow.com/questions/583255/c-code-in-header-files/), and [Splitting code into headers/source files](http://stackoverflow.com/questions/2584856/splitting-code-into-headers-source-files), and [Why have header files and `.cpp` files in C++](http://stackoverflow.com/questions/333889/why-have-header-files-and-cpp-files-in-c). – Jonathan Leffler Feb 01 '15 at 07:00
2 Answers
1
You should use .h file for function prototype and data type declarations and also for pre-processor directives, and .cpp files for definitions. For example, test.h
might be look like
#define CONSTANT 123 // pre-processor directive
void myfunction(char* str);
and your test.cpp
might look like
#include <stdio.h>
#include "test.h"
int main(int argc char **argv)
{
myfunction("Hello World");
return 0;
}
void myfunction (char* str)
{
printf("%s and constant %d", str, CONSTANT);
return;
}

Atul
- 3,778
- 5
- 47
- 87
-
2You might want to mention `inline`-functions (both implicit and explicit) and `template`s. – Deduplicator Jan 31 '15 at 22:38
0
Usually the class declaration goes into the (.h) header file, and the implementation goes in the .cpp file.
You include the header file in the cpp file, so all the functions will be recognized, and you should remember to use #ifndef in the header file to avoid errors (includes loops)