Declaring - typedefs and structs

Sep 21, 2015 at 11:02pm
Hello. I am trying to compile my program but GCC accuses a few errors. Amongst them, there's two about "redeclaration" of typedefs/structs.
What am I doing wrong? How do I declare the signatures/headers on the .h and implementation on the .c?

On my .h I have
1
2
3
4
5
6
7
8
#ifndef QUEUE_H
#define QUEUE_H

#include <stdbool.h>
#include <stdlib.h>

struct queue;
typedef struct queue queue_t;


And on my .c I have
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include "queue.h"

typedef struct
{
    void* data;
    struct node_queue_t* next; /*!*/
} node_queue_t;


struct
{
    node_queue_t* first;
    node_queue_t* last;
} queue_t;
Sep 21, 2015 at 11:14pm
Sep 22, 2015 at 12:37am
Sorry, but it's not exactly the same. I am trying to separate the headers, but GCC tells me I am redeclaring the functions or that there's an "unknown type" if I write the structs like you've told me.
Sep 22, 2015 at 3:00am
Ah, I see. The problem is not in the code I suggested to you, but in the way you are structuring your headers.

The way things look belong in the headers. The way things work belong in the .c file.

queue.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#ifndef QUEUE_H
#define QUEUE_H

typedef struct node_queue_tag
{
    void* data;
    node_queue_tag* next;
}
node_queue_type;

typedef struct
{
    node_queue_type* first;
    node_queue_type* last;
}
queue_type;

void queue_push( queue_type* q, void* data );

#endif 

queue.c
1
2
3
4
5
6
7
8
9
#include <stdbool.h>
#include <stdlib.h>

#include "queue.h"

void queue_push( queue_type* q, void* data )
{
  ...
}

Notice how I moved the standard headers into the .c file? Only include files strictly necessary for the header in the header. Stuff needed by the .c file goes in the .c file.

Hope this helps.
Last edited on Sep 22, 2015 at 3:00am
Sep 22, 2015 at 9:17pm
Thank you again for your help!

Just to inform: I was expected to write the nested structs like this:

1
2
3
4
5
6
7
//.h
struct node_queue;
typedef struct node_queue node_queue_t;

struct queue;
typedef struct queue queue_t;



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//.c
#include "queue.h"

struct node_queue
{
    void* data;
    struct node_queue_t* next; /*!*/
};

struct queue
{
    node_queue_t* first;
    node_queue_t* last;
};

Last edited on Sep 22, 2015 at 9:22pm
Sep 23, 2015 at 4:14am
Ah, well, I guess you can do that...

You are confusing the compiler on line 7 by using a typedef with a 'struct' keyword. Pick either:

struct node_queue* next;

or

node_queue_t* next;

Sorry for being so slow...
Topic archived. No new replies allowed.