-2

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").

Ovidiu Firescu
  • 385
  • 3
  • 11

1 Answers1

1

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

t.niese
  • 39,256
  • 9
  • 74
  • 101
  • @OvidiuFirescu the file endings `.cpp` and `.h` do not mean anything for the compiler. It is just a convention to name your files that way. Important is what those file contain and what you do with them, if you compile them and link them together, if you include them, ... . – t.niese Jul 23 '19 at 16:07
  • Yeah, I understood now, I know how a program compiles and in the first step of preprocessing the files that start with (#) (also include files) are replace with the content it holds, so I though there will be no problem. But this is exactly why there is a problem because as you said will result in duplicate definitions. Didn't met this situation until now. Thanks again – Ovidiu Firescu Jul 23 '19 at 17:46