I have this in a C file:
struct T
{
int foo;
};
the C file has an include to an h file with those lines:
typedef struct T T;
void listInsertFirst(T data, int key, LinkedList* ListToInsertTo);
the function listInsertFirst
is the one I'm getting the warning on. How can I fix it?
As we've found out in the comments, the problem was that the definition of struct T
occurred after the definition of T
in the header. You really have things backwards here. The header should be defining all the types and function prototypes and your C files should be using them.
What you want to be doing instead is change the signature of your insert function to receive a pointer to your data and the size of the data. Then you can allocate some memory for the data, copy it and store it. You don't need a specific type, just declare it a void *
.
void listInsertFirst(void *data, size_t data_size, int key, LinkedList* ListToInsertTo);
Then the caller would do something like this:
struct T { int foo; };
struct T x = { ... };
int someKey = ...;
LinkedList *someList = ...;
listInsertFirst(&x, sizeof x, someKey, someList);
When you include the header file, the compiler knows that T
is a structure of unknown size and that listInsertFirst
wants one as its first argument. But the compiler cannot arrange a call to listInsertFirst
as it doesn't know how many bytes to push on the stack for the T data
parameter, the size of T
is only known inside the file where listInsertFirst
is defined.
The best solution would be to change listInsertFirst
to take a T*
as its first argument so your header file would say this:
extern void listInsertFirst(T *data, int key, LinkedList* ListToInsertTo);
Then you get an opaque pointer for your T
data type and, since all pointers are the same size (in the modern world at least), the compiler will know how to build the stack when calling listInsertFirst
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With