Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When using a header only in C/C++?

Tags:

c++

c

math

header

is it usual to use for a class like "vec3" only a header?

This is my actual code:

#ifndef VECTOR3_H
#define VECTOR3_H

#include <math.h>

class vec3
{
public:
    double x, y, z;
    vec3();
    vec3(double x, double y, double z) : x(x), y(y), z(z) {}
    double lenght()
    { return sqrt(pow(x, 2) * pow(y, 2) * pow(z, 2));}
    double lenghtSquared()
    { return pow(x, 2) + pow(y, 2) + pow(z, 2);}
    double distance(vec3 v)
    { return sqrt(pow(x - v.x, 2) * pow(y - v.y, 2) * pow(z - v.z, 2));}
    double distanceSquared(vec3 v)
    { return pow(x - v.x, 2) + pow(y - v.y, 2) + pow(z - v.z, 2);}
    float angle(vec3 v)
    { return (float) acos(dot(v) / lenght() * v.lenght());}
    double dot(vec3 v)
    { return x * v.x + y * v.y + z * v.z;}
    void cross(vec3 v) {
        double a = y * v.z - v.y * z; double b = z * v.x - v.z * x;
        double c = x * v.y - v.x * y; x = a; y = b; z = c;}
    void normalize()
    { x, y, z /= lenght();}
};

#endif // VECTOR3_H

Can I better create also a source file instead of only a header? If you have some tips, I like them :)

Thanks in advance

EDIT: And what means inline exactly?

like image 936
Vision Avatar asked Jun 18 '26 09:06

Vision


1 Answers

The class definition needs to go in a header, if you want it to be generally usable. If it's in a source file, then it's only available within that source file, not in others.

The member function definitions can either be inline like yours are; or you could move them to a source file, leaving just declarations in the class.

There are pros and cons to both approaches. A header-only implementation is easier to share and distribute, and offers more optimisation opportunities since the functions are easier to inline; but can lead to longer build times if there are a lot of large functions included in many translation unit, and makes the header more cluttered if you want to use it as "documentation" for the class interface.

And what means inline exactly?

It means a function is either defined inside a class, or declared inline. In either case, its purpose is to relax the "One Definition Rule", so that you are allowed to define the function in more than one translation unit; and it must be defined in every unit in which it's used. This is necessary if you want the definition to appear in a header (which may be included from multiple units). It gives the compiler a better opportunity to inline function calls, replacing them with the body of the function to avoid the cost of the calls.

like image 170
Mike Seymour Avatar answered Jun 20 '26 22:06

Mike Seymour



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!