-1

I'm struggling with breaking up working code that exists in 2 files (A main.cpp and header.h -> A main.cpp, functions.cpp, and header.h)

My problem seems to completely revolve around this struct and my use of the *root pointer:

struct avl_node
{
    int data;
    struct avl_node* left;
    struct avl_node* right;
}*root;

When my code is in just two files (the main.cpp and header.h) the code runs fine, it's the moment I split the definitions of my functions into a functions.cpp that the LNK1169 error starts to appear.

Am I misunderstanding how things should work?

Chris Catignani
  • 5,040
  • 16
  • 42
  • 49
cVos
  • 27
  • 1
  • 5
  • 1
    Showing a full example of your code (splitted in files if that is the case) provides a lot of info fro getting help. – Ripi2 Oct 10 '20 at 18:13

1 Answers1

1

In the header:

struct avl_node
{
    int data;
    avl_node* left;
    avl_node* right;
};
extern avl_node* root;

In exactly one source file:

#include "ThatHeader.h"
avl_node* root;

Currently, you put the definition of root into the header. Which means that every source file that includes this header ends up containing that definition. And when those files are linked together, the linker discovers multiple definitions of the same name, and complains.

The solution is to provide only a declaration in the header file (that's what extern keyword does), and a definition in only one source file.

See also: One Definition Rule

Igor Tandetnik
  • 50,461
  • 4
  • 56
  • 85