Sometimes it’s useful to group a few functions that always work together in the same file and let them share variables that are global to that file.
A Global Variable for the Awesome Library
Let’s say you want your awesome function to track how many times it has been called in your application. And, you want a function named awesome_getCount to report the number of times awesome was called. Here’s one way to make those changes to awesome.c:
- In SimpleIDE, use the Open Project button to open libawesome.side.
- If the Project Manager pane is not visible, click the Show Project button in the bottom-left corner of the SimpleIDE window.
- Click awesome.c in the Project manager to open the file.
- Modify it as shown here.
Now, each time the awesome function gets called, it adds 1 to a variable named calls. Your application will also be able to call the awesome_getCount function to find out how many times the awesome function was called.
Did You Know?
The static modifier makes it so that only functions within the same file can see that variable. There are advantages to making your library file variables static; for instance, you can decide to add a static variable named calls to epic.c using similar code, and not have to worry that functions of one file could read the calls variable from another. The awesome.c static calls variable would only keep track of the number of times awesome is called, and the epic.c static calls variable would only keep track of the number of times epic was called.
Finish the Library Update
This modified library isn’t quite ready to use yet. Since we added a function to the library, we need to make sure to update the header file with an awesome_getCount function prototype.
- Click the awesome.h tab, and add a function prototype for awesome_getCount.
Make sure to update your tests harness code in libawesome.c to exercise this new function and make sure it works.
- Click the libawesome tab and modify the code as shown below.
- Run the program and verify that it correctly reports the number of times the awesome function was called.
If the test harness code works correctly, you can build the library for the memory models the library is designed to support.
- In the Project Manager’s Project Options tab, set the Memory Model to CMM, and click the Build Project button in the button bar near the top of the SimpleIDE window.
- Repeat for other memory models you’ll support.
Your Turn
- Repeat these steps with the epic.c file. For the sake of practice, use a static variable named calls and name the function for reporting calls to epic, epic_getCount.