Forward declaration C - c

I have 2 header files api.h and impl.h
api.h is visible to outside files and will be included in other ".c" files. So api.h includes impl.h
api.h defines 2 structures
typedef struct
{
uint32_t att;
union
{
struct
{
void* buffer;
size_t length;
} x;
struct
{
int a, b;
} v;
} content;
}dummy;
and impl.h has some other structures and function def which uses this structure.
I tried forward declaration but it doesn't help me .
Please help .

Actually, your dummy is not a structure, but a typedef to an unnamed structure. Try naming the structure, you can then forward-declare it:
typedef struct sdummy dummy; // forward declaration
void foo(dummy *);
struct sdummy { ... }; // definition

Either reorder your code in api.h so the type declaration precedes the #include "impl.h" or give your (currently anonymous) structure itself a name like dummy, dummy_, dummy_s so you can add a forward declaration
typedef struct dummy_ dummy;
to impl.h.

If you want to hide the details of your struct then you have to define it in some .c file, let's say impl.c, so that it has internal linkage to that compilation unit. To use it you have to expose create, destroy, getter and setter functions. So a basic setup would look like this:
api.h with forward declaration for your struct
// forward declaration
typedef struct dummy* dummy_t;
// create / destroy / setter / getter (omitted)
dummy_t alloc_dummy();
void free_dummy(dummy_t);
void set_number(dummy_t, int);
void set_string(dummy_t, char*);
void print_dummy(dummy_t);
Then comes impl.c
#include "api.h"
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
struct dummy {
int n;
char* s;
};
dummy_t alloc_dummy()
{
return malloc(sizeof(struct dummy));
}
void free_dummy(dummy_t dummy)
{
if(dummy) {
free(dummy->s);
free(dummy);
}
}
void set_number(dummy_t dummy, int n)
{
if(dummy) {
dummy->n = n;
}
}
void set_string(dummy_t dummy, char* s)
{
if(dummy && s) {
dummy->s = strdup(s);
}
}
void print_dummy(dummy_t dummy)
{
if(dummy) {
printf("%d, %s\n", dummy->n, dummy->s);
}
}
And finally the usage in some other C files, here main.c
#include "api.h"
int main(int argc, char** argv)
{
// struct dummy d; // error! type is unknown
// instead use the create function
dummy_t d = alloc_dummy();
// d->n = 1; // error! dereference of unknown type
// instead use the setter function
set_number(d, 1);
set_string(d, "Hello, world!");
print_dummy(d);
free_dummy(d);
return 0;
}
Ouput
1, Hello, world!

Related

How to send to a function a variable that is in another module?

