I’m in the process of creating a simple 2D game engine in C with a group of friends at school. I’d like to write this engine in an Object-Oriented way, using structs as classes, function pointers as methods, etc. To emulate standard OOP syntax, I created a create() function which allocates space in memory for the object. I’m in the process of testing it out, and I’m receiving an error. Here is my code for two files that I’m using to test:
test.c:
#include <stdio.h>
int main()
{
typedef struct
{
int i;
} Class;
Class *test = (Class*) create(Class);
test->i = 1;
printf("The value of \"test\" is: %i\n", test->i);
return 0;
}
utils.c:
#include <stdio.h>
#include <stdlib.h>
#include "utils.h"
void* create(const void* class)
{
void *obj = (void*) malloc(sizeof(class));
if (obj == 0)
{
printf("Error allocating memory.\n");
return (int*) -1;
}
else {
return obj;
}
}
void destroy(void* object)
{
free(object);
}
The utils.h file simply holds prototypes for the create() and destroy() functions.
When I execute gcc test.c utils.c -o test, I’m receiving this error message:
test.c: In function 'main':
test.c:10:32: error: expected expression before 'Class'
I know it has something to do with my typedef at the beginning, and how I’m probably not using proper syntax. But I have no idea what that proper syntax is. Can anyone help?
Your code make no sense in this area
Classis a type name. Why are you trying to pass it as an argument tocreate? You cannot use type names as a function arguments in C.Your
createfunction seems to expect some sort of pointer as an argument. The purpose of that pointer is entirely unclear to me, but the bottom line here is that type nameClasscannot be used as an argument here.Inside your
createyou usesizeof(class)as the amount of memory to allocate. Thissizeof(class)will simply evaluate to a pointer size, which is absolutely not what you need.Basically, you need to rethink what you are trying to do and do it from scratch. I’d suggest reading so book on C first. What you have now is just… random.