How does function-like macros work, this example - c

void someOtherFunction(void)
{
...
}
//Is it possible to call the #define like this, in the global scope? When does the execution come here?
SYSTEM_CONTROL_REGISTER_INIT_FUNCTION( credHandlerInit, LEVEL_APPLICATION, SYSTEM_CONTROL_ORDER_DONT_CARE );
void credHandlerInit(void)
{
portBASE_TYPE result;
result = xTaskCreate( credHandlerTask,
(portCHAR *) MBS_CFG_TASK_NAME_CRED_HANDLER,
MBS_CFG_TASK_STACK_CRED_HANDLER,
NULL,
MBS_CFG_TASK_PRIO_CRED_HANDLER,
&credHandlerTaskHandle );
}
and in a .h-file the following macro is defined:
#define SYSTEM_CONTROL_REGISTER_INIT_FUNCTION( _initFunctionName, \
_initLevel, \
_initOrder ) \
\
void _initFunctionName( void ); \
\
SystemControlInitListRecord const systemControlInitRecord_ ## _initLevel ## _initOrder ## _ ## _initFunctionName \
__attribute__ ((section (".systemControlInitList"))) \
= { \
.name = #_initFunctionName, \
.syncedInitFunction = NULL, \
.unsyncedInitFunction = _initFunctionName, \
.level = _initLevel, \
.order = _initOrder, \
.initType = SYSTEM_CONTROL_RTOS_RUNNING \
}; \
\
void _initFunctionName( void )
What I don't understand is how this function is called?
I do not see any call to this function in the code.
Can someone explain how this work?
Is the code below valid, calling the macro like this?
//main.c
#define SOMETHING(x) (someVariable = x)
static uint32_t someVariable;
SOMETHING(5);
int main(void)
{
printf("%d", someVariable); //should print 5 here then?
}

