C语言 如何声明extern typedef结构?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3227654/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 05:52:22  来源:igfitidea点击:

How to declare extern typedef struct?

cextern

提问by Framester

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

我有两个 c 文件,具有功能的 foo.c 和测试 foo.c 功能的 test_foo.c。

Is there a way to access the struct typedef BARI 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.

有没有办法BAR在不使用头文件的情况下访问我在 test_foo.c 中的 foo.c 中定义的 struct typedef ?到目前为止,我能够避免 ah 文件,因此整个程序将由 foo.c 组成。谢谢。

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

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

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

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

采纳答案by Shiroko

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.cand 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.

答案是有一个,您应该改用头文件。您可以将结构的定义复制typedef struct BAR_{...} bar;到其中test_foo.c,它将起作用。但这会导致重复。每个有效的解决方案都必须使 struct 的实现可用于test_foo.c. 如果在这种情况下适合您,您也可以使用 ADT。

回答by harald

Drop the typedef.

删除 typedef。

In foo.c:

在 foo.c 中:

struct bar 
{
    ...
};

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

In test_foo.c:

在 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.

请注意,您只能通过这种方式获得 struct bar 对象的存在,test_foo.c 中的用户对对象的内容一无所知。

回答by Brian Hooper

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.

您需要在 test_foo.c 中提供 BAR 的定义。这种重复是否比拥有标题更可取取决于您。