like9orphanz
like9orphanz

Reputation: 55

Forward declaration error I'm having trouble making sense of

Header file declaration:

    typedef struct Queue *QueueP;

C File implementation:

    struct Queue
    {
      char *head;
      char *tail;
      QueueItemT item; //char typedef from the header file, not what's giving error
      int SizeL;
      int sizeP;
      int QueueSize;
    };

C main file:

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

    int main()
    {   
      struct Queue queue;
      QueueP myQueue = &queue;
      return 0;
    }

I am getting errors on the following lines with the following messages respectively:

    struct Queue queue;
                 ^
                 Main : variable has incomplete type 'struct Queue'

    typedef struct Queue *QueueP;
                   ^
                   Header : note: forward declaration of 'struct Queue'

Any idea what might be causing these errors? I'm new to working with multiple files and header files in C, so I'm really having trouble wrapping my head around these errors. Any help would be great, thanks!!

Upvotes: 1

Views: 2983

Answers (2)

like9orphanz
like9orphanz

Reputation: 55

Actually, the reason I was getting forward declaration problems was because I was trying to access the struct (that was declared in the .c file) from within the main file.

Not only was this bad programming practice, the desired feature of the project was that the end user (i.e. the person using the interface and implementation to build their 'main.c' file) should have no idea what kind of struct was being used, they should simply be able to build a queue with the functions given and not know what was going on behind the scenes.

D'oh!!!

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726579

You put structure definition into a c file. This is not how it works: you need to put the definition into the header.

This is because a definition of a struct is not an implementation. C compiler needs this information in order to process declarations of the struct correctly. A forward declaration lets you define a pointer to your struct; declaring a struct itself requires a full definition.

If you would like to keep the details of your struct private, put it into a private header file. Include the public header file from your private header, too:

queue.h

typedef struct Queue *QueueP;

queue_def.h

#include "queue.h"
struct Queue
{
  char *head;
  char *tail;
  QueueItemT item; //char typedef from the header file, not what's giving error
  int SizeL;
  int sizeP;
  int QueueSize;
};

main.c:

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

Now your project should compile without problems.

Upvotes: 1

Related Questions