The intention of this code is the following:
The macro declares a function named credHandlerInit. This name is passed to the _initFunctionName macro parameter name. Whoever wrote the macro didn't quite know what they are doing, so we end up with two function declarations void credHandlerInit(void );, which is OK but very fishy. Perhaps they optionally meant the macro to be followed by the function definition in the form of { ... }. At any rate, not the best idea.
The whole SystemControlInitListRecord const part declares a read-only struct of that type, then names it systemControlInitRecord_LEVEL_APPLICATION_SYSTEM_CONTROL_ORDER_DONT_CARE _credHandlerInit. This is where I'd start to suspect that the programmer who wrote this is paid per letter written... and also that they were not an expert at C programming.
NOTE: identifiers longer than 32 characters is a safety hazard in C, see 5.2.4.1 translation limits. So if this function name will act as an external identifier, which we have all the reasons to believe since it ain't static, a conforming compiler may not be able to distinguish between different functions with the systemControlInitRecord_LEVEL_APPLICATION_ prefix. There's no guarantee of "name mangling" but the compiler might end up generating source that calls the wrong function from the external caller side.
In practice, modern compilers tend to distinguish between far more than 32 characters, but they aren't guaranteed to do so. Best case scenario, the code is non-portable between standard compilers. Worst case, the whole code will go completely haywire on the designated compiler.
So this is a subtle and severe bug who the original programmer was not aware of. Someone will need to slap 'em from inventing such ridiculously long identifier names. It is both dangerous and completely unreadable.
The __attribute__ ((section (".systemControlInitList"))) is a common non-standard extension used by gcc and a bunch of other compilers for creating custom memory segments. These names need to correspond to a memory section in the linker script. Why this variable needs to reside in that memory section, I don't know, but this is obviously part of some embedded system where named memory sections are quite common practice (used for bootloaders, on-chip library code, NVM variables, ISRs, flash drivers etc etc).
The whole { .name = #_initFunctionName, .syncedInitFunction = NULL, ... part is a struct initializer list utilizing _designated initializers. The first member is apparently a string and the # "stringification" operator turns the name string into "credHandlerInit".
The void _initFunctionName( void ), as already mentioned, might optionally begin the function definition, which is then apparently expected to continue on the caller-side. Or otherwise the ; in the macro call makes this a 2nd function declaration.
As you can hopefully tell from my comments, this code is very badly written by someone obsessing in making things as needlessly complicated as possible, whereas the truly good C programmers try to make things as simple as possible.
I would guess it is part of some smelly RTOS source and used for user-side task creation or similar? I would stay clear of this source, since there's lots of code smell and I already found one severe bug from just reading one single macro.

A "function-like macro" just means a macro which takes arguments.
In this example you have a macro which takes arguments but it is not being used like a function at all.
This macro expands to a constant object definition. The object is a structure with information about a function and when to call it. The object is placed in a custom non-standard section called ".systemControlInitList".
In order to use this code you must have a corresponding custom linker control script (usually called something.ld). This will collect all the objects that are placed in the custom section and put them somewhere in the program image, probably ROM. It will put some custom symbol at the the start of the block of such objects, and probably another symbol at the end.
There will then need to be some custom code that runs as part of your application start or boot sequence that looks for that symbol and executes all the functions referred to by the array of structure.

Related

C pre-processor or C++ magic to automatically make an object per file?

I have a function whose behavior may need to be modified based on the file it is called from (e.g., to increase debugging trace output). This modification would need to be done without recompiling (e.g., by editing a configuration file or changing an environment variable).
Just as an example that would fill this need, I could write Function() as:
FunctionModifiable( const char* pszFile, int i );
Then make a macro thusly:
#define Function( i ) FunctionModifiable( __FILE__, (i) )
And FunctionModifiable() would have the duty to check pszFile in say an unordered_set<> that was populated during initialization to see if special functionality need be activated.
However, the overhead of that search is a minus (this is high-performance software and the function is called a huge number of times), and there is some per-file data that would need to be cached in this situation. We can eliminate the search, and have get storage for the cached info, by passing in not __FILE__ but a pointer to a helper object. This object needs the filename so that, when it undergoes one-off initialization, it can consult config or environment variables or what have you to know whether it needs special handling.
FunctionHelperObject fho( __FILE__ );
#define Function( i ) FunctionModifiable( &fho, (i) ) // C-style solution
#define Function( i ) fho.MethodModifiable( (i) ) // C++-style solution
OK, now say I want to avoid users having to define that fho in every file. (Inter alia, we can't re-write all existing files calling Function(), though say we're willing to recompile them).
The idea I had was the unusual step of putting a variable definition in the header file, so that any program including the header for Function() would get a FunctionHelperObject fho( __FILE__ ) for free. (Such definition would be #pragma once or guarded by a preprocessor variable.
The problem is that __FILE__ at that point would be the name of the header, not of the top-level compilation unit. If there was a __CFILE__ symbol, that would be the solution, but there's not.
Ultimately the best I can think of has shortcomings: 1) the "modifiable" aspect would only be available in source code explicitly written to use it, and 2) you'd have to do that explicit writing, and 3) starting to get a little complicated. In code you want to add the ability to modify behavior to you'd write USE_MODIFIABLE_FUNCTION somewhere after including the header in question. That'd be a macro that creates the FunctionHelperObject above, this time in the right "file" so __FILE__ would have the required value, and furthermore defines a macro as seen above that would mask the non-customizable function Function() with one of the two macros seen above. In short: the previous example, plus
#define USE_MODIFIABLE_FUNCTION FunctionHelperObject fho( __FILE__ );\n#define Function( i ) fho.MethodModifiable( (i) )
Code written without USE_MODIFIABLE_FUNCTION would simply call the uncustomizable Function() the normal way.
But surely this is some other accepted, portable way to provide this behavior? Although I've talked exclusively about the C preprocessor, is there perhaps any C++ template magic or any other approach that would work?
Cache the result.
// in the header with Function macro
static FunctionHelperObject functionhelper;
static inline void FunctionModifiableInterface(const char *file, int i) {
static initialized = 0;
if (initialized == 0) {
initialized = 1;
functionhelper = FunctionHelperObject(file);
}
FunctionModifiable(&functionhelper, i);
}
#define Function(i) FunctionModifiableInterface(__FILE__, (i))
You can't predict where the user would want to call you Function(i), so you can't predict the value of __FILE__. Just initialize it on the first call, which also is great, because you will not initialize it if Function is not called. You could do the same initialized check inside FunctionHelperObject constructor.
The really cool and hard to do trick is to modify your build system to allow you to pass a macro with the filename of compiled C file. Because build systems compile one C file at a time, it is possible (and it's a shame compilers doesn't do that by themselves). If you are using cmake with make backend (or really just make by itself), you could do something like this:
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -D__MY_FILE__='\"$(notdir $(abspath $<))\"'")
And then use FunctionHelperObject fho(__MY_FILE__) like you wanted to, because __MY_FILE__ depends only on the output filename from make.
One option is something like this (rough example, keeping the C++ syntax from the OP) :
#define Function(i) do { \
static FunctionHelperObject obj(__FILE__); \
FunctionModifiable(&obj, (i)); \
} while (0)
Note the above will have to be modified to accommodate for a return value if the function has one.
Also : an alternative to __FILE__ might be __func__ if that fits better with your needs.

