Can we nest #define and #if in C language? - c++

I want to write the following code but it can't be compiled.
(core code piece)
void g();
#define MACRO(x) \
#if (x == 0) \
g(); \
#else \
h(); \
#endif
MACRO(0)
I think the reason may be that #if and #else must be placed in different lines but #define statement can only have one line. I don't know how can I fix the code. Can anyone help me? Thank you very much!
Update: This question occurs when I want to export a list of functions, each of which has one or more internal implementation. All the implementations may be of best perforamance depending on the parameters. See the code below.
void fun_1_algo_1(int x);
void fun_1_algo_2(int x);
void fun_2_algo_1(int x);
void fun_2_algo_2(int x);
// fun_1 and fun_2 both have two implementations.
// If x > 1, algo_1 is faster; otherwise algo_2 is faster
void fun_3_aogo_1(int x);
void fun_4_aogo_1(int x);
#define CHECK(x) .... //check if x is a legal number
#define Export(i) \
void fun_##i(int x) { \
CHECK(x); \
#if (i >= 1 && i <= 2) \
if (x > 1) fun_##i##_algo_1(x); \
else fun_##i##_algo_2(x); \
#else \
fun_##i##_algo_1(x); \
#endif \
}
Export(1)
Export(2)
Export(3)
Export(4)
In this example, I can't change #if to if because fun_3_algo_2(x) is undefined. The exported function will be used as a library.

No, you can't do that. You could approximate a solution using templates though.
// generic template to call h() for all values of x
template<uint32_t x>
struct func_chooser {
static inline void f()
{ h(); }
};
// specialise for the zero case (calls g())
template<>
struct func_chooser<0> {
static inline void f()
{ g(); }
};
// the macro just defers to the template
#define MACRO(x) \
func_chooser<x>::f();

Is there a reason you need the inner test to be a macro?
#define MACRO(x) ((x) == 0 ? g() : h())
will give you the behavior you want, and if you call it with a constant
MACRO(0)
the optimizer will constant fold and dead code eliminate it (so you'll end up with just a single call in the executable.) The only real drawback of this is that you can call it with a non-constant and it will compile to a test and two calls.
If you really need to do this in the preprocessor, you can use various token-pasting tricks to build macros that "evaluate" expressions by defining lots of macros covering every possible combination. BOOST_PP exists which may do a lot of this for you, or you can define a minimal set that meets your needs. In your case, something like:
#define IF1OR2ELSE_1(T, F) T
#define IF1OR2ELSE_2(T, F) T
#define IF1OR2ELSE_3(T, F) F
#define IF1OR2ELSE_4(T, F) F
#define IF1OR2ELSE_(I, T, F) IF1OR2ELSE_##I(T, F)
#define IF1OR2ELSE(I, T, F) IF1OR2ELSE_(I, T, F)
#define Export(i) \
void fun_##i(int x) { \
CHECK(x); \
IF1OR2ELSE(i, \
if (x > 1) fun_##i##_algo_1(x); \
else fun_##i##_algo_2(x); , \
fun_##i##_algo_1(x); \
) \
}
Export(1)
Export(2)
Export(3)
Export(4)
should do the trick. The basic idea is that the macro IF1OR2ELSE will expand to either its 2nd or 3rd argument depending on whether the first argument is 1 or 2 -- note that that is a token not a value, so something like 1U is not the same as 1.
You can generalize the above by building a bunch of helper macros that evaluate expressions (like BOOST_PP does)
#define IFELSE_true(T, F) T
#define IFELSE_false(T, F) F
#define IFELSE_(C, T, F) IFELSE_##C(T, F)
#define IFELSE(C, T, F) IFELSE_(C, T, F)
#define EQ_0_0 true
#define EQ_0_1 false
#define EQ_0_2 false
... many (100s?) of these for many different values
#define EQ_4_4 true
#define EQ_(A,B) EQ_##A##_##B
#define EQ(A,B) EQ(A, B)
#define OR_true_true true
#define OR_true_false true
#define OR_false_true true
#define OR_false_false false
#define OR_(A, B) OR_##A##_##B
#define OR(A, B) OR_(A, B)
now you can use
IFELSE(OR(EQ(i,1), EQ(i, 2)),
..code for i == 1 or i == 2 ,
..code for other cases
)
in your macros.

