dotNoted

Icon

Observations of .Net development in the wild

Why C++ needs .H files

I never questioned why C++ needs .h files – I just accepted it. Definitions go into .h files, and code goes in .cpp or .c files. Strange, I know – me just accepting without questioning. Huh. I suppose it was the nice side effect of having the .h file be your API definition. But that’s not really why it _has_ to have one. You need it because the C++ compiler is a clunky beast which only does a single pass through the code. Sure, there is some history for this, but there really isn’t a tenable argument to be found why it should stay this way.

I found all this out by trying to resolve a circular reference among objects which I am creating to wrap the Shapefile library by Frank Warmerdam. This post helped me unravel that issue, and deduct the real reason behind .h files.

So basically, you can do this:

In ShapeObject.h:

                // a "stub" definition for the related class which contains ShapeObject
                ref class ShapeFile;

	public ref class ShapeObject
	{
	private:
		Boolean		_isDisposed;
		SHPObject*	_internalHandle;
		Int32		_index;
		ShapeType	_type;

                                // Now we don't get a compilation error here
		ShapeFile^	_parentFile;
                                .
                                .
                                .
                };

And in ShapeFile.h:

                #include "ShapeObject.h"
	public ref class ShapeObjectsCollection : public System::Collections::Generic::List
	{
	public:
		ShapeObjectsCollection() { }
	};

	public ref class ShapeFile
	{
	
	private:
		ShapeObjectsCollection ^ _shapes;
                                .
                                .
                                .

                 };

The important thing is the stub declaration… since the C++ compiler only does one pass, it needs to be declared before hand… implementation can be done later, which is where the .h/.c[pp] split comes in.

Filed under: .Net Basics