Based on Mats Petersson’s results, I did some tests. My work on turning the assert on and off by defining a macro is not necessary. My conclusions are:
- Including standard headers such as
<cassert>,<vector>,<memory>and so on, takes little compilation time. We don’t need to care. - Be careful in including your own files. Include those that are really needed because the dependent requires recompilation after the change of the depended.
- Be careful when including collection headers of class library, such as
<QWidgets>(Qt header to include all its widgets). This takes a huge time in compilation.
[Original Post]
Does it take long compilation time if every files includes “assert.h”? I think similar questions on “math.h” or other common files. I don’t like pre-compiled header. This happens when I have a Vector3D class which represents a vector in 3D space with x, y, z component. The class is used almost everywhere. I have a function named component(int i) where i is asserted between 0 and 2. For performance reason, I don’t put its implementation in cpp file. Thus “assert.h” is included almost everywhere.
#pragma once
#include <assert.h>
/// A vector in a 3D space with 3 components: x, y, and z.
class Vector3D
{
public:
Vector3D(float x = 0, float y = 0, float z = 0)
{
m_component[0] = x;
m_component[1] = y;
m_component[2] = z;
}
float x() const {return m_component[0];}
float y() const {return m_component[1];}
float z() const {return m_component[2];}
void setX(float x) {m_component[0] = x;}
void setY(float y) {m_component[1] = y;}
void setZ(float z) {m_component[2] = z;}
float component(int i) const
{
assert(i >= 0 && i < 3);
return m_component[i];
}
float& component(int i)
{
assert(i >= 0 && i < 3);
return m_component[i];
}
private:
float m_component[3];
};
Inspired by Floris Velleman, I add a file to define my ASSERT to turn on and off it. It requires changing assert to ASSERT in the code using assert. Thanks.
#ifdef USE_ASSERT
# include <assert.h>
# define ASSERT(statement) assert(statement)
#else
# define ASSERT(statement)
#endif
All headers use the same inclusion model, which is tremendously slow. Some headers may be more complex than others, but in general, you don’t include a header you don’t need.