No, you cannot use #if (or any other preprocessor directive) inside a #define. Just use an ordinary if and let the compiler optimize out the unused code branch as needed.
#define MACRO(x) \
{ \
if (x == 0) \
g(); \
else \
h(); \
}
#endif
MACRO(0)

Related

C++ or macro magic to generate method and forward arguments

I would like to create a magical macro, or anything, that would generate a something like this:
MAGICAL_MACRO(return_type, method_name, ...)
should work like this:
MAGICAL_MACRO(void, Foo, int a, int b)
->
virtual void Foo(int a, int b)
{
_obj->Foo(a, b);
}
Is this possible? I am afraid it is not.
Two questions: Are you open to a slightly different syntax for the arguments of MAGIC_MACRO? And can you use the Boost.Preprocessor header-only library?
If both answers are "yes", I have a solution for you:
#define MAGICAL_MACRO(Type, Name, ...) \
virtual Type Name(MAGICAL_GENERATE_PARAMETERS(BOOST_PP_VARIADIC_TO_SEQ(__VA_ARGS__))) {\
_obj->Name(MAGICAL_GENERATE_ARGUMENTS(BOOST_PP_VARIADIC_TO_SEQ(__VA_ARGS__))); \
}
#define MAGICAL_GENERATE_PARAMETERS(Args) \
BOOST_PP_SEQ_ENUM(BOOST_PP_SEQ_TRANSFORM(MAGICAL_MAKE_PARAMETER, %%, Args))
#define MAGICAL_GENERATE_ARGUMENTS(Args) \
BOOST_PP_SEQ_ENUM(BOOST_PP_SEQ_TRANSFORM(MAGICAL_MAKE_ARGUMENT, %%, Args))
#define MAGICAL_MAKE_PARAMETER(s, Unused, Arg) \
BOOST_PP_TUPLE_ELEM(2, 0, Arg) BOOST_PP_TUPLE_ELEM(2, 1, Arg)
#define MAGICAL_MAKE_ARGUMENT(s, Unused, Arg) \
BOOST_PP_TUPLE_ELEM(2, 1, Arg)
Usage looks like this:
MAGICAL_MACRO(void, Foo, (int, a), (int, b))
[Live example]
The %% used in the macro definitions is just my way of indicating "this value is not used." You could use pretty much anything else there (unless it contains a comma).
The above solution will work as long as the types involved are not spelled with a comma. If they are, introduce a type alias for them (typedef or using). Note that it is possible to get around this within the preprocessor magic itself, but it complicates already ugly code.
If you don't mind changing the syntax for the macro arguments, you could use following trick which abuses declaration syntax:
#define MAGICAL_MACRO(return_type, method_name, ...) \
virtual return_type method_name(__VA_ARGS__)
{ \
_obj->method_name(__VA_ARGS__); \
}
MAGICAL_MACRO(void, foo, int(a), int(b))
That will expand to:
virtual void foo(int(a), int(b))
{
_obj->foo(int(a), int(b));
}
Where void func(int(a), int(b)) is completely equivalent to void func(int a, int b).
The extra casts (or constructor calls depending on argument types) are ugly, but both GCC and Clang (with -O0) seem to ignore them not only for primitive types/PODs, but also for non-POD classes even if their copy constructors have side effects:
#include <iostream>
struct A
{
int x;
A(int value) : x(value) {}
A(const A &o)
{
x = o.x;
std::cout << "copy";
}
};
void func(A a)
{
std::cout << a.x << '\n';
}
void func1(A a)
{
func(a);
}
void func2(A a)
{
func(A(a));
}
int main()
{
func1(1); // prints `copy1`
func2(2); // prints `copy2`
}
The code below is working for what you've asked for with up to 1024 arguments and without using additional stuff like boost. It defines an EVAL(...) and also a MAP(m, first, ...) macro to do recursion and to use for each iteration the macro m with the next parameter first.
It is mostly copied from C Pre-Processor Magic. It is also great explained there. You can also download these helper macros like EVAL(...) at this git repository, there are also a lot of explanation in the actual code. It is variadic so it takes the number of arguments you want.
But I changed the FIRST and the SECOND macro as it uses a Gnu extension like it is in the source I've copied it from.
To split arguments like int a into int and a I used this answer from SO.
Your macro will be:
#define MAGICAL_MACRO(return_type, method_name, ...) \
virtual return_type method_name(__VA_ARGS__) \
{ \
return _obj->method_name(EVAL(MAP(TYPE_NAME, __VA_ARGS__))); \
}
Examples and limitations:
MAGICAL_MACRO(void, FOO, int a, double b, char c);
--> virtual void FOO(int a, double b, char c) { return _obj->FOO(a , b , c); };
MAGICAL_MACRO(int, FOO, int a, double b, char c);
--> virtual int FOO(int a, double b, char c) { return _obj->FOO(a , b , c); } ;
MAGICAL_MACRO(void, FOO, int* a, double* b, char* c);
--> virtual void* FOO(int* a, double* b, char* c) { return _obj->FOO(* a , * b , * c); };
/* maybe not what you want: pointer are dereferenced */
All the other macros needed, note that type splitting need to be defined per macro here:
/* Define all types here */
#define SPLIT_int int COMMA
#define SPLIT_char char COMMA
#define SPLIT_float float COMMA
#define SPLIT_double double COMMA
#define FIRST_(a, ...) a
#define SECOND_(a, b, ...) b
#define FIRST(...) FIRST_(__VA_ARGS__,)
#define SECOND(...) SECOND_(__VA_ARGS__,)
#define EMPTY()
#define EVAL(...) EVAL1024(__VA_ARGS__)
#define EVAL1024(...) EVAL512(EVAL512(__VA_ARGS__))
#define EVAL512(...) EVAL256(EVAL256(__VA_ARGS__))
#define EVAL256(...) EVAL128(EVAL128(__VA_ARGS__))
#define EVAL128(...) EVAL64(EVAL64(__VA_ARGS__))
#define EVAL64(...) EVAL32(EVAL32(__VA_ARGS__))
#define EVAL32(...) EVAL16(EVAL16(__VA_ARGS__))
#define EVAL16(...) EVAL8(EVAL8(__VA_ARGS__))
#define EVAL8(...) EVAL4(EVAL4(__VA_ARGS__))
#define EVAL4(...) EVAL2(EVAL2(__VA_ARGS__))
#define EVAL2(...) EVAL1(EVAL1(__VA_ARGS__))
#define EVAL1(...) __VA_ARGS__
#define DEFER1(m) m EMPTY()
#define DEFER2(m) m EMPTY EMPTY()()
#define DEFER3(m) m EMPTY EMPTY EMPTY()()()
#define DEFER4(m) m EMPTY EMPTY EMPTY EMPTY()()()()
#define IS_PROBE(...) SECOND(__VA_ARGS__, 0)
#define PROBE() ~, 1
#define CAT(a,b) a ## b
#define NOT(x) IS_PROBE(CAT(_NOT_, x))
#define _NOT_0 PROBE()
#define BOOL(x) NOT(NOT(x))
#define IF_ELSE(condition) _IF_ELSE(BOOL(condition))
#define _IF_ELSE(condition) CAT(_IF_, condition)
#define _IF_1(...) __VA_ARGS__ _IF_1_ELSE
#define _IF_0(...) _IF_0_ELSE
#define _IF_1_ELSE(...)
#define _IF_0_ELSE(...) __VA_ARGS__
#define HAS_ARGS(...) BOOL(FIRST(_END_OF_ARGUMENTS_ __VA_ARGS__)())
#define _END_OF_ARGUMENTS_() 0
#define MAP(m, first, ...) \
m(first) \
IF_ELSE(HAS_ARGS(__VA_ARGS__))( \
COMMA DEFER2(_MAP)()(m, __VA_ARGS__) \
)( \
/* Do nothing, just terminate */ \
)
#define _MAP() MAP
#define COMMA ,
#define CALL(A,B) A B
#define SPLIT(D) EVAL1(CAT(SPLIT_, D))
#define TYPE_NAME(D) CALL(SECOND,(SPLIT(D)))

