Is there a way to have some kind of default constructor (like a C++ one) for C user types defined with a structure?
I already have a macro which works like a fast in
Following is a simple program that makes use of a constructor. Function "default_constructor" gets called inside main without any explicit function call.
#include <stdio.h>
void __attribute__ ((constructor)) default_constructor()
{
printf("%s\n", __FUNCTION__);
}
int main()
{
printf("%s\n",__FUNCTION__);
return 0;
}
Output: default_constructor main
Within the constructor function you can include some initialization statements and use the destructor function to free memory as follows,
#include <stdio.h>
#include <stdlib.h>
struct somestruct
{
int empid;
char * name;
};
struct somestruct * str1;
void __attribute__ ((constructor)) a_constructor()
{
str1 = (struct somestruct *) malloc (sizeof(struct somestruct));
str1 -> empid = 30228;
str1 -> name = "Nandan";
}
void __attribute__ ((destructor)) a_destructor()
{
free(str1);
}
int main()
{
printf("ID = %d\nName = %s\n", str1 -> empid, str1 -> name);
return 0;
}
Hope this will help you.