Search code examples
cincludeinclude-guards

Include Guard Problem in C (Compiler still reports redefiniton errors)


AS the title says I am having an issue using include guards. I was not sure if I was using them correctly and so I have already checked several related posts and they all contain code that seems to be the same as mine. Please advise me as to what is wrong with my use of include guards.

For context I have several header files that I want to be able to use in other programs, because of this multiple files include the same dependency header (a linkedList file) and this is where the issue arises. Even though I appear to have include guards the compiler still reports that the code has a redefinition error. Below is the include guard that isn't working.

 #ifndef UNI_LINKED_LIST_LIB_H
 #define UNI_LINKED_LIST_LIB_H "uniLinkedListLibV02.h"
 #include UNI_LINKED_LIST_LIB_H
 #endif

My understanding is that the #ifndef will return false if I try to include this header more than once. And on the first include it should define UNI_LINKED_LIST_H and then include the library.


Solution

  • Here's a .h file with a guard:

    // guard.h -- include file with a guard
    
    #ifndef GUARD_H
    #define GUARD_H
    
    #define SPECIAL_VALUE   23
    
    #endif
    

    Here's a .c file that uses it:

    // main.c -- program that includes the guarded file
    
    #include <stdio.h>
    
    #include "guard.h"
    
    int
    main(void)
    {
    
        printf("%d\n",SPECIAL_VALUE);
    
        return 0;
    }
    

    Here is a .c file that includes the file incorrectly:

    // bad.c -- program that includes the guarded file _incorrectly_
    
    #include <stdio.h>
    
    // do _not_ do this:
    #ifndef GUARD_H
    #define GUARD_H
    #include "guard.h"
    #endif
    
    int
    main(void)
    {
    
        printf("%d\n",SPECIAL_VALUE);
    
        return 0;
    }