C multiple definition error

I am currently doing an adt simulation in c, and I have to create a binary search tree into which the lines are inserted, I am currently running the encoding, but I get this error and it does not say where the error is coming from, here is the code, can anyone -Never help me.

//Tree.h #ifndef tree_h #define tree_h #include <stdbool.h> #include <stdlib.h> typedef struct tree_node* node_ptr; struct tree_node { char* word; node_ptr leftNode, rightNode; }; node_ptr start = NULL; void addItem(char*, int); void display(); #endif //tree.c #include "tree.h" #include <stdio.h> #include <stdlib.h> #include <stdbool.h> void addItem(char arr[], int mode) { node_ptr temp, temp2; temp = (node_ptr)malloc(sizeof(struct tree_node)); temp->leftNode=NULL; temp->rightNode=NULL; if(mode == 1){ temp->word = arr; start = temp; } } void display() { node_ptr temp; temp = start; printf("%s", start->word); } //main.c #include "tree.h" #include <stdio.h> #include <conio.h> int main() { char word[31]; printf("Enter Root Word: "); gets(word); addItem(word, 1); } 
+4
source share
4 answers

The problem is the statement in tree.h

 node_ptr start = NULL; 

And you include tree.h in main.c and tree.c This gives a multiple definition error for the start variable, which is in the global scope. What do you really need

 // tree.h extern node_ptr start; 

And have a definition in one source file, for example -

 // tree.c #include "tree.h" ........ node_ptr start = null; 
+15
source

The error you are talking about:

 ... multiple definition of `start' 

Since you have node_ptr start = NULL; in tree.h , each compilation unit that includes tree.h will have its own definition of the start variable. When the bind time comes, the linker will see a few definitions of the start variable and throw an error.

To avoid this, define start in tree.c :

 node_ptr start; 

And then declare start as extern so that other compilation units know about it, but don't try to define it yourself, in your tree.h header file:

 extern node_ptr start; 
+7
source

Your mistake is that you define:

 node_ptr start = NULL; 

In your header file, so when you import it (regardless of macro protection) you will get two start overrides.

+3
source
 if(mode == 1) { temp->word = arr;/*here is another error*/ start = temp; } 

arr is local to the main one, and I think for more nodes, you should reuse the arr array to get input. At this time, it reflects in all nodes, since your word of each node indicates the same place in memory. not the possibility of a direct appointment.

You must also allocate memory dynamically for the string. Then use the strcpy () function to copy the data to the dynamic memory location.

ok use this code in this place: -

 if(mode==1) { w_len=sizeof(char)*(strlen(arr)+1);//one extra character for null character temp->word=malloc(w_len); strcpy(temp->word,arr); start=temp; } 
+1
source

All Articles