Is there a way to use designated initializers to initialize parts of the same array in separate files? - arrays

I have thousands of "commands" that are all defined in their own files, and I want to be able to do things with them programmatically using an enum as a key.
The only way I can think of to do this is to have an externally linked initialization function for each "command" that is called by some other code to add a function pointer to a data structure. This sucks because then I have to declare these initialization functions in a header, define them in the individual files, and call them from somewhere else.
This method adds several lines of boiler plate for each "command," which is made worse because the boilerplate is spread across several files.
If it is possible, I'd like to have a single const array of function pointers to these static functions. Is there anything in the C99 standard that would allow me to do this?
The following code is a simplified representation of my problem, and some of it is definitely wrong, because I don't know how to do this or if it is even possible in C99.
Header included in all files
typedef enum
{
EXAMPLE_ENUM_0
EXAMPLE_ENUM_1
EXAMPLE_ENUM_2
EXAMPLE_ENUM_MAX_NUM_T,
} example_enum_t;
typedef void (*p_func_t)(void);
File 0
static void static_function_0(void)
{
void * p_peripheral = 0x00000200;
*p_peripheral = PERIPH_0_CONFIG;
}
extern int initialized_in_multiple_files[EXAMPLE_ENUM_MAX_NUM_T] = {
[EXAMPLE_ENUM_0] = &static_function_0
};
File 1
static void static_function_1(void)
{
void * p_peripheral = 0x00000300;
*p_peripheral = PERIPH_1_CONFIG;
}
extern int initialized_in_multiple_files[EXAMPLE_ENUM_MAX_NUM_T] = {
[EXAMPLE_ENUM_1] = &static_function_1
};
File 2
static void static_function_2(void)
{
void * p_peripheral = 0x00000400;
*p_peripheral = PERIPH_2_CONFIG;
}
extern int initialized_in_multiple_files[EXAMPLE_ENUM_MAX_NUM_T] = {
[EXAMPLE_ENUM_2] = &static_function_2
};
File where I want to use all the function pointers
p_func_t initialized_in_multiple_files[EXAMPLE_ENUM_MAX_NUM_T] = {0U};
for (uint32_t index = 0U; index < EXAMPLE_ENUM_MAX_NUM_T; index += 1U)
{
p_func_t p_func = initialized_in_multiple_files[index];
if (NULL != p_func)
{
p_func();
}
}

Is there a way to use designated initializers to initialize parts of the same array in separate files?
There can be many declarations of the same object, but only one definition. A declaration that initializes the object is a definition. Designated initializers do not alter this. Moreover, there is no partial initialization. Any initializer for an object initializes the whole object.
I'd like to have a single const array of function pointers to these static functions. Is there anything in the C99 standard that would allow me to do this?
No, not if the functions have internal linkage and are defined in separate files. However, you can work around the constness part by declaring a corresponding pointer to const elements in the header but defining the array itself non-const. Code in the translation unit where it is defined could then pass it (decayed to a pointer) to various functions to fill in its elements, but code in other translation units, seeing its const declaration in the header, would not be able to alter its contents (at least, not without casting away the constness).
Alternatively, if you give the functions external linkage then you could write one big initializer in the file of your choice.
Either way, you might be able to write a code generator to help you. That could significantly reduce the amount of boilerplate code you have to maintain manually.

Related

Class approximation in C - Is this witchcraft or technically acceptable?

