Preferred Approach to Organizing ANSI C Project? - c

I'm a new C programmer, so this is a pretty basic question. What is the preferred approach to organizing ANSI C files in a project? I have about a dozen .c files each with their own .h file to hold local declarations, enums, etc. But I also have quite a few global parameters such as...
float LandingAltitudeList[2][17] = {
// P100
{12,-1000,0,1000,2000,3000,4000,5000,6000,7000,8000,9000,10000},
// P300
{16,-1000,0,1000,2000,3000,4000,5000,6000,7000,8000,9000,10000,1000,12000,13000,14000} };
enum PType {P100,P300};
enum Boolean {No=0,Yes=1,Off=0,On=1};
In addition, I have a number of global variables such as...
float Alt_min = LandingAltitudeList[PhenomType][1];
int Max = LandingAltitudeList[PhenomType][0];
float Alt_max = LandingAltitudeList[PhenomType][Max];
which I calculate just once, but use throughout the project. These need to be in a function in order to work.
How should I organize my files to handle these global parameters? Many thanks.

One option is to declare these variables in a header file. It would be probably more appropriate to make the variables themselves invisible and to declare access functions to interface them. Consider the following example:
/* in access.h */
int access_secret();
...
/* in access.c */
/* the private variable */
static int very_secret;
void calculate_secret() {
very_secret = 42;
}
void access_secret() {
return very_secret;
}
calculate_secret is called just once, when the module is initialized, and access_secret, when the variable value is needed. It is easy to enhance the system by adding array index parameter for arrays.

Related

Achieving Object-Oriented Design in the C Language by using proper function names

