I saw some piece of code in one of the old files.
void (*const m_exec[N_EXECS])(void) =
{
#define PROCESS_DEF_TIMED(name) name, // defines macro for use in proclist.h
#define PROCESS_TIMED // define switch for section in proclist.h
#include "proclist.h"
#undef PROCESS_TIMED // undefine switch
#undef PROCESS_DEF_TIMED // undefines macro
};
I am unable to understand the meaning of this code. Is this a function pointer with declaration and function definition together? But if I try to declare similar function pointer like below, I get compilation error
void (*voidFptr)(void) =
{
printf("Hello\n");
}
Also what is #define here? Why this is inside the function I am not sure.
This:
void (*const m_exec[N_EXECS])(void)
is the way you declare an array of function pointers in C. You are not alone in finding this difficult to read. It declares an array of length N_EXECS, where each element in the array is a function that takes no arguments and returns a pointer to a const-void.
The braces-enclosed block after it is the array initializer; probably proclist.h has a whole list of function pointer declarations in it, and this is essentially pasting those into this array. If you want to see what's actually happening after the #include, you can use the -E flag of your compiler. So if this were in main.c, you would run:
gcc -E -Ipath/to/headers -Iother/path/to/headers main.c
And it would give you a (probably huge) dump of source code, which is the result of pushing that file through the preprocessor and evaluating all of the #include statements.
Edit: missed your last question.
Probably (and this is conjecture without seeing proclist.h), the things its defining change the contents of proclist.h. For example, if it contained:
#ifdef PROCESS_TIMED
&function1_timed,
&function2_timed
#else
&function1,
&function2
#endif
Then #define PROCESS_TIMED would change what ended up in your m_exec array.
Related
Short version: I would like to declare a function in the same statement that calls it. The syntax I'm looking for is something of this sort:
// foo is undeclared in this file, and implemented in another file
int main() {
void* p = (cast_to_function_that_receivs_ints_and_returns_pointer)foo(1,2);
}
Long version:
The following code creates an obvious implicit declaration warning and undefined reference error, because of the call to foo:
// a.c
int main() {
void* p = foo(1,2);
}
I add the following file to the compilation to solve the undefined reference:
// b.c
void* foo(int a, int b) {
return (void*)0xbadcafe;
}
I would now like to solve the implicit declaration. The usual solution is to modify a.c to either #include a declaration to foo or declare it itself, something like:
// a.c
void* foo(int a, int b);
int main() {
void* p = foo(1,2);
}
But I would rather not declare foo, instead modifying the line that calls foo, similar to function pointers syntax, or to the example I posted in the "short versions". Is it even possible?
Assume I am proficient in C and that I have a valid motivation - I would like to "override" the behavior of foo by recompiling with -Dfoo=bar.
So if I understand correctly, your motivation is that you have existing code that looks like
p = bar(1,2);
and you would like to define macros so that it calls foo(1,2) instead. But you don't want to modify the source file to include a declaration of foo - you want to do everything by means of command-line macro definitions. Have I got that right?
Since you've tagged this gcc, perhaps you are willing to consider non-standard gcc extensions to the C language. If so, you can do it with gcc statement expressions, also supported by clang and icc. Define bar to expand to an expression containing a block which declares foo and whose value is a pointer to foo. That is:
#define bar ({ extern void *foo(int, int); foo; })
Or from the command line:
gcc -D'bar=({ extern void *foo(int, int); foo; })' call_bar.c
Try it on godbolt.
This has
A variant would be to define a macro bar(a,b) with two arguments, where the corresponding statement expression actually calls foo:
gcc -D'bar(a,b)=({ extern void *foo(int, int); foo((a), (b)); })' call_bar.c
but this will fail if the original code tries to call p = (bar)(a,b) or tries to take the address of bar.
I'm not aware of any way to get this exact effect in standard C. But a different approach would be to create a header file containing the declaration of foo, and then using -include to "inject" it at the top of the source file:
gcc -include declare_foo.h -Dbar=foo call_bar.c
This isn't technically what you asked for, because at some level it does involve declaring foo "beforehand", but it may still help solve your problem. In this case everything is standard C, but we have moved the "non-portability" from the code to the build process.
On the other hand, if the desired replacement for bar is something simple enough to put in a macro, like the constant return in your example, then you can cut out the middleman foo and just define a macro:
gcc -D'bar(a,b)=((void *)0xbadcafe)' call_bar.c
There's no way around the declaration requirement. You must define a symbol for the compiler to work with. Some compilers allow you to use a pragma or other non-standard feature to create the mapping between the symbol and physical/virtual address.
Compile your mock_foo.c file and link the object file to the program instead of foo.c.
Another approach is only ever call through a macro definition:
#ifdef MOCK_FOO
#define (FOO(a, b) mock_foo(a, b))
#else
#define (FOO(a, b) foo(a, b)
#endif
Otherwise, you have to understand how the compiler/linker and OS/loader work, to correctly hook functions to call mocks. There's a reason tooling for quality mock frameworks cost so much money. They are very complex.
You can cast a function as you call it:
void *p = ((void *(*)(int, int))foo)(1, 2);
It's ugly, I don't see a valid reason for it, but you can.
Currently looking at some C code that doesn't make any sense to me. What is (elementSize)? How am supposed to pass arguments to this static function? What is the name of this syntax style so I can learn more abour it?
static int torch_Tensor_(elementSize)(lua_State *L)
{
luaT_pushinteger(L, THStorage_(elementSize)());
return 1;
}
https://github.com/torch/torch7/blob/master/generic/Tensor.c
This is the file I am trying to understand for reference.
Normally
static int torch_Tensor_(elementSize)(lua_State *L)
would mean torch_Tensor_ is a function that takes a single parameter called elementSize that has no type (?! - syntax error) and returns a function that takes a pointer to lua_State and returns an int. This is blatantly invalid (functions cannot return other functions).
But what's actually going on here is that torch_Tensor_ is defined as a function-like macro, so before the compiler even sees this declaration, torch_Tensor_(elementSize) is replaced by something else.
In https://github.com/torch/torch7/blob/master/Tensor.c there is
#include "general.h"
#define torch_Storage_(NAME) TH_CONCAT_4(torch_,Real,Storage_,NAME)
#define torch_Storage TH_CONCAT_STRING_3(torch.,Real,Storage)
#define torch_Tensor_(NAME) TH_CONCAT_4(torch_,Real,Tensor_,NAME)
#define torch_Tensor TH_CONCAT_STRING_3(torch.,Real,Tensor)
#include "generic/Tensor.c"
#include "THGenerateAllTypes.h"
#include "generic/Tensor.c"
#include "THGenerateHalfType.h"
with TH_CONCAT_... defined in lib/TH/THGeneral.h.in:
#define TH_CONCAT_STRING_3(x,y,z) TH_CONCAT_STRING_3_EXPAND(x,y,z)
#define TH_CONCAT_STRING_3_EXPAND(x,y,z) #x #y #z
#define TH_CONCAT_4_EXPAND(x,y,z,w) x ## y ## z ## w
#define TH_CONCAT_4(x,y,z,w) TH_CONCAT_4_EXPAND(x,y,z,w)
So torch_Tensor_ is defined as a macro before generic/Tensor.c is included.
torch_Tensor_(elementSize)
expands to
TH_CONCAT_4(torch_,Real,Tensor_,elementSize)
which expands to
TH_CONCAT_4_EXPAND(torch_,...,Tensor_,elementSize)
... is a placeholder, not real code. Real is defined as a macro in the various THGenerate*Type.h files, so this line actually becomes
TH_CONCAT_4_EXPAND(torch_,char,Tensor_,elementSize)
TH_CONCAT_4_EXPAND(torch_,int,Tensor_,elementSize)
TH_CONCAT_4_EXPAND(torch_,float,Tensor_,elementSize)
...
depending on context. Anyway, the end result is a single identifier of the form
torch_charTensor_elementSize
torch_intTensor_elementSize
torch_floatTensor_elementSize
...
(one token).
The resulting function definition thus looks like e.g.
static int torch_charTensor_elementSize(lua_State *L)
{
...
}
depending on which context generic/Tensor.c was included in.
The reason things are done this way is to have what amounts to the same code, but for multiple different types. In C++ you would write a function template:
namespace torch {
template<typename Real>
static int Tensor_elementSize(lua_State *L) { ... }
}
But C has no templates (nor namespaces), so the only way to get "generic" code like this is to do it manually with macros and preprocessing tricks (and manually "decorating" names; e.g. the elementSize function for floats is really called torch_floatTensor_elementSize).
All we're really trying to do is abstract over a type parameter, here called Real.
I am dealing with the following issue in C. I use global variables for defining some global parameters in my code. I would like such global variables to be constant, even though they have to be initialized inside a routine that reads their values from an input data file. In a nutshell, I am looking for a good way to "cast away" constness during variable initialization in C (I guess in C++ this would not be an issue thanks to const_cast)
I came up with a pattern based on macros to do so, as illustrated below.
It seems to work fine, but I have the following questions.
Does anyone see any hidden flaw or potential danger in the procedure below?
Would anyone discourage the following approach in favor of a simpler one?
My approach:
I have a main header file containing the definition of my global variable (int N) like so
/* main_header.h */
#ifdef global_params_reader
#define __TYPE__QUAL__
#else
#define __TYPE__QUAL__ const
#endif
__TYPE__QUAL__ int N;
I have a file "get_global_params.c" implementing the initialization of N, which sees N as "int N" (as it includes "main_header.h" after defining global_params_reader)
/* get_global_params.c */
#define global_params_reader
#include get_global_params.h
void get_global_params(char* filename){
N = ... ; // calling some function that reads the value of N from
// the datafile "filename" and returns it
}
and the corresponding header file "get_global_params.h"
/* get_global_params.h */
#include "main_header.h"
void get_global_params(char* filename);
Finally, I have a main.c, which sees N as "const int N" (as it includes "main_header.h" without defining global_params_reader):
/* main.c */
#include "main_header.h"
#include "get_global_params.h"
int main(int argc, char **argv){
// setting up input data file //
...
// initialize N //
get_global_params(datafile);
// do things with N //
...
}
I hope my explanation was clear enough.
Thanks for any feedback.
Just contain the globals in a separate file.
globl.h:
struct Globals{
int N;
//...
};
extern const struct Globals *const globals;
init_globl.h:
init_globals(/*Init Params*/);
globl.c
#include globl.h
#include init_globl.h
static struct Globals _globals;
const struct Globals *const globals = &_globals;
init_globals(/*Init Params*/){
// Initialize _globals;
//...
}
Now you can initialize the globals at startup by including init_globl.h in whatever file needs access to that functionality, everyone else can directly access the globals just by including globl.h, and using the notation globals->N.
If I were you, I would simply avoid this kind of global variables. Instead, I would define a struct with all those program parameters, and define one function that returns a const pointer to the one and only instance of this struct (singleton pattern). That way, the function that returns the pointer has non-const access to the singleton, while the entire rest of the program does not. This is precisely what you need, it's clean and object oriented, so there is no reason to mess around with macros and casts.
The instance can be declared as a static variable within the function or it can be malloc'ed to a static pointer. It does not really matter, because that is an implementation detail of that function which is never leaked to the outside. Nor does the rest of the code need to be aware of when the parameters are actually read, it just calls the function and it gets the one and only object with all valid parameters.
"I would like such global variables to be constant, even though they have to be initialized inside a routine that reads their values from an input data file."
It is not possible to initialize a const in c during run-time. In c value either has or has not a const qualifier, and it is defined upon declaration. c does not support changing it. The semantics are fixed. But some expert with quoting the standard would be nicer and more ensuring.
I don't think this is possible in c++ either, but I won't bet on it, since c++ can do some magic here and there.
In one of my project source files, I found this C function definition:
int (foo) (int *bar)
{
return foo (bar);
}
Note: there is no asterisk next to foo, so it's not a function pointer. Or is it?
What is going on here with the recursive call?
In the absence of any preprocessor stuff going on, foo's signature is equivalent to
int foo (int *bar)
The only context in which I've seen people putting seemingly unnecessary parentheses around function names is when there are both a function and a function-like macro with the same name, and the programmer wants to prevent macro expansion.
This practice may seem a little odd at first, but the C library sets a precedent by providing some macros and functions with identical names.
One such function/macro pair is isdigit(). The library might define it as follows:
/* the macro */
#define isdigit(c) ...
/* the function */
int (isdigit)(int c) /* avoid the macro through the use of parentheses */
{
return isdigit(c); /* use the macro */
}
Your function looks almost identical to the above, so I suspect this is what's going on in your code too.
The parantheses don't change the declaration - it's still just defining an ordinary function called foo.
The reason that they have been used is almost certainly because there is a function-like macro called foo defined:
#define foo(x) ...
Using (foo) in the function declaration prevents this macro from being expanded here. So what is likely happening is that a function foo() is being defined with its body being expanded from the function-like macro foo.
The parentheses are meaningless.
The code you show is nothing but an infinite recursion.
When defining a function pointer, you sometimes see strange parentheses that do mean something. But this isn't the case here.
That may be really simple but I'm unable to find a good answer.
How can I make a macro representing first a certain value and then a different one?
I know that's nasty but I need it to implicitly declare a variable the first time and then do nothing.
This variable is required by other macros that I'm implementing.
Should I leverage "argument prescan"?
The thing you need to know is the fact I'm generating the code:
#define INC_X x++ //should be declared if needed to
#define PRINT_X printf("VALUE OF X: %d\n", x)
int func() {
[...]
INC_X;
[...]
INC_X;
[...]
PRINT_X;
[...]
}
As far as I know, this is impossible. I know of no way for the expansion of a macro to control the way another macro -- or itself -- will be expanded after. C99 introduced _Pragma so that #pragma things can be done in macros, but there is no equivalent for #define or #undef.
#include <stdio.h>
#define FOO &s[ (!c) ? (c++, 0) : (4) ]
static int c = 0;
const char s[] = { 'f', 'o', 'o', '\0', 'b', 'a', 'r', '\0' };
int main() {
puts(FOO);
puts(FOO);
return 0;
}
Does the above help?
From the look of it, you could try if Boost.Preprocessor contains what you are looking for.
Look at this tutorial
http://www.boostpro.com/tmpbook/preprocessor.html
from the excellent C++ Template Metaprogramming book.
With the edit, I'll have a go at an answer. It requires your compiler to support __FUNCTION__, which MSVC and GCC both do.
First, write a set of functions which maps strings to integers in memory, all stored in some global instance of a structure. This is left as an exercise for the reader, functionally it's a hashmap, but I'll call the resulting instance "global_x_map". The function get_int_ptr is defined to return a pointer to the int corresponding to the specified string, and if it doesn't already exist to create it and initialize it to 0. reset_int_ptr just assigns 0 to the counter for now, you'll see later why I didn't just write *_inc_x_tmp = 0;.
#define INC_X do {\
int *_inc_x_tmp = get_int_ptr(&global_x_map, __FILE__ "{}" __FUNCTION__); \
/* maybe some error-checking here, but not sure what you'd do about it */ \
++*_inc_x_tmp; \
} while(0)
#define PRINT_X do {\
int *_inc_x_tmp = get_int_ptr(&global_x_map, __FILE__ "{}" __FUNCTION__); \
printf("%d\n", *_inc_x_tmp); \
reset_int_ptr(&global_x_map, _inc_x_tmp); \
} while(0)
I've chose the separator "{}" on the basis that it won't occur in a mangled C function name - if your compiler for some reason might put that in a mangled function name then of course you'd have to change it. Using something which can't appear in a file name on your platform would also work.
Note that functions which use the macro are not re-entrant, so it is not quite the same as defining an automatic variable. I think it's possible to make it re-entrant, though. Pass __LINE__ as an extra parameter to get_int_ptr. When the entry is created, store the value of __LINE__.
Now, the map should store not just an int for each function, but a stack of ints. When it's called with that first-seen line value, it should push a new int onto the stack, and return a pointer to that int thereafter whenever it's called for that function with any other line value. When reset_int_ptr is called, instead of setting the counter to 0, it should pop the stack, so that future calls will return the previous int.
This only works of course if the "first" call to INC_X is always the same, is called only once per execution of the function, and that call doesn't appear on the same line as another call. If it's in a loop, if() block, etc, it goes wrong. But if it's inside a block, then declaring an automatic variable would go wrong too. It also only works if PRINT_X is always called (check your early error exits), otherwise you don't restore the stack.
This may all sound like a crazy amount of engineering, but essentially it is how Perl implements dynamically scoped variables: it has a stack for each symbol name. The difference is that like C++ with RAII, Perl automatically pops that stack on scope exit.
If you need it to be thread-safe as well as re-entrant, then make global_x_map thread-local instead of global.
Edit: That __FILE__ "{}" __FUNCTION__ identifier still isn't unique if you have static functions defined in header files - the different versions in different TUs will use the same counter in the non-re-entrant version. It's OK in the re-entrant version, though, I think. You'll also have problems if __FILE__ is a basename, not a full path, since you could get collisions for static functions of the same name defined in files of the same name. That scuppers even the re-entrant version. Finally, none of this is tested.
What about having the macro #define some flag at the end of it's execution and check for that flag first?
#def printFoo
#ifdef backagain
bar
#else
foo
#def backagain
Need to add some \ chars to make it work - and you probably don't want to actually do this compared to an inline func()
An alternative to some of the methods proposed thus far would be to use function pointers. It might not be quite what you are looking for, but they can still be a powerful tool.
void foo (void);
void bar (void);
void (*_func_foo)(void) = foo;
void foo (void) {
puts ("foo\n");
}
void bar (void) {
puts ("bar"\n");
}
#define FOO() _func_foo(); \
_func_foo = bar;
int main (void) {
FOO();
FOO();
FOO();
return 0;
}
#define FOO __COUNTER__ ? bar : foo
Edit: removed all unneeded code