So the other day, I was looking through some old C++ books and noticed a way of creating a C++ class I had never seen before. Everything I have seen up to that point had always used the #include “header.h” and compiled the implementation files separately. What I saw the author of this book do is actually put an include directive to the implementation at the end of the header file and omitting the .cpp file from the compilation. Has anybody used this style?
For Example:
I have
main.cpp
employee.h
employee.cpp
//main.cpp
#include <iostream>
#include <stdio.h>
#include <string>
#include "employee.h"
void main()
{/*some code*/}
//employee.h
#ifndef EMPLOYEE_H
#define EMPLOYEE_H
class employee
{
public:
//public members
private:
//private members
}
#endif
//employee.cpp
#include "employee.h"
#include <string>
//public member definitions
I would normaly compile this project like so:
g++ main.cpp employee.cpp
But in the author’s example is like this
//main.cpp
#include <iostream>
#include <stdio.h>
#include <string>
#include "employee.h"
void main()
{/*some code*/}
//employee.h
#ifndef EMPLOYEE_H
#define EMPLOYEE_H
class employee
{
public:
//public members
private:
//private members
}
#include "employee.cpp" // <-- the line of code that caught my attention
#endif
//employee.cpp
#include <string>
//public member definitions
And the resulting code compiles as
g++ main.cpp
Is this merely a style preference or are there any real benefits in this? I would think it wouldn’t scale very well, but I am not a super proficient C++ programmer either.
Doing this will bring the definition of the class in to every translation unit where the header file is included. This is a very unusual paradigm, and could be hazardous to your coding health. In particular, if you have
main.cppandfoo.cppboth of which#include "employee.h", then all the methods onemployeewill be defined twice, which is a violation of the One Definition Rule and will create linker errors. In order to resolve those linker errors, you need to either move the definitions to their own translation unit, or mark theminline(which may or may not work).This is however a useful idiom in some instances. Particularly with templates, which must be defined within the translation unit. In that case, when you want the declaration and implementation in separate files for readability, you can do an end-of-file
#include. When I do this, I use a special file extension,.hppto signify that the file is special in that it is not intended to be compiled on its own. See this answer for an example.