Hello,
I am making a number of libraries to help me with my projects and I am torn between two approaches. I will show you what each looks like. I have no idea which would be considered 'better' in general.
Locals:
#ifndef SOME_GUARD
#define SOME_GUARD VERSION_NUMBER
#ifdef __cplusplus
extern "C" {
#endif
typedef struct { /*something here*/ } myNewTypeTAG, *myNewType;
myNewType function(myNewType); // for example
#ifdef __cplusplus
}
class myNewTypeCppMode
{
//private:
myNewType t;
public:
myNewTypeCppMode &function(myNewType o) {
t=function(o);
return *this;
}
};
#endif
#endif
Context (weightless):
#ifndef SOME_GUARD
#define SOME_GUARD VERSION_NUMBER
#ifdef __cplusplus
extern "C"{
#endif
typedef struct { /*something here*/ } myNewTypeTAG__, *myNewType__;
typedef struct {
myNewType *x;
size_t s;
} myNewContextTAG, *myNewContext;
typedef size_t myNewType;
myNewContext getContext();
myNewType function(myNewType, myNewContext); // uses context->x[object] to access the data
#ifdef __cplusplus
}
class myNewTypeCppMode
//see above example
#endif
//optional main override:
#ifdef OVERRIDE_MAIN
int myNewMain( /*any args I wish to pass*/ , myNewContext);
#define main(X,Y) \
main(X,Y) { \
myNewContext con = getContext(); \
return myNewMain( /*args again*/ , con); \
} \
int myNewMain( /*args*/ , myNewContext con__)
#define REALfunction(X) function(X,con__)
#endif // OVERRIDE_MAIN
#endif
Context (heavy):
#ifndef SOME_GUARD
#define SOME_GUARD VERSION_NUMBER
#ifdef __cplusplus
extern "C"{
#endif
typedef struct { /*something here*/ } myNewTypeTAG__, *myNewType__;
typedef struct {
myNewType *x;
size_t s;
} myNewContextTAG, *myNewContext;
typedef size_t myNewType;
myNewContext current_context__;
myNewContext newContext(); // also sets the context
void setContext(myNewContext);
myNewType function(myNewType); // uses current_context__->x[object] to access the data
#ifdef __cplusplus
}
class myNewTypeCppMode
//see above example
#endif
//optional main override:
#ifdef OVERRIDE_MAIN
int myNewMain( /*any args I wish to pass*/ );
#define main(X,Y) \
main(X,Y) { \
myNewContext con = newContext(); \
myNewMain( /*args*/ ); \
} \
int myNewMain( /*args*/ )
#endif // OVERRIDE_MAIN
#endif
I tend to prefer the heavy context method, but that breaks the 'rule' that libraries should be weightless (even if it is only 1 pointer too heavy). I do not like the locals idea because then if people don't delete every object they make you can end up with a memory leak. Which way is considered 'best'?