Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to fix multiple definition error in c++?

Tags:

c++

definition

I tried to look at other related posts but I'm sill stuck

My header files looks 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 queue looks like

#include<iostream>
using namespace std;

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

And main looks like

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

I'm getting 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?

like image 726
rose Avatar asked Feb 07 '23 16:02

rose


1 Answers

Don't define global variables in header file, sperate the declaration and definition to header and implmentation file. Such as,

In header file (Node.hpp)

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

In implmentation file (I think it's better to make a Node.cpp here)

Node *start;
Node *end;
int count = 0;
like image 165
songyuanyao Avatar answered Feb 20 '23 02:02

songyuanyao