Search code examples
credefinition

Getting an error : redefinition of struct within a .h program


#include <stdio.h>
#include <stdlib.h>

typedef struct sommet sommet;
typedef struct voisin voisin;
typedef struct graphe graphe;

struct sommet{  
    int indice;
    sommet* next;
    voisin* first_voisin;
};

struct voisin{
    int indice;
    voisin* next_voisin; 
};

struct graphe{
    sommet* premier_sommet;
}; 

Here's a simple struct definition h program. I get an Error : redefinition of struct for each of these. How can I fix this ? Thanks !

I tried putting directly

typedef struct sommet {
 //code
};

and also

typedef struct{
 //code 
}sommet;

Solution

  • Confidence is high that you can resolve your redefinition compile-time issue(s) by following best practices such as the following... please note that this code represents 2 files -- a MyHeaderFile.h and main.c.

    The include guard MY_HEADER_FILE_Hat the top of MyHeaderFile.h ensures that the structure definitions (and anything else in the include file) will only be defined once, and this is key. It tells the compiler, "Only enter past this point if MY_HEADER_FILE_H is NOT defined." This prevents a 2nd definition of everything that follows.

    Beyond that there is not much else to tell -- it is your code, after all.

    Runnable code here.

    /* ---------- MyHeaderFile.h ---------- */
    #ifndef MY_HEADER_FILE_H
    #define MY_HEADER_FILE_H
    
    #include <stdio.h>  /* Pls see Ted Lyngmo's comment on this */
    #include <stdlib.h>
    
    typedef struct sommet sommet;
    typedef struct voisin voisin;
    typedef struct graphe graphe;
    
    struct sommet{  
        int indice;
        sommet* next;
        voisin* first_voisin;
    };
    
    struct voisin{
        int indice;
        voisin* next_voisin; 
    };
    
    struct graphe{
        sommet* premier_sommet;
    };
    
    #endif //MY_HEADER_FILE_H
    
    /* ---------- main.c ---------- */
    #include "MyHeaderFile.h"
    
    int main()
    {
    
        voisin v = {5, NULL};
    
        printf("%d\n", v.indice);
        return 0;
    }
    

    Output:

        5