如果包含"assert.h"的每个文件都需要很长的编译时间吗?

use*_*020 1 c++ compilation

根据Mats Petersson的结果,我做了一些测试.我没有必要通过定义宏来打开和关闭断言.我的结论是:

  1. 包括标准头,如<cassert>,<vector>,<memory>等等,需要一点编译时间.我们不需要关心.
  2. 包含自己的文件时要小心.包括那些真正需要的,因为依赖项需要在更改依赖项后重新编译.
  3. 包含类库的集合头时要小心,例如<QWidgets>(Qt头包含其所有小部件).这需要花费大量时间进行编译.

[原帖]

如果每个文件都包含"assert.h",是否需要很长的编译时间?我认为关于"math.h"或其他常见文件的类似问题.我不喜欢预编译的标题.当我有一个Vector3D类来表示具有x,y,z分量的3D空间中的矢量时,会发生这种情况.该课程几乎用于所有地方.我有一个函数名称component(int i)i0和2之间断言.出于性能原因,我没有把它的实现放在cpp文件中.因此"assert.h"几乎包含在所有地方.

#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];
};
Run Code Online (Sandbox Code Playgroud)

受Floris Velleman的启发,我添加了一个文件来定义我的ASSERT以打开和关闭它.它需要使用assert 更改assertASSERT代码.谢谢.

#ifdef USE_ASSERT
# include <assert.h>
# define ASSERT(statement) assert(statement)
#else
# define ASSERT(statement)
#endif
Run Code Online (Sandbox Code Playgroud)

Pup*_*ppy 5

所有标题使用相同的包含模型,这非常慢.某些标头可能比其他标头更复杂,但一般情况下,您不包含您不需要的标头.