I am writing a MISRA compliant code that runs on a microcontroller, and this program must be written in the C language.
I would like to design my software according to the object-oriented design. However, the C-language lacks OOP support.
Therefore, I decided to create "classes" and "packages" through C-files and Folders, respectively.
Currently, all legacy function names were having the following names: <Module_Name>_f_<Function_Name>_<Return type>.
This function naming convention works as long as there is only a single Module. However, if I add SubModules or even SubSubModules, then the function name might get confusing.
For example, having Module, Submodule, and a SubSubModule might end up in one the following function names:
<Module_Name><SubModule_Name><SubSubModule_Name>_f_<Function_Name>_<Return type>
<Module_Name>_<SubModule_Name>_<SubSubModule_Name>_f_<Function_Name>_<Return type>
<Module_Name>_f_<SubModule_Name>_<SubSubModule_Name>_<Function_Name>_<Return type>
...
What would be a good name for such functions, and their respective C-files? I would like to have a naming convention that one can read and still understand the "class"/"package" structure?
To make it more clear, we can take more concrete example with the following file structure containing Folders and C-files:
Module (Folder)
- SubModule_1 (Folder)
- SubSubModule_1_1.c
- SubSubModule_1_2.c
- SubSubSubModule_1_2_1.c (Maybe also put in a seperate Sub-Folder?)
- SubSubSubModule_1_2_2.c (Maybe also put in a seperate Sub-Folder?)
...
- SubModule_n (Folder)
- SubSubModule_n_1.c
- SubSubModule_n_2.c
...
The above file structure might look like this in an OOP pseudocode:
class Module:
begin Module;
# Field Declarations
SubModule_1 subModule_1_Instance;
SubModule_2 subModule_2_Instance;
...
# Function declarations
Module_f_<Function_Name>_<return type>;
...
end Module;
class SubModule_1:
begin SubModule_1;
# Field Declarations
SubSubModule_1_1 subSubModule_1_1_Instance;
SubSubModule_1_2 subSubModule_1_2_Instance;
...
# Function declarations
ModuleSubModule1_f_<Function_Name>_<return type>;
OR
Module_SubModule1_f_<Function_Name>_<return type>;
OR
Module_f_SubModule1_f_<Function_Name>_<return type>;
...
end SubModule_1;
class SubSubModule_1_1:
begin SubSubModule_1_1;
# Function declarations
ModuleSubModule1SubModuleSubModule11_f_<Function_Name>_<return type>;
OR
Module_SubModule1_SubModule11_f_<Function_Name>_<return type>;
OR
Module_f_SubModule1_SubModule11__f_<Function_Name>_<return type>;
...
end SubSubModule_1_1;
So for the SubSubModule_1_1, I might end up with:
ModuleSubModule1SubModuleSubModule11_f_<Function_Name>_<return type>;
Module_SubModule1_SubModule11_f_<Function_Name>_<return type>;
Module_f_SubModule1_SubModule11__f_<Function_Name>_<return type>;
Is there maybe a better way to name those functions? I am looking forward to Your replays/alternatives.
Thank you in advance.
Sticking to an OO design is almost always a good idea, but you need to boil down OO to the things that matter. Namely:
Autonomous objects that only know of their designated purpose and know nothing about unrelated things.
For example in an embedded system, your SPI driver shouldn't and needn't know anything about the LCD you are using, even though you are communicating with the LCD through SPI.
Private encapsulation that hides information away to reduce complexity, tight coupling and namespace collisions.
In some cases, inheritance.
For example if you are writing a portable HAL that should function the same no matter the underlying microcontroller hardware. (Like for example a SPI driver.)
All of the above OO can be achieved in C and the language directly or indirectly has language support for it. There's misc other concepts like "RAII", which are handy but not necessary. Unfortunately we can't get automatically called constructors/destructors in C, so we have to live with calling them explicitly.
The main thing to concider when doing OO in C (and other languages) is to do it on a file level. The header file should contain the public interface - everything that the caller needs to know, that you would normally have declared public in a language with keyword support. Each header file contains a corresponding .c file containing the private implementation details.
It's a good idea to have a strict naming policy like in your examples, so that the caller knows where a certain function belongs. The functions belonging to the SPI driver spi.h should be named spi_init, spi_transceive and so on, with the source code prefix first.
Not sure if I like the SubSubModule idea though, seems a bit burdensome. Also, in an embedded system there should be just so many cases where you actually need inheritance, it is a bit of a rare beast rather than the main attraction in most programs. Often it can rather be a sign of poor design and over-engineering with far too many abstraction layers. It's also important to never let your inheritance API be set in stone. Don't hesitate to change it later on, when you discover new requirements that weren't considered during the initial design.
Regarding private encapsulation, C supports that through the static keyword. Functions declared static in the .c file are truly private and can't be accessed from other files. It doesn't work quite as well for variables though. You can use static file scope variables as a "poor man's private", that's in fact how it is done most of the time in embedded systems. static variables have some limitations though: they force the object to become a "singleton pattern" with only one instance possible. Which is fine if you only need one instance of the SPI driver, but what if the MCU comes with 5 different SPI peripherals, all behaving identically?
As a side note, static variables aren't thread-safe in larger, multi-process/multi-thread programs. Could become relevant in case of RTOS.
It is however possible to take OO one step further in C, by using the concept known as opaque type / opaque pointers. Examples. This allows you to create multi-instance classes, fully encapsulated, or optionally with some public parts. It can be used to model inheritance and polymorphism, by letting the first object of the inherited class contain a struct instance of its parent. Function pointers enable "virtual" inherited functions, where calling a function through a base class pointer invokes the corresponding function in the caller.
An object declared as opaque through pointers to incomplete type cannot be allocated by the caller, they can only declare pointers to them. From the caller's perspective they work essentially just the same as abstract base classes in C++. You will have to encapsulate the object allocation inside the init function (constructor). This is a bit of a disadvantage in low-end embedded systems, since sanity demands that we don't use malloc there. Instead memory allocation will have to be done through a fixed maximum size static memory pool. Examples: Static allocation of opaque data types
From a MISRA-C perspective, they actually encourage the use of opaque type since MISRA-C:2012 (Dir 4.8).
Do not over-use opaque type though. It makes perfect sense for things like HAL on top of drivers, portable code, protocol handling etc. But not so much for hiding away non-portable, application-specific logic, which doesn't benefit from abstraction layers since you won't be able to re-use or port it anyway.
Overall, program design is highly qualified work. It takes lots of experience to get it done properly. Add too much abstraction and you end up in over-engineered, meta-programming hell. Add too little and you end up in spaghetti-programming, tight-coupling hell.
The concept missing from this discussion is the "this" pointer to have instance-specific data.
It's implicit in C++, but must be explicit in C.
For example, in a hypothetical module NSMotionController.c:
typedef struct NSMotionControllerStruct {
float speed__m_s;
} NSMotionController_t;
float NSMotionController_SpeedGet__m_s(NSMotionController_t const * const this) {
return this->speed__m_s;
}
bool NSMotionController_Initialize(NSMotionController_t * const this, float const speedCurrent__m_s) {
this->speed__m_s = speedCurrent__m_s;
return true;
}
We can use this like so:
int main(int argc, char ** argv) {
NSMotionController_t motionControllerInstance1;
NSMotionController_Initialize(motionControllerInstance1, 1.0f);
NSMotionController_t motionControllerInstance2;
NSMotionController_Initialize(motionControllerInstance1, 2.0f);
printf("speed1: %.1f\n", NSMotionController_SpeedGet__m_s(&motionControllerInstance1));
printf("speed2: %.1f\n", NSMotionController_SpeedGet__m_s(&motionControllerInstance2));
}
As far as naming, I use a two-letter namespace ("NS" above) since C doesn't support namespaces idiomatically.
I use the module name, then an underscore to start the method name.
I use two underscores to separate a units suffix ("__m_s" above indicates "meters per second").
For polymorphism, you can use function pointers. So, augmenting our example with function pointers:
typedef float (*NSMotionControllerInterface_SpeedGet__m_s_t)(void const * const this);
typedef struct NSMotionControllerStruct {
NSMotionControllerInterface_SpeedGet__m_s_t SpeedGet__m_s;
float speed__m_s;
} NSMotionController_t;
float NSMotionController_SpeedGet__m_s(void const * const this) {
NSMotionController_t const * const motionThis = (NSMotionController_t const *) this;
return motionThis->speed__m_s;
}
bool NSMotionController_Initialize(NSMotionController_t * const this, float const speedCurrent__m_s) {
this->SpeedGet__m_s = NSMotionController_SpeedGet__m_s;
this->speed__m_s = speedCurrent__m_s;
return true;
}
int main(int argc, char ** argv) {
NSMotionController_t motionControllerInstance1;
NSMotionController_Initialize(motionControllerInstance1, 1.0f);
NSMotionController_t motionControllerInstance2;
NSMotionController_Initialize(motionControllerInstance1, 2.0f);
printf("speed1: %.1f\n", motionControllerInstance1.SpeedGet__m_s(&motionControllerInstance1));
printf("speed2: %.1f\n", motionControllerInstance2.SpeedGet__m_s(&motionControllerInstance2));
}
Rather than using polymorphism on a single function, though, you can gather them up in a struct and pass that to other modules.
typedef float (*NSMotionControllerInterface_SpeedGet__m_s_t)(void const * const this);
typedef bool (*NSMotionControllerInterface_SpeedSet__m_s_t)(void const * const this, float const speedNew__m_s);
typedef struct NSMotionControllerInterfaceStruct {
NSMotionControllerInterface_SpeedGet__m_s_t SpeedGet__m_s;
NSMotionControllerInterface_SpeedSet__m_s_t SpeedSet__m_s;
} NSMotionControllerInterface_t;
typedef struct NSMotionControllerStruct {
NSMotionControllerInterface_t interface;
float speed__m_s;
} NSMotionController_t;
float NSMotionController_SpeedGet__m_s(void const * const this) {
NSMotionController_t const * const motionThis = (NSMotionController_t const *) this;
return motionThis->speed__m_s;
}
bool NSMotionController_SpeedSet__m_s(void const * const this, float const speedNew__m_s) {
NSMotionController_t const * const motionThis = (NSMotionController_t const *) this;
motionThis->speed__m_s = speedNew__m_s;
return true;
}
bool NSMotionController_Initialize(NSMotionController_t * const this, float const speedCurrent__m_s) {
this->interface.SpeedGet__m_s = NSMotionController_SpeedGet__m_s;
this->interface.SpeedSet__m_s = NSMotionController_SpeedSet__m_s;
this->speed__m_s = speedCurrent__m_s;
return true;
}
int main(int argc, char ** argv) {
NSMotionController_t motionControllerInstance1;
NSMotionController_Initialize(motionControllerInstance1, 1.0f);
NSMotionController_t motionControllerInstance2;
NSMotionController_Initialize(motionControllerInstance1, 2.0f);
NSMotionControllerInterface_t * const interface1 = motionControllerInstance1.interface;
NSMotionControllerInterface_t * const interface2 = motionControllerInstance2.interface;
printf("speed1: %.1f\n", interface1->SpeedGet__m_s(&interface1));
printf("speed2: %.1f\n", interface2->SpeedGet__m_s(&interface2));
interface1->SpeedSet__m_s(&interface1, 5.0f);
printf("speed1 (faster): %.1f\n", interface1->SpeedGet__m_s(&interface1));
/* Example of passing abstract interface */
NSGroundControl_t groundControl;
NSGroundControl_Initialize(&groundControl, interface1);
}
In short, never use statics when you can avoid it. This will also help unit testing, which I imagine is next (or hopefully first) if you're working in a MISRA environment.