I need to do a large Project in C and C only, without external librairies (except for SDL).
I started looking for ways to do some kind of class in C, what led me to that :
typedef void (*voidFunction)(void);
typedef struct{
int id;
voidFunction printId;
} Object;
Object *new_Object(int id){
Object *newObject = malloc(sizeof(Object));
newObject->id = id;
void printId(){
static Object *this = NULL;
if(!this) this = newObject;
printf("%d\n", this->id);
};
newObject->printId = printId;
return newObject;
}
int main(){
Object *object = new_Object(5);
object->printId();
object->id++;
object->printId();
return 0;
}
Output of main :
5
6
So this works, but does it seems reasonable ?
Should I expect a backlash if I use this kind of architecture for a big project? Maybe I'm typing out of my allocated memory without realizing it?
Techniques for implementing polymorphism in C are long established, check this answer for instance https://stackoverflow.com/a/351745/4433969
Your implementation seems to be broken. Nested functions are non-standard extension. I also have doubts about static this variable.
The non-standard nested function printId is used incorrectly. In GCC documentation Nested functions one can read:
If you try to call the nested function through its address after the containing function exits, all hell breaks loose.
The nested functions are called via trampolines, the small pieces of executable code located on stack. This code is invalidated when the parent function exits.
Though as the functions does not refer to any local variables the code will likely work. The compiler will likely avoid trampolines but rather create a kind-of "anonymous" static function.
The idiomatic solution should take a pointer to "Object" as an argument rather than use a static variable.
typedef struct Object {
int id;
void (*printId)(struct Object*);
} Object;
void printId(Object *this){
printf("%d\n", this->id);
};
...
object->printId(object);
There are advantages for using a struct to organize data for bulk processing. However, the only advantage of using the function pointer rather than calling the function directly would be:
To allow the function pointer to point to different functions having the same type for different instances of the object.
To hide the "member" function definition from the linker. For example, the function printId could be declared as static within the module containing the definition for "constructor" new_Object.

Apparently no meaning line in a program [duplicate]