How macros in embedded C affect memory?

I know that macros in C such as:
#define VARNULL (u8)0
doesn't store this VARNULL in RAM, but this of course will increase the code size in the FLASH.
But what if I have a multi-line macro such as:
#define CALL_FUNCS(x) \
do { \
func1(x); \
func2(x); \
func3(x); \
} while (0)
By knowing that func1, func2, and func3 are functions from different .c files. Does this means that these functions will be stored in RAM? And of course in the FLASH (the code).
Kindly correct me if I'm wrong?
You keep saying that "of course" the macros will be "stored" in flash memory on your target device, but that is not true.
The macros exist in the source code only; they are replaced with their defined values during compilation. The program in flash memory will not "contain" them in any meaningful way.
Macros, and any other directive prefixed with a # are processed before C compilation by the pre-processor; they do not generate any code, but rather generate source code that is then processed by the compiler as if you had typed in the code directly. So in your example the code:
int main()
{
CALL_FUNCS(2) ;
}
Results in the following generated source code:
int main()
{
do { \
func1(2);
func2(2);
func3(2);
} while (0) ;
}
Simple as that. If you never invoke the macro, it will generate exactly no code. If you invoke it multiple times, it will generate code multiple times. There is nothing clever going on the macro is merely a textual replacement generated before compilation; what the compiler does with that depends entirely on what the macro expands to and not the fact that it is a macro - the compiler sees only the generated code, not the macro definition.
With respect to const vs #define, a literal constant macro is also jyst a textual replacement and will be placed in the code as a literal constant. A const on the other hand is a variable. The compiler may simply insert a literal constant where that generates less code that fetching the constant from memory, in C++ that is guaranteed for simple types, and it would be unusual for a C compiler not to behave in the same way. However, because it is a variable you can take it's address - if your code does take the address of a const, then the const will necessarily have storage. Whether that storage is in RAM or ROM depends on your compiler and linker configuration - you should consult the toolchain documentation to see how it handles const storage.
One benefit of using a const is that const variables have strong typing and scope unlike macros.

How can I get the function name as text not string in a macro?

