Aniruddha
Aniruddha

Reputation: 70

Can we use extern keyword with typedef datatype in header file?

I want to implement stack and its functions using static libraries in c. But even after declaring STACK in header file using extern i am getting errors that STACK is not declared.I have declared stack in a separate stack_1.c file and want other functions like push, pop etc to access this stack.Is it possible to do so?

Upvotes: 1

Views: 2116

Answers (3)

Rishikesh Raje
Rishikesh Raje

Reputation: 8614

.I have declared stack in a separate stack_1.c file and want other functions like push, pop etc to access this stack.

No, you will have to add the definition of the type STACK in a header file which is included in stack_main.c and push.c.

Easiest option is to move the definition of the type STACK to the header file lib.h

What you can also do is to define the structure in the stack_1.c and the typedef in the header file. This can hide your internal workings of the STACK, from the external world. However in your case, i would go with the first approach.

e.g. in stack_1.c (or preferably in another header file)

struct stack1{

    int stk[MAX] ;
    int top;  
};

and in lib.h

typedef struct stack1 STACK;

Upvotes: 3

MayurK
MayurK

Reputation: 1957

You are getting that error because the compiler is not able to understand what is "STACK" while compiling stack_main.c

The "extern" keyword is not for the type but for variables. i.e. If you have defined global a variable in a .c file and want to use in another .c file, then you have to tell second .c file that there is a variable already defined in another .c file and just use that variable using "extern" keyword.

So to fix the errors, you need to define STACK type in a .h file and include that .h file in both the .c file.

Upvotes: 1

Some programmer dude
Some programmer dude

Reputation: 409422

The compiler doesn't know what STACK is when you have the external declaration. And you can't use extern type-aliases anyway.

But you can solve it just the way that the standard C library does with the FILE structure:

typedef struct stack_struct STACK;

As long as the users of your library only use pointers to STACK (i.e. STACK *) then they don't need the structure definition itself. This makes the stack an opaque data type.

Then in your implementation you simply have

struct stack_struct
{
    // Your structure...
};

in a private header file that you include in your implementation source files. And it's important that you put the structure definition in a header file, having the structure in a source file makes it available to that single source file only.

Upvotes: 4

Related Questions