PDA

View Full Version : Help with Modularizing C code



CT_Bolt
December 12th, 2006, 21:48
How do I make 2 modular files of this code:

Assuming I have the proper preprocessors included in main.c

// Blah.c or Blah.h
typedef struct clsBlah{
int a, b;
}BLAH;
///////////////////////

// Foo.c or Foo.h
typedef struct clsFoo{
BLAH blah;
}FOO;

void useFoo(FOO f){
f.blah.a = 0;
}
///////////////////////

That is my example code.
The 2 files would be something like:
1. Blah.c or Blah.h
2. Foo.c or Foo.h

yaustar
December 13th, 2006, 00:23
// Blah.c or Blah.h
typedef struct clsBlah{
int a, b;
}BLAH;
///////////////////////
Blah.h since it is a declartion of a struct. I would also add a header guard (ref: Organizing Code Files in C and C++ (http://www.gamedev.net/reference/articles/article1798.asp) ) so it would look like this:

#ifndef BLAH_H
#define BLAH_H

typedef struct clsBlah{
int a, b;
}BLAH;

#endif // BLAH_H


// Foo.c or Foo.h
typedef struct clsFoo{
BLAH blah;
}FOO;
Foo.h since it is a declartion of a struct. I would also add a header guard so it would look like this:


#ifndef FOO_H
#define FOO_H

#include "./blah.h"

typedef struct clsFoo{
BLAH blah;
}FOO;

void useFoo(FOO f); // See next section on why this is here.

#endif // FOO_H

Finally:

void useFoo(FOO f){
f.blah.a = 0;
}

Would be in foo.c since it is code. The function declaration should be in foo.h. This would now look like:

#include "./foo.h"
void useFoo(FOO f){
f.blah.a = 0;
}

Some other notes: Don't use Full caps for struct/class names (eg FOO). Full caps are normally used for constants.

The function useFoo should pass by pointer or reference rather then by value because:

- You are trying to modify the object you passed in. If you pass by value, you are only modifying the function's local copy.

- Rather then copying a large struct full of data, you are only passing the memory address where the data is. Much more efficent.

CT_Bolt
December 13th, 2006, 20:34
:thumbup: THANK YOU SO MUCH YAUSTAR!
You have helped me alot. I can't thank you enough.