Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why getting multiple definition error in C code?

Tags:

c

i'm currently doing a simulation of adt in c, and i'm supposed to make a binary search tree invloving strings, i'm currently starting coding but i get this error and it doesnt say where the error comes from, here's the code, can somebody 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);
}
like image 624
cjBucketHead Avatar asked Nov 27 '22 11:11

cjBucketHead


2 Answers

The problem is with the statement in tree.h.

node_ptr start = NULL;

And you are including tree.h in both main.c and tree.c. This gives the multiple definition error for the variable start which is at global scope. What you actually need is,

// tree.h

extern node_ptr start;  

And have the definition in a single source file like -

// tree.c

#include "tree.h"
........
node_ptr start = null;
like image 154
Mahesh Avatar answered Dec 22 '22 10:12

Mahesh


The error that you're talking about is:

... multiple definition of `start'

Since you have node_ptr start = NULL; in tree.h, each compilation unit that includes tree.h will have their own definition of the variable start. When it comes time to linking, the linker will see multiple definitions of the variable start 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 won't try and define it themselves, in your header file tree.h:

extern node_ptr start;
like image 38
AusCBloke Avatar answered Dec 22 '22 10:12

AusCBloke