I have a header file port.h, port.c, and my main.c
I get the following error: 'ports' uses undefined struct 'port_t'
I thought as I have declared the struct in my .h file and having the actual structure in the .c file was ok.
I need to have the forward declaration as I want to hide some data in my port.c file.
In my port.h I have the following:
/* port.h */
struct port_t;
port.c:
/* port.c */
#include "port.h"
struct port_t
{
unsigned int port_id;
char name;
};
main.c:
/* main.c */
#include <stdio.h>
#include "port.h"
int main(void)
{
struct port_t ports;
return 0;
}
Many thanks for any suggestions,
In C++, classes and structs can be forward-declared like this: class MyClass; struct MyStruct; In C++, classes can be forward-declared if you only need to use the pointer-to-that-class type (since all object pointers are the same size, and this is what the compiler cares about).
You've declared the variable, but you haven't set the value anywhere, so it has an undefined value. You can set a default value in your constructor. You should also verify you are including the header file that defines the FIconDataStruct.
You can create a structure by using the struct keyword and declare each of its members inside curly braces: struct MyStructure { // Structure declaration. int myNum; // Member (int variable) char myLetter; // Member (char variable) }; // End the structure with a semicolon.
The general syntax for a struct declaration in C is: struct tag_name { type member1; type member2; /* declare as many members as desired, but the entire structure size must be known to the compiler. */ };
Unfortunately, the compiler needs to know the size of port_t
(in bytes) while compiling main.c, so you need the full type definition in the header file.
If you want to hide the internal data of the port_t
structure you can use a technique like how the standard library handles FILE
objects. Client code only deals with FILE*
items, so they do not need (indeed, then generally can't) have any knowlege of what is actually in the FILE
structure. The drawback to this method is that the client code can't simply declare a variable to be of that type - they can only have pointers to it, so the object needs to be created and destroyed using some API, and all uses of the object have to be through some API.
The advantage to this is that you have a nice clean interface to how port_t
objects must be used, and lets you keep private things private (non-private things need getter/setter functions for the client to access them).
Just like how FILE I/O is handled in the C library.
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