I need to convert an expression to its result before applying it on a preprocessor. This is probably a simple problem, but I couldn't figure out a way to do it.
My preprocessor is like this:
#define ABCD(BITPOS) \
if(BIT##BITPOS##_MASK & 0x01) { \
Do something; }
And BIT0_MASK to BIT100_MASK is defined at some place.
If I call ABCD(5), preprocessor converts it to BIT5_MASK and it works fine.
But, I want to call it like this:
ABCD(START_VAL+2),
it gives me compilation error saying BITSTART_VAL is not declared, )_MASK is not defined and whole bunch of related errors.
How can I make it work ? Appreciate your responses.
The preprocessor macro system cannot evaluate arithmetic operators. It can only splice tokens together and substitute identifiers.
You will need to find another solution.
If you really really must do this, the folks at Boost created macros to perform some basic arithmetic, using only splicing and substitution as a basis. That is not an appropriate tool for this job, though.
Looks like you need an inline function rather than a macro.
inline size_t ABCD(unsigned int bitmask)
{
if (bitmask & 0x01U)
{
something();
}
}
The inline keyword will hint to the compiler that you want the code to be pasted rather than called.
Related
does anyone know why this is syntactically wrong?
Im trying to covert this
#define OUTS_FROM_FP(_fp, _argCount) ((u4*) ((u1*)SAVEAREA_FROM_FP(_fp) - sizeof(u4) * (_argCount)))
to this
#define OUTS_FROM_FP(_fp, _argCount) {\
((u4*) ((u1*)SAVEAREA_FROM_FP(_fp) - sizeof(u4) * (_argCount))); \
cout<<"Hello World"<<endl; \
}
outs = OUTS_FROM_FP(fp, vsrc1); --this is how it is being called
I get a lot of errors when running this: they start from statements that say that variables that were passed to the macro before are unused
Expanded, the original macro will look like this:
outs = ((u4*) ((u1*)SAVEAREA_FROM_FP(fp) - sizeof(u4) * (vsrc)));
That's (as far as I can tell as you didn't provide much context) valid code.
Your modified macro expands the same statement to this:
outs = { /* ... */ };
Your compiler gets all kinds of confused as you are attempting to assign a code block to a variable...
All the usual caveats regarding the use of macros in general aside, you could use the comma operator to get your modified macro "working":
#define OUTS_FROM_FP( _fp, _argCount ) \
cout << "Hello world\n", \
((u4*) ((u1*)SAVEAREA_FROM_FP(_fp) - sizeof(u4) * (_argCount)))
(The output is put first, as statements separated by the comma operator evaluate to the result of the last statement -- putting the output first makes the macro still evaluate to the same value as the original macro.)
All in all, you're probably better off turning that macro into a function.
Assuming that _fp and _argCount are variables or simple expressions, the original version is an expression of type u4*.
The second is more complicated. The braces make it a block, but syntactically you’re using it as an expression. This is not allowed in the C++ standard, but is supported by g++ and some other compilers. Since you say you’re using GCC, the value of this expression is the value of the last line of the block, which in this case is cout<<"Hello World"<<endl. If you were using a compiler which did not support statement expressions, you’d get a more confused syntax error.
I expect that unless you can convert an ostream to a u4 pointer (which, given what context we have, seems very unlikely), this won’t work. In this simple case, you can fix it by simply switching the order of the lines in the block. In a more complicated case, which I expect is the end goal, you probably would need to do something like
#define OUTS_FROM_FP(_fp, _argCount) {\
u4* result = ((u4*) ((u1*)SAVEAREA_FROM_FP(_fp) - sizeof(u4) * (_argCount))); \
cout<<"Hello World"<<endl; \
result; \
}
This saves the output of the macro to a temporary variable, does whatever calculations you want (which can change result), and then on the last line “returns” result outside the macro. This is less portable than DevSolar’s solution, but it works better if you need to create temporary variables, and in my opinion is more readable.
However, as others point out in the comments, there is little reason (at least that we can see) to keep this as a macro instead of converting it to a function. Functions are much more robust in a variety of ways. Reasons you might still want to keep it as a macro include the definition of SAVEAREA_FROM_FP changing or the types u4 and u1 being different in different places. Neither of these would not be good programming practice, but you can’t control what others have done before and I don’t know enough about Dalvik to say it isn’t the case.
In the LLVM C Api, instructions are passed around by LLVMValueRef. How do I determine what instruction type (add, store, fence, whatever) an LLVMValueRef is, if it's an instruction at all?
If anyone is still looking for this: in 2016 a LLVMGetValueKind function was added: https://reviews.llvm.org/D18729.
It looks like there's LLVMTypeOf and then LLVMTypeKind functions to get a type enumeration from a value.
There are LLVMIsA* functions for each value subclass. They're maybe a bit hard to find because they're generated by macros. The declarations, in Core.h, look like this:
#define LLVM_DECLARE_VALUE_CAST(name) \
LLVMValueRef LLVMIsA##name(LLVMValueRef Val);
LLVM_FOR_EACH_VALUE_SUBCLASS(LLVM_DECLARE_VALUE_CAST)
And the definitions, in Core.cpp, look like this:
#define LLVM_DEFINE_VALUE_CAST(name) \
LLVMValueRef LLVMIsA##name(LLVMValueRef Val) { \
return wrap(static_cast<Value*>(dyn_cast_or_null<name>(unwrap(Val)))); \
}
LLVM_FOR_EACH_VALUE_SUBCLASS(LLVM_DEFINE_VALUE_CAST)
So for an LLVMValueRef V should be able to write e.g. LLVMIsAStoreInst(V), which will return either the same value back or null. Intermediate subclasses also work, as in e.g. LLVMIsAInstruction(V), LLVMIsAConstant(V), etc.
Alternatively, for instructions in particular, you can use LLVMGetInstructionOpcode, and compare the enum against the LLVMOpcode values. It will also conveniently return 0 if the argument is not an instruction.
Incidentally (in response to your comment), I think the header files are often the best place to look for LLVM documentation, as the doxygen docs are sometimes confusing. For example Core.h is pretty straightforward to read through, and this comment answers your question.
Hello all I was having trouble with macros so I thought I would practice and I was looking at the ## macro operator and thought I could use it for my problem I wan't to be able to call multiple functions based on the parameter for example if I have a macro like so:
#define macro(a) func##a();
int main()
{
.....
for(int i = 0;i< length;i++)
{
macro(i)
}
func1()
{
}
....
func31()
{
}
Anyone have an idea of how I can accomplish this??
You can only combine two preprocessor tokens. However, func isn't a preprocessor token. You need to jump through an extra hoop, calling some form of "concat" macro:
#define CONCAT(a, b) a ## b
#define macro(a) CONCAT(func,a)
Of course, the tokens produced by you macro won't be func1, ..., func31 (of course, they would also need to start with func0 if your logic were correct) but rather funci. The expansion of macros happens at the beginning of compilation while the execution of the for-loop happens at run-time (some optimizations may hoist it into compile-time but that won't affect the macros).
If you need to expand a sequence of integers in combination with a macro, you may want to have a look at the Boost preprocessor library, in particular at the BOOST_PP_REPEAT functionality.
If you just need to statically expand a sequence of integers to function calls, you might also consider looking at function template templatized on an integers: I would certainly consider using an approach using templates before trying to use the preprocessor library...
In C++ I want to make functions that when declared, gets automatically added to a map( or vector, doesn't really matter in this case) as a function pointer and is called later automatically. For example this would be useful if I am writing unit test framework and I just want users to declare each of their unit tests like this:
UNIT_TEST_FUNCTION(function_name){
// do something
}
and instead something like this gets called
void function_name(){
//do something
}
int temp = register_function("function_name", function_name);
Where register_function() adds the user defined function in a map of function pointers for example. So basically, I need a mechanism that adds additional lines of code after a function definition, so that some action is performed automatically on the defined function. Is this possible using macros perhaps?
A macro can only generate a consecutive block of text. It can't lay things out the way you show in the question.
However if you're willing to rearrange a little, it can be done.
#define UNIT_TEST_FUNCTION(function_name) \
void function_name(); // forward declaration \
int temp##function_name = register_function(#function_name, function_name); \
void function_name()
A single preprocessor macro can't do what you want because it can only generate a single, contiguous block of text. Preprocessor macros are stupid in the sense that they don't understand anything about the language -- hence the preprocessor in 'preprocessor macro'.
What you can do is use a pair of macros or tuple of macros to delimit the begin and end of your test case mapping, and a single macro for each individual test case. Something along these lines:
TEST_CASES_BEGIN
UNIT_TEST_FUNCTION(function_name){
// do something
}
TEST_CASES_END
The Boost unit test facility uses a mechanism very similar to this. You might even (eventually) find this design to be a little more expressive than the design you are trying to achieve.
I have a .h file in which hundreds of constants are defined as macros:
#define C_CONST_NAME Value
What I need is a function that can dynamically get the value of one of these constants.
needed function header :
int getConstValue(char * constName);
Is that even possible in the C langage?
---- EDIT
Thanks for the help, That was quick :)
as i was thinking there is no miracle solution for my needs.
In fact the header file i use is generated by "SCADE : http://www.esterel-technologies.com/products/scade-suite/"
On of the solution i got from #Chris is to use some python to generate c code that does the work.
Now its to me to make some optimizations in order to find the constant name. I have more than 5000 constants O(500^2)
i'm also looking at the "X-Macros" The first time i hear of that, home it works in C because i'm not allowed to use c++.
Thanks
C can't do this for you. You will need to store them in a different structure, or use a preprocessor to build the hundreds of if statements you would need. Something like Cogflect could help.
Here you go. You will need to add a line for each new constant, but it should give you an idea about how macros work:
#include <stdio.h>
#define C_TEN 10
#define C_TWENTY 20
#define C_THIRTY 30
#define IFCONST(charstar, define) if(strcmp((charstar), #define) == 0) { \
return (define); \
}
int getConstValue(const char* constName)
{
IFCONST(constName, C_TEN);
IFCONST(constName, C_TWENTY);
IFCONST(constName, C_THIRTY);
// No match
return -1;
}
int main(int argc, char **argv)
{
printf("C_TEN is %d\n", getConstValue("C_TEN"));
return 0;
}
I suggest you run gcc -E filename.c to see what gcc does with this code.
A C preprocessor macro (that is, something named by a #define statement) ceases to exist after preprocessing completes. A program has no knowledge of the names of those macros, nor any way to refer back to them.
If you tell us what task you're trying to perform, we may be able to suggest an alternate approach.
This is what X-Macros are used for:
https://secure.wikimedia.org/wikipedia/en/wiki/C_preprocessor#X-Macros
But if you need to map a string to a constant, you will have to search for the string in the array of string representations, which is O(n^2).
You can probably do this with gperf, which generates a lookup function that uses a perfect hash function.
Create a file similar to the following and run gperf with the -t option:
struct constant { char *name; int value; };
%%
C_CONST_NAME1, 1
C_CONST_NAME2, 2
gperf will output C (or C++) code that does the lookup in constant time, returning a pointer to the key/value pair, or NULL.
If you find that your keyword set is too large for gperf, consider using cmph instead.
There's no such capability built into C. However, you can use a tool such as doxygen to extract all #defines from your source code into a data structure that can be read at runtime (doxygen can store all macro definitions to XML).