Keil Logo

GENERAL: MODULAR PROGRAMMING


Information in this article applies to:

  • ANSI C Compilers All Versions

QUESTION

I want to declare a global variable that can be addressed from various modules. My program is as follows:

File1.C:

unsigned int val = 0;

void main (void) {
  while (1) {
    myfunc ();      // a function in a different module
  }
}

File2.C:

void myfunc (void)  {
  val = 1;         // does not work
}

How do I need to structure my project?

ANSWER

Good modular programming uses a header file that defines the resources of the application. In complex applications you may have a header file for each module.

Example:

stuff.h:

extern void myfunc (void);    // function in File2.C
extern unsigned int val;      // variable in File1.C

Now you use this header file in all your C modules to define the global resources of your application.

File1.C:

#include "stuff.h"

unsigned int val = 0;

void main (void) {
  while (1) {
    myfunc ();      // a function in a different module
  }
}

File2.C:

#include "stuff.h"

void myfunc (void)  {
  val = 1;         // uses the extern definition in stuff.h
}

For another example of this, review the Measure example included in all Keil development tool packages.

MORE INFORMATION

  • ANSI C Books like the "The C Programming Language" by Kernigan & Ritchie.

SEE ALSO

FORUM THREADS

The following Discussion Forum threads may provide information related to this topic.

Last Reviewed: Tuesday, January 9, 2007


Did this article provide the answer you needed?
 
Yes
No
Not Sure
 
  Arm logo
Important information

This site uses cookies to store information on your computer. By continuing to use our site, you consent to our cookies.

Change Settings

Privacy Policy Update

Arm’s Privacy Policy has been updated. By continuing to use our site, you consent to Arm’s Privacy Policy. Please review our Privacy Policy to learn more about our collection, use and transfers
of your data.