The first code
I made a GitHub Gist to display the code. Thanks to Jason for the suggestion.
Given there is not a whole lot going on here, but let me point out a few things worth noticing.
- First of all, I have a working directory with the include files separate from the C code. This keeps things clean and neat for the future. I am also a big fan on one include for the interface to a file, and never put an include inside an include. Yes, then the order of include files matters. You will thank me when the project gets big and compile times stay short.
- I put the main() function inside the one file to get started quickly.
- The main is calling runAllTasks() which passes a made up, dummy task list into the taskRunner function. Seems simple, and gets things working here.
- The typedef for the Task structure is right, as are the types and the pointer and array being passed in. That can be tricky, but once it is correct, no worries.
- The size of the array is automatically calculated based on the number of items in the array and the structure. This will always be correct. There is no need to keep track of the array position or use an enumeration for each task. Tasks have names, but if that takes up too much space, it can be changed. (It should probably be a char * pointing at the string.) The divide of two “sizeof()” operations will happen at compile time. The value used at run time is a constant. No performance problems here.
- There is enough test code that the two ‘if’ statements have been tested. The conditional running of tasks works, and the error handling to break out of the loop works. We have a start on unit testing.
- The whole thing is debugged with simple printf statements.
Still, a lot to do
This is very basic. You get the idea here. We will keep the tasks in a table, then let the task runner run each task for us. This structure keeps the tasks small and independent. There are a couple more cool tricks we will introduce as we go.
The types are all standard C types. In a real system we would use sized types, like int16_t or uint16_t. The standard types make it easy for you to build and try, and quick to get moving.
Quick, get started
The code you see took about 35 minutes to code up and build. It is a directory on my Linux machine. I don’t even have a makefile at this point, I am just doing ‘cc src/runtask.c’ and it builds.
dougg:tasker$ cc src/runtask.c
a.out include src test
Running Tasks, 3
Running Tasks, 3
Final task result = 3
And, best of all, it works.
What do you think? Please let me know in the comments.