What is the use of ## preprocessor in C [duplicate] - c

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
C preprocessor and concatenation
can anybody explain with example ?

It allows to construct indentifiers from their parts. Eg:
#define CLASS_NAME(name) CLASS__ ## name
would expand CLASS_NAME(alpha) to CLASS__alpha. It is vastly used in tricks used by the boost preprocessor library, eg.
#define IF0(a, b) b
#define IF1(a, b) a
#define IF(cond, a, b) IF ## cond(a, b)
which would expand IF(0, a, b) to a and IF(1, a, b) to b. Also, sometimes, it is used to generate struct and function names (akin to c++ templates).

I'm not sure what you meen by "##" preprocessor.
C has a preprocessor for expanding macros before compile time. This is a first pass on the source code. There are a few different things it is used for:
including other source / header files (#include)
conditionally compiling code (#ifdef etc.)
expanding macros (#define)
handy for constants
simple functions
Note, though, that this is not really "C" (though part of the spec) and can cause headaches if you get it wrong. I believe new languages would not do it this way anymore.

Related

Why is #define used after an #undef directive? [duplicate]

This question already has answers here:
What is the benefit of putting #undef before #define?
(2 answers)
Closed last year.
I'm reviewing the open source FANN library. As far as I have examined, the developers contributing to the project are quite experienced in C. But I wonder why they do the following in doublefann.h file:
#undef DOUBLEFANN
#define DOUBLEFANN
What's the purpose of removing an identifier using #undef and then redefining it using #define?
I don't think there's any secret; it's just that the author of that code wanted to override any existing preprocessor-value of DOUBLEFANN (e.g. as set by an earlier line in some header-file, or perhaps as provided by a -DDOUBLEFANN=something argument on the compiler's command-line) and replace it with his own definition of DOUBLEFANN as a defined preprocessor macro with an empty value.
As to why the author felt it was necessary to do that, I have no idea.

Dynamically prefix macro names with a variadic macro

Background
I've utilized a set of preprocessor macros from another question that allows me to prefix symbol names (enums, function names, struct names, etc) in my source, i.e.:
#include <stdio.h>
#define VARIABLE 3
#define PASTER(x,y) x ## _ ## y
#define EVALUATOR(x,y) PASTER(x,y)
#define NAME(fun) EVALUATOR(fun, VARIABLE)
void NAME(func)(int i);
int main(void)
{
NAME(func)(123);
return 0;
}
void NAME(func)(int i)
{
printf("i is %d in %s.\n", i, __func__);
}
Problem
This works as expected, with the following output: i is 123 in func_3.
Edit
I would like this code:
#define NAME(SOME_MACRO_CONST) (123)
#define NAME(SOME_MACRO_CONST2) (123)
To expand to:
#define 3SOME_MACRO_CONST (123)
#define 3SOME_MACRO_CONST2 (123)
I realize the macro shouldn't start with a digit. In the final code I'll be using names like LIB_A_ and LIB_B_ as prefixes.
/Edit
However, if I attempt to do the same with macros as the arguments to my NAME variadic macro, it fails like so:
Re-using NAME macro:
Code
#define NAME(MY_CONST) (3)
Output
test.c:7:0: warning: "NAME" redefined
#define NAME(MY_CONST) 3
Manually pasting prefix:
Code:
#define VARIABLE ## MY_CONST (3)
Output:
test.c:8:18: error: '##' cannot appear at either end of a macro expansion
#define VARIABLE ## MY_CONST (3)
Question
How can I create simple macro definitions (name + value) that has a common prefix for all the macros? The goal is to be able to make multiple copies of the source file and compile them with different flags so all versions can be linked together into the same final binary without symbol/macro name collisions (the macros will later be moved into header files). The final file will be too big to write in something like M4 or a template language. Ideally, the solution would involve being able to use a single macro-function/variadic-macro for all use cases, but I'm OK with one macro for symbol prefixing, and another for macro-name prefixing.
I would like this code:
#define NAME(SOME_MACRO_CONST) (123)
#define NAME(SOME_MACRO_CONST2) (124)
To expand to:
#define 3SOME_MACRO_CONST (123)
#define 3SOME_MACRO_CONST2 (124)
(I corrected the second number to 124 to make it different from the first one, for readability purposes)
This is impossible with the C preprocessor
for several reasons:
3SOME_MACRO_CONST is not a valid identifier (both for the preprocessor, and for the C compiler itself) since it does not start with a letter or an underscore. So let's assume you want your code to be expanded to:
/// new desired expansion
#define THREE_SOME_MACRO_CONST (123)
#define THREE_SOME_MACRO_CONST2 (124)
this is still impossible, because the preprocessor works before anything else and cannot generate any preprocessor directive (e.g. #define).
A workaround, if you only want to #define some numbers (computable at compile-time !!!) might be to expand to some anonymous enum like
enum {
THREE_SOME_MACRO_CONST= 123,
THREE_SOME_MACRO_CONST2= 124,
};
and you know how to do that in the details. Read also about X-macros.
However, even if you can change your requirement to something that is possible, it might be not recommendable, because your code becomes very unreadable (IMHO). You could sometimes consider writing some simple script (e.g. in sed or awk ...), or use some other preprocessor like GPP, to generate a C file from something else.
Notice that most serious build automation tools (like GNU make or ninja) -or even IDEs (they can be configured to) permit quite easily (by adding extra targets, recipes, commands, etc...) to generate some C (or C++) code from some other file, and that meta-programming practice has been routinely used since decades (e.g. bison, flex, autoconf, rpcgen, Qt moc, SWIG ...) so I am surprised you cannot do so. Generating a header file containing many #define-s is so common a practice that I am surprised you are forbidden to do so. Perhaps you just need to discuss with your manager or colleagues. Maybe you need to look for some more interesting job.
Personally, I am very fond of such meta-programming approaches (I did my PhD on these in 1990, and I would discuss them at every job interview; a job where metaprogramming is forbidden is not for me. Look for example at my past GCC MELT project, and my future project also will have metaprogramming). Another way of promoting that approach is to defend domain specific languages (and the ability to make your DSL inside some large software project; for example the GCC compiler has about a dozen of such DSLs inside it....). Then, your DSL can (naturally) be compiled to C which is a common practice. On modern operating systems that generated C code could be compiled at runtime and dynamically loaded as a (generated) plugin (using dlopen on POSIX...)
Sometimes, you can trick the compiler. For a project compiled by GCC, you could consider writing your GCC plugin..... (that is a lot more work than adding a command generating C code; your plugin could provide extra magic pragmas or builtins or attributes used by some other macros).
You could also configure the spec file of your gcc to handle specifically some C files. Beware, that could affect every future compilation!

Compute minimal list of macro combinations from source

How would one compute efficiently the minimal list of macro definitions combinations that will give the same code ? The list of macros is known before-hand.
The objective would be to compile less versions of the program (possibly a shader) and thus skip some compilation time by knowing what macro combinations are equivalent.
eg. if a program built with MACRO_A and MACRO_B is the same as a program built only with MACRO_A.
For the sake of simplicity, those macro are either defined or not, and their value doesn't matter (meaning there is no #if SOMEMACRO).
For example with:
#ifdef A
#ifdef B
// some code
#endif
// some code
#elif defined(C)
// some code
#else
// some code
#endif
A trivial way to generate all the programs would be to compile with all the combinations made from A,B and C. It would mean creating 2^3=8 combinations. However, only the following combinations really are useful (! means the macro is not defined, ~that the macro doesn't matter and can be either defined or undefined ):
( A, B, ~C) (same as A, B, C and A, B, !C)
( A, !B, ~C)
(!A, ~B, C)
(!A, ~B, !C)
Which means compiling only programs with the following definitions is enough:
A B
A
C
No defines
With this list, I know that when asked for a program with the (A, !B, C) combination I can simply use the one built with only A defined.
What tools could be used ?
Notes:
Most preprocessors will only give the path for a given set of defines
Perhaps building the control flow graph of the preprocessor would help?
Some work has been done with clang here by J. Trull to add conditional nodes to the AST, but seems to be aimed at refactoring, not sure if it is the best way to do it

C Preprocessor: Own implementation for __COUNTER__

I'm currently using the __COUNTER__ macro in my C library code to generate unique integer identifiers. It works nicely, but I see two issues:
It's not part of any C or C++ standard.
Independent code that also uses __COUNTER__ might get confused.
I thus wish to implement an equivalent to __COUNTER__ myself.
Alternatives that I'm aware of, but do not want to use:
__LINE__ (because multiple macros per line wouldn't get unique ids)
BOOST_PP_COUNTER (because I don't want a boost dependency)
BOOST_PP_COUNTER proves that this can be done, even though other answers claim it is impossible.
In essence, I'm looking for a header file "mycounter.h", such that
#include "mycounter.h"
__MYCOUNTER__
__MYCOUNTER__ __MYCOUNTER__
__MYCOUNTER__
will be preprocessed by gcc -E to
(...)
0
1 2
3
without using the built-in __COUNTER__.
Note: Earlier, this question was marked as a duplicate of this, which deals with using __COUNTER__ rather than avoiding it.
You can't implement __COUNTER__ directly. The preprocessor is purely functional - no state changes. A hidden counter is inherently impossible in such a system. (BOOST_PP_COUNTER does not prove what you want can be done - it relies on #include and is therefore one-per-line only - may as well use __LINE__. That said, the implementation is brilliant, you should read it anyway.)
What you can do is refactor your metaprogram so that the counter could be applied to the input data by a pure function. e.g. using good ol' Order:
#include <order/interpreter.h>
#define ORDER_PP_DEF_8map_count \
ORDER_PP_FN(8fn(8L, 8rec_mc(8L, 8nil, 0)))
#define ORDER_PP_DEF_8rec_mc \
ORDER_PP_FN(8fn(8L, 8R, 8C, \
8if(8is_nil(8L), \
8R, \
8let((8H, 8seq_head(8L)) \
(8T, 8seq_tail(8L)) \
(8D, 8plus(8C, 1)), \
8if(8is_seq(8H), \
8rec_mc(8T, 8seq_append(8R, 8seq_take(1, 8L)), 8C), \
8rec_mc(8T, 8seq_append(8R, 8seq(8C)), 8D) )))))
ORDER_PP (
8map_count(8seq( 8seq(8(A)), 8true, 8seq(8(C)), 8true, 8true )) //((A))(0)((C))(1)(2)
)
(recurses down the list, leaving sublist elements where they are and replacing non-list elements - represented by 8false - with an incrementing counter variable)
I assume you don't actually want to simply drop __COUNTER__ values at the program toplevel, so if you can place the code into which you need to weave __COUNTER__ values inside a wrapper macro that splits it into some kind of sequence or list, you can then feed the list to a pure function similar to the example.
Of course a metaprogramming library capable of expressing such code is going to be significantly less portable and maintainable than __COUNTER__ anyway. __COUNTER__ is supported by Intel, GCC, Clang and MSVC. (not everyone, e.g. pcc doesn't have it, but does anyone even use that?) Arguably if you demonstrate the feature in use in real code, it makes a stronger case to the standardisation committee that __COUNTER__ should become part of the next C standard.
You are confusing two different things:
1 - the preprocessor which handles#define and #include like stuff. It does only works as the text (meaning character sequences) level and has very few computing capabilities. It is so limited that it cannot implement __COUNTER__. The preprocessor work consist only in macro expansion and file replacement. The crucial point it that it occur before the compilation even start.
2 - the C++ language and in particular the template (meta)programming language which can be used to compute stuff during the compilation phase. It is indeed turing complete but as I already said compilation start after preprocessing.
So what you are asking is not doable in standard C or C++. To solve this problem boost implement its own preprocessor which is not standard compliant and has much more computing capabilities. In particular it is possible to use build an analogue to __counter__ with it.
This small header of mine contains an own implementation of a C preprocessor counter (it uses a slightly different syntax).

C/C++ preprocessor single quote? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
How to single-quote an argument in a macro?
How can it do the following:
#define MACRO(X) ...
MACRO(a) // should give 'a'
I might be missing an easier way, but how about #define MACRO(X) ((#X)[0]). The # stringtizes X and then [0] selects the first character.
Seems it can't be done with the C preprocessor, at least the gcc docs states it bluntly:
There is no way to convert a macro
argument into a character constant.
Like this:
#include <string>
std::string Macro(const std::string& s)
{
std::string ret = "'";
ret += s;
ret += "'";
return ret;
}
EDIT:
I posted this answer before it was revealed that this was needed for metaprogramming. I don not know of a way to accomplish this for metaprogramming, but metaprogramming is not my forte.
Also, as for why I am effectively saying "don't use the preprocessor" in the first place, read the comments below. But in short, I believe that almost everything that is commonly done using the preprocessor can and should be done using first-level constructs instead. Using the preprocessor skirts the C++ type system and reduces safety. Macros are difficult to debug, difficult to extend. Extensively using macros will result in code that isn't familiar to the programmers who didn't create the macro, resulting in a kind of "secret language" only 1 person knows, decreasing maintainability of not only the macros, but the functions where they are used.
OK, I guess that wasn't so short, but there it is.

Resources