C append to an array in header file

I have multiple header files, each of them must append a number to an array to register it's functions.
Currently I have a function with a unique name in each header file, and in the program file I need to call all those functions in one combining function.
int register1() { return 100; }; //in header1.h
int register2() { return 200; }; //in header2.h
int register3() { return 300; }; //in header3.h
int register4() { return 400; }; //in header4.h
int registered[] = {register1(),register2(),register3(),register4()}; //main.c
But this is quite inconvenient because I need to modify in two places when I add or remove header files. Better would be to modify the header file only. I was thinking about a preprocessor define, so in each header I can just use something like:
#define Registered Registered,100 // header1.h
#define Registered Registered,200 // header2.h
int registered[] = {Registered}; // main.c
But this of course will not compile, because new define redefines the old one. So is there a way to append a define? Or other way to append a number to an array without modifying two files?
This is C, not C++, otherwise I would use a class instance with constructor that would just write to an array. Somethink like that:
struct __header1{ __header1() {
global_array[global_array_ptr++] = 100;
} } __header1_inst;
and then convert it to a nice macro:
#define register(hdr, func) struct __header##hdr{ __header##hdr() { \
global_array[global_array_ptr++] = func; \
} } __header##hdr##_inst;
register(1, 100) // header1.h
register(2, 200) // header2.h
IMHO, this is a hack and I would advise against it. Even if you could do that in C, consider situation where one such header file is included by several modules. There will be an identical entry in the global array for every such module. Next, even though you can do it in C++, the order of global object initialization is undefined there, so initialization of another global object relying on contents of the global array will be unreliable.
Additionally, this is a really complicated way to do a simple thing, and obscures the meaning considerably. Apart from the array-filling code itself being complex, tracking includes will become burdensome when dependencies get beyond trivial. So, just fill that global array in a specific place explicitly.