I am trying to use a function-like macro to generate an object-like macro name (generically, a symbol). The following will not work because __func__ (C99 6.4.2.2-1) puts quotes around the function name.
#define MAKE_AN_IDENTIFIER(x) __func__##__##x
The desired result of calling MAKE_AN_IDENTIFIER(NULL_POINTER_PASSED) would be MyFunctionName__NULL_POINTER_PASSED. There may be other reasons this would not work (such as __func__ being taken literally and not interpreted, but I could fix that) but my question is what will provide a predefined macro like __func__ except without the quotes? I believe this is not possible within the C99 standard so valid answers could be references to other preprocessors.
Presently I have simply created my own object-like macro and redefined it manually before each function to be the function name. Obviously this is a poor and probably unacceptable practice. I am aware that I could take an existing cpp program or library and modify it to provide this functionality. I am hoping there is either a commonly used cpp replacement which provides this or a preprocessor library (prefer Python) which is designed for extensibility so as to allow me to 'configure' it to create the macro I need.
I wrote the above to try to provide a concise and well defined question but it is certainly the Y referred to by #Ruud. The X is...
I am trying to manage unique values for reporting errors in an embedded system. The values will be passed as a parameter to a(some) particular function(s). I have already written a Python program using pycparser to parse my code and identify all symbols being passed to the function(s) of interest. It generates a .h file of #defines maintaining the values of previously existing entries, commenting out removed entries (to avoid reusing the value and also allow for reintroduction with the same value), assigning new unique numbers for new identifiers, reporting malformed identifiers, and also reporting multiple use of any given identifier. This means that I can simply write:
void MyFunc(int * p)
{
if (p == NULL)
{
myErrorFunc(MYFUNC_NULL_POINTER_PASSED);
return;
}
// do something actually interesting here
}
and the Python program will create the #define MYFUNC_NULL_POINTER_PASSED 7 (or whatever next available number) for me with all the listed considerations. I have also written a set of macros that further simplify the above to:
#define FUNC MYFUNC
void MyFunc(int * p)
{
RETURN_ASSERT_NOT_NULL(p);
// do something actually interesting here
}
assuming I provide the #define FUNC. I want to use the function name since that will be constant throughout many changes (as opposed to LINE) and will be much easier for someone to transfer the value from the old generated #define to the new generated #define when the function itself is renamed. Honestly, I think the only reason I am trying to 'solve' this 'issue' is because I have to work in C rather than C++. At work we are writing fairly object oriented C and so there is a lot of NULL pointer checking and IsInitialized checking. I have two line functions that turn into 30 because of all these basic checks (these macros reduce those lines by a factor of five). While I do enjoy the challenge of crazy macro development, I much prefer to avoid them. That said, I dislike repeating myself and hiding the functional code in a pile of error checking even more than I dislike crazy macros.
If you prefer to take a stab at this issue, have at.
__FUNCTION__ used to compile to a string literal (I think in gcc 2.96), but it hasn't for many years. Now instead we have __func__, which compiles to a string array, and __FUNCTION__ is a deprecated alias for it. (The change was a bit painful.)
But in neither case was it possible to use this predefined macro to generate a valid C identifier (i.e. "remove the quotes").
But could you instead use the line number rather than function name as part of your identifier?
If so, the following would work. As an example, compiling the following 5-line source file:
#define CONCAT_TOKENS4(a,b,c,d) a##b##c##d
#define EXPAND_THEN_CONCAT4(a,b,c,d) CONCAT_TOKENS4(a,b,c,d)
#define MAKE_AN_IDENTIFIER(x) EXPAND_THEN_CONCAT4(line_,__LINE__,__,x)
static int MAKE_AN_IDENTIFIER(NULL_POINTER_PASSED);
will generate the warning:
foo.c:5: warning: 'line_5__NULL_POINTER_PASSED' defined but not used
As pointed out by others, there is no macro that returns the (unquoted) function name (mainly because the C preprocessor has insufficient syntactic knowledge to recognize functions). You would have to explicitly define such a macro yourself, as you already did yourself:
#define FUNC MYFUNC
To avoid having to do this manually, you could write your own preprocessor to add the macro definition automatically. A similar question is this: How to automatically insert pragmas in your program
If your source code has a consistent coding style (particularly indentation), then a simple line-based filter (sed, awk, perl) might do. In its most naive form: every function starts with a line that does not start with a hash or whitespace, and ends with a closing parenthesis or a comma. With awk:
{
print $0;
}
/^[^# \t].*[,\)][ \t]*$/ {
sub(/\(.*$/, "");
sub(/^.*[ \t]/, "");
print "#define FUNC " toupper($0);
}
For a more robust solution, you need a compiler framework like ROSE.
Gnu-C has a __FUNCTION__ macro, but sadly even that cannot be used in the way you are asking.

C function seemingly not defined anywhere!

I'm looking at the vim source code, specifically the file normal.c, and I see this function nv_operator being used, but it's not defined anywhere (I grepped the entire src directory)
It's only declared as:
static void nv_operator __ARGS((cmdarg_T *cap));
I've looked up the definition of __ARGS but it's just ... nothing (pretty much)
in vim.h:
#define __ARGS(x) x
So what could be going on? Is this some kind of C technique to create a dummy function or something?
There is a definition present here:
/*
* Handle an operator command.
* The actual work is done by do_pending_operator().
*/
static void
nv_operator(cap)
cmdarg_T *cap;
....
That style of definition is using an identifier list for its parameters. The style is deprecated (obsolescent) but can still be used in C. The identifiers are named in the parameter list, and their type are named in declarations that immediately follow the function declarator but precede the functions body.
The __ARGS macro is there to handle compilers that don't know about prototypes for functions (the other form to declare parameters - with type and name combined directly in the function parameter list). It would then just emit no parameters at all in declarations, i think.
Update: See this code in vim.h:
#if defined(MACOS) && (defined(__MRC__) || defined(__SC__))
/* Apple's Compilers support prototypes */
# define __ARGS(x) x
#endif
#ifndef __ARGS
# if defined(__STDC__) || defined(__GNUC__) || defined(WIN3264)
# define __ARGS(x) x
# else
# define __ARGS(x) ()
# endif
#endif
It's simply a forward declaration, so that the function is known to the C compiler (and can be used (called from other functions)) before it's actually defined (in line 8247). The actual formatting of the definition (which includes newlines) makes it hard to grep for it's existence.
Don't get distracted by the __ARGS macro. It's only a compatibility macro for the different function declaration syntaxes of K&R C vs. ANSI C.
In ANSI C a function declaration must look like this:
int getopt(int, char * const *, const char *);
In the (older) Kernighan and Ritchie C http://en.wikipedia.org/wiki/C_(programming_language)#K.26R_C
int getopt();
Its hard to find because of how it is defined:
nv_operator(cap)
appears on a line by itself.
I am not too sure what is going on, but here are some hints to help you in your search:
First of all, the __ARGS macro seems to be there because there may be versions of C where you shouldn't include the args in the declaration of the functions (Notice that the macro is defined differently depending on other preprocessor symbols... the comments say it).
Secondly, searching for the function nv_operator may not be good enough. The function might be generated by macros and such, so you can't search for an explicit definition.... for example, maybe the "nv" prefix is added by the preprocessor.
Hope this helps.

Defining const values in C

I have a C project where all code is organized in *.c/*.h file pairs, and I need to define a constant value in one file, which will be however also be used in other files. How should I declare and define this value?
Should it be as static const ... in the *.h file? As extern const ... in the *.h file and defined in the *.c file? In what way does it matter if the value is not a primitive datatype (int, double, etc), but a char * or a struct? (Though in my case it is a double.)
Defining stuff inside *.h files doesn't seem like a good idea generally; one should declare things in the *.h file, but define them in the *.c file. However, the extern const ... approach seems inefficient, as the compiler wouldn't be able to inline the value, it instead having to be accessed via its address all the time.
I guess the essence of this question is: Should one define static const ... values in *.h files in C, in order to use them in more that one place?
The rule I follow is to only declare things in H files and define them in C files. You can declare and define in a single C file, assuming it will only be used in that file.
By declaration, I mean notify the compiler of its existence but don't allocate space for it. This includes #define, typedef, extern int x, and so on.
Definitions assign values to declarations and allocate space for them, such as int x and const int x. This includes function definitions; including these in header files frequently lead to wasted code space.
I've seen too many junior programmers get confused when they put const int x = 7; in a header file and then wonder why they get a link error for x being defined more than once. I think at a bare minimum, you would need static const int x so as to avoid this problem.
I wouldn't be too worried about the speed of the code. The main issue with computers (in terms of speed and cost) long ago shifted from execution speed to ease of development.
If you need constants (real, compile time constants) you can do that three ways, putting them into header files (there is nothing bad with that):
enum {
FOO_SIZE = 1234,
BAR_SIZE = 5678
};
#define FOO_SIZE 1234
#define BAR_SIZE 5678
static const int FOO_SIZE = 1234;
static const int BAR_SIZE = 5678;
In C++, i tend to use the enum way, since it can be scoped into a namespace. For C, i use the macro. This basicially comes down to a matter of taste though. If you need floating point constants, you can't use the enumeration anymore. In C++ i use the last way, the static const double, in that case (note in C++ static would be redundant then; they would become static automatically since they are const). In C, i would keep using the macros.
It's a myth that using the third method will slow down your program in any way. I just prefer the enumeration since the values you get are rvalues - you can't get their address, which i regard as an added safety. In addition, there is much less boiler-plate code written. The eye is concentrated on the constants.
Do you really have a need to worry about the advantage of inline? Unless you're writing embedded code, stick to readability. If it's really a magic number of something, I'd use a define; I think const is better for things like const version strings and modifying function call arguments. That said, the define in .c, declare in .h rule is definitely a fairly universally accepted convention, and I wouldn't break it just because you might save a memory lookup.
As a general rule, you do not define things as static in a header. If you do define static variables in a header, each file that uses the header gets its own private copy of whatever is declared static, which is the antithesis of DRY principle: don't repeat yourself.
So, you should use an alternative. For integer types, using enum (defined in a header) is very powerful; it works well with debuggers too (though the better debuggers may be able to help with #define macro values too). For non-integer types, an extern declaration (optionally qualified with const) in the header and a single definition in one C file is usually the best way to go.
I'd like to see more context for your question. The type of the value is critical, but you've left it out. The meaning of the const keyword in C is quite subtle; for example
const char *p;
does not mean that pointer p is a constant; you can write p all you like. What you cannot write is the memory that p points to, and this stays true even as p's value changes. This is about the only case I really understand; in general, the meaning of the subtle placement of const eludes me. But this special case is extremely useful for function parameters because it extracts a promise from the function that the memory the argument points to will not be mutated.
There is one other special case everyone should know: integers. Almost always, constant, named integers should be defined in a .h file as enumeration literals. enum types not only allow you to group related constants together in a natural way, but also allow you the names of those constants to be seen in the debugger, which is a huge advantage.
I've written tens of thousands of lines of C; probably hundreds if I try to track it down. (wc ~/src/c/*.c says 85 thousand, but some of that is generated, and of course there's a lot of C code lurking elsewhere). Aside from the two cases about, I've never found much use for const. I would be pleased to learn a new, useful example.
I can give you an indirect answer. In C++ (as opposed to C) const implies static. Thatis to say in C++ static const is the same thing as const. So that tells you how that C++ standards body feels about the issue i.e. all consts should be static.
for autoconf environment:
You can always define constants in the configure file as well. AC_DEFINE() i guess is the macro to define across the entire build.
To answer the essence of your question:
You generally do NOT want to define a static variable in a header file.
This would cause you to have duplicated variables in each translation units (C files) that include the header.
variables in a header should really be declared extern since that is the implied visibility.
See this question for a good explanation.
Actually, the situation might not be so dire, as the compiler would probably convert a const type to a literal value. But you might not want to rely on that behavior, especially if optimizations are turned off.
In C++, you should always use
const int SOME_CONST = 17;
for constants and never
#define SOME_CONST 17
Defines will almost always come back and bite you later. Consts are in the language, and are strongly typed, so you won't get weird errors because of some hidden interaction. I would put the const in the appropriate header file. As long as it's #pragma once (or #ifndef x / #define x / #endif), you won't ever get any compile errors.
In vanilla C, you might have compatibility problems where you must use #defines.

Resources