Alex Rivera | Logout

How to make a structure extern and define its typedef

Asked 2012-03-17T12:21:15.473
26

I'm trying to implement tree algorithms in C. I have declared a extern struct in a header file that is completely independent (b_tree_ds.h). Now I plan to import the file in all source files that want to use this struct. So I must declare it using extern in header.

Now the problem is thhat I want to define its typedef as well. the compiler gives error of multiple storage classes. How should I do that.

typedef extern struct node {
    struct node* left;
    struct node* right;
    int key;    // contains value
}NODE;

The actual problem is as follow, which I still can't fix??? I recently learnt how can we use multiple source files with header files to make code portable and hierarchical. In order to do so, I tired creating my tree program using this principal. Here are my files

b_tree_ds.h - This will contain a declaration of datastructure of node of a tree, which can be called to various functions implementing different functionality of the tree (which may be in different source files)

typedef struct node {
    struct node* left;
    struct node* right;
    int key;    // contains value
}NODE;

When i try adding a extern as in typedef extern struct node it gives a error of multiple storage class but if I miss it, I get error for multiple definitions.

Here are my other source files

traverse.h - contains declaration of traverse function

void traverse_print (NODE* p);

Here also I get error for unknown identifier NODE

traverse.c - contains definition to that function

#include <stdio.h>
#include "b_tree_ds.h"
#include "traverse.h"

void traverse_print(NODE* p)
{
    if(p->left != NULL)
    {
        traverse_print(p->left);
    }

    if (p->right != NULL)
    {
        traverse_print(p->right);
    }

    printf ("\n%d",p->key);
}

Finally main.c

<
Edit
Report

1 Answer

3

In your header file declare node.h like this

#ifndef NODE_H
#define NODE_H

#ifdef  __cplusplus
extern "C" {
#endif

typedef struct node {
        struct node* left;
        struct node* right;
        int key;    // contains value
    }NODE;


#ifdef  __cplusplus
}
#endif

#endif  /* NODE_H */  

you can include this header file in any c program and use it like

NODE* newNode = NULL;
answered 2012-03-17T12:30:41.330

Your Answer