How to declare extern typedef struct?

30,798

Solution 1

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.

Solution 2

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.

Solution 3

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.

Share:
30,798

Related videos on Youtube

Framester
Author by

Framester

Updated on July 13, 2020

Comments

  • Framester
    Framester almost 4 years

    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’

  • harald
    harald almost 14 years
    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.
  • Framester
    Framester almost 14 years
    For now, I just copied the definition into the other c file.
  • Nick
    Nick over 9 years
    You might as well keep the typedef and just cast it to void in foo.c then.
  • Nick
    Nick over 9 years
    I am doing the same - I am developing a test harness that is supposed to wrap around production code. In the production code the structure definition has no business being public and should be buried. Therefore I had to copy the definition into my test harness. This is duplication but my linker is smart enough to give me warnings if one changes but not the other.