I always feel a pain when I switch from C# or python back to C++ and meet the .h and .cpp separation.
So I thought that maybe there is a tool that at pre-compilation step can take header (o file with some special extension) and split it to .h and .cpp?
So if original file like this:
class MyClass
{
public:
void HaHaHa()
{
//some logic
}
}
And a result would be as .h and .cpp files:
//.h
class MyClass
{
public:
void HaHaHa();
}
// .cpp
#include "MyClass.h"
void MyClass::HaHaHa()
{
//some logic
}
Some googling didn't show up the ready to use tools. But I'm pretty sure it is not a new idea and such tools should exist.
P.S. It is known that i.e. Visual Assist X and VIM has tools to handle .h and .cpp separation with less pain. But I'm asking about a possibility to have a code in one files and separate them automatically as a part of build process.
This tool may help you: lazycplusplus [Wayback link because the domain was lost]
Project repo: https://github.com/mjspncr/lzz3
I think you're going about it backwards: you want to write the header
file, without the implementations, before writing the code. What would
be nice is a tool which would read the header file and generate the
outline code for the implementation: with namespaces, nested classes and
such, just the wrappers can be quite verbose. But the closest I've seen
is Rational Rose, which starts with a (highly) annotated ULM diagram,
and generates both the header and the boilerplate of the implementation.
It's a very nice tool—I use it whenever it's available—but
it's a bit pricy for the home user, and probably even for small
corporations.
Under Windows Visual Assist X by Whole Tomato does that sort of thing. Not automated though I don't think.
Related
I have classes that look like this:
Header (.h):
class DatabaseX ; //forward declare
class DeepClass
{
public:
void DeepClass(DatabaseX* db);
void doStuff();
private:
DatabaseX *m_db;
};
Definition (.cpp)
#include "some/path/that/stretches/into/a/rather/deep/structure/DeepClass.h"
#include "another/somewhat/disturbing/long/path/to/somewhere/distant/DatabaseX.h"
void DeepClass::DeepClass(DatabaseX* db):m_db(db){ m_db->open() }
void DeepClass::~DeepClass(){ m_db->close(); delete m_db; }
void DeepClass::doStuff(){ // <complicated stuff here> }
Now I want a test that checks that doStuff() does the right kind of stuff.
So I write my own mock DatabaseX.
But I have a problem, my own mock database lives in the test directory, it has no place in production code, and what's worse, DatabaseX was never written to be inherited and overloaded.
It's a concrete class, and isn't anything like an interface.
So my question is, how do I write a test, with all these hard-coded include paths everywhere?
Do I for example:
create another duplicate file structure that matches the include paths, and put my mock DatabaseX there in this duplicate file structure?
Somehow rewite each cpp file before the compiler accesses it by some indirection magic or other?
Add macros to eat up the paths?
Write a python/perl/bash script to temporarily remove the include paths prior to compiling my tests?
Just include everything, accept the dependencies of DatabaseX, and just compile the real thing, and all it's dependencies and then replace at link time?
Accept defeat; don't write any tests, and bury my head in the sand.
OR ... ?
I should say there are well over a million lines of code, so changing the source code isn't an option.
Is there a very simple way to overcome this nightmare via a nice simple compiler option or other?
(Perhaps it's not relevant but I'm using Qt's QTest & QtCreator. Maybe there is some magical switch that makes all these gruesome paths go away!).
I am using GCC 4.8.5
What's the thoughts on allowing simple constructor/method definitions in header files in C++. Some classes I am creating are simple data objects that compose another object say, so they need there own constructor and get/set methods. However these are usually < 3-4 lines each with the constructors using init lists. Is it OK to just have .h for these classes.?
UPDATE::
What about where to store .h files, in a seperate directory from the cpp files?
I'd vote for only putting declarations in your header file. This will make the header file more clean (no implementation cluttering your view). The user can look upon the header file to view the interface, without being confronted with irrelevant implementation details.
Putting definitions (as opposed to declarations) in your header file can also cause linker errors (as mentioned by Captain Comic). Maybe not currently, but surely when you expand your code.
Besides, explicitly separating declaration from definition (lets forget templates and inline functions here) also works towards a more "perfect" model. The code will be completely modularized in separate source files. From my personal experiences this takes time and care, but is consistent and avoids linker errors etc.
Surely, if you're writing a quick application nobody else is going to see...nobody is there to criticize ;)
Go for it.
If you want a better response, elaborate on your problems, post code, etc.
I put .h files in the same directory as the .cpp files. They are coupled anyway, so why split them up?!
It's much easier for the IDE to locate the matching file when you want to jump between declaration (in foo.h) and definition (in foo.cpp).
Only for external headers, that is those headers that are used by external projects, I might create a separate folder.
One important thing you have to bear in mind is that it is the .cpp files that are compiled, not header files. So design carefully who will include you headers, otherwise you'll get linker errors.
I asked my professor this same question a few hours ago, when he advocated putting a few getters in a .h file, which was foreign to me as a C programmer.
He said that one purpose of the .h file was to give a quick overview of the class. If you've ever programmed in Java, you've probably built or read some huge classes, and locating a specific function can be a pain. A good text editor with folding capabilities or an IDE with an outline view can help you cope with the problem, but that's not always available. A one-line getter/setter or initializing constructor which will not slow a reader down is probably permissible.
Sometimes it all depends on the IDE or the environment in which you are developing the code. Usually
/source-tree
/bin -------> executables or lib or dlls
/h -------> headers
/source -------> source codes
/Makefile -------> The root make file
Now about the code structure, it depends on what you are developing. If some APIs for some data container, which will be used across different modules, It is something like, -
Header Files ------->
//ICoordinate.hpp
template <class T>
class ICoordinate
{
public:
virtual ~ICoordinate() {}
virtual void SetX(T ) = 0;
virtual void SetY(T ) = 0;
virtual T GetX(void) = 0;
};
// Co-ordinate system for ploting decimal points :-)
// class template specialization.
template <>
class ICoordinate<int>
{
public:
virtual ~ICoordinate() {}
void SetX(int );
void SetY(int );
private:
int x,y;
};
Source File --------->
// DecimalCoordinate.cpp
// Implementation for DecimalCoordinate
If you do not have problem with vtable lookup latency, you can always define with some pure virtual methods (just what i did here). There is post regarding the interface declaration.
I tend to prototype C++ classes as a self-contained class, i.e. like:
class BlahBlahBlah
{
public:
void SomeMethod()
{
// some code here
}
};
and then later when I am happy with the design I will turn it into a .h/.cpp pair. This is mostly a mechanical task so is there any tool out there that can help with that?
Try Lzz.
Visual Assist has a refactor tool that does this. You can bind it to a keyboard shortcut so you can do it case-by-case, rather than robotically.
As an alternative to Lzz you might consider taking a look at Preprocess - A preprocessor for C and C++ modules. Unlike Lzz, it does preserve comments. However, it does have some limitations. It does not support namespaces or nested classes. But since it's written in PERL and I imagine it would not be too difficult to extend and customize.
There is also inlsplit: Inline C++ Source and Header splitter. It is a very simple awk script which parses a single .inl file and places all member functions with a # folowing their prototype into the source file, keeping only the declaration in the header. There is also a #source tag for code to go straight into the implementation. Compared to lzz and preprocess, it is very lightweight. However it has been abandoned and there is no new development.
I'm trying to learn C++ for Qt development, and I'm a little scared of header files. What I'd like to know is, what's the best workflow for keeping *.cpp and *.h files synched? For example, is the norm to write the class file and then copy the relevant info over to the header?
Sorry if this doesn't make any sense...I'm just looking for an efficient workflow for this.
Thanks!
Justin
For example, is the norm to write the class file and then copy the relevant info over to the header?
While there is no single standard approach, its usually a good idea to:
first think about the public interface
put that in the header
implement in the source file accordingly
update the header if needed
Jumping straight into the implementation can make for a painful refactoring later on.
So:
You'll get linker errors if something's in the header, used by a client, and not in the cpp.
You'll get compile errors if something in the cpp is not defined or is defined differently in the .h
What scenario are you worried about?
Create the test code that uses your class/functions (this way you can play with the end results before even writing any code)
Create the header with the class and the methods.
Implement those methods in your cpp file
If you run into the case where you have to change the signature of the methods, you will need to manually change it both place (header + source).
You can shell out a small amount of money and buy Visual Assist X. With Visual Assist X, you right click the method in your cpp file, choose Refactor -> Change Signature. Perform the change and hit Ok. It is changed in both places.
So, in short, there is no way to keep them in sync automatically, but with the right refactor tool, your life will be better.
In general for the first version I write the class file in the .h and when done I copy the method declarations to the .cpp and there change them into definitions (i.e. methods and their bodies). In this phase I declared only the public methods of the class, because I'm more concerned about its interface than the internals.
Later, when I'm implementing the public methods, if I need a new private method I begin by calling it wherever it's needed, so I get the parameters well defined. Then I write its declaration in the .h and go back to the .cpp to write its body.
It may be of interest to you the concepts of Tracer Bullet Design, which fits well with this workflow. It's described in the book The Pragmatic Programmer:
http://www.amazon.com/Pragmatic-Programmer-Journeyman-Master/dp/020161622X/ref=sr_1_1?ie=UTF8&s=books&qid=1279150854&sr=8-1
This page contains a brief description
http://www.artima.com/intv/tracer2.html
You keep them both open at the same time (I frequently use a horizontal split for this) and when you change one file you change the other file. It's just the same as how you keep the prototypes at the top of a file in sync with the function definitions at the bottom of the file when you're writing a program that fits in a single .cpp file.
Should you declare the getters/setters of the class inside the .h file and then define them in .cpp Or do both in .h file. Which style do you prefer and why? I personally like the latter wherein all of them are in .h and only methods which have logic associated with it other than setters/getters in .cpp.
For me it depends on who's going to be using the .h file. If it's a file largely internal to a module, then I tend to put the tiny methods in the header. If it's a more external header file that presents a more fixed API, then I'll put everything in the .cpp files. In this case, I'll often use the PIMPL Idiom for a full compilation firewall.
The trade-offs I see with putting them in the headers are:
Less typing
Easier inlining for the compiler (although compilers can sometimes do inlining between multiple translation units now anyway.)
More compilation dependencies
I would say that header files should be about interface, not implementation. I'd put them in the .cpp.
For me this depends on what I'm doing with the code. For code that I want maintained and to last over time, I put everything in the .cc file for the following reasons:
The .h file can remain sparse as documentation for people who want to look for function and method definitions.
My group's coding guidelines state that we put everything in the .cpp file and like to follow those, even if the function definition only takes one line. This eliminates guessing games about where things actually live, because you know which file you should examine.
If you're doing frequent recompiles of a big project, keeping the function definition in the .cpp file saves you some time compared to keeping function definitions in header files. This was relevant very recently for us, as we recently went through the code and added a lot of runtime assert statements to validate input data for our classes, and that required a lot of modification to getters and setters. If these method declarations had lived in .cpp files, this would have turned into a clean recompile for us, which can take ~30min on my laptop.
That's not to say that I don't play fast-and-dirty with the rules occasionally and put things in .h files when implementing something really fast, but for code I'm serious about I all code (regardless of length) in the .cpp file. For big projects (some of) the rules are there for a reason, and following them can be a virtue.
Speaking of which, I just thought of yet another Perl script I can hack together to find violations of the coding guidelines. It's good to be popular. :)
I put put all single-liners in the header as long as they do not require too much additional headers included (because calling methods of other classes).
Also I do not try to put all code in one line so I can put most of the methods in the header :-)
But Josh mentioned a good reason to put them in the .cpp anyway: if the header is for external use.
I prefer to keep the .h file as clean as possible. Therefore, small functions that are as simple as get/set I often use to put in a separate file as inline-defined functions, and then include that file (where I use the extension .inl) into the .h header file:
// foo.h
class foo
{
public:
int bar() const;
private:
int m_bar;
};
#include "foo.inl"
// foo.inl
inline
int foo::bar() const
{
return m_bar;
}
I think that this gives the best of two worlds, at the same time hiding most of the implementation from the header, and still keep the advantage of inlining simple code (as a rule of thumb I keep it within at most 3 statements).
I pretty much always follow the division of declaring them in the header, and defining in the source. Every time I don't, I end up having to go back and do it any way later.
I prefer to put them into the .cpp file, for the sake of fast compile/link times. Even tiny one-liners (empty virtual destructors!) can blow up your compile times, if they are instantiated a lot. In one project, I could cut the compile time by a few seconds by moving all virtual destructors into the .cpp files.
Since then, I'm sold on this, and I would only put them into the header again if a profiler tells me that I can profit from inlining. Only downside is you need more typing, but if you create the .cpp file while you write the header, you can often just copy&paste the declarations and fill them out in the .cpp file, so it's not that bad. Worse of course if you later find out you want to move stuff into a .cpp file.
A nice side effect is that reading stuff is simpler when you have only documentation and declarations in your header, especially if new developers join the project.
I use next rule: header for declaration, code file for realization. It becomes for actual when your header would be use outside of project - than more lightweight your header is, then it's more comfort in use