I am reading the book "Programming in C" and found in Chapter 10 an example like this:
#include <stdio.h>
void test (int  *int_pointer)
{
     *int_pointer = 100;
}
int main (void)
{
     void test (int  *int_pointer);
     int  i = 50, *p = &i;
     printf ("Before the call to test i = %i\n", i);
     test (p);
     printf ("After the call to test i = %i\n", i);
     return 0;
}
I understand the example, but I don't understand the line void test (int *int_pointer); inside of main. Why do I define the signature of test again? Is that idiomatic C?
It's definitely not idiomatic C, despite being fully valid (multiple declarations are okay, multiple definitions are not). It's unnecessary, so the code will still work perfectly without it.
If at all, perhaps the author meant to do
void test (int *int_pointer);
int main (void) {
...
}
in case the function definition was put after main ().
void test (int *int_pointer); is just a declaration (or prototype) of function test. No need of this declaration in main because you already have function definition before main.
If the definition of test were after main then it would be worth of putting its declaration there to let the compiler know about the return type, number of arguments and arguments types of test before calling it.
It's not idomatic C, but still valid.
The line is a declaration of the function test, not definition. A function can't be defined multiple times, but it's valid to have multiple declarations.
It is perfectly idiomatic C, and it actually has a (limited) practical use - although not one that is demonstrated by this example.
When you declare a function or other name at the usual global level, it is brought into scope for all function bodies in the code following the declaration. A declaration cannot be removed from a scope once it has been introduced. The function is permanently visible to the rest of the translation unit.
When you declare a function or other name within a braced block, the scope of the declaration is limited to that block. Declaring a function within the scope of another function will limit its visibility, and not pollute the global namespace or make it visible to any other functions defined in the same translation unit.
This is meaningless in the case of the example, because the definition of test also brings it into scope for all following bodies - but if test were defined in another translation unit, or even if it were defined only at the very bottom of this TU, hiding the declaration inside main would protect any other functions defined afterwards from being able to see its name in their scope.
In practical terms this is of limited use - normally if you don't want a function to be visible, you put it in another translation unit (and preferably make it static) - but you can probably contrive a situation where you might want to use this ability for constructing a module-loading system that doesn't export the original declarations of its components, or something like that (and the fact that this doesn't rely on static/separate object files might potentially have some relevance to embedded/non-hosted target environments where the linking step might not work as it does on PC, allowing you to achieve a measure of namespace protection in a purely-#include-based build system).
Example:
struct module {
void * (* alloc)(size_t);
void (* dealloc)(void *);
} loaded_module;
int main(void) {
if (USE_GC) { // dynamically choose the allocator system
void * private_malloc_gc(size_t);
void private_free_noop(void *);
loaded_module = (struct module){ private_malloc_gc, private_free_noop };
} else {
void * private_malloc(size_t);
void private_free(void *);
loaded_module = (struct module){ private_malloc, private_free };
}
do_stuff();
//...
}
// cannot accidentally bypass the module and manually use the wrong dealloc
void do_stuff(void) {
int * nums = module.alloc(sizeof(int) * 32)
//...
module.dealloc(nums);
}
#include "allocator_implementations.c"
It's not idiomatic; you typically see it in code that has problems getting their header files in order.
Any function is either used in one file only, or it is used in multiple files. If it is only used in its own file, it should be static. If it is used in multiple files, its declaration should be in a header file, and anyone using it should include the header file.
What you see here is very bad style (the function should either be static, or the declaration should be taken from a header style), and also quite pointless because the compiler can see the declaration already. Since the function is in the same file, it's not dangerous; if the declaration and function don't match the compiler will tell you. I have often seen this kind of thing when the function was in a different file; that is dangerous. If someone changes the function, the program is likely to crash or misbehave.

How to give some variables "constant status" that are read from a fixed memory area in the beginning of a embedded program?

Detail of the problem:
Some variables are read from a fixed memory area in RAM into an array. From that array I need to read some variables and use it across the code but these variables need to be constant as they wont be changed in the program any where. Need suggestions to do it effectively! Thanks in advance for any help.
The thought was given for using const variables but then Const variables needs to be initialised during declaration itself. I need to extract bit by bit for each of these variables as I am not able to use memcpy for ensuring portability. Hence I find trouble in declaring the variables as constant.
Put those variables {myVar1, myVar2,...myVarN} into a C file myconsts.c (static to the compilation unit, this will make sure they are not visible outside). Add a header file myconsts.h with function declarations
int getmyVar1(void);
and so on for all the variables and implement the functions in myconsts.c.
They aren't const in the C sense, but they are unwriteable from outside the myconsts.c file. You can initialise them inside myconsts.c, just dont forget to call the init().
If you mean that you are trying to guarantee that these 'constants' end up in flash as opposed to your RAM memory...consult your manual.
You could use inline functions to access the data direct from the array, e.g
static inline myvar() { return array[myvaroffset]; }
Or, if you want the offsets hidden, don't use inline functions and just have a small module that just provides the functions.
If 'myvaroffset' is calculated rather than being a constant and you want to avoid the indexing overhead, copy the array element to a variable during initialisation and return that from the function. If you use real functions, the variables can be static within the function module.
in the function module
/* initialisation */
static int myvarlocal = array[myvaroffset];
...
/* function definitions */
...
int myvar() { return myvarlocal; }
When you want to use it:
i = myvar();
There is probably no need to make things complicated with const pointers etc. Simply use private encapsulation:
// data.h
int data_get (int index);
// data.c
#include "data.h"
static int the_array [N];
int data_get (int index)
{
if(index >= N)
{
// handle errors
}
return array[index];
}

What are some practical uses for const-qualified variables in C?

As has been discussed in several recent questions, declaring const-qualified variables in C (as opposed to const variables in C++, or pointers to const in C) usually serves very little purpose. Most importantly, they cannot be used in constant expressions.
With that said, what are some legitimate uses of const qualified variables in C? I can think of a few which have come up recently in code I've worked with, but surely there must be others. Here's my list:
Using their addresses as special sentinel values for a pointer, so as never to compare equal to any other pointer. For example: char *sentinel(void) { static const char s; return &s; } or simply const char sentinel[1]; Since we only care about the address and it actually wouldn't matter if the object were written to, the only benefit of const is that compilers will generally store it in read-only memory that's backed by mmap of the executable file or a copy of the zero page.
Using const qualified variables to export values from a library (especially shared libraries), when the values could change with new versions of the library. In such cases, simply using #define in the library's interface header would not be a good approach because it would make the application dependent on the values of the constants in the particular version of the library it was built with.
Closely related to the previous use, sometimes you want to expose pre-defined objects from a library to the application (the quintessential examples being stdin, stdout, and stderr from the standard library). Using that example, extern FILE __stdin; #define stdin (&__stdin) would be a very bad implementation due to the way most systems implement shared libraries - usually they require the entire object (here, FILE) to be copied to an address determined when the application is linked, and introduce a dependency on the size of the object (the program will break if the library is rebuilt and the size of the object changes). Using a const pointer (not pointer-to-const) here fixes all the problems: extern FILE *const stdin;, where the const pointer is initialized to point to the pre-defined object (which itself is likely declared static) somewhere internal to the library.
Lookup tables for mathematical functions, character properties, etc. This is the obvious one I originally forgot to include, probably because I was thinking of individual const variables of arithmetic/pointer type, as that's where the question topic first came up. Thanks to Aidan for triggering me to remember.
As a variant on lookup tables, implementation of state machines. Aidan provided a detailed example as an answer. I've found the same concept is also often very useful without any function pointers, if you can encode the behavior/transitions from each state in terms of a few numeric parameters.
Anyone else have some clever, practical uses for const-qualified variables in C?
const is quite often used in embedded programming for mapping onto GPIO pins of a microcontroller. For example:
typedef unsigned char const volatile * const tInPort;
typedef unsigned char * const tOutPort;
tInPort my_input = (tInPort)0x00FA;
tOutPort my_output = (tOutPort)0x00FC;
Both of these prevent the programmer from accidentally changing the pointer itself which could be disastrous in some cases. The tInPort declaration also prevents the programmer from changing the input value.
Using volatile prevents the compiler from assuming that the most recent value for my_input will exist in cache. So any read from my_input will go directly to the bus and hence always read from the IO pins of the device.
For example:
void memset_type_thing(char *first, char *const last, const char value) {
while (first != last) *(first++) = value;
}
The fact that last can't be part of a constant-expression is neither here nor there. const is part of the type system, used to indicate a variable whose value will not change. There's no reason to modify the value of last in my function, so I declare it const.
I could not bother declaring it const, but then I could not bother using a statically typed language at all ;-)
PC-lint warning 429 follows from the expectation that a local pointer to an allocated object should be consumed
by copying it to another pointer or
by passing it to a "dirty" function (this should strip the "custodial" property of the pointer) or
by freeing it or
by passing it up the caller through a return statement or a pass-by-pointer parameter.
By "dirty" I mean a function whose corresponding pointer parameter has a non-const base type. The description of the warning absolves library functions such as strcpy() from the "dirty" label, apparently because none of such library functions takes ownership of the pointed object.
So when using static analysis tools such as PC-lint, the const qualifier of parameters of called functions keeps locally allocated memory regions accounted.
const can be useful for some cases where we use data to direct code in a specific way. For example, here's a pattern I use when writing state machines:
typedef enum { STATE1, STATE2, STATE3 } FsmState;
struct {
FsmState State;
int (*Callback)(void *Arg);
} const FsmCallbacks[] = {
{ STATE1, State1Callback },
{ STATE2, State2Callback },
{ STATE3, State3Callback }
};
int dispatch(FsmState State, void *Arg) {
int Index;
for(Index = 0; Index < sizeof(FsmCallbacks)/sizeof(FsmCallbacks[0]); Index++)
if(FsmCallbacks[Index].State == State)
return (*FsmCallbacks[Index].Callback)(Arg);
}
This is analogous to something like:
int dispatch(FsmState State, void *Arg) {
switch(State) {
case STATE1:
return State1Callback(Arg);
case STATE2:
return State2Callback(Arg);
case STATE3:
return State3Callback(Arg);
}
}
but is easier for me to maintain, especially in cases where there's more complicated behavior associated with the states. For example, if we wanted to have a state-specific abort mechanism, we'd change the struct definition to:
struct {
FsmState State;
int (*Callback)(void *Arg);
void (*Abort)(void *Arg);
} const FsmCallbacks[] = {...};
and I don't need to modify both the abort and dispatch routines for the new state. I use const to prevent the table from changing at runtime.
A const variable is useful when the type is not one that has usable literals, i.e., anything other than a number. For pointers, you already give an example (stdin and co) where you could use #define, but you'd get an lvalue that could easily be assigned to. Another example is struct and union types, for which there are no assignable literals (only initializers). Consider for instance a reasonable C89 implementation of complex numbers:
typedef struct {double Re; double Im;} Complex;
const Complex Complex_0 = {0, 0};
const Complex Complex_I = {0, 1}; /* etc. */
Sometimes you just need to have a stored object and not a literal, because you need to pass the data to a polymorphic function that expects a void* and a size_t. Here's an example from the cryptoki API (a.k.a. PKCS#11): many functions require a list of arguments passed as an array of CK_ATTRIBUTE, which is basically defined as
typedef struct {
CK_ATTRIBUTE_TYPE type;
void *pValue;
unsigned long ulValueLen;
} CK_ATTRIBUTE;
typedef unsigned char CK_BBOOL;
so in your application, for a boolean-valued attribute you need to pass a pointer to a byte containing 0 or 1:
CK_BBOOL ck_false = 0;
CK_ATTRIBUTE template[] = {
{CKA_PRIVATE, &ck_false, sizeof(ck_false)},
... };
They can be used for memory-mapped peripherals or registers that cannot be changed by user code, only some internal mechanism of the microprocessor. Eg. on the PIC32MX, certain registers indicating program state are qualified const volatile - so you can read them, and the compiler won't try to optimise out, say, repeated accesses, but your code cannot write to them.
(I don't any code to hand, so I can't cite a good example right now.)

