1

I have a simple c++ app:

node.h:

#include<iostream>

using namespace::std;

class Node
{
private:
    int data;
    Node *next;

public:
    Node(int nodeData,Node *nextNode);
};

node.cpp:

#include "node.h"


Node::Node(int nodeData, Node *nextNode) {
    data = nodeData;
    next = nextNode;
}

linked_list.h

#include "node.h"

class LinkedList
{
private:
    Node *head;
    Node *tail;
    int size;
public:
    LinkedList();
    int getSize();
};

linked_list.cpp:

#include "linked_list.h"

LinkedList::LinkedList()
{
    size = 0;
}

int LinkedList::getSize() {
    return size;
}

main.cpp:

#include <iostream>
#include "node.h"
#include "linked_list.h"

using namespace ::std;

int main()
{
    cout << "This is main!\n";
    return 0;
}

I am on linux, inside the projcet's directory, I open a terminal there and try to compile them by this command:

g++ *.cpp *.h -o app

but I get this error:

In file included from linked_list.h:1:0,
                 from main.cpp:3:
node.h:1:7: error: redefinition of ‘class Node’
 class Node
       ^~~~
In file included from main.cpp:2:0:
node.h:1:7: note: previous definition of ‘class Node’
 class Node
       ^~~~

I looked at some posts here on stackoverlfow but had no luck in solving my problem. I am new to c++, I know that the compiler thinks I am redefining class Node somewhere, but where is this somewhere so I can remove the definition?

1
  • Put #pragma once at the beginning of every header file. Commented Jun 22, 2020 at 17:26

1 Answer 1

3

Your linked_list.h includes node.h, so the compiler will see the definition in node.h twice while compiling main.cpp.

To avoid this problem, you should add "include guard" to your header files.
It should be like this:

node.h:

#ifndef NODE_H_GUARD // add this
#define NODE_H_GUARD // add this

#include<iostream>

using namespace::std;

class Node
{
private:
    int data;
    Node *next;

public:
    Node(int nodeData,Node *nextNode);
};

#endif // add this

The macro name to define and check should be different for each headers.

Another way to avoid this problem is to adding #pragma once as the first lines of your headers if your compiler supports this.

Sign up to request clarification or add additional context in comments.

2 Comments

the #ifndef method worked without warnings, the pragma method worked but gave me warning : node.h:1:9: warning: #pragma once in main file #pragma once ^~~~ is this ok?
You shouldn't include *.h in your compiling command line because *.h files are for being included from *.cpp files and not for compiled directly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.