How can I send a pointer that´s in another module to a new module?
Hello, I´m just starting a Programming Proyect in c of a game for class. This game contains a struct called game that also contains differents types data like Players ir Objects. Those structs are identified by a long Id, classified so that the objects have an Id between #0 and #100 for example.
To make it easier I´ve been creating a function "what_id" that recibing just an Id it returns a pointer to the struct that corresponds to it. I know how by sending the 'game' struct where are contained all the ids, and an Id, return the variable, but there´re modules that do not use in any case that big 'game' variable, for example player.c.
How can I send 'game' to this function without having it?
typedef struct _Game{
Player* player[MAX_PLAYERS + 1];
Object* object[MAX_OBJECTS + 1];
Space* spaces[MAX_SPACES + 1];
T_Command last_cmd;
} Game;
typedef struct _Object{
Id id;
char name[MAX_SPACES];
}
void* what_id(Game* game, Id id){
if(id == NO_ID) return ERROR;
if(0 <id<=MAX_SPACES){
return what_space(game->space, id);
}else if(MAX_SPACES<id<=(MAX_OBJECTS+MAX_SPACES)){
return what_object(game->object, id);
}else if((MAX_OBJECTS+MAX_SPACES<id<(MAX_PLAYERS+MAX_OBJECTS+MAX_SPACES)){
return what_player(game->player, id);
}else {
fprinf(stderr,"Id asigment max stacked.";
return ERROR;
}
}
Space* what_space(const Space* space, Id id){
int i;
for(i=0;i<MAX_SPACES;i++){
if(space[i]->id == id)return space[i];
}
fprintf(stderr, "Error no space_id %d founded", id);
return ERROR;
}
It's not clear what you mean by "module", or where Game is going to come from. If by modules you mean separate sources files that produce separate object files, there are generally two ways to do this.
The first is to declare a global variable and import it as an extern:
file1.c:
// declare struct
typedef struct {
int value;
} Foo;
// declare global variable
Foo *globalfoo;
// declare external function from another module
void printfoo();
void main()
{
Foo foo;
foo.value = 3;
globalfoo = &foo;
printfoo();
}
file2.c:
#include <stdio.h>
// declare struct
typedef struct {
int value;
} Foo;
// declare variable from another module
extern Foo *globalfoo;
void printfoo()
{
printf("foo: %d\n", globalfoo->value);
}
The other way to do it is to pass it via a function argument:
file1.c:
typedef struct {
int value;
} Foo;
void printfoo(Foo *foo);
void main()
{
Foo foo;
foo.value = 3;
printfoo(&foo);
}
file2.c:
#include <stdio.h>
typedef struct {
int value;
} Foo;
void printfoo(Foo *foo)
{
printf("foo: %d\n", foo->value);
}
You can avoid re-declaring structs and functions in multiple source files by putting them in a header file and #including it:
myproject.h:
typedef struct {
int value;
} Foo;
void printfoo(Foo *foo);
file1.c:
#include <myproject.h>
void main()
{
Foo foo;
foo.value = 3;
printfoo(&foo);
}
file2.c:
#include <myproject.h>
#include <stdio.h>
void printfoo(Foo *foo)
{
printf("foo: %d\n", foo->value);
}

C - Pass struct by reference

I am trying to pass a structure by reference in C so that I can modify the values from within the function. This is the code I have so far, but it produces some warnings and one error.
main.c
#include <stdio.h>
#include "myfunctions.h"
#include "structures.h"
int main(int argc, char const *argv[] {
struct MyStruct data;
data.value = 6;
printf("Before change: %d\n", data.value);
changeData(data);
printf("After change: %d\n", data.value);
}
myfunctions.c
#include "structures.h"
void changeData(MyStruct data) {
data.value = 7;
}
myfunctions.h
#ifndef MyStruct
#define MyStruct
void changeData(MyStruct data);
#endif
structures.h
typedef struct {
int value;
} MyStruct;
Errors Produced
In file included from main.c:2:0:
myfunctions.h:4:1: warning: parameter names (without types) in function declaration
void changeData(MyStruct data);
^
In file included from main.c:3:0:
structures.h:5:1: warning: unnamed struct/union that defines no instances
} MyStruct;
^
main.c: In function ‘main’:
main.c:9:5: error: ‘data’ undeclared (first use in this function)
data.value = 6;
^
main.c:9:5: note: each undeclared identifier is reported only once for each function it appears in
That's all caused by
#define MyStruct
With this line, you've defined MyStruct as a macro that expands to nothing. I.e. you've effectively removed all occurrences of MyStruct in the following code, which is why the compiler is so confused about seeing things like
typedef struct {
int value;
} ;
or
void changeData( data);
To fix this, use
#ifndef MYFUNCTIONS_H_
#define MYFUNCTIONS_H_
instead. (This is the reason why we use ALL_UPPERCASE names for macros: To avoid accidental name clashes with normal identifiers.)
applying all my comments and elimination of the unnecessary 'typedef', and placing it all in one file ( Note: there is no problem with extracting the various files), results in the following code:
#ifndef STRUCTURES_H
#define STRUCTURES_H
struct MyStruct
{
int value;
};
#endif // STRUCTURES_H
#ifndef MYFUNCTIONS_H
#define MYFUNCTIONS_H
void changeData( struct MyStruct *data);
#endif // MYFUNCTIONS_H
#include <stdio.h>
//#include "myfunctions.h"
//#include "structures.h"
int main( void )
{
struct MyStruct data;
data.value = 6;
printf("Before change: %d\n", data.value);
changeData(&data);
printf("After change: %d\n", data.value);
} // end function: main
//#include "structures.h"
void changeData( struct MyStruct *data)
{
data->value = 7;
} // end function: changeData
which cleanly compiles and does do the desired operation

Why the C structure definition in the implementation file is unavailable?

I give the following example to illustrate my question:
1) a.h where the structure is declared
a.h
struct A_Structure;
typedef struct A_Structure *A_Structure_Ptr;
2) b.c where the structure definition is implemented
#include "a.h"
struct A_Structure
{
int a;
int b;
int c;
};
2) main.c where the structure is invoked
#include <stdlib.h>
#include "a.h"
int main ()
{
struct A_Structure b;
return 0;
}
However, I cannot compile these C codes as I receive the following error message:
>main.c(6): error C2079: 'b' uses undefined struct 'A_Structure'
Any ideas? Thank in advance.
EDIT:
#include <stdlib.h>
#include "a.h"
int main ()
{
struct A_Structure *b=0;
b=(struct A_Structure*)malloc(12);
b->a=3;
free(b);
return 0;
}
I tried to create the structure in this way but still failed.
You probably need this:
struct A_Structure
{
int a;
int b;
int c;
};
in a.h
This is the typical approach when defining structs
If you're trying to implement an opaque pointer, you need a function that instantiates A_Structure and returns a pointer, as well as functions that manipulate A_Structure pointers:
in a.h
A_Structure_Ptr CreateA(int a, int b, int c);
void FreeA(A_Structure_Ptr obj);
void SetA_a( A_Structure_Ptr obj, int a );
int GetA_a( A_Structure_Ptr obj );
// etc.
in b.c
A_Structure_Ptr CreateA(int a, int b, int c)
{
A_Structure_Ptr s = malloc( sizeof(A_Structure) );
s->a = a;
s->b = b;
s->c = c;
}
void FreeA(A_Structure_Ptr obj)
{
free( obj );
}
void SetA_a( A_Structure_Ptr obj, int a )
{
obj->a = a;
}
in main.c
int main ()
{
struct A_Structure *b = CreateA( 1, 2, 3);
SetA_a( b, 3 );
FreeA(b);
return 0;
}
When you put the structure declaration in a header file, but leave the definition in the .c file, this is known as using an opaque pointer API.
In an API like this, consumers only use pointers to the objects. Only the implementation needs to know the size or contents of the object. This is how you do OOP in C, and is key to information hiding which provides better decoupling of components. Here's a more complete example:
foo.h
struct foo; // forward declaration
struct foo *foo_create(void);
void foo_use(struct foo *f);
void foo_destroy(struct foo *f);
foo.c
#include <stdlib.h>
#include "foo.h"
struct foo {
int a, b, c; // Consumers don't know about these!
};
struct foo *foo_create(void)
{
struct foo *f = malloc(sizeof(*f));
if (!f)
return NULL;
*f = (struct foo) {
.a = 1,
.b = 2,
.c = 3,
};
return f;
}
void foo_use(struct foo *f)
{
// something with f->a, f->b
}
void foo_destroy(struct foo *f)
{
free(f);
}
main.c
#include "foo.h"
int main(void)
{
struct foo *f; // As a consumer of foo, we can only use **pointers**
f = foo_create();
if (!f)
return 1;
// I cannot access the members of `struct foo` here.
// In an opaque API, the struct members are considered
// an implementation detail and cannot be used outside
// of the implementation.
foo_use(f);
foo_destroy(f);
return 0;
}
You have to decide whether you want to hide the details of the structure from the "outside" or not. If you don't want to hide them, just put the structure definition in a.h. Hiding it ensures better decoupling and central control of your b.c over the content, but that means you have to provide a way to create an object in b.c (e.G.
struct A_Structure *create_A_Structure(void);
and use this from the outside.
an unrelated stylistic advice: better don't typedef pointers. While your _Ptr suffix makes it kind of obvious, it's still better to just have the asterisk everywhere because that is what C programmers are used to, so the fact that it's a pointer is obvious at the first glance.
I'd suggest something like this:
/* header */
typedef struct A A;
A *A_create(void);
/* implementation */
struct A
{
int foo;
}
A *A_create(void)
{
return malloc(sizeof(A));
}