Automatic C wrappers for C++ functions

Let's say I have some unspecified type called variant, as well as two functions allowing to convert to/from this type, with the following signature:
struct converter
{
template<typename T>
static variant to(const T&);
template<typename T>
static T from(const variant&);
};
Now, what I'd like to do is create wrappers for arbitrary C++ functions as in the following example:
SomeObject f_unwrapped(const std::string& s, int* x)
{
//... do something with the inputs...
return SomeObject();
}
extern "C" variant f(variant s, variant x)
{
return converter::to<SomeObject>(f_unwrapped(converter::from<std::string>(s), converter::from<int*>(x)));
}
Ideally I'd want the wrapper to be a one-line declaration or macro that would take only the f_unwrapped function and the name f as inputs.
I've tried to wrap the function into a function object, then do the bureaucratic work using variadic templates. While this does work, I don't know how to make the resulting function extern "C".
What is the most idiomatic way of achieving this goal?
If we use the EVAL, helper, Conditional, and map macros from the first two code blocks here.
The map will need to be made more general for our needs.
#define MM1() MM_CALL1
#define MM_NEXT1(Macro,a,...) \
IS_DONE(a)( \
EAT \
, \
OBSTRUCT(COMMA)() OBSTRUCT(MM1)() \
) \
(Macro,a,__VA_ARGS__)
#define MM_CALL1(Macro,a,...) \
Macro(a) \
MM_NEXT1(Macro,__VA_ARGS__)
#define MacroMap1(Macro,...) MM_CALL1(Macro,__VA_ARGS__,DONE)
#define MM2() MM_CALL2
#define MM_NEXT2(Macro,a,...) \
IS_DONE(a)( \
EAT \
, \
OBSTRUCT(COMMA)() OBSTRUCT(MM2)() \
) \
(Macro,a,__VA_ARGS__)
#define MM_CALL2(Macro,a,b,...) \
Macro(a,b) \
MM_NEXT2(Macro,__VA_ARGS__)
#define MacroMap2(Macro,...) MM_CALL2(Macro,__VA_ARGS__,DONE)
We will also want the WithTypes and WithoutTypes from here.
We can define AMACRO to do the job you wanted.
#define AsVariant(param) variant param
#define ConvertFrom(type,param) converter::from<type>(param)
#define HEADDER(type,func,params) type func ##_unwrapped (WithTypes params)
#define WRAPPER(type,func,params) \
extern "C" variant func (OBSTRUCT(MacroMap1)(AsVariant,WithoutTypes params)) \
{ \
return converter::to< type >(func ## _unwrapped( \
MacroMap2(ConvertFrom,IDENT params) \
)); \
}
#define AMACRO(type,func,params) \
EVAL( \
HEADDER(type,func,params); \
WRAPPER(type,func,params) \
HEADDER(type,func,params) \
)
Which will turn this:
AMACRO(SomeObject,f,(const std::string&, s, int*, x))
{
// ... do something with the inputs ...
return SomeObject();
}
Into this (after formatting):
SomeObject f_unwrapped (const std::string& s , int* x );
extern "C" variant f (variant s , variant x )
{
return converter::to<SomeObject>(f_unwrapped(converter::from<const std::string&>(s),converter::from<int*>(x)));
}
SomeObject f_unwrapped (const std::string& s , int* x )
{
return SomeObject();
}
NOTE:
If the const needs removing from the parameter, a conditional, similar to the ISDONE, can be made and added to the ConvertFrom macro.

