tags:

views:

149

answers:

4

Hi there,

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’

A: 

You would need to supply the definition of BAR in test_foo.c. Whether that duplication is preferable to having a header is up to you.

Brian Hooper
A: 

Several errors in your code sample: typedef creates the 'new' type bar and this is what you should use for the type of your variables.

Further if you want to access the internals of the struct you need a prototype of it, else you will have only a pointer.

slashmais
+2  A: 

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.

Shiroko
Moving the definition to the header file is the right solution only if test_foo.c (or any other modules outside of foo.c) needs to access the contents struct itself. If it's an ADT or for some other reason test_foo.c don't need the internals of the type, I think a forward declaration is a better solution.
harald
For now, I just copied the definition into the other c file.
Framester
+1  A: 

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.

harald