I'm working on a project in which I'm forced to use some previously written code that uses many header files calling other header files. I'm trying to keep my application separated, but I still need to use many of the types and functions defined in the previous code.

I've added forward declarations in my own header files, when referencing data types declared in other header files. My problem now, is I'm trying to reference a union type from within a function definition in a source file and I'm not quite sure how to do it.

Old header file:

/* filename: include.h */

typedef union SOME_UNION_TYPE
{
  int a;
  .
  .
}SOME_UNION_TYPE;


My source file:

/* filename: file.c */

void func()
{
  SOME_UNION_TYPE A;
  .
  .
  return;
}


I know it would be easier to just include "include.h" in my source code, but I'm trying to avoid it as much as possible. My attempt so far has been to forward declare the union in my header file, in hopes of exposing the typedef name to the compiler.

My header file:

/* filename: file.h */

union SOME_UNION_TYPE;


However, when I compile, I receive an error complaining about unknown size for A in func().

Thanks in advance for any help.

有帮助吗?

解决方案

If you need to create an actual instance of the type, you need the complete declaration, not just the name.

The right thing to do in this case is to bite the bullet and include the header file that defines the type.

其他提示

The #include directive is not something to be avoided. If you're concerned about other people's code polluting your code, you can make a header that includes the headers you need, and include that one directly.

Duplicating code is bad.

The other code probably includes a bunch of other headers because it needs them! You should just include the other header otherwise you are duplicating code which is bad.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top