How avoid using global variable when using nftw

I want to use nftw to traverse a directory structure in C.
However, given what I want to do, I don't see a way around using a global variable.
The textbook examples of using (n)ftw all involve doing something like printing out a filename. I want, instead, to take the pathname and file checksum and place those in a data structure. But I don't see a good way to do that, given the limits on what can be passed to nftw.
The solution I'm using involves a global variable. The function called by nftw can then access that variable and add the required data.
Is there any reasonable way to do this without using a global variable?
Here's the exchange in previous post on stackoverflow in which someone suggested I post this as a follow-up.
Using ftw can be really, really bad. Internally it will save the the function pointer that you use, if another thread then does something else it will overwrite the function pointer.
Horror scenario:
thread 1: count billions of files
thread 2: delete some files
thread 1: ---oops, it is now deleting billions of
files instead of counting them.
In short. You are better off using fts_open.
If you still want to use nftw then my suggestion is to put the "global" type in a namespace and mark it as "thread_local". You should be able to adjust this to your needs.
/* in some cpp file */
namespace {
thread_local size_t gTotalBytes{0}; // thread local makes this thread safe
int GetSize(const char* path, const struct stat* statPtr, int currentFlag, struct FTW* internalFtwUsage) {
gTotalBytes+= statPtr->st_size;
return 0; //ntfw continues
}
} // namespace
size_t RecursiveFolderDiskUsed(const std::string& startPath) {
const int flags = FTW_DEPTH | FTW_MOUNT | FTW_PHYS;
const int maxFileDescriptorsToUse = 1024; // or whatever
const int result = nftw(startPath.c_str(), GetSize, maxFileDescriptorsToUse , flags);
// log or something if result== -1
return gTotalBytes;
}
No. nftw doesn't offer any user parameter that could be passed to the function, so you have to use global (or static) variables in C.
GCC offers an extension "nested function" which should capture the variables of their enclosing scopes, so they could be used like this:
void f()
{
int i = 0;
int fn(const char *,
const struct stat *, int, struct FTW *) {
i++;
return 0;
};
nftw("path", fn, 10, 0);
}
The data is best given static linkage (i.e. file-scope) in a separate module that includes only functions required to access the data, including the function passed to nftw(). That way the data is not visible globally and all access is controlled. It may be that the function that calls ntfw() is also part of this module, enabling the function passed to nftw() to also be static, and thus invisible externally.
In other words, you should do what you are probably doing already, but use separate compilation and static linkage judiciously to make the data only visible via access functions. Data with static linkage is accessible by any function within the same translation unit, and you avoid the problems associated with global variables by only including functions in that translation unit that are creators, maintainers or accessors of that data.
The general pattern is:
datamodule.h
#if defined DATAMODULE_INCLUDE
<type> create_data( <args>) ;
<type> get_data( <args> ) ;
#endif
datamodule.c
#include "datamodule.h"
static <type> my_data ;
static int nftwfunc(const char *filename, const struct stat *statptr, int fileflags, struct FTW *pfwt)
{
// update/add to my_data
...
}
<type> create_data( const char* path, <other args>)
{
...
ret = nftw( path, nftwfunc, fd_limit, flags);
...
}
<type> get_data( <args> )
{
// Get requested data from my_data and return it to caller
}

