How to fix multiple definition error in C ++?

I tried to see other related posts, but I fell into place

My header files look something like this:

Node.hpp

      #include<iostream>
using namespace std;
#ifndef NODE_HPP
    #define NODE_HPP



        struct Node
        {
            int value;
             Node *start;
             Node *end;
        }
         *start, *end;
         int count= 0;


        #endif

and

Queue.hpp

  #include<iostream>
using namespace std;
#ifndef QUEUE_HPP
#define QUEUE_HPP
#include "Node.hpp"

class Queue{
    public:
        Node *nNode(int value);
        void add(int value);
        void remove();
        void display();
        void firstItem();
        Queue()
        {   
            start = NULL;
            end = NULL;
        }   
    };
    #endif

My implementation for the queue looks like

#include<iostream>
using namespace std;

#include "Queue.hpp"
#include<cstdio>
#include<cstdlib>

And most importantly it looks like

  #include<iostream>
    using namespace std;
    #include "Queue.hpp"
    #include<cstdio>
    #include<cstdlib>

I get the following errors

 /tmp/ccPGEDzG.o:(.bss+0x0): multiple definition of `start'
    /tmp/ccJSCU8M.o:(.bss+0x0): first defined here
    /tmp/ccPGEDzG.o:(.bss+0x8): multiple definition of `end'
    /tmp/ccJSCU8M.o:(.bss+0x8): first defined here
    /tmp/ccPGEDzG.o:(.bss+0x10): multiple definition of `count'
    /tmp/ccJSCU8M.o:(.bss+0x10): first defined here

What am I doing wrong here?

+4
source share
4 answers

Others have already explained the cause of the error: you define the same global variables in several translation units.

A possible fix is ​​to define them at only one point and declare them as externin the header file.

, , : ? , .

class Queue{
    public:
        Node *nNode(int value);
        void add(int value);
        void remove();
        void display();
        void firstItem();
        Queue()
        {   
            start = NULL;
            end = NULL;
        }   
        Node *start, *end; // <----
    };

, , . , , .

TL; DR: , .

+2

, . ,

(Node.hpp)

extern Node *start;
extern Node *end;
extern int count;

implmentation ( , Node.cpp )

Node *start;
Node *end;
int count = 0;
+5

start, end count . , , , ,

, , , .

, extern:

extern struct Node *start, *end;
extern int count;
+1

start, count end , , .

0
source

Source: https://habr.com/ru/post/1630015/


All Articles