Compile time generated block in C++

I have a struct in my server that I would like to generate it with macro or template in C++ as it has a lot of redundant things:
struct MyBlock {
void Merge(const MyBlock& from) {
if (apple.HasData()) {
apple.Merge(from.apple);
}
if (banana.HasData()) {
banana.Merge(from.banana());
}
...
}
void Clear() {
apple.Clear();
banana.Clear();
...
}
void Update(const SimpleBlock& simple_block) {
if (simple_block.apple.Updated()) {
apple.Add(simple_block.apple);
}
if (simple_block.banana.Updated()) {
banana.Add(simple_block.banana);
}
...
}
Fruit apple;
Fruit banana;
Animal dog;
Animal cat;
...
}
struct SimpleBlock {
SimpleFruit apple;
SimpleFruit banana;
SimpleAnimal dog;
SimpleAnimal cat;
...;
}
I would like to define more variables in the two blocks like apple and dog. I would also like to define more pairs of such blocks. But it involves a lot of trivial work. So my question is how we can use macro, template or some other C++ features including C++11 to generate these blocks in compile time?
The reason why I don't use collections to store those variable is because MyBlock struct would be passed as a parameter in another template class which would dynamically allocate and release this block in run time. It is actually a thread local block that would be aggregated periodically.
Straightforward enough with preprocessor list iteration:
#define M_NARGS(...) M_NARGS_(__VA_ARGS__, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0)
#define M_NARGS_(_10, _9, _8, _7, _6, _5, _4, _3, _2, _1, N, ...) N
#define M_CONC(A, B) M_CONC_(A, B)
#define M_CONC_(A, B) A##B
#define M_ID(...) __VA_ARGS__
#define M_LEFT(L, R) L
#define M_RIGHT(L, R) R
#define M_FOR_EACH(ACTN, ...) M_CONC(M_FOR_EACH_, M_NARGS(__VA_ARGS__)) (ACTN, __VA_ARGS__)
#define M_FOR_EACH_0(ACTN, E) E
#define M_FOR_EACH_1(ACTN, E) ACTN(E)
#define M_FOR_EACH_2(ACTN, E, ...) ACTN(E) M_FOR_EACH_1(ACTN, __VA_ARGS__)
#define M_FOR_EACH_3(ACTN, E, ...) ACTN(E) M_FOR_EACH_2(ACTN, __VA_ARGS__)
#define M_FOR_EACH_4(ACTN, E, ...) ACTN(E) M_FOR_EACH_3(ACTN, __VA_ARGS__)
#define M_FOR_EACH_5(ACTN, E, ...) ACTN(E) M_FOR_EACH_4(ACTN, __VA_ARGS__)
//.. extend this to higher numbers with some copy&paste
#define MYBLOCK(...) struct MyBlock { \
void Merge(const MyBlock& from) { \
M_FOR_EACH(BLOCK_MERGE, __VA_ARGS__) \
} \
void Clear() { \
M_FOR_EACH(BLOCK_CLEAR, __VA_ARGS__) \
} \
void Update(const SimpleBlock& simple_block) { \
M_FOR_EACH(BLOCK_UPDATE, __VA_ARGS__) \
} \
M_FOR_EACH(BLOCK_FIELD, __VA_ARGS__) \
}
#define BLOCK_MERGE(F) if (M_ID(M_RIGHT F).HasData()) { \
M_ID(M_RIGHT F).Merge(from.M_ID(M_RIGHT F)); \
}
#define BLOCK_CLEAR(F) M_ID(M_RIGHT F).Clear;
#define BLOCK_UPDATE(F) if (simple_block.M_ID(M_RIGHT F).Updated()) { \
M_ID(M_RIGHT F).Add(simple_block.M_ID(M_RIGHT F)); \
}
#define BLOCK_FIELD(F) M_ID(M_LEFT F) M_ID(M_RIGHT F);
#define SIMPLEBLOCK(...) struct SimpleBlock { M_FOR_EACH(SIMPLE_DECL, __VA_ARGS__) }
#define SIMPLE_DECL(F) M_CONC(Simple, M_ID(M_LEFT F)) M_ID(M_RIGHT F);
#define FIELDS (Fruit, apple),(Fruit,banana),(Animal,dog),(Animal,cat)
MYBLOCK(FIELDS);
SIMPLEBLOCK(FIELDS);
Add the necessary further member variables to FIELDS in the existing format, and they will be added to the structs emitted by MYBLOCK and SIMPLEBLOCK. (Remember to extend M_FOR_EACH with more iterations... easy to to with a few ctrl+c,ctrl+v.)
template <typename SimpleT>
class BlockTemplate
{
public:
void Merge(const BlockTemplate& from) {
if (HasData()) {
Merge(from.simpleData);
}
}
void Update(const SimpleT& simple_block) {
if (simple_block.Updated()) {
Add(simple_block.data);
}
}
protected:
SimpleT simpleData;
};
Now, you can create objects of type BlockTemplate<SimpleFruit>, BlockTemplate<SimpleAnimal> etc. You could also store pointers to all these BlockTemplate objects in a container after having BlockTemplate inherit from an abstract type. Or, better yet, use the new-fangled type-erasure methods - boost::type_erasure::any for example.
EDIT : If you don't want to use the container that way, you could also make BlockTemplate variadic and store a tuple of different(type-wise) SimpleT objects and modify the Merge and Update functions accordingly. The problem with this is that it becomes much harder to track your SimpleT objects - std::tuple doesn't allow you to give names. You would be referring to the values as get<N>(tupleData).
The description of why you don't use a collection sounds like some optimization thing. Have you measured?
Anyway, one simple solution is store pointers to the objects in a collection.
Then you can iterate over the collection.