How can I check that all my init functions have been called?

I am writing a large C program for embedded use. Every module in this program has an init() function (like a constructor) to set up its static variables.
The problem is that I have to remember to call all of these init functions from main(). I also have to remember to put them back if I have commented them out for some reason.
Is there anything clever I do to make sure that all of these functions are getting called? Something along the lines of putting a macro in each init function that, when you call a check_inited() function later, sends a warning to STDOUT if not all the functions are called.
I could increment a counter, but I'd have to maintain the correct number of init functions somewhere and that is also prone to error.
Thoughts?
The following is the solution I decided on, with input from several people in this thread
My goal is to make sure that all my init functions are actually being called. I want to do
this without maintaining lists or counts of modules across several files. I can't call
them automatically as Nick D suggested because they need to be called in a certain order.
To accomplish this, a macro included in every module uses the gcc constructor attribute to
add the init function name to a global list.
Another macro included in the body of the init function updates the global list to make a
note that the function was actually called.
Finally, a check function is called in main() after all of the inits are done.
Notes:
I chose to copy the strings into an array. This not strictly necessary because the
function names passed will always be static strings in normal usage. If memory was short
you could just store a pointer to the string that was passed in.
My reusable library of utility functions is called "nx_lib". Thus all the 'nxl' designations.
This isn't the most efficient code in the world but it's only called a boot time so that
doesn't matter for me.
There are two lines of code that need to be added to each module. If either is omitted,
the check function will let you know.
you might be able to make the constructor function static, which would avoid the need to give it a name that is unique across the project.
this code is only lightly tested and it's really late so please check carefully before trusting it.
Thank you to:
pierr who introduced me to the constructor attribute.
Nick D for demonstrating the ## preprocessor trick and giving me the framework.
tod frye for a clever linker-based approach that will work with many compilers.
Everyone else for helping out and sharing useful tidbits.
nx_lib_public.h
This is the relevant fragment of my library header file
#define NX_FUNC_RUN_CHECK_NAME_SIZE 20
typedef struct _nxl_function_element{
char func[NX_FUNC_RUN_CHECK_NAME_SIZE];
BOOL called;
} nxl_function_element;
void nxl_func_run_check_add(char *func_name);
BOOL nxl_func_run_check(void);
void nxl_func_run_check_hit(char *func_name);
#define NXL_FUNC_RUN_CHECK_ADD(function_name) \
void cons_ ## function_name() __attribute__((constructor)); \
void cons_ ## function_name() { nxl_func_run_check_add(#function_name); }
nxl_func_run_check.c
This is the libary code that is called to add function names and check them later.
#define MAX_CHECKED_FUNCTIONS 100
static nxl_function_element m_functions[MAX_CHECKED_FUNCTIONS];
static int m_func_cnt = 0;
// call automatically before main runs to register a function name.
void nxl_func_run_check_add(char *func_name)
{
// fail and complain if no more room.
if (m_func_cnt >= MAX_CHECKED_FUNCTIONS) {
print ("nxl_func_run_check_add failed, out of space\r\n");
return;
}
strncpy (m_functions[m_func_cnt].func, func_name,
NX_FUNC_RUN_CHECK_NAME_SIZE);
m_functions[m_func_cnt].func[NX_FUNC_RUN_CHECK_NAME_SIZE-1] = 0;
m_functions[m_func_cnt++].called = FALSE;
}
// call from inside the init function
void nxl_func_run_check_hit(char *func_name)
{
int i;
for (i=0; i< m_func_cnt; i++) {
if (! strncmp(m_functions[i].func, func_name,
NX_FUNC_RUN_CHECK_NAME_SIZE)) {
m_functions[i].called = TRUE;
return;
}
}
print("nxl_func_run_check_hit(): error, unregistered function was hit\r\n");
}
// checks that all registered functions were called
BOOL nxl_func_run_check(void) {
int i;
BOOL success=TRUE;
for (i=0; i< m_func_cnt; i++) {
if (m_functions[i].called == FALSE) {
success = FALSE;
xil_printf("nxl_func_run_check error: %s() not called\r\n",
m_functions[i].func);
}
}
return success;
}
solo.c
This is an example of a module that needs initialization
#include "nx_lib_public.h"
NXL_FUNC_RUN_CHECK_ADD(solo_init)
void solo_init(void)
{
nxl_func_run_check_hit((char *) __func__);
/* do module initialization here */
}
You can use gcc's extension __attribute__((constructor)) if gcc is ok for your project.
#include <stdio.h>
void func1() __attribute__((constructor));
void func2() __attribute__((constructor));
void func1()
{
printf("%s\n",__func__);
}
void func2()
{
printf("%s\n",__func__);
}
int main()
{
printf("main\n");
return 0;
}
//the output
func2
func1
main
I don't know how ugly the following looks but I post it anyway :-)
(The basic idea is to register function pointers, like what atexit function does.
Of course atexit implementation is different)
In the main module we can have something like this:
typedef int (*function_t)(void);
static function_t vfunctions[100]; // we can store max 100 function pointers
static int vcnt = 0; // count the registered function pointers
int add2init(function_t f)
{
// todo: error checks
vfunctions[vcnt++] = f;
return 0;
}
...
int main(void) {
...
// iterate vfunctions[] and call the functions
...
}
... and in some other module:
typedef int (*function_t)(void);
extern int add2init(function_t f);
#define M_add2init(function_name) static int int_ ## function_name = add2init(function_name)
int foo(void)
{
printf("foo\n");
return 0;
}
M_add2init(foo); // <--- register foo function
Why not write a post processing script to do the checking for you. Then run that script as part of your build process... Or better yet, make it one of your tests. You are writing tests, right? :)
For example, if each of your modules has a header file, modX.c. And if the signature of your init() function is "void init()"...
Have your script grep through all your .h files, and create a list of module names that need to be init()ed. Then have the script check that init() is indeed called on each module in main().
If your single module represents "class" entity and has instance constructor, you can use following construction:
static inline void init(void) { ... }
static int initialized = 0;
#define INIT if (__predict_false(!initialized)) { init(); initialized = 1; }
struct Foo *
foo_create(void)
{
INIT;
...
}
where "__predict_false" is your compiler's branch prediction hint. When first object is created, module is auto-initialized (for once).
Splint (and probably other Lint variants) can give a warning about functions that are defined but not called.
It's interesting that most compilers will warn you about unused variables, but not unused functions.
Larger running time is not a problem
You can conceivably implement a kind of "state-machine" for each module, wherein the actions of a function depend on the state the module is in. This state can be set to BEFORE_INIT or INITIALIZED.
For example, let's say we have module A with functions foo and bar.
The actual logic of the functions (i.e., what they actually do) would be declared like so:
void foo_logic();
void bar_logic();
Or whatever the signature is.
Then, the actual functions of the module (i.e., the actual function declared foo()) will perform a run-time check of the condition of the module, and decide what to do:
void foo() {
if (module_state == BEFORE_INIT) {
handle_not_initialized_error();
}
foo_logic();
}
This logic is repeated for all functions.
A few things to note:
This will obviously incur a huge penalty performance-wise, so is
probably not a good idea (I posted
anyway because you said runtime is
not a problem).
This is not a real state-machine, since there are only two states which are checked using a basic if, without some kind of smart general logic.
This kind of "design-pattern" works great when you're using separate threads/tasks, and the functions you're calling are actually called using some kind of IPC.
A state machine can be nicely implemented in C++, might be worth reading up on it. The same kind of idea can conceivably be coded in C with arrays of function pointers, but it's almost certainly not worth your time.
you can do something along these lines with a linker section. whenever you define an init function, place a pointer to it in a linker section just for init function pointers. then you can at least find out how many init functions have been compiled.
and if it does not matter what order the init functions are called, and the all have the same prototype, you can just call them all in a loop from main.
the exact details elude my memory, but it works soemthing like this::
in the module file...
//this is the syntax in GCC..(or would be if the underscores came through in this text editor)
initFuncPtr thisInit __attribute((section(.myinits)))__= &moduleInit;
void moduleInit(void)
{
// so init here
}
this places a pointer to the module init function in the .myinits section, but leaves the code in the .code section. so the .myinits section is nothing but pointers. you can think of this as a variable length array that module files can add to.
then you can access the section start and end address from the main. and go from there.
if the init functions all have the same protoytpe, you can just iterate over this section, calling them all.
this, in effect, is creating your own static constructor system in C.
if you are doing a large project and your linker is not at least this fully featured, you may have a problem...
Can I put up an answer to my question?
My idea was to have each function add it's name to a global list of functions, like Nick D's solution.
Then I would run through the symbol table produced by -gstab, and look for any functions named init_* that had not been called.
This is an embedded app so I have the elf image handy in flash memory.
However I don't like this idea because it means I always have to include debugging info in the binary.

