Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare extern typedef struct?

Tags:

c

extern

I have two c files, foo.c with the functionality and test_foo.c which test the functions of foo.c.

Is there a way to access the struct typedef BAR I defined in foo.c in test_foo.c without using a header file? So far, I was able to avoid a h file so that the whole program would consist of foo.c. Thanks.

foo.c   
typedef struct BAR_{...} bar;
BAR *bar_new(...) {..}

test_foo.c
extern BAR *bar_new(...)

error: expected declaration specifiers or ‘...’ before ‘BAR’

like image 634
Framester Avatar asked Jul 12 '10 10:07

Framester


People also ask

How to make a struct an extern struct?

You can't make a struct extern. Just define it in an include-guard protected header and include that header everywhere you need it. A structure type definition describes the members that are part of the structure. It contains the struct keyword followed by an optional identifier (the structure tag) and a brace-enclosed list of members.

Why do we use struct and typedef in C++?

This lets you access members of a structure variable for both reading and writing. Many tend to use struct and typedef in tandem like this: One advantage by doing this is that you don’t have to write struct every time you declare a variable of this type (like we did in the last chapter on code snippet line 7 and 9).

Should you use struct and typedef in tandem?

Many tend to use struct and typedef in tandem like this: One advantage by doing this is that you don’t have to write struct every time you declare a variable of this type (like we did in the last chapter on code snippet line 7 and 9).

What is typedef in C++?

What? typedef is a keyword in C and C++ which lets you create custom data types, or more accurately: create an alias name for another data type. Keep om mind that it does not create a new type, but instead adds a new name for some existing type.


2 Answers

The answer is that there is one, and you should use an header file instead. You can copy the definition of the struct typedef struct BAR_{...} bar; into test_foo.c and it will work. But this causes duplication. Every solution that works must make the implementation of struct available to the compiler in test_foo.c. You may also use an ADT if this suits you in this case.

like image 144
Shiroko Avatar answered Oct 22 '22 20:10

Shiroko


Drop the typedef.

In foo.c:

struct bar 
{
    ...
};

struct bar *bar_new(....)
{
    return malloc(sizeof(struct bar));
}

In test_foo.c:

struct bar;

struct bar *mybar = bar_new(...);

Note that you only get the existence of a struct bar object in this way, the user in test_foo.c does not know anything about the contents of the object.

like image 26
harald Avatar answered Oct 22 '22 21:10

harald