Set compile-time warnings in Visual Studio 2008 with "static_if"-like sulution?

I have a big macro, which contains a plenty of strings of code, i. e. casts from one type to another. When one does some changes to initial types in the structure declaration, cast from bigger type to lesser might take its place. Then compiler starts warning:
warning C4309: 'argument' : truncation of constant value
pointing the line number of macro in my code, telling nothing of the real string and parameter name.
I would like to write a static compiler-time hack, where msg will be the casted field name:
#if defined(__GNUC__)
# define DEPRECATE(foo, msg) foo __attribute__((deprecated(msg)))
#elif defined(_MSC_VER)
# define DEPRECATE(foo, msg) __declspec(deprecated(msg)) foo
#else
# error This compiler is not supported
#endif
#define STATIC_WARNING(name, expr, msg) \
{ \
struct expr##__ { \
DEPRECATE(void name##(), msg) {} \
expr##__() { name##(); } \
}; }
but first of all I need to have something like "static_if". I mean I should compare initial and final type, and if they are not equal, I will use STATIC_WARNING mentioned above. Is it possible to write something like that in MS Visual Studio 2008. By the way, it doesn't support anything from C++0x. So I can't even use BOOST_STATIC_ASSERT_MSG, though it needs C++0x to enable messages.
As a matter of fact Andrew advised me to use template specialization:
#if defined(__GNUC__)
# define DEPRECATE(foo, msg) foo __attribute__((deprecated(msg)))
#elif defined(_MSC_VER)
# define DEPRECATE(foo, msg) __declspec(deprecated(msg)) foo
#else
# error This compiler is not supported
#endif
template<typename T, bool> struct UseDeprecated { UseDeprecated() { T()._(); } };
template<typename T> struct UseDeprecated<T, true> { };
#define STATIC_WARNING(condition, expr, msg) \
{ struct expr##__ { \
DEPRECATE(void _(), msg) {} \
}; UseDeprecated<expr##__, condition>(); }