How to create a Singleton in C?

What's the best way to create a singleton in C? A concurrent solution would be nice.
I am aware that C isn't the first language you would use for a singleton.
First, C is not suitable for OO programming. You'd be fighting all the way if you do. Secondly, singletons are just static variables with some encapsulation. So you can use a static global variable. However, global variables typically have far too many ills associated with them. You could otherwise use a function local static variable, like this:
int *SingletonInt() {
static int instance = 42;
return &instance;
}
or a smarter macro:
#define SINGLETON(t, inst, init) t* Singleton_##t() { \
static t inst = init; \
return &inst; \
}
#include <stdio.h>
/* actual definition */
SINGLETON(float, finst, 4.2);
int main() {
printf("%f\n", *(Singleton_float()));
return 0;
}
And finally, remember, that singletons are mostly abused. It is difficult to get them right, especially under multi-threaded environments...
You don't need to. C already has global variables, so you don't need a work-around to simulate them.
It's the same as the C++ version pretty much. Just have a function that returns an instance pointer. It can be a static variable inside the function. Wrap the function body with a critical section or pthread mutex, depending on platform.
#include <stdlib.h>
struct A
{
int a;
int b;
};
struct A* getObject()
{
static struct A *instance = NULL;
// do lock here
if(instance == NULL)
{
instance = malloc(sizeof(*instance));
instance->a = 1;
instance->b = 2;
}
// do unlock
return instance;
};
Note that you'd need a function to free up the singleton too. Especially if it grabs any system resources that aren't automatically released on process exit.
EDIT: My answer presumes the singleton you are creating is somewhat complex and has a multi-step creation process. If it's just static data, go with a global like others have suggested.
A singleton in C will be very weird . . . I've never seen an example of "object oriented C" that looked particularly elegant. If possible, consider using C++. C++ allows you to pick and choose which features you want to use, and many people just use it as a "better C".
Below is a pretty typical pattern for lock-free one-time initialization. The InterlockCompareExchangePtr atomically swaps in the new value if the previous is null. This protects if multiple threads try to create the singleton at the same time, only one will win. The others will delete their newly created object.
MyObj* g_singleton; // MyObj is some struct.
MyObj* GetMyObj()
{
MyObj* singleton;
if (g_singleton == NULL)
{
singleton = CreateNewObj();
// Only swap if the existing value is null. If not on Windows,
// use whatever compare and swap your platform provides.
if (InterlockCompareExchangePtr(&g_singleton, singleton, NULL) != NULL)
{
DeleteObj(singleton);
}
}
return g_singleton;
}
DoSomethingWithSingleton(GetMyObj());
Here's another perspective: every file in a C program is effectively a singleton class that is auto instantiated at runtime and cannot be subclassed.
Global static variables are your private class members.
Global non static are public (just declare them using extern in some header file).
Static functions are private methods
Non-static functions are the public ones.
Give everything a proper prefix and now you can use my_singleton_method() in lieu of my_singleton.method().
If your singleton is complex you can write a generate_singleton() method to initialize it before use, but then you need to make sure all the other public methods check if it was called and error out if not.
I think this solution might be the simplest and best for most use cases...
In this example, I am creating a single instance global dispatch queue, which you'd definitely do, say, if you were tracking dispatch source events from multiple objects; in that case, every object listening to the queue for events could be notified when a new task is added to the queue. Once the global queue is set (via queue_ref()), it can be referenced with the queue variable in any file in which the header file is included (examples are provided below).
In one of my implementations, I called queue_ref() in AppDelegate.m (main.c would work, too). That way, queue will be initialized before any other calling object attempts to access it. In the remaining objects, I simply called queue. Returning a value from a variable is much faster than calling a function, and then checking the value of the variable before returning it.
In GlobalQueue.h:
#ifndef GlobalQueue_h
#define GlobalQueue_h
#include <stdio.h>
#include <dispatch/dispatch.h>
extern dispatch_queue_t queue;
extern dispatch_queue_t queue_ref(void);
#endif /* GlobalQueue_h */
In GlobalQueue.c:
#include "GlobalQueue.h"
dispatch_queue_t queue;
dispatch_queue_t queue_ref(void) {
if (!queue) {
queue = dispatch_queue_create_with_target("GlobalDispatchQueue", DISPATCH_QUEUE_SERIAL, dispatch_get_main_queue());
}
return queue;
}
To use:
#include "GlobalQueue.h" in any Objective-C or C implementation source file.
Call queue_ref() to use the dispatch queue. Once queue_ref() has been called, the queue can be used via the queue variable in all source files
Examples:
Calling queue_ref():
dispatch_queue_t serial_queue_with_queue_target = dispatch_queue_create_with_target("serial_queue_with_queue_target", DISPATCH_QUEUE_SERIAL, **queue_ref()**);
Calling queue:
dispatch_queue_t serial_queue_with_queue_target = dispatch_queue_create_with_target("serial_queue_with_queue_target", DISPATCH_QUEUE_SERIAL, **queue**));]
Just do
void * getSingleTon() {
static Class object = (Class *)malloc( sizeof( Class ) );
return &object;
}
which works in a concurrent environment too.

Resources