c++lnk2005

LNK2005 function already defined in


I read that "if you declare and implement a function in a header file (Header.h) and if this file gets included twice, then you'll most likely will get a function already defined error at some point.". But in my code all the functions that I get errors on are in a .cpp file.

List.h

#pragma once

typedef struct list
{

    int lin;
    int col;
    int val;

    struct list* next;
    struct list* prev;

}list;

List.cpp

#include "List.h"

bool empty(list*& start)
{
    return (start == nullptr);
}

Matrice.h

#pragma once

#include "List.h"   

class Matrice
{
private:

    list* start;
    list* finish;

public:

    Matrice() :start(nullptr), finish(nullptr) {}
    Matrice(const Matrice& matrice);

};

Matrice.cpp

#include "Matrice.h"
#include "List.cpp"

Matrice::Matrice(const Matrice& matrice)
{
    if (empty(start))
    {
        // Code
    }
}

Source.cpp

#include "Matrice.h"
#include <iostream>

int main()
{
    Matrice a;
    Matrice b;
    a = b;
}

I added all the files, maybe there's something I don't see. The error is on the bool empty(list*& start) function ("already defined in List.obj").


Solution

  • You have an #include<List.cpp> in your Matrice.cpp and as you compile and link all cpp files together this will result duplicate definitions of everything defined in List.cpp as they are also defined in Matrice.cpp due to the include.

    Replace the #include<List.cpp> with #include<List.h> and add the declaration of empty into the List.h