Boost preprocessor not expanding

I have the following code:
#include <boost/preprocessor.hpp>
#define ARGS(r, data, elem) \
BOOST_PP_COMMA_IF(BOOST_PP_SUB(r, 2)) \
BOOST_PP_SEQ_ELEM(0, elem) BOOST_PP_SEQ_ELEM(1, elem)
#define DEF_FUN(name, args) void name(BOOST_PP_SEQ_FOR_EACH(ARGS,,args));
#define DEF_FUNCTIONS_ELEM(r, data, elem) DEF_FUN(BOOST_PP_SEQ_ELEM(0, elem), BOOST_PP_SEQ_ELEM(1, elem))
#define DEF_FUNCTIONS(funSeqs) \
BOOST_PP_SEQ_FOR_EACH(DEF_FUNCTIONS_ELEM,, funSeqs)
DEF_FUNCTIONS_ELEM(2,, (fun0) (((int)(arg0)) ((char)(arg1))))
DEF_FUNCTIONS
(
((fun0) (((int)(arg0)) ((char)(arg1))))
((fun1) (((char)(arg0)) ((long)(arg1)) ((short)(arg2))))
((fun3) ())
)
When I preprocess this with Clang 3.2 or g++ 4.6.3, I get:
void fun0( int arg0 , char arg1 );
void fun0(BOOST_PP_SEQ_FOR_EACH(ARGS,,((int)(arg0)) ((char)(arg1))));
void fun1(BOOST_PP_SEQ_FOR_EACH(ARGS,,((char)(arg0)) ((long)(arg1)) ((short)(arg2))));
void fun3(BOOST_PP_SEQ_FOR_EACH(ARGS,,));
(I added line-breaks for clarity)
The question is, why is the inner BOOST_PP_SEQ_FOR_EACH not expanded?
Passing this output again expands the expected result.
EDIT: After a lot of searching I read that a macro wont expand if it's called twice, I think that's why.
EDIT: I should've used PP_SEQ_FOR_EACH_I, the R is not meant to be used as a subscript.
BOOST_PP_SEQ_FOR_EACH is not reentrant. There are only a few macros in Boost.PP that are reentrant(BOOST_PP_FOR, BOOST_PP_WHILE, and BOOST_PP_REPEAT). However, you can workaround it by using deferred expressions, like this:
#include <boost/preprocessor.hpp>
#define EXPAND(...) __VA_ARGS__
#define EMPTY()
#define DEFER(x) x EMPTY()
// An indirection macro to avoid direct recursion
#define BOOST_PP_SEQ_FOR_EACH_ID() BOOST_PP_SEQ_FOR_EACH
#define ARGS(r, data, elem) \
BOOST_PP_COMMA_IF(BOOST_PP_SUB(r, 2)) \
BOOST_PP_SEQ_ELEM(0, elem) BOOST_PP_SEQ_ELEM(1, elem)
// Defer BOOST_PP_SEQ_FOR_EACH_ID here
#define DEF_FUN(name, args) void name(DEFER(BOOST_PP_SEQ_FOR_EACH_ID)()(ARGS,,args));
#define DEF_FUNCTIONS_ELEM(r, data, elem) DEF_FUN(BOOST_PP_SEQ_ELEM(0, elem), BOOST_PP_SEQ_ELEM(1, elem))
// Add EXPAND here to apply another scan to expand the deferred expression
#define DEF_FUNCTIONS(funSeqs) \
EXPAND(BOOST_PP_SEQ_FOR_EACH(DEF_FUNCTIONS_ELEM,, funSeqs))
DEF_FUNCTIONS
(
((fun0) (((int)(arg0)) ((char)(arg1))))
((fun1) (((char)(arg0)) ((long)(arg1)) ((short)(arg2))))
((fun3) ())
)
#include <boost/preprocessor.hpp>
#define ARGS(r, data, index, elem) \
BOOST_PP_SEQ_ELEM(0, elem) BOOST_PP_SEQ_ELEM(1, elem) BOOST_PP_COMMA_IF(BOOST_PP_NOT_EQUAL(index, BOOST_PP_DEC(data)))
#define DEF_FUN(name, args) void name(BOOST_PP_SEQ_FOR_EACH_I(ARGS,BOOST_PP_SEQ_SIZE(args),args));
#define DEF_FUNCTIONS_ELEM(r, data, elem) DEF_FUN(BOOST_PP_SEQ_ELEM(0, elem), BOOST_PP_SEQ_ELEM(1, elem))
#define DEF_FUNCTIONS(funSeqs) \
BOOST_PP_SEQ_FOR_EACH(DEF_FUNCTIONS_ELEM,, funSeqs)
DEF_FUNCTIONS_ELEM(2,, (fun0) (((int)(arg0)) ((char)(arg1))))
DEF_FUNCTIONS
(
((fun0) (((int)(arg0)) ((char)(arg1))))
((fun1) (((char)(arg0)) ((long)(arg1)) ((short)(arg2))))
((fun3) ())
)