zsljulius
zsljulius

Reputation: 4123

How should I organize this C project

I am doing this programming assignment in C. But I am confused as to how to organize it.

So, here is the situation. I have two tree implementations and declare their struct/includes/function prototypes and so on in two separate header files. Then I have two c source code for the two implementations. Now here comes the problem. I have one test c file (only one main function for running tests) for the ADTs of Trees. Since the two implementations are going to use the same test. How can I avoid making two copies of the same main.c file? when I include the header file of tree implementation1, I can do gcc Tree_implementation1.c main.c. But to do implementation2, I have to got back in the main source file and manually change the include to tree implementation2, and then I can use the same compilation command. How do I work around this to toggle between the two implementations with only one main.c?

Upvotes: 0

Views: 186

Answers (3)

Artem Markov
Artem Markov

Reputation: 411

Another solution for your problem is using of dynamic interface. Work the way like that:

#include "Imp_1.h"
#include "Imp_2.h"

typedef void (*TreeFunctionType1)(Tree,param);
typedef void (*TreeFunctionType2)(Tree);

typedef struct ITree
{
    TreeFunctionType1 func1;
    TreeFunctionType2 func2;
}ITree;

static ITree _Itree={0};

void SetImp(TreeFunctionType1 f1,TreeFunctionType2 f2)
{
    tree.func1 = f1;
    tree.func2 = f2;
}

/*Use only this functions in your Tests code*/
//{
void Func1(Tree tree,Param param)
{
    (*_Itree.func1)(tree,param);
}

void Func2(Tree tree)
{
    (*_Itree.func2)(tree);
}
//}

int main(int argc, char const *argv[])
{
    SetImp(Imp_1_f1,Imp_1_f2);
    TestCode();
    SetImp(Imp_2_f1,Imp_2_f2);
    TestCode();
    return 0;
}   

Upvotes: 1

pb2q
pb2q

Reputation: 59667

Use the preprocessor and a constant that you can set on the command line:

In your main.c:

#ifdef TREE_IMPL1
#include "TreeImplementation1.h"
#else
#include "TreeImplementation2.h"
#endif

// ...

int main(int argc, char **argv)
{
#ifdef TREE_IMPL1
    // code for testing TreeImplementation1
#else
    // code for testing TreeImplementation2
#endif
}

When you compile, pass or omit TREE_IMPL1 on the command line, or set it in your IDE:

gcc -DTREE_IMPL1 main.c ...

Upvotes: 1

Luchian Grigore
Luchian Grigore

Reputation: 258688

Do your implementations have the same name? They shouldn't.

If (or when) they don't have the same name, you can just include both headers in main.c and test either one depending on some preprocessor directive.

//main.c
#include "Tree_implementation1.h"
#include "Tree_implementation2.h"

int main()
{
#ifdef TEST_FIRST
   testFirstTree();  //declared in Tree_implementation1.h
#else
   testSecondTree();  //declared in Tree_implementation2.h
#endif
   return 0;
}

Upvotes: 1

Related Questions