[英]How to define an ADT struct in header file that will be defined in implementation file
I have a header file that declares an ADT modeling a tuple.我有一个头文件声明一个 ADT 建模一个元组。 The header contains a declaration of the struct as typedef struct Tuple * Tuple;
标头包含结构声明为typedef struct Tuple * Tuple;
The corresponding implementation file defines this as相应的实现文件将其定义为
struct Tuple
{
int x;
int y;
int z;
int w;
};
The problem is that I want to import just the header file in client code (such as a test file or a file containing main).问题是我只想导入客户端代码中的头文件(例如测试文件或包含 main 的文件)。 I don't want to include the.c implementation file.我不想包含.c 实现文件。 Not doing so however results in an error message when attempting code from client code such as:但是,如果不这样做,则在尝试从客户端代码中尝试代码时会出现错误消息,例如:
Tuple tuple = ( Tuple ) calloc( 1, THREE_TUPLE_COORDINATES * sizeof( Tuple ) );
tuple->x ;
that reads as follows: error: dereferencing pointer to incomplete type 'struct Tuple'
内容如下: error: dereferencing pointer to incomplete type 'struct Tuple'
Is it possible leave leave the struct incomplete/undefined in the header and then define it in the implementation file or is this not done/not best practice?是否可以在标头中留下不完整/未定义的结构,然后在实现文件中定义它,或者这不是完成/不是最佳实践?
error: dereferencing pointer to incomplete type 'struct Tuple'
Is it possible leave leave the struct incomplete/undefined in the header and then define it in the implementation file or is this not done/not best practice?是否可以在标头中留下不完整/未定义的结构,然后在实现文件中定义它,或者这不是完成/不是最佳实践?
You cannot use an abstract / incomplete data type in any context where the actual definition matters.您不能在实际定义很重要的任何上下文中使用抽象/不完整的数据类型。 Such contexts include declaring instances, accessing members, and determining the size.此类上下文包括声明实例、访问成员和确定大小。 How is the compiler supposed to know how much space to reserve?编译器应该如何知道要保留多少空间? Or where within that space to find the member with a particular name?或者在那个空间的什么地方可以找到具有特定名称的成员? Or whether such a member even exists?或者这样的成员是否存在?
You can provide functions for most of those things in the same translation unit(s) where the type is defined, and then let other translation units rely on those functions.您可以在定义类型的同一翻译单元中为其中的大部分内容提供功能,然后让其他翻译单元依赖这些功能。 All instances obtained that way will need to be dynamically allocated, and all member accesses will incur the cost of a function call.以这种方式获得的所有实例都需要动态分配,并且所有成员访问都将产生函数调用的成本。 This sort of thing is sometimes done, but it's also often not done.这种事情有时做,但也经常不做。 Do think carefully about what you want to gain by doing it.仔细考虑你想通过这样做获得什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.