Typecasting (or deference) void * to struct foo*

In api.h
typedef void* hidden_my_type;
void do_something(my_type x);
In core.c
struct _my_type
{
int a;
}
void do_something(hidden_my_type void_x)
{
struct *_my_type x = void_x; /*Don't understand is that correct way to do, as I'm getting segmentation fault error */
printf("Value: %d\n", x->a);
}
Other way I thought as,
struct *_my_type x = (struct _my_type *)malloc(sizeof(struct _my_type));
void_x = x
printf(Value: %d\n", x->a);
But still I'm getting seg-fault error.
ok here is the problem with void*....
e.g.
in core.c
void init_my_type(hidden_my_type a)
{
my_type *the_a = malloc(...);
a = the_a // <<<<<<<<<<<<<<<<<<<<<<<<<<<< is this correct?! a is void* and the_a // is original type
pthread_cond_init(&the_a->...);
.. (in short any other methods for init ..)
}
void my_type_destroy(my_hidden_type x)
{
my_type *the_x = x;
pthread_detroy(&the_x-> ...);
}
in main.c
test()
{
my_hidden_type x;
init_my_type(x);
....
my_type_detroy(x);
}
this it self should fail. as in main.c test function, x is void* ... init will allocate but in destroy I'm again passing void* .. which can be anything!
EDIT (Solved for me)
In api.h
typedef void* hidden_my_type;
void do_something(my_type x);
In core.c
struct _my_type
{
int a;
}
void init_hidden_type(hidden_my_type void_p_my_type)
{
struct _my_type *real_my_type = (struct _my_type *)malloc(sizeof(struct _my_type));
//--- Do init for your type ---
void_p_my_type = real_my_type;
}
void do_something(hidden_my_type void_x)
{
struct *_my_type x = void_x;
printf("Value: %d\n", x->a);
}
Version 0 — Critique of Question's Code
The posted code does not compile.
api.h
typedef void* hidden_my_type;
void do_something(my_type x);
This defines hidden_my_type but not the my_type that is passed to do_something(). Presumably, you intended:
typedef void *my_type;
void do_something(my_type x);
core.c
struct _my_type
{
int a;
}
As noted below too, there is a semi-colon missing after the structure definition.
void do_something(hidden_my_type void_x)
{
struct *_my_type x = void_x;
printf("Value: %d\n", x->a);
}
You have the hidden_my_type vs my_type problem again. You have the * of the pointer where it cannot go; it must go after the struct _my_type. You probably intended something like:
void do_something(my_type void_x)
{
struct _my_type *x = void_x;
printf("Value: %d\n", x->a);
}
This is now syntactically correct (I think; I haven't actually run it past a compiler). You have not shown how it is used; indeed, since the user code has no way to generate a pointer to a valid structure, there is no way for this code to be used safely.
Your test code (unshown — why don't you show your test code) might look something like this:
#include "api.h"
int main(void)
{
my_type x = 0;
do_something(x);
return 0;
}
Alternatively, it might not have the = 0 initializer in place. Either way, your code is unable to function sanely, and a core dump is almost inevitable. When you hide the structure from the user, you have to provide them with a mechanism to get hold of a valid (pointer to) the structure, and you've not done that.
Version 1
This is a better way to do it, because it is more nearly type-safe:
api.h version 1
typedef struct _my_type *my_type;
void do_something(my_type x);
core.c version 1
#include "api.h"
struct _my_type
{
int a;
};
Note the added semi-colon, and the include of the api.h file.
void do_something(my_type x)
{
// Now you don't have to do casting here!
//struct *_my_type x = void_x; /*Don't understand is that correct way to do, as I'm getting segmentation fault error */
printf("Value: %d\n", x->a);
}
Version 2
Actually, we can debate the wisdom of hiding the pointer; I would prefer not to do so:
api.h version 2
#ifndef API_H_INCLUDED
#define API_H_INCLUDED
typedef struct my_type my_type;
extern void do_something(my_type *x);
extern my_type *my_type_initializer(void);
extern void my_type_release(my_type *x);
#endif /* API_H_INCLUDED */
core.c version 2
#include "api.h"
#include <stdio.h>
#include <stdlib.h>
struct my_type
{
int a;
};
void do_something(my_type *x)
{
printf("Value: %d\n", x->a);
}
my_type *my_type_initializer(void)
{
my_type *x = malloc(sizeof(*x));
x->a = 57; // More plausibly, this would be 0
return x;
}
void my_type_release(my_type *x)
{
free(x);
}
main.c
#include "api.h"
int main(void)
{
my_type *x = my_type_initializer();
do_something(x);
my_type_release(x);
return 0;
}
That's nice and clean. Of course, the user cannot allocate a struct my_type (only a pointer to it), so you need a function to allocate the structure for them. Think of the Standard C Library, and the FILE type, and fopen() to allocate and fclose() to release and fprintf() etc to manipulate the type. The my_type_initializer() is functioning as an analogue to fopen(), my_type_release() as an analogue to fclose(), and do_something() as an analogue to fprintf().
Jonathan, you beat me to an answer, but this may be helpful as well. Here, api.c contains the (private) implementation, and api.h provides the interface to be consumed by other code such as main.c.
// main.c: uses only the public interface to the private code
#include "api.h"
int main(int argc, char *argv[]) {
void *foo;
foo = create_foo("five", 5);
print_foo(foo);
delete_foo(foo);
}
// EOF main.c
// api.h: the public interface
#ifndef _api_h_
#define _api_h_
void *create_foo(char *name, int number);
void print_foo(void *foo);
void delete_foo(void *foo);
#endif // _api_h_
// api.c: the private implementation
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// The real structure is private to the implementation.
typedef struct {
char name[20];
int number;
} real_struct;
// Create a new structure, initialize, return as ptr-to-void.
void *create_foo(char *name, int number) {
real_struct *s = malloc(sizeof(real_struct));
strcpy(s->name, name);
s->number = number;
return (void *) s;
}
// Print the data.
void print_foo(void *foo) {
real_struct *s = (real_struct *) foo;
printf("name: %s, number: %d\n", s->name, s->number);
}
// Release the memory.
void delete_foo(void *foo) {
free(foo);
}
// EOF api.c
This code should compile and run:
$ gcc -o foo main.c api.c
$ ./foo
name: five, number: 5

Accessing members of the struct via void *

The solution consists of two parts, one is a static library that receives instances of struct from the user of the library. Library doesn't know what will be the type of structs, all it knows there will be two function pointers to it with a specific name.
Library Code
pre-compiled library has no way of knowing types of user structs, hence receiving via void*
void save(void *data) {
// library will save/cache user's object
data->registered(); // if register successful
}
void remove(void *data) {
// library will remove the object from memory
data->remove(); // if removed successful
}
User of the Library Code
struct Temp { // random order of fields
void (*custom1)();
void (*registered)();
void (*custom2)();
void (*remove)();
void (*custom3)();
}
void reg() {
printf("registered");
}
void rem() {
printf("removed");
}
void custom1() {}
void custom2() {}
void custom3() {}
var temp = malloc(struct Temp, sizeof(struct Temp));
temp->registered = reg;
temp->remove = rem;
temp->custom1 = custom1; // some custom functions
temp->custom2 = custom2;
temp->custom3 = custom3;
// calling library code
save(temp);
remove(temp);
Q. Is there a way for the Library to know how to iterate and go through member fields and see if there's a pointer to such function and call it available.
Is there a way for the Library to know how to iterate and go through member fields and see if there's a pointer to such function and call it available.
No there is not.
Your best bet is to create a structure in the library that has these members, and pass that structure instead of void*.
As #immibis said, there is no way for this to work (i.e. no way for the compiler to justify compiling such code) if the compiler does not know what the types of the data being passed to the function are.
Since you wanted to pass the objects along to the library without storing information about the type of each object in the library, you can fake polymorphism in C, by doing the following:
callback.h
#ifndef _CALLBACK_H_
#define _CALLBACK_H_
typedef struct {
void (*registered)();
void (*removed)();
} ICallback;
#endif _CALLBACK_H_
pre_comp.h
#ifndef _PRE_COMP_H_
#define _PRE_COMP_H_
#include "callback.h"
void save(ICallback* data);
void remove(ICallback* data);
#endif /* _PRE_COMP_H_ */
precomp.c
#include <stdlib.h> /* NULL */
#include "callback.h"
#include "pre_comp.h"
void save(ICallback *data) {
if (NULL != data && NULL != data->registered) {
data->registered(); // if register successful
}
}
void remove(ICallback *data) {
if (NULL != data && NULL != data->removed) {
data->removed(); // if removed successful
}
}
main.c
#include <stdio.h>
#include "pre_comp.h"
#include "callback.h"
struct Temp {
ICallback base; // has to be defined first for this to work
void (*custom1)();
void (*custom2)();
void (*custom3)();
};
// calling library code
void reg() {
puts("registered");
}
void rem() {
puts("removed");
}
int main() {
struct Temp data = {{reg, rem}};
save((ICallback*)&data);
remove((ICallback*)&data);
}
compiling
gcc pre_comp.c main.c
output
registered
removed
If the library has 0 information about the possible struct types, then you
cannot do it. The library has to get somehow the information or the offsets.
The only way I can think of is:
All register member have the same prototype
Pass the offset to the function.
I created an example of this
#include <stdio.h>
#include <stddef.h>
#include <stdint.h>
// function that does not know anything about any struct
void reg(void *data, size_t offset)
{
uintptr_t *p = (uintptr_t*) (((char*) data) + offset);
void (*reg)() = (void(*)()) *p;
reg();
}
struct A {
int c;
void (*reg)();
};
struct B {
int b;
int c;
void (*reg)();
};
void reg_a()
{
printf("reg of A\n");
}
void reg_b()
{
printf("reg of B\n");
}
int main(void)
{
struct A a;
struct B b;
a.reg = reg_a;
b.reg = reg_b;
reg(&a, offsetof(struct A, reg));
reg(&b, offsetof(struct B, reg));
return 0;
}
This prints:
$ ./c
reg of A
reg of B
I run it with valgrind and I did not get any errors nor warnings. I'm not sure if
this violates somehow strict aliasing rules or yields undefined behaviour
because of the uintptr_t* conversions, but at least it seems to work.
I think however, the more cleaner solution is to rewrite the register (btw. register
is a keyword in C, you cannot use that for a function name) function to
accept a function pointer and possible parameters, something like this:
#include <stdio.h>
#include <stdarg.h>
void reg(void (*func)(va_list), int dummy, ...)
{
if(func == NULL)
return;
va_list ap;
va_start(ap, dummy);
func(ap);
va_end(ap);
}
void reg1(int a, int b)
{
printf("reg1, a=%d, b=%d\n", a, b);
}
void vreg1(va_list ap)
{
int a = va_arg(ap, int);
int b = va_arg(ap, int);
reg1(a, b);
}
void reg2(const char *text)
{
printf("reg2, %s\n", text);
}
void vreg2(va_list ap)
{
const char *text = va_arg(ap, const char*);
reg2(text);
}
int main(void)
{
reg(vreg1, 0, 3, 4);
reg(vreg2, 0, "Hello world");
return 0;
}
This has the output:
reg1, a=3, b=4
reg2, Hello world
Note that reg has a dummy parameter. I do that because the man page of
stdarg says:
man stdarg
va_start():
[...]
Because the address of this argument may be used in the va_start() macro,
it should not be declared as a register variable, or as a
function or an array type.
You can take an approach similar to qsort and pass function pointers in addition to a void pointer to the structure.
Here is the function prototype for qsort, which is a function that can be used to sort arrays of any type:
void qsort(void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *));
It takes a function pointer that performs the comparison because without it qsort wouldn't know how to compare two objects.
This can be applied to your task with a function prototype like this:
int DoFoo(void *thing, void (*register)(void *), void (*remove)(void *))
This function takes a void pointer to your struct and then two functions that it can call when it needs to register or remove that struct. Having the functions be members of the struct is not required and I generally do not recommend it. I recommend reading up on qsort because it is does something similar to what you are trying to do.

Resources