C variables scope in struct

I've faced three separate situations in C lately that I would assistance on:
My C code has a global variable:
int ref_buf; //declared in a header file
In a function definition I use the same name as a parameter:
void fun(int ref_buf, param2, param3)
{
}
Will it overwrite the originally defined global variable and will it cause bugs?
Can I declare a static variable in a C data structure like so?:
struct my
{
int a;
static int b;
};
Does it work? Is there any specific situation where one would need it?
Can I initialize a individual structure variable as follows:
struct my
{
int a;
int b = 4;
};
Question 1
All references to ref_buf in that function will bind to the parameter and not the global variable.
Question 2
This is not legal in C but is legal in C++. The keyword static in C can only be used on file scope variables or on locals.
Question 3
No this is not legal in C (or C++). You will need to create a factory method to handle this.
my create_my() {
my m;
m.b = 4;
return m;
}
On Q3: GCC allows you to initialize a struct like this (as required by the C99 standard):
struct
{
int a;
int b;
} my = { .b = 4 };
GCC doc on designated initializers
1a) The local and global variables are separate entities, and so the local one won't overwrite the global. However, the global one won't be accessible inside the function (see also notes below).
1b) It not actually incorrect, but it is guaranteed to cause confusion, and confusion causes bugs, so it's best to use different names for each.
2) No, that's not legal C. You can however make the whole struct static.
3) No. You do it like this:
struct my
{
int a;
int b;
} = {0, 4};
Note 1: Variables should be declared in .c files, not .h files. If you need to make a variable accessible in multiple files, put an extern declaration in the header file.
Note 2: Avoid global variables if at all possible.
Question 1:
I think the variable declared in the local scope takes precidence, it shouldn't overwrite it but in the scope that the variable is declared it will be used instead.
That is assuming that it compiles.
On Q1:
Do not declare variables in a header file. If you include that header file in two source files and compile the source files together, you've got problems. Maybe your linker will get you out of them, maybe not.
If you really need global variables, and this happens a lot less than typical beginners think, put something like extern int ref_buf; in the header file, and int ref_buf; in a source file. That means there is one ref_buf, and all other source files will be able to find it.
The function parameter is essentially a new variable with the same name, and all references in the function will be to it. You will not be able to access the global variable from within that function. The function creates an inner scope, and variables declared in an inner scope are different from those in an outer one. This is potentially confusing, and makes it easy to create bugs, so having variables of the same name and different scopes is generally discouraged. (Variables of the same name in different struct definitions are usually not confusing, since you have to specify what struct contains the variable.)
The compiler will compile the function, but a good compiler will issue a warning message. If it refuses to compile because of one variable shadowing another of the same name, it isn't a real C compiler.
1) Local variables always take precedence e.g.
int ref = 10;
void fun(int ref)
{
printf("\n%d\n", ref);
}
int main()
{
fun(252);
return 0;
}
shows: 252
Qs 2 and 3 won't work in C.
Yes, it will technically overwrite, but a good compiler will warn you about this situation, and you will have "warnings = errors" on when you compile, so this won't actually compile.
Not needed, since the "my" struct is already declared as static, and it is therefore declared for the entire struct. This allocates the memory for the entire struct, so there is no need to say "take part of the struct which is already static and make it static".
No, not in the definition, but you can when you create an "instance", something like:
struct my MY =
{
{0, 4}
};

Resources