Results 1 to 3 of 3

Thread: Help with Modularizing C code

                  
   
  1. #1
    DCEmu Newbie CT_Bolt's Avatar
    Join Date
    Mar 2006
    Location
    Somewhere in Space
    Posts
    39
    Rep Power
    0

    psp Help with Modularizing C code

    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

  2. #2
    GP2X Coder/Moderator
    Join Date
    Jan 2006
    Posts
    1,678
    Rep Power
    84

    Default

    // 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++ ) 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.

  3. #3
    DCEmu Newbie CT_Bolt's Avatar
    Join Date
    Mar 2006
    Location
    Somewhere in Space
    Posts
    39
    Rep Power
    0

    psp Thank you!

    :thumbup: THANK YOU SO MUCH YAUSTAR!
    You have helped me alot. I can't thank you enough.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •