Search code examples
c++linkerheader-filesheader-only

Inclusion of a header-only library to multiple files producing a linker error


I'm using a header-only single-file "library" to load .obj-models from a file into a graphics program. A simple linker error has popped up:

LNK2005 "Info here" already defined in main.obj

Now I know what this means and normally I'd proceed with moving the implementation to a separate file. However, this is a file provided by someone way smarter than I, and so relying on authority I'd expect the thing to work.

It only complains about a vector multiplication operator overload and a single function among loads of other functions:

glm::vec3 operator*(const float& left, const glm::vec3& right){
    return glm::vec3(right.x * left, right.y * left, right.z * left);
}

bool inTriangle(glm::vec3 point, glm::vec3 tri1, glm::vec3 tri2, glm::vec3 tri3)
{
    // Starting vars
    glm::vec3 u = tri2 - tri1;
    glm::vec3 v = tri3 - tri1;
    glm::vec3 w = point - tri1;
    glm::vec3 n = glm::cross(u, v);

    float y = glm::dot(glm::cross(u, w), n) / glm::dot(n, n);
    float b = glm::dot(glm::cross(u, w), n) / glm::dot(n, n);
    float a = 1 - y - b;

    // Projected point
    glm::vec3  p = (a * tri1) + (b * tri2) + (y * tri3);

    if (a >= 0 && a <= 1
        && b >= 0 && b <= 1
        && y >= 0 && y <= 1)
    {
        return true;
    }
    else
        return false;
}

Is there something special about these functions?

The file is from OBJ Loader, which I have modified just to use the glm vectors and utilities I'm currently using elsewhere.


Solution

  • Is there something special about these functions?

    Yes, they were not marked as inline like all the other free functions in the algorithm namespace.

    When you define a function in a header file you need to mark it as inline so that it can be defined in multiple translation units (included in multiple source files) without error.