mardi 21 septembre 2021

Understanding why a namespace was required to resolve LNK2005 error [closed]

I have written a simple wavefront obj parser in C++ that is contained in a single header file. That file includes both declarations and definitions, as I wanted to experiment with header only library creation, and this seemed like a good stepping in point.

When I include the file into my main entry point cpp file I can call its only function "loadOBJ()" with no issues. It takes a single std::istream& as its only argument, and functions as expected as a MVP that I need to expand upon.

However, when I removed the objParser's #include directive from my main entry point and then added it to my precompiled header for my solution, "pch.h" which contains other headers such as

#include <vector>
#include <fstream>

etc...

I got a LNK2005 error LNK1169 error which do go hand in hand. The error eluded to the fact that class std::vector<struct objVert ... had already been defined. Now I know that it has only been defined once in the entire MSVS-2019 solution.

However, when I placed the function loadOBJ() into an anonymous namespace and called the loadOBJ function, the linker error had been resolved.

For clarity I was using VS-2019 as my IDE on Window 10, with the ISO C++ 20 standard.

Please can anyone shed any light into why this was the case?

Many thanks.

Code snippet of the obj parser below:

#pragma once
#include <istream>
#include <sstream>
#include <string>
#include <vector>

namespace {
    //Data structures
    struct vert
    {
        float x, y, z;
    };

    struct textCoord
    {
        float u, v;
    };

    struct normal
    {
        float xn, yn, zn;
    };

    struct objVert
    {
        vert pos;
        textCoord uvPos;
        normal normalVec;
    };

    //loading logic
    std::vector<objVert> loadOBJ(std::istream& input)

Aucun commentaire:

Enregistrer un commentaire